text:
"""
Asynchronous-friendly error mechanism.

See L{Failure}.
"""

from __future__ import division, absolute_import, print_function

# System Imports
import sys
import linecache
import inspect
import opcode
from inspect import getmro

from twisted.python.compat import NativeStringIO as StringIO
from twisted.python import reflect
from twisted.python._oldstyle import _oldStyle, _shouldEnableNewStyle

count = 0
traceupLength = 4

class DefaultException(Exception):
    pass

def format_frames(frames, write, detail="default"):
    """Format and write frames.

    @param frames: is a list of frames as used by Failure.frames, with
        each frame being a list of
        (funcName, fileName, lineNumber, locals.items(), globals.items())
    @type frames: list
    @param write: this will be called with formatted strings.
    @type write: callable
    @param detail: Four detail levels are available:
        default, brief, verbose, and verbose-vars-not-captured.
        C{Failure.printDetailedTraceback} uses the latter when the caller asks
        for verbose, but no vars were captured, so that an explicit warning
        about the missing data is shown.
    @type detail: string
    """
    if detail not in ('default', 'brief', 'verbose',
                      'verbose-vars-not-captured'):
        raise ValueError(
            "Detail must be default, brief, verbose, or "
            "verbose-vars-not-captured. (not %r)" % (detail,))
    w = write
    if detail == "brief":
        for method, filename, lineno, localVars, globalVars in frames:
            w('%s:%s:%s\n' % (filename, lineno, method))
    elif detail == "default":
        for method, filename, lineno, localVars, globalVars in frames:
            w( '  File "%s", line %s, in %s\n' % (filename, lineno, method))
            w( '    %s\n' % linecache.getline(filename, lineno).strip())
    elif detail == "verbose-vars-not-captured":
        for method, filename, lineno, localVars, globalVars in frames:
            w("%s:%d: %s(...)\n" % (filename, lineno, method))
        w(' [Capture of Locals and Globals disabled (use captureVars=True)]\n')
    elif detail == "verbose":
        for method, filename, lineno, localVars, globalVars in frames:
            w("%s:%d: %s(...)\n" % (filename, lineno, method))
            w(' [ Locals ]\n')
            # Note: the repr(val) was (self.pickled and val) or repr(val)))
            for name, val in localVars:
                w("  %s : %s\n" %  (name, repr(val)))
            w(' ( Globals )\n')
            for name, val in globalVars:
                w("  %s : %s\n" %  (name, repr(val)))

# slyphon: i have a need to check for this value in trial
#          so I made it a module-level constant
EXCEPTION_CAUGHT_HERE = "--- <exception caught here> ---"

class NoCurrentExceptionError(Exception):
    """
    Raised when trying to create a Failure from the current interpreter
    exception state and there is no current exception state.
    """

class _Traceback(object):
    """
    Fake traceback object which can be passed to functions in the standard
    library L{traceback} module.
    """

    def __init__(self, frames):
        """
        Construct a fake traceback object using a list of frames. Note that
        although frames generally include locals and globals, this information
        is not kept by this object, since locals and globals are not used in
        standard tracebacks.

        @param frames: [(methodname, filename, lineno, locals, globals), ...]
        """
        assert len(frames) > 0, "Must pass some frames"
        head, frames = frames[0], frames[1:]
        name, filename, lineno, localz, globalz = head
        self.tb_frame = _Frame(name, filename)
        self.tb_lineno = lineno
        if len(frames) == 0:
            self.tb_next = None
        else:
            self.tb_next = _Traceback(frames)

class _Frame(object):
    """
    A fake frame object, used by L{_Traceback}.

    @ivar f_code: fake L{code<types.CodeType>} object
    @ivar f_globals: fake f_globals dictionary (usually empty)
    @ivar f_locals: fake f_locals dictionary (usually empty)
    """

    def __init__(self, name, filename):
        """
        @param name: method/function name for this frame.
        @type name: C{str}
        @param filename: filename for this frame.
        @type name: C{str}
        """
        self.f_code = _Code(name, filename)
        self.f_globals = {}
        self.f_locals = {}

class _Code(object):
    """
    A fake code object, used by L{_Traceback} via L{_Frame}.
    """
    def __init__(self, name, filename):
        self.co_name = name
        self.co_filename = filename

@_oldStyle
class Failure:
    """
    A basic abstraction for an error that has occurred.

    This is necessary because Python's built-in error mechanisms are
    inconvenient for asynchronous communication.

    The C{stack} and C{frame} attributes contain frames.  Each frame is a tuple
    of (funcName, fileName, lineNumber, localsItems, globalsItems), where
    localsItems and globalsItems are the contents of
    C{locals().items()}/C{globals().items()} for that frame, or an empty tuple
    if those details were not captured.

    @ivar value: The exception instance responsible for this failure.
    @ivar type: The exception's class.
    @ivar stack: list of frames, innermost last, excluding C{Failure.__init__}.
    @ivar frames: list of frames, innermost first.
    """

    pickled = 0
    stack = None

    # The opcode of "yield" in Python bytecode. We need this in _findFailure in
    # order to identify whether an exception was thrown by a
    # throwExceptionIntoGenerator.
    _yieldOpcode = chr(opcode.opmap["YIELD_VALUE"])

    def __init__(self, exc_value=None, exc_type=None, exc_tb=None,
                 captureVars=False):
        """
        Initialize me with an explanation of the error.

        By default, this will use the current C{exception}
        (L{sys.exc_info}()).  However, if you want to specify a
        particular kind of failure, you can pass an exception as an
        argument.

        If no C{exc_value} is passed, then an "original" C{Failure} will
        be searched for. If the current exception handler that this
        C{Failure} is being constructed in is handling an exception
        raised by L{raiseException}, then this C{Failure} will act like
        the original C{Failure}.

        For C{exc_tb} only L{traceback} instances or L{None} are allowed.
        If L{None} is supplied for C{exc_value}, the value of C{exc_tb} is
        ignored, otherwise if C{exc_tb} is L{None}, it will be found from
        execution context (ie, L{sys.exc_info}).

        @param captureVars: if set, capture locals and globals of stack
            frames.  This is pretty slow, and makes no difference unless you
            are going to use L{printDetailedTraceback}.
        """
        global count
        count = count + 1
        self.count = count
        self.type = self.value = tb = None
        self.captureVars = captureVars

        if isinstance(exc_value, str) and exc_type is None:
            raise TypeError("Strings are not supported by Failure")

        stackOffset = 0

        if exc_value is None:
            exc_value = self._findFailure()

        if exc_value is None:
            self.type, self.value, tb = sys.exc_info()
            if self.type is None:
                raise NoCurrentExceptionError()
            stackOffset = 1
        elif exc_type is None:
            if isinstance(exc_value, Exception):
                self.type = exc_value.__class__
            else: #allow arbitrary objects.
                self.type = type(exc_value)
            self.value = exc_value
        else:
            self.type = exc_type
            self.value = exc_value
        if isinstance(self.value, Failure):
            self.__dict__ = self.value.__dict__
            return
        if tb is None:
            if exc_tb:
                tb = exc_tb
            elif getattr(self.value, "__traceback__", None):
                # Python 3
                tb = self.value.__traceback__

        frames = self.frames = []
        stack = self.stack = []

        # added 2003-06-23 by Chris Armstrong. Yes, I actually have a
        # use case where I need this traceback object, and I've made
        # sure that it'll be cleaned up.
        self.tb = tb

        if tb:
            f = tb.tb_frame
        elif not isinstance(self.value, Failure):
            # we don't do frame introspection since it's expensive,
            # and if we were passed a plain exception with no
            # traceback, it's not useful anyway
            f = stackOffset = None

        while stackOffset and f:
            # This excludes this Failure.__init__ frame from the
            # stack, leaving it to start with our caller instead.
            f = f.f_back
            stackOffset -= 1

        # Keeps the *full* stack.  Formerly in spread.pb.print_excFullStack:
        #
        #   The need for this function arises from the fact that several
        #   PB classes have the peculiar habit of discarding exceptions
        #   with bareword "except:"s.  This premature exception
        #   catching means tracebacks generated here don't tend to show
        #   what called upon the PB object.

        while f:
            if captureVars:
                localz = f.f_locals.copy()
                if f.f_locals is f.f_globals:
                    globalz = {}
                else:
                    globalz = f.f_globals.copy()
                for d in globalz, localz:
                    if "__builtins__" in d:
                        del d["__builtins__"]
                localz = localz.items()
                globalz = globalz.items()
            else:
                localz = globalz = ()
            stack.insert(0, (
                f.f_code.co_name,
                f.f_code.co_filename,
                f.f_lineno,
                localz,
                globalz,
                ))
            f = f.f_back

        while tb is not None:
            f = tb.tb_frame
            if captureVars:
                localz = f.f_locals.copy()
                if f.f_locals is f.f_globals:
                    globalz = {}
                else:
                    globalz = f.f_globals.copy()
                for d in globalz, localz:
                    if "__builtins__" in d:
                        del d["__builtins__"]
                localz = list(localz.items())
                globalz = list(globalz.items())
            else:
                localz = globalz = ()
            frames.append((
                f.f_code.co_name,
                f.f_code.co_filename,
                tb.tb_lineno,
                localz,
                globalz,
                ))
            tb = tb.tb_next
        if inspect.isclass(self.type) and issubclass(self.type, Exception):
            parentCs = getmro(self.type)
            self.parents = list(map(reflect.qual, parentCs))
        else:
            self.parents = [self.type]

    def trap(self, *errorTypes):
        """Trap this failure if its type is in a predetermined list.

        This allows you to trap a Failure in an error callback.  It will be
        automatically re-raised if it is not a type that you expect.

        The reason for having this particular API is because it's very useful
        in Deferred errback chains::

            def _ebFoo(self, failure):
                r = failure.trap(Spam, Eggs)
                print('The Failure is due to either Spam or Eggs!')
                if r == Spam:
                    print('Spam did it!')
                elif r == Eggs:
                    print('Eggs did it!')

        If the failure is not a Spam or an Eggs, then the Failure will be
        'passed on' to the next errback. In Python 2 the Failure will be
        raised; in Python 3 the underlying exception will be re-raised.

        @type errorTypes: L{Exception}
        """
        error = self.check(*errorTypes)
        if not error:
            if _shouldEnableNewStyle:
                self.raiseException()
            else:
                raise self
        return error

    def check(self, *errorTypes):
        """Check if this failure's type is in a predetermined list.

        @type errorTypes: list of L{Exception} classes or
                          fully-qualified class names.
        @returns: the matching L{Exception} type, or None if no match.
        """
        for error in errorTypes:
            err = error
            if inspect.isclass(error) and issubclass(error, Exception):
                err = reflect.qual(error)
            if err in self.parents:
                return error
        return None

    # It would be nice to use twisted.python.compat.reraise, but that breaks
    # the stack exploration in _findFailure; possibly this can be fixed in
    # #5931.
    if getattr(BaseException, "with_traceback", None):
        # Python 3
        def raiseException(self):
            raise self.value.with_traceback(self.tb)
    else:
        exec("""def raiseException(self):
    raise self.type, self.value, self.tb""")

    raiseException.__doc__ = (
        """
        raise the original exception, preserving traceback
        information if available.
        """)

    def throwExceptionIntoGenerator(self, g):
        """
        Throw the original exception into the given generator,
        preserving traceback information if available.

        @return: The next value yielded from the generator.
        @raise StopIteration: If there are no more values in the generator.
        @raise anything else: Anything that the generator raises.
        """
        return g.throw(self.type, self.value, self.tb)

    def _findFailure(cls):
        """
        Find the failure that represents the exception currently in context.
        """
        tb = sys.exc_info()[-1]
        if not tb:
            return

        secondLastTb = None
        lastTb = tb
        while lastTb.tb_next:
            secondLastTb = lastTb
            lastTb = lastTb.tb_next

        lastFrame = lastTb.tb_frame

        # NOTE: f_locals.get('self') is used rather than
        # f_locals['self'] because psyco frames do not contain
        # anything in their locals() dicts.  psyco makes debugging
        # difficult anyhow, so losing the Failure objects (and thus
        # the tracebacks) here when it is used is not that big a deal.

        # handle raiseException-originated exceptions
        if lastFrame.f_code is cls.raiseException.__code__:
            return lastFrame.f_locals.get('self')

        # handle throwExceptionIntoGenerator-originated exceptions
        # this is tricky, and differs if the exception was caught
        # inside the generator, or above it:

        # it is only really originating from
        # throwExceptionIntoGenerator if the bottom of the traceback
        # is a yield.
        # Pyrex and Cython extensions create traceback frames
        # with no co_code, but they can't yield so we know it's okay to just return here.
        if ((not lastFrame.f_code.co_code) or
            lastFrame.f_code.co_code[lastTb.tb_lasti] != cls._yieldOpcode):
            return

        # if the exception was caught above the generator.throw
        # (outside the generator), it will appear in the tb (as the
        # second last item):
        if secondLastTb:
            frame = secondLastTb.tb_frame
            if frame.f_code is cls.throwExceptionIntoGenerator.__code__:
                return frame.f_locals.get('self')

        # if the exception was caught below the generator.throw
        # (inside the generator), it will appear in the frames' linked
        # list, above the top-level traceback item (which must be the
        # generator frame itself, thus its caller is
        # throwExceptionIntoGenerator).
        frame = tb.tb_frame.f_back
        if frame and frame.f_code is cls.throwExceptionIntoGenerator.__code__:
            return frame.f_locals.get('self')

    _findFailure = classmethod(_findFailure)

    def __repr__(self):
        return "<%s %s: %s>" % (reflect.qual(self.__class__),
                                reflect.qual(self.type),
                                self.getErrorMessage())

    def __str__(self):
        return "[Failure instance: %s]" % self.getBriefTraceback()

    def __getstate__(self):
        """Avoid pickling objects in the traceback.
        """
        if self.pickled:
            return self.__dict__
        c = self.__dict__.copy()

        c['frames'] = [
            [
                v[0], v[1], v[2],
                _safeReprVars(v[3]),
                _safeReprVars(v[4]),
            ] for v in self.frames
        ]

        # added 2003-06-23. See comment above in __init__
        c['tb'] = None

        if self.stack is not None:
            # XXX: This is a band-aid.  I can't figure out where these
            # (failure.stack is None) instances are coming from.
            c['stack'] = [
                [
                    v[0], v[1], v[2],
                    _safeReprVars(v[3]),
                    _safeReprVars(v[4]),
                ] for v in self.stack
            ]

        c['pickled'] = 1
        return c

    def cleanFailure(self):
        """
        Remove references to other objects, replacing them with strings.

        On Python 3, this will also set the C{__traceback__} attribute of the
        exception instance to L{None}.
        """
        self.__dict__ = self.__getstate__()
        if getattr(self.value, "__traceback__", None):
            # Python 3
            self.value.__traceback__ = None

    def getTracebackObject(self):
        """
        Get an object that represents this Failure's stack that can be passed
        to traceback.extract_tb.

        If the original traceback object is still present, return that. If this
        traceback object has been lost but we still have the information,
        return a fake traceback object (see L{_Traceback}). If there is no
        traceback information at all, return None.
        """
        if self.tb is not None:
            return self.tb
        elif len(self.frames) > 0:
            return _Traceback(self.frames)
        else:
            return None

    def getErrorMessage(self):
        """Get a string of the exception which caused this Failure."""
        if isinstance(self.value, Failure):
            return self.value.getErrorMessage()
        return reflect.safe_str(self.value)

    def getBriefTraceback(self):
        io = StringIO()
        self.printBriefTraceback(file=io)
        return io.getvalue()

    def getTraceback(self, elideFrameworkCode=0, detail='default'):
        io = StringIO()
        self.printTraceback(file=io, elideFrameworkCode=elideFrameworkCode, detail=detail)
        return io.getvalue()

    def printTraceback(self, file=None, elideFrameworkCode=False, detail='default'):
        """
        Emulate Python's standard error reporting mechanism.

        @param file: If specified, a file-like object to which to write the
            traceback.

        @param elideFrameworkCode: A flag indicating whether to attempt to
            remove uninteresting frames from within Twisted itself from the
            output.

        @param detail: A string indicating how much information to include
            in the traceback.  Must be one of C{'brief'}, C{'default'}, or
            C{'verbose'}.
        """
        if file is None:
            from twisted.python import log
            file = log.logerr
        w = file.write

        if detail == 'verbose' and not self.captureVars:
            # We don't have any locals or globals, so rather than show them as
            # empty make the output explicitly say that we don't have them at
            # all.
            formatDetail = 'verbose-vars-not-captured'
        else:
            formatDetail = detail

        # Preamble
        if detail == 'verbose':
            w( '*--- Failure #%d%s---\n' %
               (self.count,
                (self.pickled and ' (pickled) ') or ' '))
        elif detail == 'brief':
            if self.frames:
                hasFrames = 'Traceback'
            else:
                hasFrames = 'Traceback (failure with no frames)'
            w("%s: %s: %s\n" % (
                    hasFrames,
                    reflect.safe_str(self.type),
                    reflect.safe_str(self.value)))
        else:
            w( 'Traceback (most recent call last):\n')

        # Frames, formatted in appropriate style
        if self.frames:
            if not elideFrameworkCode:
                format_frames(self.stack[-traceupLength:], w, formatDetail)
                w("%s\n" % (EXCEPTION_CAUGHT_HERE,))
            format_frames(self.frames, w, formatDetail)
        elif not detail == 'brief':
            # Yeah, it's not really a traceback, despite looking like one...
            w("Failure: ")

        # postamble, if any
        if not detail == 'brief':
            w("%s: %s\n" % (reflect.qual(self.type),
                            reflect.safe_str(self.value)))

        # chaining
        if isinstance(self.value, Failure):
            # TODO: indentation for chained failures?
            file.write(" (chained Failure)\n")
            self.value.printTraceback(file, elideFrameworkCode, detail)
        if detail == 'verbose':
            w('*--- End of Failure #%d ---\n' % self.count)

    def printBriefTraceback(self, file=None, elideFrameworkCode=0):
        """Print a traceback as densely as possible.
        """
        self.printTraceback(file, elideFrameworkCode, detail='brief')

    def printDetailedTraceback(self, file=None, elideFrameworkCode=0):
        """Print a traceback with detailed locals and globals information.
        """
        self.printTraceback(file, elideFrameworkCode, detail='verbose')

def _safeReprVars(varsDictItems):
    """
    Convert a list of (name, object) pairs into (name, repr) pairs.

    L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
    exceptions will be raised by faulty C{__repr__} methods.

    @param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
        C{locals().items()}.
    @returns: a sequence of (name, repr) pairs.
    """
    return [(name, reflect.safe_repr(obj)) for (name, obj) in varsDictItems]

# slyphon: make post-morteming exceptions tweakable

DO_POST_MORTEM = True

def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
               captureVars=False,
               Failure__init__=Failure.__init__):
    """
    Initialize failure object, possibly spawning pdb.
    """
    if (exc_value, exc_type, exc_tb) == (None, None, None):
        exc = sys.exc_info()
        if not exc[0] == self.__class__ and DO_POST_MORTEM:
            try:
                strrepr = str(exc[1])
            except:
                strrepr = "broken str"
            print("Jumping into debugger for post-mortem of exception '%s':" % (strrepr,))
            import pdb
            pdb.post_mortem(exc[2])
    Failure__init__(self, exc_value, exc_type, exc_tb, captureVars)

def startDebugMode():
    """Enable debug hooks for Failures."""
    Failure.__init__ = _debuginit


text:
@interface SidebarViewController ()
{
    UIViewController  *_currentMainController;
    UITapGestureRecognizer *_tapGestureRecognizer;
    UIPanGestureRecognizer *_panGestureReconginzer;
    BOOL sideBarShowing;
    CGFloat currentTranslate;
}
@property (strong,nonatomic)LeftSideBarViewController *leftSideBarViewController;
@property (strong,nonatomic)RightSideBarViewController *rightSideBarViewController;
@end

@implementation SidebarViewController
@synthesize leftSideBarViewController,rightSideBarViewController,contentView,navBackView;

static SidebarViewController *rootViewCon;
const int ContentOffset=290;
const int ContentMinOffset=60;
const float MoveAnimationDuration = 0.3;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

+ (id)share
{
    return rootViewCon;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (rootViewCon) {
        rootViewCon = nil;
    }

	rootViewCon = self;

    sideBarShowing = NO;
    currentTranslate = 0;

    self.contentView.layer.shadowOffset = CGSizeMake(0, 0);
    self.contentView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.contentView.layer.shadowOpacity = 1;

    LeftSideBarViewController *_leftCon = [[LeftSideBarViewController alloc] initWithNibName:@"LeftSideBarViewController" bundle:nil];
    _leftCon.delegate = self;
    self.leftSideBarViewController = _leftCon;

    RightSideBarViewController *_rightCon = [[RightSideBarViewController alloc] initWithNibName:@"RightSideBarViewController" bundle:nil];
    self.rightSideBarViewController = _rightCon;

    [self addChildViewController:self.leftSideBarViewController];
    [self addChildViewController:self.rightSideBarViewController];
    self.leftSideBarViewController.view.frame = self.navBackView.bounds;
    self.rightSideBarViewController.view.frame = self.navBackView.bounds;
    [self.navBackView addSubview:self.leftSideBarViewController.view];
    [self.navBackView addSubview:self.rightSideBarViewController.view];

    _panGestureReconginzer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panInContentView:)];
    [self.contentView addGestureRecognizer:_panGestureReconginzer];
}

- (void)contentViewAddTapGestures
{
    if (_tapGestureRecognizer) {
        [self.contentView   removeGestureRecognizer:_tapGestureRecognizer];
        _tapGestureRecognizer = nil;
    }

    _tapGestureRecognizer = [[UITapGestureRecognizer  alloc] initWithTarget:self action:@selector(tapOnContentView:)];
    [self.contentView addGestureRecognizer:_tapGestureRecognizer];
}

- (void)tapOnContentView:(UITapGestureRecognizer *)tapGestureRecognizer
{
    [self moveAnimationWithDirection:SideBarShowDirectionNone duration:MoveAnimationDuration];
}

- (void)panInContentView:(UIPanGestureRecognizer *)panGestureReconginzer
{

	if (panGestureReconginzer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat translation = [panGestureReconginzer translationInView:self.contentView].x;
        self.contentView.transform = CGAffineTransformMakeTranslation(translation+currentTranslate, 0);
        UIView *view ;
        if (translation+currentTranslate>0)
        {
            view = self.leftSideBarViewController.view;
        }else
        {
            view = self.rightSideBarViewController.view;
        }
        [self.navBackView bringSubviewToFront:view];

	} else if (panGestureReconginzer.state == UIGestureRecognizerStateEnded)
    {
		currentTranslate = self.contentView.transform.tx;
        if (!sideBarShowing) {
            if (fabs(currentTranslate)<ContentMinOffset) {
                [self moveAnimationWithDirection:SideBarShowDirectionNone duration:MoveAnimationDuration];
            }else if(currentTranslate>ContentMinOffset)
            {
                [self moveAnimationWithDirection:SideBarShowDirectionLeft duration:MoveAnimationDuration];
            }else
            {
                [self moveAnimationWithDirection:SideBarShowDirectionRight duration:MoveAnimationDuration];
            }
        }else
        {
            if (fabs(currentTranslate)<ContentOffset-ContentMinOffset) {
                [self moveAnimationWithDirection:SideBarShowDirectionNone duration:MoveAnimationDuration];

            }else if(currentTranslate>ContentOffset-ContentMinOffset)
            {

                [self moveAnimationWithDirection:SideBarShowDirectionLeft duration:MoveAnimationDuration];

            }else
            {
                [self moveAnimationWithDirection:SideBarShowDirectionRight duration:MoveAnimationDuration];
            }
        }

	}

}

#pragma mark - nav con delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{

}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([navigationController.viewControllers count]>1) {
        [self removepanGestureReconginzerWhileNavConPushed:YES];
    }else
    {
        [self removepanGestureReconginzerWhileNavConPushed:NO];
    }

}

- (void)removepanGestureReconginzerWhileNavConPushed:(BOOL)push
{
    if (push) {
        if (_panGestureReconginzer) {
            [self.contentView removeGestureRecognizer:_panGestureReconginzer];
            _panGestureReconginzer = nil;
        }
    }else
    {
        if (!_panGestureReconginzer) {
            _panGestureReconginzer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panInContentView:)];
            [self.contentView addGestureRecognizer:_panGestureReconginzer];
        }
    }
}
#pragma mark - side bar select delegate

- (void)leftSideBarSelectWithController:(UIViewController *)controller
{
    if ([controller isKindOfClass:[UINavigationController class]]) {
        [(UINavigationController *)controller setDelegate:self];
    }
    if (_currentMainController == nil) {
		controller.view.frame = self.contentView.bounds;
		_currentMainController = controller;
		[self addChildViewController:_currentMainController];
		[self.contentView addSubview:_currentMainController.view];
		[_currentMainController didMoveToParentViewController:self]; //通知父视图完成添加
	} else if (_currentMainController != controller && controller !=nil) {
		controller.view.frame = self.contentView.bounds;
		[_currentMainController willMoveToParentViewController:nil];
		[self addChildViewController:controller];
		self.view.userInteractionEnabled = NO;
		[self transitionFromViewController:_currentMainController
						  toViewController:controller
								  duration:0
								   options:UIViewAnimationOptionTransitionNone
								animations:^{}
								completion:^(BOOL finished){
									self.view.userInteractionEnabled = YES;
									[_currentMainController removeFromParentViewController];
									[controller didMoveToParentViewController:self];
									_currentMainController = controller;
								}
         ];
	}

    [self showSideBarControllerWithDirection:SideBarShowDirectionNone];
}

- (void)rightSideBarSelectWithController:(UIViewController *)controller
{

}

- (void)showSideBarControllerWithDirection:(SideBarShowDirection)direction
{

    if (direction!=SideBarShowDirectionNone) {
        UIView *view ;
        if (direction == SideBarShowDirectionLeft)
        {
            view = self.leftSideBarViewController.view;
        }else
        {
            view = self.rightSideBarViewController.view;
        }
        [self.navBackView bringSubviewToFront:view];
    }
    [self moveAnimationWithDirection:direction duration:MoveAnimationDuration];
}

#pragma animation

- (void)moveAnimationWithDirection:(SideBarShowDirection)direction duration:(float)duration
{
    void (^animations)(void) = ^{
		switch (direction) {
            case SideBarShowDirectionNone:
            {
                self.contentView.transform  = CGAffineTransformMakeTranslation(0, 0);
            }
                break;
            case SideBarShowDirectionLeft:
            {
                self.contentView.transform  = CGAffineTransformMakeTranslation(ContentOffset, 0);
            }
                break;
            case SideBarShowDirectionRight:
            {
                self.contentView.transform  = CGAffineTransformMakeTranslation(-ContentOffset, 0);
            }
                break;
            default:
                break;
        }
	};

    void (^complete)(BOOL) = ^(BOOL finished) {
        self.contentView.userInteractionEnabled = YES;
        self.navBackView.userInteractionEnabled = YES;

        if (direction == SideBarShowDirectionNone) {

            if (_tapGestureRecognizer) {
                [self.contentView removeGestureRecognizer:_tapGestureRecognizer];
                _tapGestureRecognizer = nil;
            }
            sideBarShowing = NO;

        }else
        {
            [self contentViewAddTapGestures];
             sideBarShowing = YES;
        }
        currentTranslate = self.contentView.transform.tx;
	};
    self.contentView.userInteractionEnabled = NO;
    self.navBackView.userInteractionEnabled = NO;
    [UIView animateWithDuration:duration animations:animations completion:complete];
}

@end

redpajama_set_name: RedPajamaGithub


text:
ALTER TABLE unmapped_object
  DROP INDEX unique_unmapped_obj_idx,
  ADD UNIQUE INDEX unique_unmapped_obj_idx
    (ensembl_id, ensembl_object_type, identifier, unmapped_reason_id,
    parent, external_db_id);

# Patch identifier:
INSERT INTO meta (species_id, meta_key, meta_value)
  VALUES (NULL, 'patch', 'patch_65_66_c.sql|reorder_unmapped_obj_index');


text:
package gif

import (
	"bufio"
	"compress/lzw"
	"errors"
	"fmt"
	"image"
	"image/color"
	"io"
)

var (
	errNotEnough = errors.New("gif: not enough image data")
	errTooMuch   = errors.New("gif: too much image data")
	errBadPixel  = errors.New("gif: invalid pixel value")
)

// If the io.Reader does not also have ReadByte, then decode will introduce its own buffering.
type reader interface {
	io.Reader
	io.ByteReader
}

// Masks etc.
const (
	// Fields.
	fColorTable         = 1 << 7
	fInterlace          = 1 << 6
	fColorTableBitsMask = 7

	// Graphic control flags.
	gcTransparentColorSet = 1 << 0
	gcDisposalMethodMask  = 7 << 2
)

// Disposal Methods.
const (
	DisposalNone       = 0x01
	DisposalBackground = 0x02
	DisposalPrevious   = 0x03
)

// Section indicators.
const (
	sExtension       = 0x21
	sImageDescriptor = 0x2C
	sTrailer         = 0x3B
)

// Extensions.
const (
	eText           = 0x01 // Plain Text
	eGraphicControl = 0xF9 // Graphic Control
	eComment        = 0xFE // Comment
	eApplication    = 0xFF // Application
)

// decoder is the type used to decode a GIF file.
type decoder struct {
	r reader

	// From header.
	vers            string
	width           int
	height          int
	loopCount       int
	delayTime       int
	backgroundIndex byte
	disposalMethod  byte

	// From image descriptor.
	imageFields byte

	// From graphics control.
	transparentIndex    byte
	hasTransparentIndex bool

	// Computed.
	globalColorTable color.Palette

	// Used when decoding.
	delay    []int
	disposal []byte
	image    []*image.Paletted
	tmp      [1024]byte // must be at least 768 so we can read color table
}

// blockReader parses the block structure of GIF image data, which
// comprises (n, (n bytes)) blocks, with 1 <= n <= 255.  It is the
// reader given to the LZW decoder, which is thus immune to the
// blocking.  After the LZW decoder completes, there will be a 0-byte
// block remaining (0, ()), which is consumed when checking that the
// blockReader is exhausted.
type blockReader struct {
	r     reader
	slice []byte
	err   error
	tmp   [256]byte
}

func (b *blockReader) Read(p []byte) (int, error) {
	if b.err != nil {
		return 0, b.err
	}
	if len(p) == 0 {
		return 0, nil
	}
	if len(b.slice) == 0 {
		var blockLen uint8
		blockLen, b.err = b.r.ReadByte()
		if b.err != nil {
			return 0, b.err
		}
		if blockLen == 0 {
			b.err = io.EOF
			return 0, b.err
		}
		b.slice = b.tmp[:blockLen]
		if _, b.err = io.ReadFull(b.r, b.slice); b.err != nil {
			return 0, b.err
		}
	}
	n := copy(p, b.slice)
	b.slice = b.slice[n:]
	return n, nil
}

// decode reads a GIF image from r and stores the result in d.
func (d *decoder) decode(r io.Reader, configOnly bool) error {
	// Add buffering if r does not provide ReadByte.
	if rr, ok := r.(reader); ok {
		d.r = rr
	} else {
		d.r = bufio.NewReader(r)
	}

	err := d.readHeaderAndScreenDescriptor()
	if err != nil {
		return err
	}
	if configOnly {
		return nil
	}

	for {
		c, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		switch c {
		case sExtension:
			if err = d.readExtension(); err != nil {
				return err
			}

		case sImageDescriptor:
			m, err := d.newImageFromDescriptor()
			if err != nil {
				return err
			}
			useLocalColorTable := d.imageFields&fColorTable != 0
			if useLocalColorTable {
				m.Palette, err = d.readColorTable(d.imageFields)
				if err != nil {
					return err
				}
			} else {
				if d.globalColorTable == nil {
					return errors.New("gif: no color table")
				}
				m.Palette = d.globalColorTable
			}
			if d.hasTransparentIndex && int(d.transparentIndex) < len(m.Palette) {
				if !useLocalColorTable {
					// Clone the global color table.
					m.Palette = append(color.Palette(nil), d.globalColorTable...)
				}
				m.Palette[d.transparentIndex] = color.RGBA{}
			}
			litWidth, err := d.r.ReadByte()
			if err != nil {
				return err
			}
			if litWidth < 2 || litWidth > 8 {
				return fmt.Errorf("gif: pixel size in decode out of range: %d", litWidth)
			}
			// A wonderfully Go-like piece of magic.
			br := &blockReader{r: d.r}
			lzwr := lzw.NewReader(br, lzw.LSB, int(litWidth))
			defer lzwr.Close()
			if _, err = io.ReadFull(lzwr, m.Pix); err != nil {
				if err != io.ErrUnexpectedEOF {
					return err
				}
				return errNotEnough
			}
			// Both lzwr and br should be exhausted. Reading from them
			// should yield (0, io.EOF).
			if n, err := lzwr.Read(d.tmp[:1]); n != 0 || err != io.EOF {
				if err != nil {
					return err
				}
				return errTooMuch
			}
			if n, err := br.Read(d.tmp[:1]); n != 0 || err != io.EOF {
				if err != nil {
					return err
				}
				return errTooMuch
			}

			// Check that the color indexes are inside the palette.
			if len(m.Palette) < 256 {
				for _, pixel := range m.Pix {
					if int(pixel) >= len(m.Palette) {
						return errBadPixel
					}
				}
			}

			// Undo the interlacing if necessary.
			if d.imageFields&fInterlace != 0 {
				uninterlace(m)
			}

			d.image = append(d.image, m)
			d.delay = append(d.delay, d.delayTime)
			d.disposal = append(d.disposal, d.disposalMethod)
			// The GIF89a spec, Section 23 (Graphic Control Extension) says:
			// "The scope of this extension is the first graphic rendering block
			// to follow." We therefore reset the GCE fields to zero.
			d.delayTime = 0
			d.hasTransparentIndex = false

		case sTrailer:
			if len(d.image) == 0 {
				return io.ErrUnexpectedEOF
			}
			return nil

		default:
			return fmt.Errorf("gif: unknown block type: 0x%.2x", c)
		}
	}
}

func (d *decoder) readHeaderAndScreenDescriptor() error {
	_, err := io.ReadFull(d.r, d.tmp[:13])
	if err != nil {
		return err
	}
	d.vers = string(d.tmp[:6])
	if d.vers != "GIF87a" && d.vers != "GIF89a" {
		return fmt.Errorf("gif: can't recognize format %s", d.vers)
	}
	d.width = int(d.tmp[6]) + int(d.tmp[7])<<8
	d.height = int(d.tmp[8]) + int(d.tmp[9])<<8
	if fields := d.tmp[10]; fields&fColorTable != 0 {
		d.backgroundIndex = d.tmp[11]
		// readColorTable overwrites the contents of d.tmp, but that's OK.
		if d.globalColorTable, err = d.readColorTable(fields); err != nil {
			return err
		}
	}
	// d.tmp[12] is the Pixel Aspect Ratio, which is ignored.
	d.loopCount = -1
	return nil
}

func (d *decoder) readColorTable(fields byte) (color.Palette, error) {
	n := 1 << (1 + uint(fields&fColorTableBitsMask))
	_, err := io.ReadFull(d.r, d.tmp[:3*n])
	if err != nil {
		return nil, fmt.Errorf("gif: short read on color table: %s", err)
	}
	j, p := 0, make(color.Palette, n)
	for i := range p {
		p[i] = color.RGBA{d.tmp[j+0], d.tmp[j+1], d.tmp[j+2], 0xFF}
		j += 3
	}
	return p, nil
}

func (d *decoder) readExtension() error {
	extension, err := d.r.ReadByte()
	if err != nil {
		return err
	}
	size := 0
	switch extension {
	case eText:
		size = 13
	case eGraphicControl:
		return d.readGraphicControl()
	case eComment:
		// nothing to do but read the data.
	case eApplication:
		b, err := d.r.ReadByte()
		if err != nil {
			return err
		}
		// The spec requires size be 11, but Adobe sometimes uses 10.
		size = int(b)
	default:
		return fmt.Errorf("gif: unknown extension 0x%.2x", extension)
	}
	if size > 0 {
		if _, err := io.ReadFull(d.r, d.tmp[:size]); err != nil {
			return err
		}
	}

	// Application Extension with "NETSCAPE2.0" as string and 1 in data means
	// this extension defines a loop count.
	if extension == eApplication && string(d.tmp[:size]) == "NETSCAPE2.0" {
		n, err := d.readBlock()
		if n == 0 || err != nil {
			return err
		}
		if n == 3 && d.tmp[0] == 1 {
			d.loopCount = int(d.tmp[1]) | int(d.tmp[2])<<8
		}
	}
	for {
		n, err := d.readBlock()
		if n == 0 || err != nil {
			return err
		}
	}
}

func (d *decoder) readGraphicControl() error {
	if _, err := io.ReadFull(d.r, d.tmp[:6]); err != nil {
		return fmt.Errorf("gif: can't read graphic control: %s", err)
	}
	flags := d.tmp[1]
	d.disposalMethod = (flags & gcDisposalMethodMask) >> 2
	d.delayTime = int(d.tmp[2]) | int(d.tmp[3])<<8
	if flags&gcTransparentColorSet != 0 {
		d.transparentIndex = d.tmp[4]
		d.hasTransparentIndex = true
	}
	return nil
}

func (d *decoder) newImageFromDescriptor() (*image.Paletted, error) {
	if _, err := io.ReadFull(d.r, d.tmp[:9]); err != nil {
		return nil, fmt.Errorf("gif: can't read image descriptor: %s", err)
	}
	left := int(d.tmp[0]) + int(d.tmp[1])<<8
	top := int(d.tmp[2]) + int(d.tmp[3])<<8
	width := int(d.tmp[4]) + int(d.tmp[5])<<8
	height := int(d.tmp[6]) + int(d.tmp[7])<<8
	d.imageFields = d.tmp[8]

	// The GIF89a spec, Section 20 (Image Descriptor) says:
	// "Each image must fit within the boundaries of the Logical
	// Screen, as defined in the Logical Screen Descriptor."
	bounds := image.Rect(left, top, left+width, top+height)
	if bounds != bounds.Intersect(image.Rect(0, 0, d.width, d.height)) {
		return nil, errors.New("gif: frame bounds larger than image bounds")
	}
	return image.NewPaletted(bounds, nil), nil
}

func (d *decoder) readBlock() (int, error) {
	n, err := d.r.ReadByte()
	if n == 0 || err != nil {
		return 0, err
	}
	return io.ReadFull(d.r, d.tmp[:n])
}

// interlaceScan defines the ordering for a pass of the interlace algorithm.
type interlaceScan struct {
	skip, start int
}

// interlacing represents the set of scans in an interlaced GIF image.
var interlacing = []interlaceScan{
	{8, 0}, // Group 1 : Every 8th. row, starting with row 0.
	{8, 4}, // Group 2 : Every 8th. row, starting with row 4.
	{4, 2}, // Group 3 : Every 4th. row, starting with row 2.
	{2, 1}, // Group 4 : Every 2nd. row, starting with row 1.
}

// uninterlace rearranges the pixels in m to account for interlaced input.
func uninterlace(m *image.Paletted) {
	var nPix []uint8
	dx := m.Bounds().Dx()
	dy := m.Bounds().Dy()
	nPix = make([]uint8, dx*dy)
	offset := 0 // steps through the input by sequential scan lines.
	for _, pass := range interlacing {
		nOffset := pass.start * dx // steps through the output as defined by pass.
		for y := pass.start; y < dy; y += pass.skip {
			copy(nPix[nOffset:nOffset+dx], m.Pix[offset:offset+dx])
			offset += dx
			nOffset += dx * pass.skip
		}
	}
	m.Pix = nPix
}

// Decode reads a GIF image from r and returns the first embedded
// image as an image.Image.
func Decode(r io.Reader) (image.Image, error) {
	var d decoder
	if err := d.decode(r, false); err != nil {
		return nil, err
	}
	return d.image[0], nil
}

// GIF represents the possibly multiple images stored in a GIF file.
type GIF struct {
	Image     []*image.Paletted // The successive images.
	Delay     []int             // The successive delay times, one per frame, in 100ths of a second.
	LoopCount int               // The loop count.
	// Disposal is the successive disposal methods, one per frame. For
	// backwards compatibility, a nil Disposal is valid to pass to EncodeAll,
	// and implies that each frame's disposal method is 0 (no disposal
	// specified).
	Disposal []byte
	// Config is the global color table (palette), width and height. A nil or
	// empty-color.Palette Config.ColorModel means that each frame has its own
	// color table and there is no global color table. Each frame's bounds must
	// be within the rectangle defined by the two points (0, 0) and
	// (Config.Width, Config.Height).
	//
	// For backwards compatibility, a zero-valued Config is valid to pass to
	// EncodeAll, and implies that the overall GIF's width and height equals
	// the first frame's bounds' Rectangle.Max point.
	Config image.Config
	// BackgroundIndex is the background index in the global color table, for
	// use with the DisposalBackground disposal method.
	BackgroundIndex byte
}

// DecodeAll reads a GIF image from r and returns the sequential frames
// and timing information.
func DecodeAll(r io.Reader) (*GIF, error) {
	var d decoder
	if err := d.decode(r, false); err != nil {
		return nil, err
	}
	gif := &GIF{
		Image:     d.image,
		LoopCount: d.loopCount,
		Delay:     d.delay,
		Disposal:  d.disposal,
		Config: image.Config{
			ColorModel: d.globalColorTable,
			Width:      d.width,
			Height:     d.height,
		},
		BackgroundIndex: d.backgroundIndex,
	}
	return gif, nil
}

// DecodeConfig returns the global color model and dimensions of a GIF image
// without decoding the entire image.
func DecodeConfig(r io.Reader) (image.Config, error) {
	var d decoder
	if err := d.decode(r, true); err != nil {
		return image.Config{}, err
	}
	return image.Config{
		ColorModel: d.globalColorTable,
		Width:      d.width,
		Height:     d.height,
	}, nil
}

func init() {
	image.RegisterFormat("gif", "GIF8?a", Decode, DecodeConfig)
}


text:
package py.com.sodep.notificationserver.facade;

import com.fasterxml.jackson.core.JsonProcessingException;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.ws.rs.core.Response.Status;
import py.com.sodep.notificationserver.db.dao.DeviceRegistrationDao;
import py.com.sodep.notificationserver.db.dao.EventoDao;
import py.com.sodep.notificationserver.db.dao.ParametroDao;
import py.com.sodep.notificationserver.db.entities.AndroidNotification;
import py.com.sodep.notificationserver.db.entities.AndroidResponse;
import py.com.sodep.notificationserver.exceptions.handlers.BusinessException;
import py.com.sodep.notificationserver.config.GlobalCodes;

/**
 * Se comunica con el servidor GCM para enviar la notificación correspondiente
 *
 * @author Gabriela Gaona <gabriela.gaona@konecta.com.py>
 *
 */
/**
 * Se comunica con el servidor GCM para enviar la notificación correspondiente
 *
 * @author Gabriela Gaona <gabriela.gaona@konecta.com.py>
 *
 */
public class GcmFacade {

    private static final Logger LOGGER = Logger.getLogger(GcmFacade.class);

    @Inject
    ObjectMapper map;

    @Inject
    EventoDao eventoDao;

    @Inject
    DeviceRegistrationDao deviceDao;

    @Inject
    ParametroDao parametroDao;

    public AndroidResponse send(String apiKey, AndroidNotification notification) throws BusinessException {
        try {
            LOGGER.info("API KEY: " + apiKey);
            Client client = ClientBuilder.newBuilder().build();
            WebTarget target = client.target(parametroDao.getByName("URL_GCM").getValor());
            Invocation.Builder builder = target.request().accept(MediaType.APPLICATION_JSON);
            builder.header(HttpHeaders.AUTHORIZATION, "key=" + apiKey);
            AndroidResponse r;
            String jsonInString = map.writeValueAsString(notification);
            LOGGER.info("Json a enviar: " + jsonInString);
            Response response = builder.post(Entity.entity(jsonInString, MediaType.APPLICATION_JSON));
            if (response.getStatus() != 200) {
                LOGGER.info("Error en la respuesta : HTTP error code :" + response.getStatus());
                LOGGER.info(response.getStringHeaders().toString());
                LOGGER.info(response.toString());
                throw new BusinessException((Status) response.getStatusInfo(), "Error en la respuesta : HTTP error code : "
                        + response.getStatus());
            }
            r = response.readEntity(AndroidResponse.class);
            LOGGER.info("[Android/Response]: " + r);
            return r;
        } catch (JsonProcessingException ex) {
            throw new BusinessException(GlobalCodes.errors.NOTIFICATION_ERROR, ex);
        }
    }
}


text:
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('underscore');
// Constructor
var Expire = function(ttl) {
	EventEmitter.call(this);
 	this.ttl = ttl;
  	this.dataSingle = new Array();
  	this.dataGroup = new Array();
  	this.loadingTimer = null;
}
//Herencia para eventos
util.inherits(Expire, EventEmitter);
// class methods
//bollean function Expired or not
var isExpire = function(dateExpired,now){
	if( dateExpired < now ){
		return true;
	}else{
		return false;
	}
}
Expire.prototype.set = function(key, value, timeExpired){
	var obj = {
		timeExpired: timeExpired,
		timeOrigin: new Date().getTime(),
		key: key,
		value: value
	}
	this.dataSingle[key] = obj;
	this.ttlInterval();
};
Expire.prototype.setByGroup = function(group, key, value, timeExpired){
	var obj = {
		timeExpired: timeExpired,
		timeOrigin: new Date().getTime(),
		key: key,
		value: value
	}
	if(!this.dataGroup.hasOwnProperty(group)){
		this.dataGroup[group] = [obj];
	}else{
		this.dataGroup[group].push(obj);
	}
	this.ttlInterval();
};
Expire.prototype.ttlInterval = function() {
	this.loadingTimer = setInterval(function(){this.checkPeriod()}.bind(this), this.ttl);
};
Expire.prototype.checkPeriod = function(){
	if(Object.keys(this.dataSingle).length === 0 && Object.keys(this.dataGroup).length === 0){
		clearInterval(this.loadingTimer);
		return;
	}
	var now = new Date().getTime();
	for(var i in this.dataSingle){
		var t = this.dataSingle[i];
		if( isExpire( (t.timeOrigin + t.timeExpired), now ) ){
			this.emit('expired', this.dataSingle[i].key);
			this.dataSingle = _.without(this.dataSingle, this.dataSingle[i].key);
		}
	}

	for(var j in this.dataGroup){
		for(var k in this.dataGroup[j]){
			var group = j;
			var obj_group = this.dataGroup[j][k];
			if( isExpire( (obj_group.timeOrigin + obj_group.timeExpired), now ) ){
				var data_expired = {
					group: group,
					key: obj_group.key,
					value: obj_group.value
				};
				this.emit('inGroupExpired', data_expired);
				this.dataGroup[group] = _.without(this.dataGroup[group], _.findWhere(this.dataGroup[group], {key: data_expired.key}));
				if(this.dataGroup[group].length === 0){
					this.dataGroup = _.without(this.dataGroup,group);
				}
				break;
			}
		}
	}

};
Expire.prototype.delForGroup = function(group, key, cback){
	this.dataGroup[group] = _.without(this.dataGroup[group], _.findWhere(this.dataGroup[group], {key: key}));
	if(this.dataGroup[group].length === 0){
		this.dataGroup = _.without(this.dataGroup,group);
	}
	return cback(null, (this.dataGroup[group])?this.dataGroup[group]:null);
};
Expire.prototype.del = function(key, cback){
	this.dataSingle = _.without(this.dataSingle, key);
	return cback(null, (this.dataSingle)?this.dataSingle:null);
};
Expire.prototype.getData = function(){
	if(this.dataSingle){
		return this.dataSingle;
	}else{
		return null;
	}
};
Expire.prototype.getForGroupValues = function(group){
	var aux = new Array();
	if(this.dataGroup[group]){
		_.each(this.dataGroup[group],function(num){
			aux.push(num.value);
		});
		return aux;
	}else{
		return null;
	}
}
Expire.prototype.getForGroup = function(group){
	if(this.dataGroup[group]){
		return this.dataGroup[group];
	}else{
		return null;
	}
};
// export the class
module.exports = Expire;


text:
@interface MKT_TPDWeakProxy ()

@property (nonatomic, weak) id theObject;

@end

@implementation MKT_TPDWeakProxy

- (instancetype)initWithObject:(id)object {
    // No init method in superclass
    self.theObject = object;
    return self;
}

// First, try to use the fast forwarding path. If theObject is nil
// the Objective C runtime will fall back to the older, slow path. This
// speeds up message forwarding performance a lot from tests; it's nearly
// as fast as directly messaging the object. If we return nil (ie, theObject
// has become dereferenced or was nil to begin with), the Objective C runtime
// falls back to the slow forwarding path.
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return self.theObject;
}

// First step of the slow forwarding path is to figure out the method signature.
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature *methodSignature;
    // Keep a strong reference so we can safely send messages
    id object = self.theObject;
    if (object) {
        methodSignature = [object methodSignatureForSelector:aSelector];
    } else {
        // If obj is nil, we need to synthesize a NSMethodSignature. Smallest signature
        // is (self, _cmd) according to the documention for NSMethodSignature.
        NSString *types = [NSString stringWithFormat:@"%s%s", @encode(id), @encode(SEL)];
        methodSignature = [NSMethodSignature signatureWithObjCTypes:[types UTF8String]];
    }
    return methodSignature;
}

// The runtime uses the method signature from above to create an NSInvocation and asks us to
// forward it along as we see fit.
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    [anInvocation invokeWithTarget:self.theObject];
}

@end


text:
package com.skubit.satoshidice.services.rest;

public class PathParameter {

	public static final String USER_ADDRESS = "useraddress";

	public static final String USER_BALANCE = "useraddress";

}


text:
jpegtran 1.3 (part of [libjpeg-turbo](http://libjpeg-turbo.virtualgl.org/)) Node.js wrapper that makes it seamlessly available as a local dependency on OS X, Linux, FreeBSD, Solaris and Windows. Most commonly used to losslessly minify JPEG images.

> libjpeg-turbo is a derivative of libjpeg that uses SIMD instructions (MMX, SSE2, NEON) to accelerate baseline JPEG compression and decompression on x86, x86-64, and ARM systems. On such systems, libjpeg-turbo is generally 2-4x as fast as the unmodified version of libjpeg, all else being equal.

## Install

- Install with [npm](https://npmjs.org/package/jpegtran-bin): `npm install --save jpegtran-bin`

## Example usage

```js
var execFile = require('child_process').execFile;
var jpegtranPath = require('jpegtran-bin').path;

execFile(jpegtranPath, ['-outfile', 'output.jpg', 'input.jpg'], function() {
    console.log('Image minified');
});
```

Can also be run directly from `./node_modules/.bin/jpegtran`.

## Dev

Note to self on how to update the binaries.

### OS X and Linux

- Run `npm install` to build the binary.

The `nasm` (Netwide Assember) package is required to build the binary on Ubuntu.

### Windows

- Download the [Windows files 32/64-bit](http://sourceforge.net/projects/libjpeg-turbo/files/) (GCC compiled) on a Windows machine

  (current version 1.3.0, x64 `libjpeg-turbo-1.3.0-gcc64.exe` and for x86 `libjpeg-turbo-1.3.0-gcc.exe`)
- Run the downloaded file to extract
- In the extracted folder go to the `bin` folder and copy `jpegtran.exe` and `libjpeg-62.dll` to `jpegtran-bin\vendor\` folder

  (for `grunt-contrib-imagemin` the folder is `grunt-contrib-imagemin\node_modules\jpegtran-bin\vendor\`)

## License

Everything excluding the binaries licensed under the [BSD license](http://opensource.org/licenses/bsd-license.php) and copyright Google.

libjpeg-turbo licensed under the BSD license and copyright dcommander.


text:
=======================
Django Mass Post Office
=======================

Django Post Office is a simple app to create emailing lists of users and sending
emails to them from admin. It depends on django-post-office (without "mass") so
please read it's documentation on how to send scheduled emails

Dependencies
============

* `django-post-office == 0.6.0 <https://github.com/ui/django-post_office>`_

Installation
============

* Package is available on PyPI, so install with pip or easy_install:

  .. code-block:: bash

	pip install django-mass-post-office

* Add ``post_office`` and ``mass_post_office to your INSTALLED_APPS in django's ``settings.py``:

  .. code-block:: python

    INSTALLED_APPS = (
        # other apps
        "post_office",
        "mass_post_office",
    )

* Run ``syncdb``::

    python manage.py syncdb

* Set ``post_office.EmailBackend`` as your ``EMAIL_BACKEND`` in django's ``settings.py``::

    EMAIL_BACKEND = 'post_office.EmailBackend'


text:
require 'bel'
require 'erb'
require 'pathname'
require 'sequel'

module BEL::Resource::Search::Plugins
  module Sqlite

    class Sqlite3FTS
      include BEL::Resource::Search
      include BEL::Resource::Search::API

      QUERY_TEMPLATE = ERB.new(
        File.read(Pathname(File.dirname(__FILE__)) + 'sqlite3_template.erb'),
        nil,
        '>'
      )
      PREPARED_STATEMENTS = {}

      def initialize(db)
        @db = db
      end

      # @see BEL::Resource::Search::API#search
      def search(query_expression, concept_type = nil, scheme_uri = nil, species = nil, options = {})
        # required SQL parameters
        size  = options.delete(:size) || -1
        if size.to_i.zero?
          fail ArgumentError.new(":size is zero")
        end

        # optional SQL parameters
        params = {
          :match                      => query_expression.encode('UTF-8'),
          :start                      => (options.delete(:start) || 0).to_i,
          :size                       => size,
          :concept_type               => (concept_type ? concept_type.to_s.encode('UTF-8') : nil),
          :scheme_uri                 => (scheme_uri ? scheme_uri.to_s.encode('UTF-8') : nil),
          :species                    => (species ? species.to_s.encode('UTF-8') : nil),
          :exclude_identifier_schemes => options.delete(:exclude_identifier_schemes),
          :exact_match                => options.delete(:exact_match)
        }

        query   = QUERY_TEMPLATE.result(binding)
        enum    = @db.fetch(query, params)

        if enum.respond_to? :lazy
          enum = enum.lazy
        end

        enum.map { |row|
          row_hash = row.to_hash
          row_hash[:alt_labels] = (row_hash[:alt_labels] || '').split('|')
          SearchResult.new(row_hash)
        }
      end
    end
  end
end


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>Spark NLP 4.2.2 ScalaDoc  - com.johnsnowlabs.util.LibrarySettings</title>
          <meta name="description" content="Spark NLP 4.2.2 ScalaDoc - com.johnsnowlabs.util.LibrarySettings" />
          <meta name="keywords" content="Spark NLP 4.2.2 ScalaDoc com.johnsnowlabs.util.LibrarySettings" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        Spark NLP 4.2.2 ScalaDoc
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        com

Definition Classes

root

        

        package

        johnsnowlabs

Definition Classes

com

        

        package

        util

Definition Classes

johnsnowlabs

        

        package

        distances

Definition Classes

util

        

        package

        external

Definition Classes

util

        

        package

        wmd4j

Definition Classes

util

                        Compatibility

                        HadoopOperations

                        HashUtil

                        InternalS3ResourceDownloader

                        JSLBuild

                        LibrarySettings

                        ModelTracer

                        ResourceMetadataFolder

                        UpdateModels

                        WithStart

                        start

o

com.johnsnowlabs.util

LibrarySettings

        

        object

        LibrarySettings

            Linear Supertypes

AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

LibrarySettings

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        def

        getAllConfigs(): (String, String)

        

        def

        getAllConfigsAsString(): String

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        def

        printAllConfigs(): Unit

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
require 'bundler'
Bundler.setup
require 'sinatra'
require 'json'
require 'byebug'

rails_validations_path = Bundler.load.specs.find { |s| s.name == 'client_side_validations' }
raise 'Client Side Validations bundle not found' if rails_validations_path.nil?

class AssetPath < Rack::Static
  def call(env)
    path = env['PATH_INFO']

    if can_serve(path)
      env['PATH_INFO'] = (path == '/' ? @index : @urls[path]) if overwrite_file_path(path)
      response = @file_server.call(env)
      if response.first == 404
        @app.call(env)
      else
        response
      end
    else
      @app.call(env)
    end
  end
end

use AssetPath, urls: ['/vendor/assets/javascripts'], root: File.expand_path('../..', settings.root)
use AssetPath, urls: ['/vendor/assets/javascripts'], root: File.expand_path('../', $LOAD_PATH.find { |p| p.include?('jquery-rails') })
use AssetPath, urls: ['/vendor/assets/javascripts'], root: rails_validations_path.full_gem_path

DEFAULT_JQUERY_VERSION = '3.6.1'
QUNIT_VERSION          = '2.19.1'

helpers do
  def jquery_version
    params[:jquery] || DEFAULT_JQUERY_VERSION
  end

  def qunit_version
    QUNIT_VERSION
  end

  def script_tag(src)
    src = "/test/#{src}.js" unless src.index('/')
    %(<script src='#{src}' type='text/javascript'></script>)
  end

  def test(*types)
    types.map do |type|
      Dir.glob(File.expand_path("public/test/#{type}/*.js", settings.root)).map { |file| File.basename(file) }.map do |file|
        script_tag "/test/#{type}/#{file}"
      end.join("\n")
    end.join("\n")
  end
end

get '/' do
  erb :index
end

get '/favicon.ico' do
  halt 200
end


text:
export default {
  pl: {
    welcome_text: 'Zaloguj się',
    enter_email_placeholder: 'Adres email',
    enter_password_placeholder: 'Hasło',
    dont_have_account: 'Nie masz konta?',
    sign_in: 'Zaloguj się',
    sign_up: 'Zarejestruj się',
    sign_out: 'Wyjdź',
    wrong_user_or_password: 'Nieprawidłowy email lub hasło',
    provide_email: 'Podaj email',
    provide_password: 'Podaj hasło',
    confirm_password: 'Powtórz hasło',
    already_have_account: 'Masz już konto?',
    cards: 'Karty',
    card: 'Karta',
    mucus_type: 'Rodzaj śluzu',
    mucus_types: 'Rodzaje śluzu',
    record_types: 'Rodzaje naklejek',
    no_records: 'Brak obserwacji',
    add_new: 'Dodaj nową',
    days: 'dni',
    date: 'Data',
    type: 'Rodzaj',
    bleeding_type: 'Intensywność',
    frequency: 'Ilość',
    notes: 'Notatki'
  },
  en: {
    welcome_text: 'Sign In',
    enter_email_placeholder: 'Enter email',
    enter_password_placeholder: 'Enter password',
    dont_have_account: 'Don\'t have an account?',
    sign_in: 'Sign in',
    sign_up: 'Sign up',
    sing_out: 'Sign out',
    wrong_user_or_password: 'Wrong email or password',
    provide_email: 'Provide email',
    provide_password: 'Provide password',
    confirm_password: 'Confirm password',
    already_have_account: 'Aleady have an account?',
    card: 'Card',
    cards: 'Cards',
    mucus_type: 'Mucus type',
    mucus_types: 'Mucus types',
    record_type: 'Record type',
    record_types: 'Records types',
    no_records: 'No records',
    add_new: 'Add new'
  }
};


text:
using DAL.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Models
{
    public class Provider
    {
        public int Id { get; set; }
        public string ServiceId { get; set; }
        public string WorkPhoneNumber { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public bool IsActive { get; set; }
        public Gender Gender { get; set; }
        public DateTime? DateOfBirth { get; set; }

        public string ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }

        public int? DepartmentId { get; set; }
        public Department Department { get; set; }

        public ICollection<AvailableTime> WorkingHours { get; set; }
        public ICollection<Appointment> Appointments { get; set; }
        public ICollection<Consultation> Consultations { get; set; }
        public ICollection<LabTest> LabTests { get; set; }

        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
    }
}


text:
package com.google.gerrit.truth;

import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Truth.assertAbout;

import com.google.common.truth.DefaultSubject;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
import com.google.common.truth.Truth;
import java.util.Optional;
import java.util.function.Function;

public class OptionalSubject<S extends Subject<S, ? super T>, T>
    extends Subject<OptionalSubject<S, T>, Optional<T>> {

  private final Function<? super T, ? extends S> valueAssertThatFunction;

  public static <S extends Subject<S, ? super T>, T> OptionalSubject<S, T> assertThat(
      Optional<T> optional, Function<? super T, ? extends S> elementAssertThatFunction) {
    OptionalSubjectFactory<S, T> optionalSubjectFactory =
        new OptionalSubjectFactory<>(elementAssertThatFunction);
    return assertAbout(optionalSubjectFactory).that(optional);
  }

  public static OptionalSubject<DefaultSubject, ?> assertThat(Optional<?> optional) {
    // Unfortunately, we need to cast to DefaultSubject as Truth.assertThat()
    // only returns Subject<DefaultSubject, Object>. There shouldn't be a way
    // for that method not to return a DefaultSubject because the generic type
    // definitions of a Subject are quite strict.
    Function<Object, DefaultSubject> valueAssertThatFunction =
        value -> (DefaultSubject) Truth.assertThat(value);
    return assertThat(optional, valueAssertThatFunction);
  }

  private OptionalSubject(
      FailureMetadata failureMetadata,
      Optional<T> optional,
      Function<? super T, ? extends S> valueAssertThatFunction) {
    super(failureMetadata, optional);
    this.valueAssertThatFunction = valueAssertThatFunction;
  }

  public void isPresent() {
    isNotNull();
    Optional<T> optional = actual();
    if (!optional.isPresent()) {
      failWithoutActual(fact("expected to have", "value"));
    }
  }

  public void isAbsent() {
    isNotNull();
    Optional<T> optional = actual();
    if (optional.isPresent()) {
      failWithoutActual(fact("expected not to have", "value"));
    }
  }

  public void isEmpty() {
    isAbsent();
  }

  public S value() {
    isNotNull();
    isPresent();
    Optional<T> optional = actual();
    return valueAssertThatFunction.apply(optional.get());
  }

  private static class OptionalSubjectFactory<S extends Subject<S, ? super T>, T>
      implements Subject.Factory<OptionalSubject<S, T>, Optional<T>> {

    private Function<? super T, ? extends S> valueAssertThatFunction;

    OptionalSubjectFactory(Function<? super T, ? extends S> valueAssertThatFunction) {
      this.valueAssertThatFunction = valueAssertThatFunction;
    }

    @Override
    public OptionalSubject<S, T> createSubject(
        FailureMetadata failureMetadata, Optional<T> optional) {
      return new OptionalSubject<>(failureMetadata, optional, valueAssertThatFunction);
    }
  }
}


text:
Shindo.tests('Cifrado | CLI#saio') do

  tests '#images' do
    test 'list' do
      Cifrado::Plugins::Saio.class_options[:api_key] = \
        Thor::Option.parse :api_key, fog_settings[:digitalocean_api_key]
      Cifrado::Plugins::Saio.class_options[:client_id] = \
        Thor::Option.parse :client_id, fog_settings[:digitalocean_client_id]
      cli = Cifrado::Plugins::Saio.new
      cli.images.size > 0
    end
  end

end


text:
@implementation UIImage (CS193p)

- (UIImage *)imageByScalingToSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

- (UIImage *)imageByApplyingFilterNamed:(NSString *)filterName
{
    UIImage *filteredImage = self;

    //Step 1: create CIImage object
    CIImage *inputImage = [CIImage imageWithCGImage:[self CGImage]];
    if (inputImage) {
        //Step 2: get the filter
        CIFilter *filter = [CIFilter filterWithName:filterName];
        //Step 3: provide arguments
        [filter setValue:inputImage forKey:kCIInputImageKey];
        //Step 4: get output image
        CIImage *outputImage = [filter outputImage];
        if (outputImage) {
            filteredImage = [UIImage imageWithCIImage:outputImage];
            if (filteredImage) {
                //Step 5: draw it into a new image
                UIGraphicsBeginImageContextWithOptions(self.size, YES, 0.0);
                [filteredImage drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
                filteredImage = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
            }
        }
    }

    return filteredImage;
}

@end


text:
#include <TMongoDriver>
#include <TMongoCursor>
#include <TBson>
#include <TSystemGlobal>
#include <QDateTime>
#include "mongo.h"

TMongoDriver::TMongoDriver()
    : mongoConnection(new mongo), mongoCursor(new TMongoCursor())
{
    mongo_init(mongoConnection);
}

TMongoDriver::~TMongoDriver()
{
    close();
    delete mongoCursor;
    mongo_destroy(mongoConnection);
    delete mongoConnection;
}

bool TMongoDriver::open(const QString &db, const QString &user, const QString &password, const QString &host, quint16 port, const QString &)
{
    if (host.isEmpty()) {
        return false;
    }

    if (!port)
        port = MONGO_DEFAULT_PORT;

    mongo_clear_errors(mongoConnection);
    mongo_set_op_timeout(mongoConnection, 1000);
    int status = mongo_client(mongoConnection, qPrintable(host), port);

    if (status != MONGO_OK) {
        switch (mongoConnection->err) {
        case MONGO_CONN_NO_SOCKET:
            tSystemError("MongoDB socket error: %s", mongoConnection->lasterrstr);
            break;

        case MONGO_CONN_FAIL:
            tSystemError("MongoDB connection failed: %s", mongoConnection->lasterrstr);
            break;

        case MONGO_CONN_NOT_MASTER:
            tSystemDebug("MongoDB not master: %s", mongoConnection->lasterrstr);
            break;

        default:
            tSystemError("MongoDB error: %s", mongoConnection->lasterrstr);
            break;
        }
        return false;
    }

    if (!user.isEmpty()) {
        status = mongo_cmd_authenticate(mongoConnection, qPrintable(db), qPrintable(user), qPrintable(password));
        if (status != MONGO_OK) {
            tSystemDebug("MongoDB authentication error: %s", mongoConnection->lasterrstr);
            return false;
        }
    }

    return (status == MONGO_OK);
}

void TMongoDriver::close()
{
    if (isOpen())
        mongo_disconnect(mongoConnection);
}

bool TMongoDriver::isOpen() const
{
    return (bool)mongo_is_connected(mongoConnection);
}

int TMongoDriver::find(const QString &ns, const QVariantMap &criteria, const QVariantMap &orderBy,
                       const QStringList &fields, int limit, int skip, int options)
{
    int num = -1;
    mongo_clear_errors(mongoConnection);
    mongo_cursor *cursor = mongo_find(mongoConnection, qPrintable(ns), (bson *)TBson::toBson(criteria, orderBy).data(),
                                      (bson *)TBson::toBson(fields).data(), limit, skip, options);
    mongoCursor->setCursor(cursor);

    if (!cursor) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
    } else {
        if (cursor->reply) {
            num = cursor->reply->fields.num;
        }
    }
    return num;
}

QVariantMap TMongoDriver::findOne(const QString &ns, const QVariantMap &criteria,
                                  const QStringList &fields)
{
    TBson bs;

    mongo_clear_errors(mongoConnection);
    int status = mongo_find_one(mongoConnection, qPrintable(ns), (bson *)TBson::toBson(criteria).data(),
                                (bson *)TBson::toBson(fields).data(), (bson *)bs.data());
    if (status != MONGO_OK) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return QVariantMap();
    }
    return TBson::fromBson(bs);
}

bool TMongoDriver::insert(const QString &ns, const QVariantMap &object)
{
    mongo_clear_errors(mongoConnection);
    int status = mongo_insert(mongoConnection, qPrintable(ns),
                              (const bson *)TBson::toBson(object).constData(), 0);
    if (status != MONGO_OK) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return false;
    }
    return true;
}

bool TMongoDriver::remove(const QString &ns, const QVariantMap &object)
{
    mongo_clear_errors(mongoConnection);
    int status = mongo_remove(mongoConnection, qPrintable(ns),
                              (const bson *)TBson::toBson(object).data(), 0);
    if (status != MONGO_OK) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return false;
    }
    return true;
}

bool TMongoDriver::update(const QString &ns, const QVariantMap &criteria, const QVariantMap &object,
                          bool upsert)
{
    mongo_clear_errors(mongoConnection);
    int flag = (upsert) ? MONGO_UPDATE_UPSERT : MONGO_UPDATE_BASIC;
    int status = mongo_update(mongoConnection, qPrintable(ns), (const bson *)TBson::toBson(criteria).data(),
                              (const bson *)TBson::toBson(object).data(), flag, 0);
    if (status != MONGO_OK) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return false;
    }
    return true;
}

bool TMongoDriver::updateMulti(const QString &ns, const QVariantMap &criteria, const QVariantMap &object)
{
    mongo_clear_errors(mongoConnection);
    int status = mongo_update(mongoConnection, qPrintable(ns), (const bson *)TBson::toBson(criteria).data(),
                              (const bson *)TBson::toBson(object).data(), MONGO_UPDATE_MULTI, 0);
   if (status != MONGO_OK) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return false;
    }
   return true;
}

int TMongoDriver::count(const QString &ns, const QVariantMap &criteria)
{
    mongo_clear_errors(mongoConnection);
    int cnt = -1;
    int index = ns.indexOf('.');
    if (index < 0)
        return cnt;

    QString db = ns.mid(0, index);
    QString coll = ns.mid(index + 1);
    cnt = mongo_count(mongoConnection, qPrintable(db), qPrintable(coll), (const bson *)TBson::toBson(criteria).data());
    if (cnt == MONGO_ERROR) {
        tSystemError("MongoDB Error: %s", mongoConnection->lasterrstr);
        return -1;
    }
    return cnt;
}

int TMongoDriver::lastErrorCode() const
{
    return mongo_get_server_err(mongoConnection);
}

QString TMongoDriver::lastErrorString() const
{
    return QLatin1String(mongo_get_server_err_string(mongoConnection));
}

QVariantMap TMongoDriver::getLastCommandStatus(const QString &db)
{
    QVariantMap ret;
    bson bs;

    memset(&bs, 0, sizeof(bs));
    if (mongo_cmd_get_last_error(mongoConnection, qPrintable(db), &bs) == MONGO_OK) {
        ret = TBson::fromBson((TBsonObject *)&bs);
    }
    bson_destroy(&bs);
    return ret;
}


text:
package com.github.jehan.model.builder;

import com.github.jehan.model.Job;

/**
 * The builder for {@link com.github.jehan.model.Job}
 */
public class JobBuilder
{
	// ------------------------- private members -------------------------

	/** */
	private Job m_job;

	// ------------------------- constructor -------------------------

	/**
	 * Constructor.
	 */
	private JobBuilder()
	{
		m_job = new Job();
	}

	// ------------------------- Méthodes public -------------------------

	public static JobBuilder create()
	{
		return new JobBuilder();
	}

	public Job get()
	{
		return m_job;
	}

	public JobBuilder withName(String p_name)
	{
		m_job.setName(p_name);
		return this;
	}

	public JobBuilder withUrl(String p_url)
	{
		m_job.setUrl(p_url);
		return this;
	}

	public JobBuilder withColor(String p_color)
	{
		m_job.setColor(p_color);
		return this;
	}

	// ------------------------- Méthodes private -------------------------
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class DataStreamReadServiceExtensions
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class DataStreamReadServiceExtensions
   ">
    <meta name="generator" content="docfx 2.43.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class DataStreamReadServiceExtensions

Extension methods for IDataStreamReadService.

Inheritance

System.Object

DataStreamReadServiceExtensions

Inherited Members

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.ToString()

Namespace: Kephas.Data.IO.DataStreams

Assembly: Kephas.Data.IO.dll

Syntax

public static class DataStreamReadServiceExtensions

Methods

    |
    <a href="https://github.com/kephas-software/kephas/new/master/apiSpec/new?filename=Kephas_Data_IO_DataStreams_DataStreamReadServiceExtensions_ReadAsync__1_Kephas_Data_IO_DataStreams_IDataStreamReadService_Kephas_Data_IO_DataStreams_DataStream_Kephas_Data_IO_IDataIOContext_System_Threading_CancellationToken_.md&value=---%0Auid%3A%20Kephas.Data.IO.DataStreams.DataStreamReadServiceExtensions.ReadAsync%60%601(Kephas.Data.IO.DataStreams.IDataStreamReadService%2CKephas.Data.IO.DataStreams.DataStream%2CKephas.Data.IO.IDataIOContext%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

ReadAsync<TRootObject>(IDataStreamReadService, DataStream, IDataIOContext, CancellationToken)

Reads the data source and converts it to an enumeration of entities.

Declaration

public static Task<TRootObject> ReadAsync<TRootObject>(this IDataStreamReadService dataStreamReadService, DataStream dataStream, IDataIOContext context = null, CancellationToken cancellationToken = default(CancellationToken))

Parameters

        Type
        Name
        Description

        IDataStreamReadService
        dataStreamReadService

The IDataStreamReadService to act on.

        DataStream
        dataStream

The DataStream containing the entities.

        IDataIOContext
        context

The data I/O context (optional).

        System.Threading.CancellationToken
        cancellationToken

The cancellation token (optional).

Returns

        Type
        Description

        System.Threading.Tasks.Task<TRootObject>

A promise of the deserialized entities.

Type Parameters

        Name
        Description

        TRootObject

Type of the root object.

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
<?php

namespace Winged\Database;

use Winged\Database\Drivers\Cubrid;
use Winged\Database\Drivers\EloquentInterface;
use Winged\Database\Drivers\MySQL;
use Winged\Database\Drivers\PostgreSQL;
use Winged\Database\Drivers\Sqlite;
use Winged\Database\Drivers\SQLServer;
use Winged\Model\Model;
use WingedConfig;

/**
 * Class AbstractEloquent
 *
 * @package Winged\Database
 */
class AbstractEloquent
{
    /**
     * @var $eloquent null | Sqlite | MySQL | Cubrid | SQLServer | PostgreSQL
     */
    protected $eloquent = null;

    public function __construct()
    {
        $reflection = false;
        try {
            $reflection = new \ReflectionClass(get_class(CurrentDB::$current->queryStringHandler));
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage(), E_USER_ERROR);
        }
        if ($reflection) {
            $this->eloquent = $reflection->newInstance();
        }
        return $this;
    }

    /**
     * Example: ['table_name.field' => 'new_name', 'table.name.field']
     *
     * @param array $fields
     *
     * @return $this
     */
    public function select($fields = [])
    {
        if (empty($fields)) {
            $fields = ['*'];
        }
        $this->eloquent->select($fields);
        return $this;
    }

    /**
     * Adds distinct clause in query
     *
     * @param bool $boolean
     *
     * @return $this
     */
    public function distinct($boolean = true)
    {
        $this->eloquent->distinct($boolean);
        return $this;
    }

    /**
     * Example: ['alias' => 'table_name', 'alias' => 'table_name', 'table_name', 'table_name']
     *
     * @param array $tables
     *
     * @return $this
     */
    public function from($tables = [])
    {
        $this->eloquent->from($tables);
        return $this;
    }

    /**
     * Example: ['alias' => 'table_name', 'alias' => 'table_name', 'table_name', 'table_name']
     *
     * @param array $tables
     *
     * @return $this
     */
    public function update($tables = [])
    {
        $this->eloquent->update($tables);
        return $this;
    }

    /**
     * Example: ['table_name.field' => 'new_name', 'table.name.field']
     *
     * @param array $fields
     *
     * @return $this
     */
    public function set($fields = [])
    {
        $this->eloquent->set($fields);
        return $this;
    }

    /**
     * Example: ['alias' => 'table_name', 'alias' => 'table_name', 'table_name', 'table_name']
     *
     * @param array $tables
     *
     * @return $this
     */
    public function delete($tables = [])
    {
        $this->eloquent->delete($tables);
        return $this;
    }

    /**
     * @return $this
     */
    public function insert()
    {
        try {
            $this->eloquent->insert();
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * @param string $table
     *
     * @return $this
     */
    public function into($table = '')
    {
        $this->eloquent->into($table);
        return $this;
    }

    /**
     * Example: ['table_name.field' => 'new_name', 'table.name.field']
     *
     * @param array $fields
     *
     * @return $this
     */
    public function values($fields = [])
    {
        $this->eloquent->values($fields);
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     */
    public function where($condition = '', $values = [])
    {
        try {
            $this->eloquent->where($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     */
    public function andWhere($condition = '', $values = [])
    {
        try {
            $this->eloquent->andWhere($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     */
    public function orWhere($condition = '', $values = [])
    {
        try {
            $this->eloquent->orWhere($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Adds limit clause to query
     *
     * @param int $initial_or_count
     * @param int $final
     *
     * @return $this
     */
    public function limit($initial_or_count, $final = 0)
    {
        $this->eloquent->limit($initial_or_count, $final);
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['alias' => 'table_name', 'alias.field' => 'other_alias.field' or Eloquent]
     *
     * @param string $condition
     * @param array  $inner
     *
     * @return $this
     */
    public function leftJoin($condition = '', $inner = [])
    {
        try {
            $this->eloquent->leftJoin($condition, $inner);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['alias' => 'table_name', 'alias.field' => 'other_alias.field' or Eloquent]
     *
     * @param string $condition
     * @param array  $inner
     *
     * @return $this
     */
    public function rightJoin($condition = '', $inner = [])
    {
        try {
            $this->eloquent->rightJoin($condition, $inner);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['alias' => 'table_name', 'alias.field' => 'other_alias.field' or Eloquent]
     *
     * @param string $condition
     * @param array  $inner
     *
     * @return $this
     */
    public function innerJoin($condition = '', $inner = [])
    {
        try {
            $this->eloquent->innerJoin($condition, $inner);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Adds order by clause in query
     *
     * @param string $direction
     * @param string $field
     *
     * @return $this
     */
    public function orderBy($direction = '', $field = '')
    {
        $this->eloquent->orderBy($direction, $field);
        return $this;
    }

    /**
     * set groupBy clause in query with fields
     *
     * @param array $fields
     *
     * @return $this
     */
    public function groupBy($fields = [])
    {
        $this->eloquent->groupBy($fields);
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     */
    public function having($condition = '', $values = [])
    {
        try {
            $this->eloquent->having($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     * @throws \Exception
     *
     */
    public function andHaving($condition = '', $values = [])
    {
        try {
            $this->eloquent->andHaving($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * Exemple: ELOQUENT_EQUAL, ['table_name.field' => value or Eloquent]
     *
     * @param $condition string
     * @param $values    array
     *
     * @return $this
     * @throws \Exception
     *
     */
    public function orHaving($condition = '', $values = [])
    {
        try {
            $this->eloquent->orHaving($condition, $values);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * perform query building
     * reset prepared infos and all registred commands in query
     *
     * @return Cubrid|Drivers\EloquentInterface|MySQL|PostgreSQL|Sqlite|SQLServer|$this
     */
    public function build()
    {
        $this->eloquent->model = &$this;
        try {
            return $this->eloquent->build();
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * perform query building
     * reset prepared infos and all registred commands in query
     *
     * @return Cubrid|Drivers\EloquentInterface|MySQL|PostgreSQL|Sqlite|SQLServer|$this
     */
    public function buildKeepRegisters()
    {
        $this->eloquent->model = &$this;
        try {
            return $this->eloquent->build(true);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * perform an pre build query
     *
     * @return Cubrid|Drivers\EloquentInterface|MySQL|PostgreSQL|Sqlite|SQLServer|$this
     *
     */
    public function prepare()
    {
        $this->eloquent->model = &$this;
        try {
            return $this->eloquent->prepare();
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $this;
    }

    /**
     * execute and eloquent object if eloquent has prepared and builded
     *
     * @param bool $selectAsArray
     *
     * @return array|bool|mixed|string|Model[]
     */
    public function execute($selectAsArray = false)
    {
        $this->eloquent->model = &$this;
        $return = null;
        try {
            $return = $this->eloquent->execute($selectAsArray);
        } catch (\Exception $exception) {
            trigger_error($exception->getMessage() . '. In file ' . $exception->getFile() . ' at line ' . $exception->getLine(), E_USER_ERROR);
        }
        return $return;
    }

    /**
     * @param bool $selectAsArray
     *
     * @return mixed|Model|null
     */
    public function one($selectAsArray = false)
    {
        $this->eloquent->model = &$this;
        $return = $this->limit(1)->execute($selectAsArray);
        if ($return) {
            return $return[0];
        }
        return null;
    }

    /**
     * method for the purpose of executing queries select for count rows from the database
     */
    public function count()
    {
        $this->eloquent->model = &$this;
        $this->buildKeepRegisters();
        $this->eloquent->builded['command'] = 'count';
        $return = $this->execute();
        if ($return) {
            return $return;
        }
        return -1;
    }

}


text:
//: io/Worm.java
// Demonstrates object serialization.
import java.io.*;
import java.util.*;
import static net.mindview.util.Print.*;

class Data implements Serializable {
  private int n;
  public Data(int n) { this.n = n; }
  public String toString() { return Integer.toString(n); }
}

public class Worm implements Serializable {
  private static Random rand = new Random(47);
  private Data[] d = {
    new Data(rand.nextInt(10)),
    new Data(rand.nextInt(10)),
    new Data(rand.nextInt(10))
  };
  private Worm next;
  private char c;
  // Value of i == number of segments
  public Worm(int i, char x) {
    print("Worm constructor: " + i);
    c = x;
    if(--i > 0)
      next = new Worm(i, (char)(x + 1));
  }
  public Worm() {
    print("Default constructor");
  }
  public String toString() {
    StringBuilder result = new StringBuilder(":");
    result.append(c);
    result.append("(");
    for(Data dat : d)
      result.append(dat);
    result.append(")");
    if(next != null)
      result.append(next);
    return result.toString();
  }
  public static void main(String[] args)
  throws ClassNotFoundException, IOException {
    Worm w = new Worm(6, 'a');
    print("w = " + w);
    ObjectOutputStream out = new ObjectOutputStream(
      new FileOutputStream("worm.out"));
    out.writeObject("Worm storage\n");
    out.writeObject(w);
    out.close(); // Also flushes output
    ObjectInputStream in = new ObjectInputStream(
      new FileInputStream("worm.out"));
    String s = (String)in.readObject();
    Worm w2 = (Worm)in.readObject();
    print(s + "w2 = " + w2);
    ByteArrayOutputStream bout =
      new ByteArrayOutputStream();
    ObjectOutputStream out2 = new ObjectOutputStream(bout);
    out2.writeObject("Worm storage\n");
    out2.writeObject(w);
    out2.flush();
    ObjectInputStream in2 = new ObjectInputStream(
      new ByteArrayInputStream(bout.toByteArray()));
    s = (String)in2.readObject();
    Worm w3 = (Worm)in2.readObject();
    print(s + "w3 = " + w3);
  }
} /* Output:
Worm constructor: 6
Worm constructor: 5
Worm constructor: 4
Worm constructor: 3
Worm constructor: 2
Worm constructor: 1
w = :a(853):b(119):c(802):d(788):e(199):f(881)
Worm storage
w2 = :a(853):b(119):c(802):d(788):e(199):f(881)
Worm storage
w3 = :a(853):b(119):c(802):d(788):e(199):f(881)
*///:~