text:
//
//  ODTabView.m
//  TabView
//
//  Created by Terminator on 2017/12/17.
//  Copyright © 2017年 Terminator. All rights reserved.
//

#import "ODTabView.h"
#import "ODTabViewItem.h"
#import "ODWindow.h"

NSString *kPrivateDragUTI = @"ODTabViewDragUTI";

@interface ODTabView () <NSMenuDelegate> {

    NSMutableArray *_tabViewItems;

    NSUInteger _selectedTabIdx;
    NSTrackingArea *_trackingArea;
    NSUInteger _count;
    NSInteger _highlightedTabIdx;

    NSColor *_backgroundColor;
    NSColor *_foregroundColor;
    NSColor *_highlightColor;
    NSColor *_shadowColor;

    NSDictionary *_activeTabFont;
    NSDictionary *_inactiveTabFont;
    BOOL _highlightDrop;
    NSInteger _draggedTabIdx;
    NSRect _draggedTabRect;

    NSMenu *_defaultMenu;

    NSUInteger _tabMenuIdx;

    NSRect *_rects;

    id<ODTabViewDelegate> _delegate;
    struct __ODTabViewDelegateRespondTo {
        unsigned int shouldMoveTabViewItem:1;
        unsigned int didMoveTabViewItem:1;
        unsigned int tabViewList:1;
    } _delegateRespondTo;

}
@end

@implementation ODTabView

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self _setUp];
#if DEBUG
        printf("%s\n", __PRETTY_FUNCTION__);
#endif
    }
    return self;
}

- (instancetype)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self _setUp];
#if DEBUG
        printf("%s\n", __PRETTY_FUNCTION__);
#endif
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self _setUp];
#if DEBUG
        printf("%s\n", __PRETTY_FUNCTION__);
#endif
    }
    return self;
}

- (void)_setUp {
    if (!_tabViewItems) {
        [self registerForDraggedTypes:@[kPrivateDragUTI, NSStringPboardType, NSFilenamesPboardType]];

        [self setAutoresizingMask:NSViewWidthSizable];
        [self setTranslatesAutoresizingMaskIntoConstraints:YES];

        _rects = malloc(sizeof(NSRect) * _count + 1);
        _tabViewItems = [NSMutableArray new];

        _selectedTabIdx = 0;
        _highlightedTabIdx = -1;
        _draggedTabIdx = -1;
        //_count = 1;

        {
            _backgroundColor = [NSColor colorWithDeviceWhite:0.95 alpha:1.0];
            _foregroundColor = [NSColor colorWithDeviceWhite:0.98 alpha:1.0];
            _highlightColor = [NSColor colorWithDeviceWhite:0.90 alpha:1.0];
            _shadowColor = [NSColor colorWithDeviceWhite:0.85 alpha:1.0];

            NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
            [paragraph setLineBreakMode: NSLineBreakByTruncatingTail];
            [paragraph setAlignment:NSTextAlignmentCenter];
            NSUInteger fontSize = 10;
            _activeTabFont =  @{
                                NSFontAttributeName:[NSFont systemFontOfSize:fontSize],
                                NSParagraphStyleAttributeName: paragraph,
                                };
            _inactiveTabFont = @{
                                 NSFontAttributeName:[NSFont systemFontOfSize:fontSize],
                                 NSParagraphStyleAttributeName: paragraph,
                                 NSForegroundColorAttributeName: [NSColor colorWithDeviceWhite:0.36 alpha:1.0],
                                 };
        }
        {
            _defaultMenu = [[NSMenu alloc] initWithTitle:@"Defalut Menu"];
           // _defaultMenu.delegate = self;
            _defaultMenu.font = [NSFont systemFontOfSize:12];
            NSMenuItem *item;
            NSMenu *subMenu;
            item = [[NSMenuItem alloc] initWithTitle:@"Close Tab"
                                              action:@selector(closeTabMenuItemClicked:)
                                       keyEquivalent:@""];
            item.target = self;
            [_defaultMenu addItem:item];

            item = [[NSMenuItem alloc] initWithTitle:@"Close Other Tabs"
                                              action:@selector(closeOtherTabsMenuItemClicked:)
                                       keyEquivalent:@""];
            item.target = self;
            [_defaultMenu addItem:item];

            item = [[NSMenuItem alloc] initWithTitle:@"Move Tab to New Window"
                                              action:@selector(moveTabToNewWindowMenuItemClicked:)
                                       keyEquivalent:@""];
            item.target = self;
            [_defaultMenu addItem:item];

            item = [[NSMenuItem alloc] initWithTitle:@"Move Tab to" action:nil keyEquivalent:@""];
            subMenu = [NSMenu new];
            item.submenu = subMenu;
            [_defaultMenu addItem:item];
            subMenu.delegate = self;
            _tabMenuIdx = -1;
        }
    }

}

- (void)setDelegate:(id<ODTabViewDelegate>)delegate {
    if ([delegate respondsToSelector:@selector(tabView:shouldMoveTabViewItem:to:)]) {
        _delegateRespondTo.shouldMoveTabViewItem = YES;
    }
    if ([delegate respondsToSelector:@selector(tabView:didMoveTabViewItem:to:)]) {
        _delegateRespondTo.didMoveTabViewItem = YES;
    }
    if ([delegate respondsToSelector:@selector(tabView:tabViewList:)]) {
        _delegateRespondTo.tabViewList = YES;
    }

    _delegate = delegate;
}

- (id<ODTabViewDelegate>)delegate {
    return _delegate;
}

#pragma mark - Tab Management

- (void)selectTabViewItem:(ODTabViewItem *)item {

    [_delegate tabView:self willSelectTabViewItem:item];
    [_selectedTabViewItem.view setHidden:YES];
    //[_selectedTabViewItem.view removeFromSuperview];
    [_selectedTabViewItem _setState:ODTabStateBackground];

    _selectedTabViewItem = item;
    NSView *contentView = self.window.contentView;
    NSView *view = item.view;
    view.frame = contentView.frame;
    //[_window addSubview:view];
    [item _setState:ODTabStateSelected];
    [view setHidden:NO];

    [_delegate tabView:self didSelectTabViewItem:item];

}

- (void)selectTabViewItemAtIndex:(NSInteger)idx {
    //if (_tabViewItems.count > idx) {

    ODTabViewItem *item = _tabViewItems[idx];

    [self selectTabViewItem:item];

    // }
}

#pragma mark - Navigation

- (void)selectFirstTabViewItem {
    [self selectTabViewItem:_tabViewItems.firstObject];
}

- (void)selectLastTabViewItem {
    [self selectTabViewItem:_tabViewItems.lastObject];
}

- (void)selectNextTabViewItem {
    NSInteger idx = [_tabViewItems indexOfObject:_selectedTabViewItem];
    idx = idx + 1;
    if (_tabViewItems.count > idx) {

        [self selectTabViewItemAtIndex:idx];

    } else {

        [self selectFirstTabViewItem];
    }
}

- (void)selectPreviousTabViewItem
{
    NSInteger idx = [_tabViewItems indexOfObject:_selectedTabViewItem];
    idx = idx - 1;
    if (0 <= idx) {

        [self selectTabViewItemAtIndex:idx];

    } else {

        [self selectLastTabViewItem];
    }
}

#pragma mark - Add/Remove

- (void)addTabViewItems:(NSArray *)objects
{
    for (ODTabViewItem *item in objects) {
        [_tabViewItems addObject:item];
    }
}

- (void)addTabViewItem:(ODTabViewItem *)item
{
    [_delegate tabView:self willAddTabViewItem:item];
    [_tabViewItems addObject:item];
    [_delegate tabView:self didAddTabViewItem:item];
    [self setNeedsDisplay:YES];
}

- (void)insertTabViewItem:(ODTabViewItem *)item atIndex:(NSInteger)idx
{
    //if (_tabViewItems.count > idx) {

        [_delegate tabView:self willAddTabViewItem:item];
        [_tabViewItems insertObject:item atIndex:idx];
        [_delegate tabView:self didAddTabViewItem:item];
        [self setNeedsDisplay:YES];
    //}
}

- (void)addTabViewItem:(ODTabViewItem *)item relativeToSelectedTab:(BOOL)value {
    if (value && _tabViewItems.lastObject != _selectedTabViewItem) {
        NSInteger idx = [_tabViewItems indexOfObject:_selectedTabViewItem];
        idx = idx + 1;
        [self insertTabViewItem:item atIndex:idx];
    } else {
        [self addTabViewItem:item];
    }
}

- (void)removeTabViewItem:(ODTabViewItem *)item
{

    if (_selectedTabViewItem == item) {

        if (_tabViewItems.count > 1) {

            (item == _tabViewItems.lastObject) ? [self selectPreviousTabViewItem] : [self selectNextTabViewItem];
        }

    }

    [_delegate tabView:self willRemoveTabViewItem:item];
    [_tabViewItems removeObject:item];
    [_delegate tabView:self didRemoveTabViewItem:item];

    if (_tabViewItems.count == 0) {

        _selectedTabViewItem = nil;
        [self.window close];
    }
    [self setNeedsDisplay:YES];
}

- (void)removeTabViewItemAtIndex:(NSInteger)idx
{
   // if (_tabViewItems.count > idx) {

        ODTabViewItem *item = [_tabViewItems objectAtIndex:idx];
        [self removeTabViewItem:item];
   // }
}

- (void)removeTabViewItemWithView:(id)view
{
    for (ODTabViewItem *item in _tabViewItems) {
        if (item.view == view) {
            [self removeTabViewItem:item];
            break;
        }
    }
}

- (void)removeSelectedTabViewItem
{
    [self removeTabViewItem:_selectedTabViewItem];
}

- (void)removeAllTabs
{
    NSArray *openTabs = _tabViewItems.copy;
    for (ODTabViewItem *item in openTabs) {
        [self removeTabViewItem:item];
    }
}

#pragma mark - Query

- (NSUInteger)numberOfTabViewItems
{
    return _tabViewItems.count;
}

- (NSInteger)indexOfTabViewItem:(ODTabViewItem *)TabViewItem
{
    return [_tabViewItems indexOfObject:TabViewItem];
}

- (ODTabViewItem *)tabViewItemAtIndex:(NSInteger)idx
{
    if (_tabViewItems.count > idx) {
        return _tabViewItems[idx];
    }

    return nil;
}

- (ODTabViewItem *)tabViewItemWithView:(id)view {
    for (ODTabViewItem *item in _tabViewItems) {
        if (item.view == view) {
            return item;
        }
    }

    return nil;
}

- (NSMutableArray *)_tabViewItemArray {
    return _tabViewItems;
}

//- (void)addTabViewItem:(ODTabViewItem *)item {
//    _count++;
//
//    [self setNeedsDisplay:YES];
//
//}
#pragma mark -
#pragma mark  Drag n Drop
#pragma mark  Destination Operations

//- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
//    /*------------------------------------------------------
//     method called whenever a drag enters our drop zone
//     --------------------------------------------------------*/
//
//    // Check if the pasteboard contains image data and source/user wants it copied
//    if ( [NSImage canInitWithPasteboard:[sender draggingPasteboard]] &&
//        [sender draggingSourceOperationMask] &
//        NSDragOperationCopy ) {
//
//        //highlight our drop zone
//        _highlightDrop = YES;
//
//        [self setNeedsDisplay: YES];
//
//        /* When an image from one window is dragged over another, we want to resize the dragging item to
//         * preview the size of the image as it would appear if the user dropped it in. */
//        [sender enumerateDraggingItemsWithOptions:NSDraggingItemEnumerationConcurrent
//                                          forView:self
//                                          classes:[NSArray arrayWithObject:[NSPasteboardItem class]]
//                                    searchOptions:@{}
//                                       usingBlock:^(NSDraggingItem *draggingItem, NSInteger idx, BOOL *stop) {
//
//                                           /* Only resize a fragging item if it originated from one of our windows.  To do this,
//                                            * we declare a custom UTI that will only be assigned to dragging items we created.  Here
//                                            * we check if the dragging item can represent our custom UTI.  If it can't we stop. */
//                                           if ( ![[[draggingItem item] types] containsObject:kPrivateDragUTI] ) {
//
//                                               *stop = YES;
//
//                                           } else {
//                                               /* In order for the dragging item to actually resize, we have to reset its contents.
//                                                * The frame is going to be the destination view's bounds.  (Coordinates are local
//                                                * to the destination view here).
//                                                * For the contents, we'll grab the old contents and use those again.  If you wanted
//                                                * to perform other modifications in addition to the resize you could do that here. */
//                                               [draggingItem setDraggingFrame:(NSRect){0, 0, 32, 32}
//                                                                     contents:[[[draggingItem imageComponents] objectAtIndex:0] contents]];
//                                           }
//                                       }];
//
//        //accept data as a copy operation
//        return NSDragOperationCopy;
//    }
//
//    return NSDragOperationNone;
//}
//
//- (void)draggingExited:(id <NSDraggingInfo>)sender {
//    /*------------------------------------------------------
//     method called whenever a drag exits our drop zone
//     --------------------------------------------------------*/
//    //remove highlight of the drop zone
//    _highlightDrop = NO;
//    _draggedTabIdx = -1;
//
//    [self setNeedsDisplay: YES];
//}
//
//- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
//    /*------------------------------------------------------
//     method to determine if we can accept the drop
//     --------------------------------------------------------*/
//    //finished with the drag so remove any highlighting
//   _highlightDrop = NO;
//
//    [self setNeedsDisplay: YES];
//
//    //check to see if we can accept the data
//    return [NSImage canInitWithPasteboard: [sender draggingPasteboard]];
//}
//
//- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
//    /*------------------------------------------------------
//     method that should handle the drop data
//     --------------------------------------------------------*/
//    if ( [sender draggingSource] != self ) {
//        NSURL* fileURL;
//
//        //set the image using the best representation we can get from the pasteboard
//        if([NSImage canInitWithPasteboard: [sender draggingPasteboard]]) {
////            NSImage *newImage = [[NSImage alloc] initWithPasteboard: [sender draggingPasteboard]];
////            [self setImage:newImage];
////            [newImage release];
//        }
//
//        //if the drag comes from a file, set the window title to the filename
//        fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
//        [[self window] setTitle: fileURL!=NULL ? [fileURL absoluteString] : @"(no name)"];
//    }
//
//    NSPoint event_location = sender.draggingLocation;
//    NSPoint local_point = [self convertPoint:event_location fromView:nil];
//    NSUInteger count = _tabViewItems.count;
//    for (int i = 0; i < count; i++) {
//        NSRect rect = _rects[i];
//        BOOL result = [self mouse:local_point inRect:rect];
//        if (result && i != _draggedTabIdx && _draggedTabIdx < count) {
//            ODTabViewItem *item = _tabViewItems[_draggedTabIdx];
//            [self removeTabViewItemAtIndex:_draggedTabIdx];
//            [self insertTabViewItem:item atIndex:i];
//
//            printf("%s\n", __PRETTY_FUNCTION__);
//            break;
//        }
//
//    }
//
//    return YES;
//}

//- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)newFrame; {
//    /*------------------------------------------------------
//     delegate operation to set the standard window frame
//     --------------------------------------------------------*/
//    //get window frame size
//    NSRect ContentRect=self.window.frame;
//
//    //set it to the image frame size
//    ContentRect.size=[[self image] size];
//
//    return [NSWindow frameRectForContentRect:ContentRect styleMask: [window styleMask]];
//};

#pragma mark Source Operations

//- (NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context {
//    /*------------------------------------------------------
//     NSDraggingSource protocol method.  Returns the types of operations allowed in a certain context.
//     --------------------------------------------------------*/
//    switch (context) {
//        case NSDraggingContextOutsideApplication:
//            return NSDragOperationCopy;
//
//            //by using this fall through pattern, we will remain compatible if the contexts get more precise in the future.
//        case NSDraggingContextWithinApplication:
//        default:
//            return NSDragOperationCopy;
//            break;
//    }
//}
//
//- (void)pasteboard:(NSPasteboard *)sender item:(NSPasteboardItem *)item provideDataForType:(NSString *)type {
//    /*------------------------------------------------------
//     method called by pasteboard to support promised
//     drag types.
//     --------------------------------------------------------*/
//    //sender has accepted the drag and now we need to send the data for the type we promised
//    if ( [type compare: NSPasteboardTypeTIFF] == NSOrderedSame ) {
//
//        //set data for TIFF type on the pasteboard as requested
//        //[sender setData:[[self image] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
//
//    } else if ( [type compare: NSPasteboardTypePDF] == NSOrderedSame ) {
//
//        //set data for PDF type on the pasteboard as requested
//        [sender setData:[self dataWithPDFInsideRect:[self bounds]] forType:NSPasteboardTypePDF];
//    }
//
//}

#pragma mark - Tracking Mouse

- (void)updateTrackingAreas {
    [super updateTrackingAreas];

    if (_trackingArea) {
        [self removeTrackingArea:_trackingArea];

    }

    _trackingArea = [[NSTrackingArea alloc] initWithRect:self.frame
                                                 options:NSTrackingActiveAlways|NSTrackingMouseEnteredAndExited|NSTrackingInVisibleRect|NSTrackingMouseMoved
                                                   owner:self
                                                userInfo:nil];

    [self addTrackingArea:_trackingArea];

}

- (void)mouseMoved:(NSEvent *)theEvent {
    NSPoint event_location = theEvent.locationInWindow;
    NSPoint local_point = [self convertPoint:event_location fromView:nil];
    NSUInteger count = _tabViewItems.count;
    for (int i = 0; i < count; i++) {
        NSRect rect = _rects[i];
        BOOL result = [self mouse:local_point inRect:rect];
        if (result && _highlightedTabIdx != i && i != _selectedTabIdx) {

            _highlightedTabIdx = i;
            [self setNeedsDisplay:YES];

            self.toolTip = nil;
            self.toolTip = [_tabViewItems[i] label];

#if DEBUG
            printf("%s\n", __PRETTY_FUNCTION__);
#endif
            break;
        }

    }
}

- (void)mouseEntered:(NSEvent *)theEvent {

}

- (void)mouseExited:(NSEvent *)theEvent {
    _highlightedTabIdx = -1;
    [self setNeedsDisplay:YES];
}

- (void)otherMouseDown:(NSEvent *)theEvent {
    NSRect draggingRect;
    NSPoint event_location = theEvent.locationInWindow;
    NSPoint local_point = [self convertPoint:event_location fromView:nil];
    NSUInteger count = _tabViewItems.count;
    for (int i = 0; i < count; i++) {
        NSRect rect = _rects[i];
        BOOL result = [self mouse:local_point inRect:rect];
        if (result) {

            draggingRect = rect;
            _draggedTabRect = rect;
            _draggedTabIdx = i;
            [self setWantsLayer:YES];
            [self setNeedsDisplay:YES];
#if DEBUG
            printf("%s\n", __PRETTY_FUNCTION__);
#endif
            break;
        }

    }
}

- (void)otherMouseDragged:(NSEvent *)theEvent {
    if (_draggedTabIdx != -1) {
        CGFloat deltaX = theEvent.deltaX;
        _draggedTabRect.origin.x += deltaX;
        [self setWantsLayer:YES];
        [self setNeedsDisplay:YES];
    }
}

- (void)otherMouseUp:(NSEvent *)theEvent {

    NSPoint event_location = theEvent.locationInWindow;
    NSPoint local_point = [self convertPoint:event_location fromView:nil];
    NSUInteger count = _tabViewItems.count;
    for (int i = 0; i < count; i++) {
        NSRect rect = _rects[i];
        BOOL result = [self mouse:local_point inRect:rect];
        if (result && i != _draggedTabIdx && _draggedTabIdx < count) {
            ODTabViewItem *item = _tabViewItems[_draggedTabIdx];
            [_tabViewItems removeObject:item];
            [_tabViewItems insertObject:item atIndex:i];
//            [self removeTabViewItemAtIndex:_draggedTabIdx];
//            [self insertTabViewItem:item atIndex:i];
#if DEBUG
            printf("%s\n", __PRETTY_FUNCTION__);
#endif
            break;
        }

    }
    [self setWantsLayer:NO];
    [self setNeedsDisplay:YES];
    _draggedTabIdx = -1;

}

- (void)rightMouseDown:(NSEvent *)theEvent {
    NSPoint event_location = theEvent.locationInWindow;
    NSPoint local_point = [self convertPoint:event_location fromView:nil];
    NSUInteger count = _tabViewItems.count;
    for (int i = 0; i < count; i++) {
        NSRect rect = _rects[i];
        BOOL result = [self mouse:local_point inRect:rect];
        if (result) {
            _tabMenuIdx = i;
              break;
        }

    }

    [_defaultMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil];
}

//- (void)otherMouseDragged:(NSEvent *)theEvent {
//    /*------------------------------------------------------
//     catch mouse down events in order to start drag
//     --------------------------------------------------------*/
//
//    /* Dragging operation occur within the context of a special pasteboard (NSDragPboard).
//     * All items written or read from a pasteboard must conform to NSPasteboardWriting or
//     * NSPasteboardReading respectively.  NSPasteboardItem implements both these protocols
//     * and is as a container for any object that can be serialized to NSData. */
//
//    NSPasteboardItem *pbItem = [NSPasteboardItem new];
//    /* Our pasteboard item will support public.tiff, public.pdf, and our custom UTI (see comment in -draggingEntered)
//     * representations of our data (the image).  Rather than compute both of these representations now, promise that
//     * we will provide either of these representations when asked.  When a receiver wants our data in one of the above
//     * representations, we'll get a call to  the NSPasteboardItemDataProvider protocol method –pasteboard:item:provideDataForType:. */
//    [pbItem setDataProvider:self forTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSPasteboardTypePDF, kPrivateDragUTI, nil]];
//
//    //create a new NSDraggingItem with our pasteboard item.
//    NSDraggingItem *dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:pbItem];
//
//
//    /* The coordinates of the dragging frame are relative to our view.  Setting them to our view's bounds will cause the drag image
//     * to be the same size as our view.  Alternatively, you can set the draggingFrame to an NSRect that is the size of the image in
//     * the view but this can cause the dragged image to not line up with the mouse if the actual image is smaller than the size of the
//     * our view. */
//    NSRect draggingRect;
//    NSPoint event_location = theEvent.locationInWindow;
//    NSPoint local_point = [self convertPoint:event_location fromView:nil];
//    NSUInteger count = _tabViewItems.count;
//    for (int i = 0; i < count; i++) {
//        NSRect rect = _rects[i];
//        BOOL result = [self mouse:local_point inRect:rect];
//        if (result) {
//
//
//            draggingRect = rect;
//            _draggedTabRect = rect;
//            _draggedTabIdx = i;
//            [self setNeedsDisplay:YES];
//            printf("%s\n", __PRETTY_FUNCTION__);
//            break;
//        }
//
//    }
//
//
//    /* While our dragging item is represented by an image, this image can be made up of multiple images which
//     * are automatically composited together in painting order.  However, since we are only dragging a single
//     * item composed of a single image, we can use the convince method below. For a more complex example
//     * please see the MultiPhotoFrame sample. */
//    [dragItem setDraggingFrame:draggingRect contents:[NSImage imageNamed:NSImageNameApplicationIcon]];
//
//    //create a dragging session with our drag item and ourself as the source.
//    NSDraggingSession *draggingSession = [self beginDraggingSessionWithItems:@[dragItem] event:theEvent source:self];
//    //causes the dragging item to slide back to the source if the drag fails.
//    draggingSession.animatesToStartingPositionsOnCancelOrFail = YES;
//
//    draggingSession.draggingFormation = NSDraggingFormationNone;
//
//}

- (BOOL)acceptsFirstMouse:(NSEvent *)event
{
    /*------------------------------------------------------
     accept activation click as click in window
     --------------------------------------------------------*/
    //so source doesn't have to be the active window
    return YES;
}

- (void)mouseDown:(NSEvent *)theEvent {

    NSEventModifierFlags flags = theEvent.modifierFlags;
    if (!(flags & NSShiftKeyMask)) {
        NSPoint event_location = theEvent.locationInWindow;
        NSPoint local_point = [self convertPoint:event_location fromView:nil];
        NSUInteger count = _tabViewItems.count;
        for (int i = 0; i < count; i++) {
            NSRect rect = _rects[i];
            BOOL result = [self mouse:local_point inRect:rect];
            if (result) {

                _highlightedTabIdx = -1;

                if (flags & NSCommandKeyMask) {
                    [self removeTabViewItemAtIndex:i];

                } else {
                    [self selectTabViewItemAtIndex:i];
                    _selectedTabIdx = i;
                }
                [self setNeedsDisplay:YES];

#if DEBUG
                printf("%s\n", __PRETTY_FUNCTION__);
#endif
                 break;
            }

        }
    }

}

//- (void)mouseUp:(NSEvent *)theEvent {
//
//}

#pragma mark - Drawing

static inline void _calcFrame(NSRect *cellFrame, CGFloat *h1, CGFloat *h2) {
    cellFrame->origin.y = (*h1 - *h2) / 2;
    cellFrame->size.height = *h2;
    cellFrame->origin.x += 4;
    cellFrame->size.width -= 8;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    NSUInteger count = _tabViewItems.count;

    if (count) {
        _selectedTabIdx = [_tabViewItems indexOfObject:_selectedTabViewItem];
        NSRect rect = self.bounds;
        CGFloat width = rect.size.width / count;
        rect.size.width = width;
        if (width != _rects[0].size.width) {
            if(_rects) {
                free(_rects);
            }
            _rects = malloc(sizeof(NSRect) * count + 1);
            for (int i = 0; i < count; i++) {
                rect.origin.x = width * i;
                _rects[i] = rect;

            }
        }

        for (int i = 0; i < count; i++) {

            NSRect cellFrame = _rects[i];
            NSDictionary *a;
            if (i == _selectedTabIdx) {

                [_foregroundColor set];
                a = _activeTabFont;
            } else {
                [_backgroundColor set];
                a = _inactiveTabFont;
            }
            if (i == _highlightedTabIdx) {
                [_highlightColor set];
            }
            NSRectFill(cellFrame);
//            if (i != _selectedTabIdx) {
//                [_shadowColor set];
//                NSFrameRect(cellFrame);
//            } else {
//                [_highlightColor set];
//                NSFrameRect(cellFrame);
//            }
            ODTabViewItem *item = _tabViewItems[i];
            NSString *title = item.label;

            //    cellFrame.origin.x += 15;
            CGFloat h1 = NSHeight(cellFrame);
            CGFloat h2 = [title sizeWithAttributes:a].height;
            _calcFrame(&cellFrame, &h1, &h2);
            [title drawInRect:cellFrame withAttributes:a];

        }

        if (_draggedTabIdx != -1) {
            ODTabViewItem *item = _tabViewItems[_draggedTabIdx];

            NSString *title = item.label;
            NSRect cellFrame = _draggedTabRect;
            [_foregroundColor set];
            NSRectFill(cellFrame);
            CGFloat h1 = NSHeight(cellFrame);
            CGFloat h2 = [title sizeWithAttributes:_activeTabFont].height;
            _calcFrame(&cellFrame, &h1, &h2);
            [title drawInRect:cellFrame withAttributes:_activeTabFont];
        }
//        [_highlightColor set];
//        //[[NSColor blackColor] set];
//        NSRect bounds = self.bounds;
//        [NSBezierPath strokeLineFromPoint:NSMakePoint(0, 0)
//                                  toPoint:NSMakePoint(0, NSHeight(bounds))];
//        [NSBezierPath strokeLineFromPoint:NSMakePoint(NSWidth(bounds), 0)
//                                  toPoint:NSMakePoint(NSWidth(bounds), NSHeight(bounds))];

       // NSFrameRect(self.bounds);
#if DEBUG
        printf("width: %f\n", width);
#endif

    }

}

#pragma mark - Tab Menu

- (void)closeTabMenuItemClicked:(id)sender {
    if (_tabMenuIdx < _tabViewItems.count) {
        [self removeTabViewItemAtIndex:_tabMenuIdx];
    }
    _tabMenuIdx = NSUIntegerMax;
}

- (void)closeOtherTabsMenuItemClicked:(id)sender {
    NSUInteger count = _tabViewItems.count;
    if (_tabMenuIdx < count) {
        [self selectTabViewItemAtIndex:_tabMenuIdx];
        ODTabViewItem *item = _tabViewItems[_tabMenuIdx];
        for (ODTabViewItem *i in _tabViewItems.copy) {
            if(i != item) {
                [self removeTabViewItem:i];
            }
        }
    }
    _tabMenuIdx = NSUIntegerMax;
}

- (void)moveTabToNewWindowMenuItemClicked:(id)sender {
    NSUInteger count = _tabViewItems.count;
    if (_tabMenuIdx < count && count > 1) {
        if (_delegateRespondTo.shouldMoveTabViewItem) {
            ODTabView *tv = nil;
            ODTabViewItem *item = _tabViewItems[_tabMenuIdx];
            if ([_delegate tabView:self shouldMoveTabViewItem:item to:&tv]) {
                if (tv) {
                    if (item == self.selectedTabViewItem) {
                        [self selectNextTabViewItem];
                    }
                    [_tabViewItems removeObject:item];
                    [tv addTabViewItem:item];
                    [tv selectTabViewItem:item];
                    if (_delegateRespondTo.didMoveTabViewItem) {
                        [_delegate tabView:self didMoveTabViewItem:item to:tv];
                    }
                }

            }
        }
    }
    _tabMenuIdx = NSUIntegerMax;
}

- (void)moveTabToOtherWindowMenuItemClicked:(NSMenuItem *)sender {
    ODTabView *tv = sender.representedObject;
    ODTabViewItem *item = _tabViewItems[_tabMenuIdx];
    if (item == self.selectedTabViewItem) {
        [self selectNextTabViewItem];
    }
    [_tabViewItems removeObject:item];
    [tv addTabViewItem:item];
    [tv selectTabViewItem:item];
    if (_delegateRespondTo.didMoveTabViewItem) {
        [_delegate tabView:self didMoveTabViewItem:item to:tv];
    }
}

- (void)menuNeedsUpdate:(NSMenu*)menu {

    if (_delegateRespondTo.tabViewList) {
        [menu removeAllItems];
        NSArray *tabViews = nil;
        NSMenuItem *menuItem = nil;
        [_delegate tabView:self tabViewList:&tabViews];
        if (tabViews) {
            for (ODTabView *tv in tabViews) {
                if (tv != self) {
                    menuItem = [[NSMenuItem alloc] initWithTitle:tv.selectedTabViewItem.label
                                                          action:@selector(moveTabToOtherWindowMenuItemClicked:)
                                                   keyEquivalent:@""];
                    menuItem.target = self;
                    menuItem.representedObject = tv;
                    [menu addItem:menuItem];
                }

            }
        }
    }

}

#pragma mark - dealloc

- (void)dealloc
{
    if(_rects) {
        free(_rects);
    }
}

@end


text:
package com.palantir.baseline.errorprone;

import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import java.util.List;

@AutoService(BugChecker.class)
@BugPattern(
        link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
        linkType = BugPattern.LinkType.CUSTOM,
        severity = SeverityLevel.WARNING,
        summary =
                "Prefer Guava's Lists.transform or Collections2.transform instead of Iterables.transform when first"
                    + " argument's declared type is a List or Collection type for performance reasons, cf."
                    + " https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Iterables.html#transform-java.lang.Iterable-com.google.common.base.Function-")
public final class PreferCollectionTransform extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {

    private static final long serialVersionUID = 1L;

    private static final Matcher<ExpressionTree> ITERABLES_TRANSFORM_MATCHER = MethodMatchers.staticMethod()
            .onClass("com.google.common.collect.Iterables")
            .named("transform");

    private static final Matcher<Tree> LIST_MATCHER = MoreMatchers.isSubtypeOf("java.util.List");
    private static final Matcher<Tree> COLLECTION_MATCHER = MoreMatchers.isSubtypeOf("java.util.Collection");

    @Override
    public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
        if (ITERABLES_TRANSFORM_MATCHER.matches(tree, state)) {
            List<? extends ExpressionTree> args = tree.getArguments();
            if (args.size() > 1 && COLLECTION_MATCHER.matches(args.get(0), state)) {
                String qualifiedType;
                String errorMessage;
                SuggestedFix.Builder fix = SuggestedFix.builder();
                if (LIST_MATCHER.matches(args.get(0), state)) {
                    // Fail on any 'Iterables.transform(List, Function) invocation
                    qualifiedType = SuggestedFixes.qualifyType(state, fix, "com.google.common.collect.Lists");
                    errorMessage = "Prefer Lists.transform";
                } else {
                    // Fail on any 'Iterables.transform(Collection, Function) invocation
                    qualifiedType = SuggestedFixes.qualifyType(state, fix, "com.google.common.collect.Collections2");
                    errorMessage = "Prefer Collections2.transform";
                }
                String method = qualifiedType + ".transform";
                return buildDescription(tree)
                        .setMessage(errorMessage)
                        .addFix(fix.replace(tree.getMethodSelect(), method).build())
                        .build();
            }
        }

        return Description.NO_MATCH;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component } from '@angular/core';
import { WeatherComponent } from './weather/weather.component';

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    directives: [WeatherComponent]

})
export class AppComponent {

}


text:
<?php
/**
 *Class for exceptions for page
 *
 *@package Exception
 *@author  Vinicius Pinheiro <viny-pinheiro@hotmail.com>
 *@license MIT License
 *@link    http://eletronjun.com.br/class/exception/categoryException.php
 */
namespace exception{

    /**
     * @codeCoverageIgnore
     */
    class CategoryException extends \Exception
    {
        public function __construct($message, $code = 0, Exception $previous = null)
        {
            parent::__construct($message, $code, $previous);
        }

        public function __toString()
        {
            return $this->message;
        }
    }
}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace WeddingBidders.Server.Models
{
    public class Customer: Person
    {
        public Customer()
        {
            this.Weddings = new HashSet<Wedding>();
        }

        [ForeignKey("Profile")]
        public int? ProfileId { get; set; }
        public ICollection<Wedding> Weddings { get; set; }
        public Profile Profile { get; set; }
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>README - RDoc Documentation</title>

<link href="./css/fonts.css" rel="stylesheet">
<link href="./css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Table of Contents

LppGrupo3

Installation

Usage

Development

Contributing

License

Pages

CODE_OF_CONDUCT

Gemfile

Gemfile.lock

Guardfile

LICENSE

README

Rakefile

setup

lpp_Grupo3.gemspec

LppGrupo3¶ ↑

Welcome to your new gem! In this directory, you'll find the files you
need to be able to package up your Ruby library into a gem. Put your Ruby
code in the file lib/lpp_Grupo3. To experiment with that code,
run bin/console for an interactive prompt.

TODO: Delete this and the text above, and describe your gem

Installation¶ ↑

Add this line to your application's Gemfile:

gem 'lpp_Grupo3'

And then execute:

$ bundle

Or install it yourself as:

$ gem install lpp_Grupo3

Usage¶ ↑

TODO: Write usage instructions here

Development¶ ↑

After checking out the repo, run bin/setup to install
dependencies. Then, run rake spec to run the tests. You can
also run bin/console for an interactive prompt that will allow
you to experiment.

To install this gem onto your local machine, run bundle exec rake
install. To release a new version, update the version number in
version.rb, and then run bundle exec rake
release, which will create a git tag for the version, push git
commits and tags, and push the .gem file to rubygems.org.

Contributing¶ ↑

Bug reports and pull requests are welcome on GitHub at github.com/[USERNAME]/lpp_Grupo3.
This project is intended to be a safe, welcoming space for collaboration,
and contributors are expected to adhere to the Contributor Covenant code of conduct.

License¶ ↑

The gem is available as open source under the terms of the MIT License.

Validate

Generated by RDoc 4.2.0.

Based on Darkfish by Michael Granger.


text:
package org.wso2.am.integration.tests.api.lifecycle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.*;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.*;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Test class is used to test the API tags visibility for anonymous and authorised users when API role based visibility
 * is used.
 */
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public class APITagVisibilityByRoleTestCase extends APIMIntegrationBaseTest {

    private final Log log = LogFactory.getLog(APITagVisibilityByRoleTestCase.class);
    private APIStoreRestClient apiStore;
    private String storeURLHttp;
    private String publisherURLHttp;
    private APIPublisherRestClient apiPublisher;
    private URL tagListUrl;
    private UserManagementClient userManagementClient1;
    private APIRequest apiRequestPublic, apiRequestRestricted;
    private String endpointUrl;

    private String apiNamePublic = "APITagVisibilityByRoleTestCaseAPIName1";
    private String APIContextPublic = "APITagVisibilityByRoleTestCaseContext1";
    private String apiNameRestricted = "APITagVisibilityByRoleTestCaseAPIName2";
    private String APIContextRestricted = "APITagVisibilityByRoleTestCaseContext2";
    private String tagsPublic = "APITagVisibilityPublicTag";
    private String tagsRestricted = "APITagVisibilityRestrictedTag";
    private String description = "This is test API create by APIM APITagVisibilityByRoleTestCase";
    private String APIVersion = "1.0.0";
    private String allowedUser = "APITagVisibilityByRoleUser";
    private char[] allowedUserPass = "password@123".toCharArray();
    private String role = "APITagVisibilityRole1";
    private String[] permissions = { "/permission/admin/login", "/permission/admin/manage/api/subscribe" };
    private Map<String, String> requestHeaders = new HashMap<String, String>();

    @Factory(dataProvider = "userModeDataProvider")
    public APITagVisibilityByRoleTestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init(userMode);

        publisherURLHttp = getPublisherURLHttp();
        storeURLHttp = getStoreURLHttp();
        endpointUrl = backEndServerUrl.getWebAppURLHttp() + "am/sample/calculator/v1/api/add";

        apiStore = new APIStoreRestClient(storeURLHttp);
        apiPublisher = new APIPublisherRestClient(publisherURLHttp);
        apiPublisher.login(user.getUserName(), user.getPassword());

        //adding new role and user
        userManagementClient1 = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(),
                                                         createSession(keyManagerContext));
        userManagementClient1.addRole(role, null, permissions);
        userManagementClient1.addUser(allowedUser, String.valueOf(allowedUserPass), new String[] {role }, null);
        tagListUrl = new URL(getStoreURLHttp() + "store/site/blocks/tag/tag-cloud/ajax/list.jag");
    }

    @Test(groups = { "wso2.am" }, description = "Create and publish two apis with public and role based visibility")
    public void testAPICreationWithVisibility() throws Exception {
        String providerName = user.getUserName();

        //API request for public visible API
        apiRequestPublic = new APIRequest(apiNamePublic, APIContextPublic, new URL(endpointUrl));
        apiRequestPublic.setTags(tagsPublic);
        apiRequestPublic.setDescription(description);
        apiRequestPublic.setVersion(APIVersion);
        apiRequestPublic.setProvider(providerName);

        //API request for role base visible API
        apiRequestRestricted = new APIRequest(apiNameRestricted, APIContextRestricted, new URL(endpointUrl));
        apiRequestRestricted.setTags(tagsRestricted);
        apiRequestRestricted.setDescription(description);
        apiRequestRestricted.setVersion(APIVersion);
        apiRequestRestricted.setProvider(providerName);
        apiRequestRestricted.setVisibility("restricted");
        apiRequestRestricted.setRoles(role);

        //add test api
        HttpResponse serviceResponse = apiPublisher.addAPI(apiRequestPublic);
        verifyResponse(serviceResponse);
        //publish the api
        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiNamePublic, user.getUserName(),
                APILifeCycleState.PUBLISHED);
        serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest);
        verifyResponse(serviceResponse);

        //add test api
        serviceResponse = apiPublisher.addAPI(apiRequestRestricted);
        verifyResponse(serviceResponse);
        //publish the api
        updateRequest = new APILifeCycleStateRequest(apiNameRestricted, user.getUserName(),
                APILifeCycleState.PUBLISHED);
        serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest);
        verifyResponse(serviceResponse);
    }

    @Test(groups = { "wso2.am" }, description = "Test the API tag visibility as a anonymous user",
            dependsOnMethods = "testAPICreationWithVisibility")
    public void testAPITagVisibilityAnonymousUser() throws Exception {
        requestHeaders.clear();

        String tenant = user.getUserDomain();
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("action", "getAllTags"));
        urlParameters.add(new BasicNameValuePair("tenant", tenant));
        HttpEntity content = new UrlEncodedFormEntity(urlParameters);
        String contentString = EntityUtils.toString(content);

        log.info("Waiting for tags to get visible in the store......");
        Thread.sleep(30000l);
        HttpResponse serviceResponse = HttpRequestUtil.doPost(tagListUrl, contentString, requestHeaders);
        //sometimes it takes some time to get the tags to appear in the store. As a result in some occasions
        //above request can happen before the tags get deployed. So do a request again if tags are not there
        if(serviceResponse.getData().contains("[]")){
        	Thread.sleep(30000l);
        	serviceResponse = HttpRequestUtil.doPost(tagListUrl, contentString, requestHeaders);
        }
        log.info("Response received from Tag list Query " + serviceResponse.getData());
        Assert.assertTrue(serviceResponse.getData().toLowerCase().contains(tagsPublic.toLowerCase()),
                "Public visibility tag is not available for anonymous user");
        Assert.assertFalse(serviceResponse.getData().toLowerCase().contains(tagsRestricted.toLowerCase()),
                "Restricted visibility tag is available for anonymous user");
    }

    @Test(groups = { "wso2.am" }, description = "Test the API tag visibility as a authorised user",
            dependsOnMethods = "testAPITagVisibilityAnonymousUser")
    public void testAPITagVisibilityAuthorisedUser() throws Exception {

        String tenant = user.getUserDomain();
        String currentUser = allowedUser;
        if ("wso2.com".equals(tenant)) {
            currentUser = currentUser + '@' + tenant;
        }
        HttpResponse response = apiStore.login(currentUser, String.valueOf(allowedUserPass));
        String cookie = response.getHeaders().get("Set-Cookie");
        requestHeaders.put("Cookie", cookie);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("action", "getAllTags"));
        urlParameters.add(new BasicNameValuePair("tenant", tenant));
        HttpEntity content = new UrlEncodedFormEntity(urlParameters);
        String contentString = EntityUtils.toString(content);

        Thread.sleep(5000l);
        HttpResponse serviceResponse = HttpRequestUtil.doPost(tagListUrl, contentString, requestHeaders);
        Assert.assertTrue(serviceResponse.getData().toLowerCase().contains(tagsPublic.toLowerCase()),
                "Public visibility tag is not available for authorised user");
        Assert.assertTrue(serviceResponse.getData().toLowerCase().contains(tagsRestricted.toLowerCase()),
                "Restricted visibility tag is not available for authorised user");

    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        apiPublisher.deleteAPI(apiNamePublic, APIVersion, user.getUserName());
        apiPublisher.deleteAPI(apiNameRestricted, APIVersion, user.getUserName());
        userManagementClient1.deleteRole(role);
        userManagementClient1.deleteUser(allowedUser);
    }

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][] { new Object[] { TestUserMode.SUPER_TENANT_ADMIN },
                new Object[] { TestUserMode.TENANT_ADMIN }, };
    }
}


text:
import createGetFormSubmitErrors from '../selectors/getFormSubmitErrors';
import immutable from '../structure/immutable';

export default createGetFormSubmitErrors(immutable);


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.kksk</groupId>
		<artifactId>parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>modules</artifactId>
	<packaging>pom</packaging>
	<modules>
		<module>../com.kksk.spi</module>
		<module>../com.kksk.identify</module>
		<module>../com.kksk.serialize</module>
		<module>../com.kksk.execution</module>
		<module>../com.kksk.assertion</module>
		<module>../com.kksk.net</module>
		<module>../com.kksk.logging</module>
		<module>../com.kksk.core</module>
	</modules>
</project>


text:
function list = getListLargeObjects

list = {'building','wall','fence','house','church','castle'};


text:
<?php namespace danharper\Stem\Handlers;

class Word extends String implements HandlerInterface
{

	public function register()
	{
		return 'word';
	}

	public function run($modifier = null)
	{
		return $this->getWord();
	}

}


text:
http://blog.yhathq.com/posts/roc-curves.html

# Tools

http://fastml.com/processing-large-files-line-by-line/
http://fastml.com/introducing-phraug/

## Python/Pandas

https://www.kaggle.com/c/titanic/details/getting-started-with-python
https://www.kaggle.com/c/titanic/details/getting-started-with-python-ii

# Pending

https://github.com/rasbt/pattern_classification
https://github.com/brandon-rhodes/pycon-pandas-tutorial
http://nbviewer.ipython.org/github/brandomr/document_cluster/blob/master/cluster_analysis_web.ipynb
https://github.com/donnemartin/data-science-ipython-notebooks
http://peterroelants.github.io/posts/neural_network_implementation_part01/
https://github.com/jatinshah/ufldl_tutorial
http://www.clg.ox.ac.uk/resources
http://radimrehurek.com/data_science_python/
https://github.com/jseabold/depy/blob/master/pandas_sklearn_rendered.ipynb
https://www.datacamp.com/courses/kaggle-tutorial-on-machine-learing-the-sinking-of-the-titanic
http://fastml.com/classifying-text-with-bag-of-words-a-tutorial/
https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words
http://www.kaggle.com/c/titanic-gettingStarted


text:
import os
import pandas as pd
import unittest

from bom_data_parser import read_water_storage_series, read_water_storage_states, read_water_storage_urns

class WaterStoragesTest(unittest.TestCase):
    def setUp(self):
        self.test_xml_file = os.path.join(os.path.dirname(__file__), 'data', 'water_storage', 'urn:bom.gov.au:awris:common:codelist:feature:lakenillahcootie')
        self.test_datasetless_xml_file = os.path.join(os.path.dirname(__file__), 'data', 'water_storage', 'urn:bom.gov.au:awris:common:codelist:feature:brewster')

        self.test_australia_xml_file = os.path.join(os.path.dirname(__file__), 'data', 'water_storage', 'urn:bom.gov.au:awris:common:codelist:region.country:australia')

        self.test_state_xml_file = os.path.join(os.path.dirname(__file__), 'data', 'water_storage', 'urn:bom.gov.au:awris:common:codelist:region.state:victoria')

    def test_read_storage(self):
        with open(self.test_xml_file, 'r') as water_storage_file:
            storage_data = read_water_storage_series(water_storage_file)

        self.assertEqual(storage_data.ix['2015-10-27'], 20929.055)
        self.assertAlmostEqual(storage_data.ix['2013-01-01'], 34895.71)
        self.assertEqual(len(storage_data), 1030)

    def test_list_states(self):
        with open(self.test_australia_xml_file, 'r') as water_storage_file:
            states = read_water_storage_states(water_storage_file)

        self.assertEqual(len(states), 8)

    def test_list_storages(self):
        with open(self.test_state_xml_file, 'r') as water_storage_file:
            storages = read_water_storage_urns(water_storage_file)

        self.assertEqual(len(storages), 71)

    def test_read_storage_without_dataset_attr(self):
        with open(self.test_datasetless_xml_file, 'r') as water_storage_file:
            storage_data = read_water_storage_series(water_storage_file)

        self.assertEqual(storage_data.ix['2014-04-04'], 0.0)
        self.assertEqual(len(storage_data), 459)


text:
package org.cloudbus.mcweb.rules.relations;

/**
 * Represents an algebraic relation with a left hand side (lhs) and
 * a rigth hand side (rhs);
 *
 * @author nikolay.grozev
 *
 * @param <T> - the compile time type of the arguements.
 */
public interface IRelation<T> {

    /**
     * Returns the left hand side (lhs) of the relation.
     * @return the left hand side (lhs) of the relation.
     */
    public T getLhs();

    /**
     * Sets the left hand side (lhs) of the relation.
     * @param lhs - the left hand side (lhs) of the relation. Must not be null. Must of the type specified by {@link IRelation.getElementType}.
     */
    public void setLhs(T lhs);

    /**
     * Returns the right hand side (lhs) of the relation.
     * @return the right hand side (lhs) of the relation.
     */
    public T getRhs();

    /**
     * Sets the right hand side (rhs) of the relation.
     * @param rhs - the right hand side (rhs) of the relation. Must not be null. Must of the type specified by {@link IRelation.getElementType}.
     */
    public void setRhs(T rhs);

    /**
     * Returns the expected type of the elements of this relation. Used for validation, because of type erasure in Java.
     * @return the expected type of the elements of this relation.
     */
    public Class<? extends T> getElementType();

    /**
     * Sets the expected type of the elements of this relation. Used for validation, because of type erasure in Java.
     * @param elementType - the expected type of the elements of this relation. Used for validation. Must not be null.
     * Must match or be a supertype of the types of lhs and rhs.
     */
    public void setElementType(Class<? extends T> elementType);

    /**
     * Returns if this relation is applicable to the specified object.
     * @param o - the object to check for.
     * @return if this relation is applicable to the specified object.
     */
    public default boolean isApplicableTo(Object o){
        return o != null && getElementType().isInstance(o);
    }
}


text:
package org.assertj.core.api.filter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.setAllowExtractingPrivateFields;
import static org.assertj.core.api.filter.Filters.filter;
import static org.assertj.core.test.ExpectedException.none;

import org.assertj.core.test.ExpectedException;
import org.assertj.core.test.Player;
import org.junit.Rule;
import org.junit.Test;

public abstract class AbstractTest_equals_filter extends AbstractTest_filter {

  @Rule
  public ExpectedException thrown = none();

  @Test
  public void should_filter_iterable_elements_with_property_equals_to_given_value() {
    Iterable<Player> bullsPlayers = filterIterable(players, "team", "Chicago Bulls");
    assertThat(bullsPlayers).containsOnly(rose, noah);
    // players is not modified
    assertThat(players).hasSize(4);

    Iterable<Player> filteredPlayers = filter(players).with("name.last", "James").get();
    assertThat(filteredPlayers).containsOnly(james);
    // players is not modified
    assertThat(players).hasSize(4);
  }

  @Test
  public void should_filter_iterable_elements_with_field_equals_to_given_value() {
    setAllowExtractingPrivateFields(true);
    Iterable<Player> bullsPlayers = filterIterable(players, "highestScore", 50);
    assertThat(bullsPlayers).containsOnly(rose, james);
    // players is not modified
    assertThat(players).hasSize(4);
  }

  protected abstract Iterable<Player> filterIterable(Iterable<Player> players, String propertyName, Object propertyValue);

  @Test
  public void should_fail_if_property_to_filter_on_is_null() {
    thrown.expectIllegalArgumentException("The property/field name to filter on should not be null or empty");
    filterIterable(players, null, 6000L);
  }

  @Test
  public void should_fail_if_elements_to_filter_do_not_have_property_used_by_filter() {
    thrown.expectIntrospectionErrorWithMessageContaining("Can't find any field or property with name 'country'");
    filterIterable(players, "country", "France");
  }

}


text:
var Postcard = require('../models/postcard');
var express = require('express');
var app = express();
const logger = require('../utils/logger').logger();

//process payment and send a postcard
app.post('/', (req, res) => {
    const body = req.body;

    if (!body.nonce) throw new Error('No payment nonce provided by client');
    if (!body.issueId) throw new Error('No issue provided');
    if (!body.user) throw new Error('No user provided');
    if (!body.representatives) throw new Error('No recipients provided');

    return Postcard.sendPostcards(body.issueId, body.nonce, body.user, body.representatives)
    .then(result => {
        // is it bad to send 201 for errored postcards?
        // if not 201 the errored postcards array can't be retrieved
        if ((result.postcards && result.postcards.length) || result.errorMessage) {
            return res.status(201).send(result);
        }
        else {
            return res.status(500).send(result);
        }
    })
    .catch(err => {
        logger.error('err', err)
        res.status(500).send(err);
    });
});

module.exports = app;


text:
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** `Object#toString` result references. */
var funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @type {Function}
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => logs the number of milliseconds it took for the deferred function to be invoked
 */
var now = Date.now;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide an options object to indicate whether `func` should be invoked on
 * the leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent calls
 * to the debounced function return the result of the last `func` invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
 * on the trailing edge of the timeout only if the debounced function is
 * invoked more than once during the `wait` timeout.
 *
 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options] The options object.
 * @param {boolean} [options.leading=false] Specify invoking on the leading
 *  edge of the timeout.
 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
 *  delayed before it's invoked.
 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
 *  edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function debounce(func, wait, options) {
  var args,
      maxTimeoutId,
      result,
      stamp,
      thisArg,
      timeoutId,
      trailingCall,
      lastCalled = 0,
      leading = false,
      maxWait = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = toNumber(wait) || 0;
  if (isObject(options)) {
    leading = !!options.leading;
    maxWait = 'maxWait' in options && nativeMax(toNumber(options.maxWait) || 0, wait);
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function cancel() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    if (maxTimeoutId) {
      clearTimeout(maxTimeoutId);
    }
    lastCalled = 0;
    args = maxTimeoutId = thisArg = timeoutId = trailingCall = undefined;
  }

  function complete(isCalled, id) {
    if (id) {
      clearTimeout(id);
    }
    maxTimeoutId = timeoutId = trailingCall = undefined;
    if (isCalled) {
      lastCalled = now();
      result = func.apply(thisArg, args);
      if (!timeoutId && !maxTimeoutId) {
        args = thisArg = undefined;
      }
    }
  }

  function delayed() {
    var remaining = wait - (now() - stamp);
    if (remaining <= 0 || remaining > wait) {
      complete(trailingCall, maxTimeoutId);
    } else {
      timeoutId = setTimeout(delayed, remaining);
    }
  }

  function flush() {
    if ((timeoutId && trailingCall) || (maxTimeoutId && trailing)) {
      result = func.apply(thisArg, args);
    }
    cancel();
    return result;
  }

  function maxDelayed() {
    complete(trailing, timeoutId);
  }

  function debounced() {
    args = arguments;
    stamp = now();
    thisArg = this;
    trailingCall = trailing && (timeoutId || !leading);

    if (maxWait === false) {
      var leadingCall = leading && !timeoutId;
    } else {
      if (!lastCalled && !maxTimeoutId && !leading) {
        lastCalled = stamp;
      }
      var remaining = maxWait - (stamp - lastCalled);

      var isCalled = (remaining <= 0 || remaining > maxWait) &&
        (leading || maxTimeoutId);

      if (isCalled) {
        if (maxTimeoutId) {
          maxTimeoutId = clearTimeout(maxTimeoutId);
        }
        lastCalled = stamp;
        result = func.apply(thisArg, args);
      }
      else if (!maxTimeoutId) {
        maxTimeoutId = setTimeout(maxDelayed, remaining);
      }
    }
    if (isCalled && timeoutId) {
      timeoutId = clearTimeout(timeoutId);
    }
    else if (!timeoutId && wait !== maxWait) {
      timeoutId = setTimeout(delayed, wait);
    }
    if (leadingCall) {
      isCalled = true;
      result = func.apply(thisArg, args);
    }
    if (isCalled && !timeoutId && !maxTimeoutId) {
      args = thisArg = undefined;
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8 which returns 'object' for typed array constructors, and
  // PhantomJS 1.9 which returns 'function' for `NodeList` instances.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3);
 * // => 3
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3');
 * // => 3
 */
function toNumber(value) {
  if (isObject(value)) {
    var other = isFunction(value.valueOf) ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

module.exports = debounce;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.fasterxml.jackson.core.JsonLocation (Jackson-core 2.4.0 API)</title>
<meta name="date" content="2014-05-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.fasterxml.jackson.core.JsonLocation

Packages that use JsonLocation

Package
Description

com.fasterxml.jackson.core

Main public API classes of the core streaming JSON
 processor: most importantly JsonFactory
 used for constructing
 JSON parser (JsonParser)
 and generator
 (JsonGenerator)
 instances.

com.fasterxml.jackson.core.base

Base classes used by concrete Parser and Generator implementations;
 contain functionality that is not specific to JSON or input
 abstraction (byte vs char).

com.fasterxml.jackson.core.json

JSON-specific parser and generator implementation classes that
 Jackson defines and uses.

com.fasterxml.jackson.core.util

Utility classes used by Jackson Core functionality.

Uses of JsonLocation in com.fasterxml.jackson.core

Fields in com.fasterxml.jackson.core declared as JsonLocation

Modifier and Type
Field and Description

protected JsonLocation
JsonProcessingException._location

static JsonLocation
JsonLocation.NA

Shared immutable "N/A location" that can be returned to indicate
 that no location information is available

Methods in com.fasterxml.jackson.core that return JsonLocation

Modifier and Type
Method and Description

abstract JsonLocation
JsonParser.getCurrentLocation()

Method that returns location of the last processed character;
 usually for error reporting purposes.

JsonLocation
JsonProcessingException.getLocation()

abstract JsonLocation
JsonParser.getTokenLocation()

Method that return the starting location of the current
 token; that is, position of the first character from input
 that starts the current token.

Constructors in com.fasterxml.jackson.core with parameters of type JsonLocation

Constructor and Description

JsonParseException(String msg,
                  JsonLocation loc)

JsonParseException(String msg,
                  JsonLocation loc,
                  Throwable root)

JsonProcessingException(String msg,
                       JsonLocation loc)

JsonProcessingException(String msg,
                       JsonLocation loc,
                       Throwable rootCause)

Uses of JsonLocation in com.fasterxml.jackson.core.base

Methods in com.fasterxml.jackson.core.base that return JsonLocation

Modifier and Type
Method and Description

JsonLocation
ParserBase.getCurrentLocation()

Method that returns location of the last processed character;
 usually for error reporting purposes

JsonLocation
ParserBase.getTokenLocation()

Method that return the starting location of the current
 token; that is, position of the first character from input
 that starts the current token.

Uses of JsonLocation in com.fasterxml.jackson.core.json

Methods in com.fasterxml.jackson.core.json that return JsonLocation

Modifier and Type
Method and Description

JsonLocation
DupDetector.findLocation()

JsonLocation
UTF8StreamJsonParser.getCurrentLocation()

JsonLocation
JsonReadContext.getStartLocation(Object srcRef)

JsonLocation
UTF8StreamJsonParser.getTokenLocation()

Uses of JsonLocation in com.fasterxml.jackson.core.util

Methods in com.fasterxml.jackson.core.util that return JsonLocation

Modifier and Type
Method and Description

JsonLocation
JsonParserDelegate.getCurrentLocation()

JsonLocation
JsonParserDelegate.getTokenLocation()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 FasterXML. All Rights Reserved.


text:
"""Tests completeness axiom, batching, and error handling for blur_ig."""
import unittest
import unittest.mock as mock

from . import blur_ig
import numpy as np
from scipy.ndimage import gaussian_filter
import tensorflow.compat.v1 as tf

class BlurIgTest(unittest.TestCase):
  """To run: "python -m saliency.tf1.blur_ig_test" top-level saliency directory."""

  def setUp(self):
    super().setUp()
    self.max_sigma = 10
    with tf.Graph().as_default() as graph:
      self.x = tf.placeholder(shape=[None, 5, 5, 1], dtype=tf.float32)
      y = tf.sin(self.x)
      y_sum = tf.reduce_sum(y, [1,2,3])
      self.gradients_node = tf.gradients(y, self.x)[0]
      self.sess = tf.Session(graph=graph)
      self.sess_spy = mock.MagicMock(wraps=self.sess)
    # All black except 2 pixels near the center.
      self.x_input_val = np.array([
          [0.0, 0.0, 0.0, 0.0, 0.0],
          [0.0, 0.5, 0.0, 0.0, 0.0],
          [0.0, 0.0, 1.0, 0.0, 0.0],
          [0.0, 0.0, 0.0, 0.0, 0.0],
          [0.0, 0.0, 0.0, 0.0, 0.0],
      ],
                                  dtype=float)
      self.x_input_val = self.x_input_val.reshape((5, 5, 1))
      # Calculate the value of `y` at the input.
      y_input_val = self.sess.run(y, feed_dict={self.x: [self.x_input_val]})

      # Baseline is the fully blurred version of the input.
      x_baseline_val = gaussian_filter(
          self.x_input_val,
          sigma=[self.max_sigma, self.max_sigma, 0],
          mode='constant')
      y_baseline_val = self.sess.run(y, feed_dict={self.x: [x_baseline_val]})

      # The expected BlurIG value is equal to the difference between
      # the `y` value at the input and the `y` value at the baseline. Because
      # each value is independent, we can calculate the expected blur_ig value
      # of each.
      #
      # Expected: [[-0, -0, -0, -0, -0],
      #            [-0, 0.641, -0, -0, -0],
      #            [-0, -0, 0.838, -0, -0],
      #            [-0, -0, -0, -0, -0],
      #            [-0, -0, -0, -0, -0]
      self.expected_val = y_input_val[0] - y_baseline_val[0]
      self.blur_ig_instance = blur_ig.BlurIG(graph,
                                             self.sess_spy,
                                             y_sum,
                                             self.x)

  def testBlurIGGetMask(self):
    """Tests that BlurIG steps are created and aggregated correctly."""
    x_steps = 2000

    # Calculate the Blur IG attribution of the input.
    mask = self.blur_ig_instance.GetMask(self.x_input_val,
                                         feed_dict=None,
                                         max_sigma=self.max_sigma,
                                         steps=x_steps)

    # Because the baseline is blurred, all zero values should still have some
    # attribution (introduced noise).
    self.assertEqual(np.count_nonzero(mask), mask.size)
    # Verify the result (for accuracy and therefore completeness).
    np.testing.assert_almost_equal(mask, self.expected_val, decimal=2)
    self.assertEqual(self.sess_spy.run.call_count, x_steps)

  def testBlurIGGetMaskBatched(self):
    """Tests that multiple BlurIG batches are created and aggregated correctly."""
    x_steps = 1001
    batch_size = 500
    expected_calls = 3  # batch size is 500, ceil(1001/500)=3
    self.blur_ig_instance.validate_xy_tensor_shape = mock.MagicMock()
    expected_validate_args = (x_steps, batch_size)

    mask = self.blur_ig_instance.GetMask(self.x_input_val,
                                         feed_dict=None,
                                         max_sigma=self.max_sigma,
                                         steps=x_steps,
                                         batch_size=batch_size)
    validate_args = self.blur_ig_instance.validate_xy_tensor_shape.call_args[0]

    # Because the baseline is blurred, all zero values should still have some
    # attribution (introduced noise).
    self.assertEqual(np.count_nonzero(mask), mask.size)
    # Verify the result (for accuracy and therefore completeness).
    np.testing.assert_almost_equal(mask, self.expected_val, decimal=2)
    self.assertEqual(self.sess_spy.run.call_count, expected_calls)
    self.assertEqual(validate_args, expected_validate_args)

  def testBlurIGGetMaskSingleBatch(self):
    """Tests that a single BlurIG batch is created and aggregated correctly."""
    x_steps = 999
    batch_size = 1000
    expected_calls = 1  # batch size is 1000, ceil(999/1000)=1

    mask = self.blur_ig_instance.GetMask(self.x_input_val,
                                         feed_dict=None,
                                         max_sigma=self.max_sigma,
                                         steps=x_steps,
                                         batch_size=batch_size)

    # Because the baseline is blurred, all zero values should still have some
    # attribution (introduced noise).
    self.assertEqual(np.count_nonzero(mask), mask.size)
    # Verify the result (for accuracy and therefore completeness).
    np.testing.assert_almost_equal(mask, self.expected_val, decimal=2)
    self.assertEqual(self.sess_spy.run.call_count, expected_calls)

  def testBlurIGGetMaskArgs(self):
    """Tests that call_model_function receives correct inputs."""
    x_steps = 5
    feed_dict = {'foo': 'bar'}
    self.sess_spy.run.return_value = [self.x_input_val.reshape((1, 5, 5, 1))]

    self.blur_ig_instance.GetMask(self.x_input_val,
                                  feed_dict=feed_dict,
                                  max_sigma=self.max_sigma,
                                  steps=x_steps)
    actual_feed_dict = self.sess_spy.run.call_args[1]['feed_dict']

    self.assertEqual(actual_feed_dict['foo'], feed_dict['foo'])

if __name__ == '__main__':
  unittest.main()


text:
export default class Storage {
    constructor(type, storageItemName) {
        this.type = type || 'localStorage';
        this.itemName = storageItemName || 'document';
        this.available = Storage.storageAvailable(this.type);
    }

    static storageAvailable(type) {
    	try {
    		let storage = window[type];
    		let x = '__storage_test__';
    		storage.setItem(x, x);
    		storage.removeItem(x);
    		return true;
    	}
    	catch(e) {
            console.warn(`${type} is not available`);
    		return false;
    	}
    }

    saveDoc(document) {
        if (!this.available) return;

        let storage = window[this.type];
        storage.setItem(this.itemName, JSON.stringify(document));
    }

    loadDoc() {
        if (!this.available) return;

        const storage = window[this.type];
        const item = storage.getItem(this.itemName);

        if (item) return JSON.parse(item)

        return item;
    }
}


text:
var radic = require('../../'),
    config = radic.app.config,
    sh = radic.sh,
    util = radic.util,

    pm2 = require('pm2'),
    fs = require('fs-extra'),
    _ = require('lodash'),
    path = require('path');

/**
 * @param {cli} cli
 */
module.exports = function (cli) {

    cli.command('login')
        .description('Login')
        .usage({
            'service [command] ': '[list|kill]'
        })
        .optional('')
        .custom("\n")
        .method(function (cmd) {
            var stormpath = require('stormpath');
            var apiPath = config.get('auth.apiPath');
            if(!apiPath){
                var home = process.env[ (process.platform === 'win32' ? 'USERPROFILE' : 'HOME') ];
                apiPath = home + '/.stormpath/apiKey.properties';
                config.set('auth.apiPath', apiPath);
            }
            var client;
            stormpath.loadApiKey(apiPath, function apiKeyFileLoaded(err, apiKey){
                if(err){
                    cli.log.fatal(err);
                }
                client = new stormpath.Client({apiKey: apiKey});
            })
        });

}


text:
from share.provider import OAIProviderAppConfig

class AppConfig(OAIProviderAppConfig):
    name = 'providers.edu.caltech'
    version = '0.0.1'
    title = 'caltech'
    long_title = 'CaltechAUTHORS'
    home_page = 'http://authors.library.caltech.edu/'
    url = 'http://authors.library.caltech.edu/cgi/oai2'


text:
describe HomeController do
  describe 'GET :index' do
    let!(:issue_1) { create :issue }
    let!(:issue_2) { create :issue }
    let!(:issue_3) { create :issue }

    it 'renders index template' do
      get :index

      expect(assigns(:subscriber).new_record?).to eq true
      expect(assigns(:issues)).to match_array [issue_1, issue_2, issue_3]

      expect(subject).to render_template :index
    end
  end
end


text:
require File.join(File.dirname(__FILE__), '..', 'lib', 'prowlr')
require File.join(File.dirname(__FILE__), 'helpers', 'config_store')
require 'pp'

config = ConfigStore.new("#{ENV['HOME']}/.prowlr")

prowlr = Prowlr.new(config['apikey'])
pp prowlr.add(:event => 'Notification from prowlr gem', :description => "Sent: #{Time.now}")