text:
#import "ABI44_0_0AIRMap.h"

#import <ABI44_0_0React/ABI44_0_0RCTEventDispatcher.h>
#import <ABI44_0_0React/ABI44_0_0UIView+React.h>
#import "ABI44_0_0AIRMapMarker.h"
#import "ABI44_0_0AIRMapPolyline.h"
#import "ABI44_0_0AIRMapPolygon.h"
#import "ABI44_0_0AIRMapCircle.h"
#import <QuartzCore/QuartzCore.h>
#import "ABI44_0_0AIRMapUrlTile.h"
#import "ABI44_0_0AIRMapWMSTile.h"
#import "ABI44_0_0AIRMapLocalTile.h"
#import "ABI44_0_0AIRMapOverlay.h"

const CLLocationDegrees ABI44_0_0AIRMapDefaultSpan = 0.005;
const NSTimeInterval ABI44_0_0AIRMapRegionChangeObserveInterval = 0.1;
const CGFloat ABI44_0_0AIRMapZoomBoundBuffer = 0.01;
const NSInteger ABI44_0_0AIRMapMaxZoomLevel = 20;

@interface MKMapView (UIGestureRecognizer)

// this tells the compiler that MKMapView actually implements this method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;

@end

@interface ABI44_0_0AIRMap ()

@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic, assign) NSNumber *shouldZoomEnabled;
@property (nonatomic, assign) NSNumber *shouldScrollEnabled;

- (void)updateScrollEnabled;
- (void)updateZoomEnabled;

@end

@implementation ABI44_0_0AIRMap
{
    UIView *_legalLabel;
    CLLocationManager *_locationManager;
    BOOL _initialRegionSet;
    BOOL _initialCameraSet;

    // Array to manually track ABI44_0_0RN subviews
    //
    // ABI44_0_0AIRMap implicitly creates subviews that aren't regular ABI44_0_0RN children
    // (ABI44_0_0SMCalloutView injects an overlay subview), which otherwise confuses ABI44_0_0RN
    // during component re-renders:
    // https://github.com/facebook/ABI44_0_0React-native/blob/v0.16.0/ABI44_0_0React/Modules/ABI44_0_0RCTUIManager.m#L657
    //
    // Implementation based on ABI44_0_0RCTTextField, another component with indirect children
    // https://github.com/facebook/ABI44_0_0React-native/blob/v0.16.0/Libraries/Text/ABI44_0_0RCTTextField.m#L20
    NSMutableArray<UIView *> *_ABI44_0_0ReactSubviews;
}

- (instancetype)init
{
    if ((self = [super init])) {
        _hasStartedRendering = NO;
        _ABI44_0_0ReactSubviews = [NSMutableArray new];

        // Find Apple link label
        for (UIView *subview in self.subviews) {
            if ([NSStringFromClass(subview.class) isEqualToString:@"MKAttributionLabel"]) {
                // This check is super hacky, but the whole premise of moving around
                // Apple's internal subviews is super hacky
                _legalLabel = subview;
                break;
            }
        }

        // 3rd-party callout view for MapKit that has more options than the built-in. It's painstakingly built to
        // be identical to the built-in callout view (which has a private API)
        self.calloutView = [ABI44_0_0SMCalloutView platformCalloutView];
        self.calloutView.delegate = self;

        self.minZoomLevel = 0;
        self.maxZoomLevel = ABI44_0_0AIRMapMaxZoomLevel;
        self.compassOffset = CGPointMake(0, 0);
    }
    return self;
}

- (void)dealloc
{
    [_regionChangeObserveTimer invalidate];
}

-(void)addSubview:(UIView *)view {
    if([view isKindOfClass:[ABI44_0_0AIRMapMarker class]]) {
        [self addAnnotation:(id <MKAnnotation>)view];
    } else {
        [super addSubview:view];
    }
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"
- (void)insertABI44_0_0ReactSubview:(id<ABI44_0_0RCTComponent>)subview atIndex:(NSInteger)atIndex {
    // Our desired API is to pass up markers/overlays as children to the mapview component.
    // This is where we intercept them and do the appropriate underlying mapview action.
    if ([subview isKindOfClass:[ABI44_0_0AIRMapMarker class]]) {
        [self addAnnotation:(id <MKAnnotation>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapPolyline class]]) {
        ((ABI44_0_0AIRMapPolyline *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapPolygon class]]) {
        ((ABI44_0_0AIRMapPolygon *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapCircle class]]) {
        ((ABI44_0_0AIRMapCircle *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapUrlTile class]]) {
        ((ABI44_0_0AIRMapUrlTile *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    }else if ([subview isKindOfClass:[ABI44_0_0AIRMapWMSTile class]]) {
        ((ABI44_0_0AIRMapWMSTile *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapLocalTile class]]) {
        ((ABI44_0_0AIRMapLocalTile *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapOverlay class]]) {
        ((ABI44_0_0AIRMapOverlay *)subview).map = self;
        [self addOverlay:(id<MKOverlay>)subview];
    } else {
        NSArray<id<ABI44_0_0RCTComponent>> *childSubviews = [subview ABI44_0_0ReactSubviews];
        for (int i = 0; i < childSubviews.count; i++) {
          [self insertABI44_0_0ReactSubview:(UIView *)childSubviews[i] atIndex:atIndex];
        }
    }
    [_ABI44_0_0ReactSubviews insertObject:(UIView *)subview atIndex:(NSUInteger) atIndex];
}
#pragma clang diagnostic pop

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"
- (void)removeABI44_0_0ReactSubview:(id<ABI44_0_0RCTComponent>)subview {
    // similarly, when the children are being removed we have to do the appropriate
    // underlying mapview action here.
    if ([subview isKindOfClass:[ABI44_0_0AIRMapMarker class]]) {
        [self removeAnnotation:(id<MKAnnotation>)subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapPolyline class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapPolygon class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapCircle class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapUrlTile class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapWMSTile class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapLocalTile class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else if ([subview isKindOfClass:[ABI44_0_0AIRMapOverlay class]]) {
        [self removeOverlay:(id <MKOverlay>) subview];
    } else {
        NSArray<id<ABI44_0_0RCTComponent>> *childSubviews = [subview ABI44_0_0ReactSubviews];
        for (int i = 0; i < childSubviews.count; i++) {
          [self removeABI44_0_0ReactSubview:(UIView *)childSubviews[i]];
        }
    }
    [_ABI44_0_0ReactSubviews removeObject:(UIView *)subview];
}
#pragma clang diagnostic pop

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"
- (NSArray<id<ABI44_0_0RCTComponent>> *)ABI44_0_0ReactSubviews {
  return _ABI44_0_0ReactSubviews;
}
#pragma clang diagnostic pop

#pragma mark Utils

- (NSArray*) markers {
    NSPredicate *filterMarkers = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        ABI44_0_0AIRMapMarker *marker = (ABI44_0_0AIRMapMarker *)evaluatedObject;
        return [marker isKindOfClass:[ABI44_0_0AIRMapMarker class]];
    }];
    NSArray *filteredMarkers = [self.annotations filteredArrayUsingPredicate:filterMarkers];
    return filteredMarkers;
}

- (ABI44_0_0AIRMapMarker*) markerForCallout:(ABI44_0_0AIRMapCallout*)callout {
    ABI44_0_0AIRMapMarker* marker = nil;
    NSArray* markers = [self markers];
    for (ABI44_0_0AIRMapMarker* mrk in markers) {
        if (mrk.calloutView == callout) {
            marker = mrk;
            break;
        }
    }
    return marker;
}

- (CGRect) frameForMarker:(ABI44_0_0AIRMapMarker*) mrkAnn {
    MKAnnotationView* mrkView = [self viewForAnnotation: mrkAnn];
    CGRect mrkFrame = mrkView.frame;
    return mrkFrame;
}

- (NSDictionary*) getMarkersFramesWithOnlyVisible:(BOOL)onlyVisible {
    NSMutableDictionary* markersFrames = [NSMutableDictionary new];
    for (ABI44_0_0AIRMapMarker* mrkAnn in self.markers) {
        CGRect frame = [self frameForMarker:mrkAnn];
        CGPoint point = [self convertCoordinate:mrkAnn.coordinate toPointToView:self];
        NSDictionary* frameDict = @{
                                    @"x": @(frame.origin.x),
                                    @"y": @(frame.origin.y),
                                    @"width": @(frame.size.width),
                                    @"height": @(frame.size.height)
                                    };
        NSDictionary* pointDict = @{
                                   @"x": @(point.x),
                                   @"y": @(point.y)
                                  };
        NSString* k = mrkAnn.identifier;
        BOOL isVisible = CGRectIntersectsRect(self.bounds, frame);
        if (k != nil && (!onlyVisible || isVisible)) {
            [markersFrames setObject:@{ @"frame": frameDict, @"point": pointDict } forKey:k];
        }
    }
    return markersFrames;
}

- (ABI44_0_0AIRMapMarker*) markerAtPoint:(CGPoint)point {
    ABI44_0_0AIRMapMarker* mrk = nil;
    for (ABI44_0_0AIRMapMarker* mrkAnn in self.markers) {
        CGRect frame = [self frameForMarker:mrkAnn];
        if (CGRectContainsPoint(frame, point)) {
            mrk = mrkAnn;
            break;
        }
    }
    return mrk;
}

#pragma mark Overrides for Callout behavior

// override UIGestureRecognizer's delegate method so we can prevent MKMapView's recognizer from firing
// when we interact with UIControl subclasses inside our callout view.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isDescendantOfView:self.calloutView])
        return NO;
    else
        return [super gestureRecognizer:gestureRecognizer shouldReceiveTouch:touch];
}

// Allow touches to be sent to our calloutview.
// See this for some discussion of why we need to override this: https://github.com/nfarina/calloutview/pull/9
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    CGPoint touchPoint = [self.calloutView convertPoint:point fromView:self];
    UIView *touchedView = [self.calloutView hitTest:touchPoint withEvent:event];

    if (touchedView) {
        UIWindow* win = [[[UIApplication sharedApplication] windows] firstObject];
        ABI44_0_0AIRMapCalloutSubview* calloutSubview = nil;
        ABI44_0_0AIRMapCallout* callout = nil;
        ABI44_0_0AIRMapMarker* marker = nil;

        UIView* tmp = touchedView;
        while (tmp && tmp != win && tmp != self.calloutView) {
            if ([tmp respondsToSelector:@selector(onPress)]) {
                calloutSubview = (ABI44_0_0AIRMapCalloutSubview*) tmp;
            }
            if ([tmp isKindOfClass:[ABI44_0_0AIRMapCallout class]]) {
                callout = (ABI44_0_0AIRMapCallout*) tmp;
                break;
            }
            tmp = tmp.superview;
        }

        if (callout) {
            marker = [self markerForCallout:callout];
            if (marker) {
                CGPoint touchPointReal = [marker.calloutView convertPoint:point fromView:self];
                if (![callout isPointInside:touchPointReal]) {
                    return [super hitTest:point withEvent:event];
                }
            }
        }

        return calloutSubview ? calloutSubview : touchedView;
    }

    return [super hitTest:point withEvent:event];
}

#pragma mark ABI44_0_0SMCalloutViewDelegate

- (NSTimeInterval)calloutView:(ABI44_0_0SMCalloutView *)calloutView delayForRepositionWithSize:(CGSize)offset {

    // When the callout is being asked to present in a way where it or its target will be partially offscreen, it asks us
    // if we'd like to reposition our surface first so the callout is completely visible. Here we scroll the map into view,
    // but it takes some math because we have to deal in lon/lat instead of the given offset in pixels.

    CLLocationCoordinate2D coordinate = self.region.center;

    // where's the center coordinate in terms of our view?
    CGPoint center = [self convertCoordinate:coordinate toPointToView:self];

    // move it by the requested offset
    center.x -= offset.width;
    center.y -= offset.height;

    // and translate it back into map coordinates
    coordinate = [self convertPoint:center toCoordinateFromView:self];

    // move the map!
    [self setCenterCoordinate:coordinate animated:YES];

    // tell the callout to wait for a while while we scroll (we assume the scroll delay for MKMapView matches UIScrollView)
    return kSMCalloutViewRepositionDelayForUIScrollView;
}

#pragma mark Accessors

- (NSArray *)getMapBoundaries
{
    MKMapRect mapRect = self.visibleMapRect;

    CLLocationCoordinate2D northEast = MKCoordinateForMapPoint(MKMapPointMake(MKMapRectGetMaxX(mapRect), mapRect.origin.y));
    CLLocationCoordinate2D southWest = MKCoordinateForMapPoint(MKMapPointMake(mapRect.origin.x, MKMapRectGetMaxY(mapRect)));

    return @[
        @[
            [NSNumber numberWithDouble:northEast.longitude],
            [NSNumber numberWithDouble:northEast.latitude]
        ],
        @[
            [NSNumber numberWithDouble:southWest.longitude],
            [NSNumber numberWithDouble:southWest.latitude]
        ]
    ];
}

- (void)setShowsUserLocation:(BOOL)showsUserLocation
{
    if (self.showsUserLocation != showsUserLocation) {
        if (showsUserLocation && !_locationManager) {
            _locationManager = [CLLocationManager new];
            if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [_locationManager requestWhenInUseAuthorization];
            }
        }
        super.showsUserLocation = showsUserLocation;
    }
}

- (void)setUserInterfaceStyle:(NSString*)userInterfaceStyle
{
    if (@available(iOS 13.0, *)) {
        if([userInterfaceStyle isEqualToString:@"light"]) {
            self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
        } else if([userInterfaceStyle isEqualToString:@"dark"]) {
            self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
        } else {
            self.overrideUserInterfaceStyle = UIUserInterfaceStyleUnspecified;
        }
    } else {
        NSLog(@"UserInterfaceStyle not supported below iOS 13");
    }
}

- (void)setTintColor:(UIColor *)tintColor
{
    super.tintColor = tintColor;
}

- (void)setFollowsUserLocation:(BOOL)followsUserLocation
{
    _followUserLocation = followsUserLocation;
}

- (void)setUserLocationCalloutEnabled:(BOOL)calloutEnabled
{
    _userLocationCalloutEnabled = calloutEnabled;
}

- (void)setHandlePanDrag:(BOOL)handleMapDrag {
    for (UIGestureRecognizer *recognizer in [self gestureRecognizers]) {
        if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
            recognizer.enabled = handleMapDrag;
            break;
        }
    }
}

- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated
{
    // If location is invalid, abort
    if (!CLLocationCoordinate2DIsValid(region.center)) {
        return;
    }

    // If new span values are nil, use old values instead
    if (!region.span.latitudeDelta) {
        region.span.latitudeDelta = self.region.span.latitudeDelta;
    }
    if (!region.span.longitudeDelta) {
        region.span.longitudeDelta = self.region.span.longitudeDelta;
    }

    // Animate/move to new position
    [super setRegion:region animated:animated];
}

- (void)setInitialRegion:(MKCoordinateRegion)initialRegion {
    if (!_initialRegionSet) {
        _initialRegionSet = YES;
        [self setRegion:initialRegion animated:NO];
    }
}

- (void)setCamera:(MKMapCamera*)camera animated:(BOOL)animated
{
    [super setCamera:camera animated:animated];
}

- (void)setInitialCamera:(MKMapCamera*)initialCamera {
    if (!_initialCameraSet) {
        _initialCameraSet = YES;
        [self setCamera:initialCamera animated:NO];
    }
}

- (void)setCacheEnabled:(BOOL)cacheEnabled {
    _cacheEnabled = cacheEnabled;
    if (self.cacheEnabled && self.cacheImageView.image == nil) {
        self.loadingView.hidden = NO;
        [self.activityIndicatorView startAnimating];
    }
    else {
        if (_loadingView != nil) {
            self.loadingView.hidden = YES;
        }
    }
}

- (void)setLoadingEnabled:(BOOL)loadingEnabled {
    _loadingEnabled = loadingEnabled;
    if (!self.hasShownInitialLoading) {
        self.loadingView.hidden = !self.loadingEnabled;
    }
    else {
        if (_loadingView != nil) {
            self.loadingView.hidden = YES;
        }
    }
}

- (UIColor *)loadingBackgroundColor {
    return self.loadingView.backgroundColor;
}

- (void)setLoadingBackgroundColor:(UIColor *)loadingBackgroundColor {
    self.loadingView.backgroundColor = loadingBackgroundColor;
}

- (UIColor *)loadingIndicatorColor {
    return self.activityIndicatorView.color;
}

- (void)setLoadingIndicatorColor:(UIColor *)loadingIndicatorColor {
    self.activityIndicatorView.color = loadingIndicatorColor;
}

// Include properties of MKMapView which are only available on iOS 9+
// and check if their selector is available before calling super method.

- (void)setShowsCompass:(BOOL)showsCompass {
    if ([MKMapView instancesRespondToSelector:@selector(setShowsCompass:)]) {
        [super setShowsCompass:showsCompass];
    }
}

- (BOOL)showsCompass {
    if ([MKMapView instancesRespondToSelector:@selector(showsCompass)]) {
        return [super showsCompass];
    } else {
        return NO;
    }
}

- (void)setShowsScale:(BOOL)showsScale {
    if ([MKMapView instancesRespondToSelector:@selector(setShowsScale:)]) {
        [super setShowsScale:showsScale];
    }
}

- (BOOL)showsScale {
    if ([MKMapView instancesRespondToSelector:@selector(showsScale)]) {
        return [super showsScale];
    } else {
        return NO;
    }
}

- (void)setShowsTraffic:(BOOL)showsTraffic {
    if ([MKMapView instancesRespondToSelector:@selector(setShowsTraffic:)]) {
        [super setShowsTraffic:showsTraffic];
    }
}

- (BOOL)showsTraffic {
    if ([MKMapView instancesRespondToSelector:@selector(showsTraffic)]) {
        return [super showsTraffic];
    } else {
        return NO;
    }
}

- (void)setScrollEnabled:(BOOL)scrollEnabled {
    self.shouldScrollEnabled = [NSNumber numberWithBool:scrollEnabled];
    [self updateScrollEnabled];
}

- (void)updateScrollEnabled {
    if (self.cacheEnabled) {
        [super setScrollEnabled:NO];
    }
    else if (self.shouldScrollEnabled != nil) {
        [super setScrollEnabled:[self.shouldScrollEnabled boolValue]];
    }
}

- (void)setZoomEnabled:(BOOL)zoomEnabled {
    self.shouldZoomEnabled = [NSNumber numberWithBool:zoomEnabled];
    [self updateZoomEnabled];
}

- (void)updateZoomEnabled {
    if (self.cacheEnabled) {
        [super setZoomEnabled: NO];
    }
    else if (self.shouldZoomEnabled != nil) {
        [super setZoomEnabled:[self.shouldZoomEnabled boolValue]];
    }
}

- (void)cacheViewIfNeeded {
    // https://github.com/ABI44_0_0React-native-maps/ABI44_0_0React-native-maps/issues/3100
    // Do nothing if app is not active
    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive) {
        return;
    }
    if (self.hasShownInitialLoading) {
        if (!self.cacheEnabled) {
            if (_cacheImageView != nil) {
                self.cacheImageView.hidden = YES;
                self.cacheImageView.image = nil;
            }
        }
        else {
            self.cacheImageView.image = nil;
            self.cacheImageView.hidden = YES;

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.cacheImageView.image = nil;
                self.cacheImageView.hidden = YES;
                UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
                [self.layer renderInContext:UIGraphicsGetCurrentContext()];
                UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();

                self.cacheImageView.image = image;
                self.cacheImageView.hidden = NO;
            });
        }

        [self updateScrollEnabled];
        [self updateZoomEnabled];
        [self updateLegalLabelInsets];
    }
}

- (void)updateLegalLabelInsets {
    if (_legalLabel) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CGRect frame = self->_legalLabel.frame;
            if (self->_legalLabelInsets.left) {
                frame.origin.x = self->_legalLabelInsets.left;
            } else if (self->_legalLabelInsets.right) {
                frame.origin.x = self.frame.size.width - self->_legalLabelInsets.right - frame.size.width;
            }
            if (self->_legalLabelInsets.top) {
                frame.origin.y = self->_legalLabelInsets.top;
            } else if (self->_legalLabelInsets.bottom) {
                frame.origin.y = self.frame.size.height - self->_legalLabelInsets.bottom - frame.size.height;
            }
            self->_legalLabel.frame = frame;
        });
    }
}

- (void)setLegalLabelInsets:(UIEdgeInsets)legalLabelInsets {
  _legalLabelInsets = legalLabelInsets;
  [self updateLegalLabelInsets];
}

- (void)setMapPadding:(UIEdgeInsets)mapPadding {
  self.layoutMargins = mapPadding;
}

- (UIEdgeInsets)mapPadding {
  return self.layoutMargins;
}

- (void)beginLoading {
    if ((!self.hasShownInitialLoading && self.loadingEnabled) || (self.cacheEnabled && self.cacheImageView.image == nil)) {
        self.loadingView.hidden = NO;
        [self.activityIndicatorView startAnimating];
    }
    else {
        if (_loadingView != nil) {
            self.loadingView.hidden = YES;
        }
    }
}

- (void)finishLoading {
    self.hasShownInitialLoading = YES;
    if (_loadingView != nil) {
        self.loadingView.hidden = YES;
    }
    [self cacheViewIfNeeded];
}

- (UIActivityIndicatorView *)activityIndicatorView {
    if (_activityIndicatorView == nil) {
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityIndicatorView.center = self.loadingView.center;
        _activityIndicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        _activityIndicatorView.color = [UIColor colorWithRed:96.f/255.f green:96.f/255.f blue:96.f/255.f alpha:1.f]; // defaults to #606060
    }
    [self.loadingView addSubview:_activityIndicatorView];
    return _activityIndicatorView;
}

- (UIView *)loadingView {
    if (_loadingView == nil) {
        _loadingView = [[UIView alloc] initWithFrame:self.bounds];
        _loadingView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _loadingView.backgroundColor = [UIColor whiteColor]; // defaults to #FFFFFF
        [self addSubview:_loadingView];
        _loadingView.hidden = NO;
    }
    return _loadingView;
}

- (UIImageView *)cacheImageView {
    if (_cacheImageView == nil) {
        _cacheImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _cacheImageView.contentMode = UIViewContentModeCenter;
        _cacheImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self addSubview:self.cacheImageView];
        _cacheImageView.hidden = YES;
    }
    return _cacheImageView;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self cacheViewIfNeeded];
    NSUInteger index = [[self subviews] indexOfObjectPassingTest:^BOOL(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *str = NSStringFromClass([obj class]);
        return [str containsString:@"MKCompassView"];
    }];
    if (index != NSNotFound) {
        UIView* compassButton;
        compassButton = [self.subviews objectAtIndex:index];
        compassButton.frame = CGRectMake(compassButton.frame.origin.x + _compassOffset.x, compassButton.frame.origin.y + _compassOffset.y, compassButton.frame.size.width, compassButton.frame.size.height);
    }
}

@end


text:
package main

import (
	exec "golang.org/x/sys/execabs"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func findGOROOT() string {
	if env := os.Getenv("GOROOT"); env != "" {
		return filepath.Clean(env)
	}
	def := filepath.Clean(runtime.GOROOT())
	if runtime.Compiler == "gccgo" {
		// gccgo has no real GOROOT, and it certainly doesn't
		// depend on the executable's location.
		return def
	}
	out, err := exec.Command("go", "env", "GOROOT").Output()
	if err != nil {
		return def
	}
	return strings.TrimSpace(string(out))
}

redpajama_set_name: RedPajamaGithub


text:
package com.coredot.jdebugconsole;

import lombok.Getter;

public class TotalStat implements Statistic {
    private final Mutex mutex = new Mutex();
    @Getter
    private String name;
    private double total = 0l;
    private long count = 0l;

    public TotalStat(String name) {
        this.name = name;
    }

    public String toString() {
        StringBuilder out = new StringBuilder();
        synchronized (mutex) {
            out.append("Total: ");
            out.append(total);
            out.append(", Mean: ");
            out.append(JMath.round(total / count, 2));
            out.append(", Collected: ");
            out.append(count);
        }
        return out.toString();
    }

    public void add(Number value) {
        synchronized (mutex) {
            count++;
            total += value.doubleValue();
        }
    }

    public void reset() {
        synchronized (mutex) {
            total = 0l;
            count = 0l;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~  Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~  WSO2 Inc. licenses this file to you under the Apache License,
  ~  Version 2.0 (the "License"); you may not use this file except
  ~  in compliance with the License.
  ~  You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing,
  ~  software distributed under the License is distributed on an
  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~  KIND, either express or implied. See the License for the
  ~  specific language governing permissions and limitations
  ~  under the License.
  -->

<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>org.wso2.ei</groupId>
        <artifactId>product-scenarios</artifactId>
        <version>6.4.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>11-Asynchronous-message-processing</artifactId>

    <packaging>pom</packaging>

    <modules>
        <module>11-SynapseConfigProject</module>
        <module>11.1-Decoupling-interacting-parties-across-time-and-space</module>
    </modules>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=128m</argLine>
                    <disableXmlReport>false</disableXmlReport>
                    <parallel>false</parallel>
                    <suiteXmlFiles>
                        <suiteXmlFile>${basedir}/src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <systemProperties>
                        <property>
                            <!-- Common resource directory (eg: Key stores, certificates, etc.)-->
                            <name>common.resources.dir</name>
                            <value>
                                ${basedir}/../../../../resources/
                            </value>
                        </property>
                        <property>
                            <!-- testcase specific  resources directory-->
                            <name>test.resources.dir</name>
                            <value>
                                ${basedir}/src/test/resources/
                            </value>
                        </property>
                        <property>
                            <!-- Directory containing carbon applications -->
                            <name>test.resources.carbonApplications.dir</name>
                            <value>
                                ${basedir}/../../../../11-SynapseConfigProject/11-synapseConfigCompositeApplication/target/
                            </value>
                        </property>
                        <property>
                            <!-- Related carbon applications (comma separated) to deploy -->
                            <name>test.resources.carbonApplications.list</name>
                            <value>
                                11-synapseConfigCompositeApplication_1.0.0
                            </value>
                        </property>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>false</value>
                        </property>
                    </systemProperties>
                    <workingDirectory>${basedir}/target</workingDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
import * as React from 'react';
import { StandardProps } from '../@types/common';

export type PlacementType = 'topStart' | 'topEnd' | 'bottomStart' | 'bottomEnd';

export interface NotificationProps extends StandardProps {
  /** The title of the message box */
  title?: React.ReactNode;

  /** The description of the message box */
  description?: React.ReactNode;

  /** message box duration (Unit: milliseconds) */
  duration?: number;

  /** The placement of the message box. */
  placement?: PlacementType;

  /** The distance from the top of the message box */
  top?: number;

  /** The distance from the bottom of the message box */
  bottom?: number;

  /** The message box is uniquely identified, and you must fill out the field if you want to manually remove the message box. */
  key?: string;

  /** Closes the callback function */
  onClose?: () => void;

  /** The parent container of Notification */
  getContainer?: () => HTMLElement;
}

export interface NotificationAPI {
  open(config: NotificationProps): void;
  info(config: NotificationProps): void;
  success(config: NotificationProps): void;
  warning(config: NotificationProps): void;
  error(config: NotificationProps): void;
  close(key?: string): void;
  closeAll(): void;
}

declare const Notification: NotificationAPI;

export default Notification;


text:
resumeApp.controller('projectsCtrl', function($scope, toastService, utilService, $location, $log) {
  var projectsList = this;
  projectsList.projects = [];

  projectsList.btnSaveProjects = "Add";
  if(JSON.parse(localStorage.getItem('addProjectObject'))){
    var resolveAddProjectObject = JSON.parse(localStorage.getItem('addProjectObject'));
    for(var i = 0; i < resolveAddProjectObject.length; i++) {
        var obj = resolveAddProjectObject[i];

        projectsList.projects.push({id: obj.id, title: obj.title, website: obj.website, desc: obj.desc});
        //console.log(obj.id);
    }
  }

  projectsList.addProject = function(){
    if(projectsList.title==undefined
      || projectsList.website==undefined
      ||projectsList.desc==undefined
      || projectsList.title==''
      || projectsList.website=='')
      return false;

    var projectId = utilService.guid();
    if(projectsList.id!=undefined && projectsList.id!=''){
      var addProjectObject = JSON.parse(localStorage.getItem('addProjectObject'));
      for (i=0;i<addProjectObject.length;i++){
        if (addProjectObject[i].id == projectsList.id) {
          addProjectObject[i].title = projectsList.title;
          addProjectObject[i].website = projectsList.website;
          addProjectObject[i].desc = projectsList.desc;
        }
      }
      localStorage.setItem('addProjectObject', JSON.stringify(addProjectObject));

      // Update the selected Project
      angular.forEach(projectsList.projects, function (p) {
        if (p.id == projectsList.id) {
          p.title = projectsList.title;
          p.website = projectsList.website;
          p.desc = projectsList.desc;
        }
      });
    }else{
      projectsList.projects.push({id:projectId, title: projectsList.title, website: projectsList.website, desc: projectsList.desc});

      var addProjectObject = JSON.parse(localStorage.getItem('addProjectObject')) || [];
      var addProjectNewItem = {'id': projectId, 'title': projectsList.title, 'website': projectsList.website, 'desc': projectsList.desc};

      addProjectObject.push(addProjectNewItem);
      localStorage.setItem('addProjectObject', JSON.stringify(addProjectObject));
    }
    projectsList.title = '';
    projectsList.website = '';
    projectsList.desc = '';
    projectsList.id = '';
    projectsList.btnSaveProjects = "Add";

    toastService.showSimpleToast();
  }

  projectsList.removeProject = function(project) {
    var _index = projectsList.projects.indexOf(project);
    var id = project.id;
    console.log(project);
    projectsList.projects.splice(_index, 1);

    var addProjectObject = JSON.parse(localStorage.getItem('addProjectObject'));
    for (i=0;i<addProjectObject.length;i++)
                if (addProjectObject[i].id == id) addProjectObject.splice(i,1);
    localStorage.setItem('addProjectObject', JSON.stringify(addProjectObject));
  }

  projectsList.bindSelectedProject = function(project) {
    projectsList.btnSaveProjects = "Save";
    projectsList.title = project.title;
    projectsList.website = project.website;
    projectsList.desc = project.desc;
    projectsList.id = project.id;
  }
})


text:
Boilerstrap is a Wordpress Theme based on the Twenty Twelve theme by the WordPress team with Bootstrap, FontAwesome, Keypress.js, custom web fonts, and much more added.

## Getting Started with Boilerstrap

There are a few different ways you can use Boilerstrap: as a WordPress theme for your website, as a base to build your own custom WordPress theme, or as a framework to build a fully customized website or web application using Bootstrap.

## As a WordPress theme for your website

Currently Boilerstrap is not in the Wordpress extensions database so in order to use it on your website you'll need to download it to your computer and upload it to your website.

**1)** Download the latest version of the theme from Github: [http://getboilerstrap.com/latest.zip](http://getboilerstrap.com/latest.zip)

**2)** Upload the theme to WordPress from the admin control panel using these instructions: [Adding New Themes (The WordPress Codex)](https://codex.wordpress.org/Using_Themes#Adding_New_Themes)

**4)** Activate the theme in your WordPress admin control panel.

## As a framework to build your own custom WordPress theme

Boilerstrap is a minimalist WordPress theme based on the Twenty Twelve theme with Bootstrap, FontAwesome, Keypress.js, and more fully integrated. Boilerstrap helps save you time by coming with the support you want out of the box so you can focus on styling it how you want it and building your site, not worrying about making sure Bootstrap gets added to your theme. You can use Bootstrap classes anywhere in your layout (scaffolding), for presentation (buttons, labels, badges, headings, etc) and for interactivity (tabs, toggles, carousel, alerts, etc.) We've designed the site to be easy to customize while still being possible to keep up to date using Git. We aren't in the WordPress theme database yet, so for now you'll need to keep your core theme files up to date using Git.

**1)** Download the latest version of the theme from Github: [http://getboilerstrap.com/latest.zip](http://getboilerstrap.com/latest.zip)

**2)** Upload the theme to WordPress from the admin control panel using these instructions: [Adding New Themes (The WordPress Codex)](https://codex.wordpress.org/Using_Themes#Adding_New_Themes)

**4)** Activate the theme in your WordPress admin control panel.

**5)** Add your site-specific CSS to `css/custom.css`, which is included in the `.gitignore` file and won't be overwritten when you update Git

**6)** Site-specific code goes in `js/boilerstrap.js`

## As an easy way to build fully custom Bootstrap websites

**1)** Download the latest version of the theme from Github: [http://getboilerstrap.com/latest.zip](http://getboilerstrap.com/latest.zip)

**2)** Upload the theme to WordPress from the admin control panel using these instructions: [Adding New Themes (The WordPress Codex)](https://codex.wordpress.org/Using_Themes#Adding_New_Themes)

**4)** Activate the theme in your WordPress admin control panel.

**5)** Install the [Advanced Custom Fields](http://www.advancedcustomfields.com/) plugin for WordPress which allows you to build very versatile layouts using custom fields applied to posts and pages using easy to configure logic.

**6)** Design a custom page template for each page you want in your website or application and store them in the `page-templates/` folder. You can use Bootstrap's CSS classes and Javascript plugins in the design of your page templates. Put all your custom JavaScript in `js/boilerstrap.js`. Tooltips and Popovers have already been initiated.

**7)** Use the Advanced Custom Fields plugin to build a set of input fields for each page or post-type you need on your site.

**8)** Now when the users update WordPress they will update each page specifically with the content they want to put on that layout specifically.

This is an easy way to quickly build a Bootstrap-powered website using WordPress as a content management system which is a great platform for a variety of wonderful plugins, and has advantages like site search, user-logins, and automatically-generated content feeds.


text: from parsing.get_fields import *


text:
namespace butil {
namespace debug {

#ifndef ENABLE_LEAK_TRACKER

// If leak tracking is disabled, do nothing.
template<typename T>
class LeakTracker {
 public:
  ~LeakTracker() {}
  static void CheckForLeaks() {}
  static int NumLiveInstances() { return -1; }
};

#else

// If leak tracking is enabled we track where the object was allocated from.

template<typename T>
class LeakTracker : public LinkNode<LeakTracker<T> > {
 public:
  LeakTracker() {
    instances()->Append(this);
  }

  ~LeakTracker() {
    this->RemoveFromList();
  }

  static void CheckForLeaks() {
    // Walk the allocation list and print each entry it contains.
    size_t count = 0;

    // Copy the first 3 leak allocation callstacks onto the stack.
    // This way if we hit the CHECK() in a release build, the leak
    // information will be available in mini-dump.
    const size_t kMaxStackTracesToCopyOntoStack = 3;
    StackTrace stacktraces[kMaxStackTracesToCopyOntoStack];

    for (LinkNode<LeakTracker<T> >* node = instances()->head();
         node != instances()->end();
         node = node->next()) {
      StackTrace& allocation_stack = node->value()->allocation_stack_;

      if (count < kMaxStackTracesToCopyOntoStack)
        stacktraces[count] = allocation_stack;

      ++count;
      std::ostringstream err;
      err << "Leaked " << node << " which was allocated by:";
      allocation_stack.OutputToStream(&err);
      LOG(ERROR) << err.str();
    }

    CHECK_EQ(0u, count);

    // Hack to keep |stacktraces| and |count| alive (so compiler
    // doesn't optimize it out, and it will appear in mini-dumps).
    if (count == 0x1234) {
      for (size_t i = 0; i < kMaxStackTracesToCopyOntoStack; ++i)
        stacktraces[i].Print();
    }
  }

  static int NumLiveInstances() {
    // Walk the allocation list and count how many entries it has.
    int count = 0;
    for (LinkNode<LeakTracker<T> >* node = instances()->head();
         node != instances()->end();
         node = node->next()) {
      ++count;
    }
    return count;
  }

 private:
  // Each specialization of LeakTracker gets its own static storage.
  static LinkedList<LeakTracker<T> >* instances() {
    static LinkedList<LeakTracker<T> > list;
    return &list;
  }

  StackTrace allocation_stack_;
};

#endif  // ENABLE_LEAK_TRACKER

}  // namespace debug
}  // namespace butil

#endif  // BUTIL_DEBUG_LEAK_TRACKER_H_


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/autofill/payments/card_unmask_otp_input_dialog_controller_impl.h"

#include <string>

#include "chrome/browser/ui/autofill/payments/card_unmask_otp_input_dialog_view.h"
#include "components/autofill/core/browser/metrics/autofill_metrics.h"
#include "components/autofill/core/browser/payments/otp_unmask_result.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "ui/base/l10n/l10n_util.h"

namespace autofill {

CardUnmaskOtpInputDialogControllerImpl::
    ~CardUnmaskOtpInputDialogControllerImpl() {
  // This part of code is executed only if the browser window is closed when the
  // dialog is visible. In this case the controller is destroyed before
  // CardUnmaskOtpInputDialogViews::dtor() is called, but the reference to
  // controller is not reset. This resets the reference via
  // CardUnmaskOtpInputDialogView::Dismiss() to avoid
  // a crash.
  if (dialog_view_)
    dialog_view_->Dismiss(/*show_confirmation_before_closing=*/false,
                          /*user_closed_dialog=*/true);
}

void CardUnmaskOtpInputDialogControllerImpl::ShowDialog(
    size_t otp_length,
    base::WeakPtr<OtpUnmaskDelegate> delegate) {
  if (dialog_view_)
    return;

  otp_length_ = otp_length;
  delegate_ = delegate;
  dialog_view_ =
      CardUnmaskOtpInputDialogView::CreateAndShow(this, web_contents());

  DCHECK(dialog_view_);
  AutofillMetrics::LogOtpInputDialogShown();
}

void CardUnmaskOtpInputDialogControllerImpl::OnOtpVerificationResult(
    OtpUnmaskResult result) {
  switch (result) {
    case OtpUnmaskResult::kSuccess:
      dialog_view_->Dismiss(/*show_confirmation_before_closing=*/true,
                            /*user_closed_dialog=*/false);
      break;
    case OtpUnmaskResult::kPermanentFailure:
      dialog_view_->Dismiss(/*show_confirmation_before_closing=*/false,
                            /*user_closed_dialog=*/false);
      break;
    case OtpUnmaskResult::kOtpExpired:
    case OtpUnmaskResult::kOtpMismatch:
      temporary_error_shown_ = true;
      AutofillMetrics::LogOtpInputDialogErrorMessageShown(
          result == OtpUnmaskResult::kOtpMismatch
              ? AutofillMetrics::OtpInputDialogError::kOtpMismatchError
              : AutofillMetrics::OtpInputDialogError::kOtpExpiredError);
      ShowInvalidState(result);
      break;
    case OtpUnmaskResult::kUnknownType:
      NOTREACHED();
      break;
  }
}

void CardUnmaskOtpInputDialogControllerImpl::OnDialogClosed(
    bool user_closed_dialog,
    bool server_request_succeeded) {
  if (delegate_)
    delegate_->OnUnmaskPromptClosed(user_closed_dialog);

  if (user_closed_dialog) {
    AutofillMetrics::LogOtpInputDialogResult(
        ok_button_clicked_ ? AutofillMetrics::OtpInputDialogResult::
                                 kDialogCancelledByUserAfterConfirmation
                           : AutofillMetrics::OtpInputDialogResult::
                                 kDialogCancelledByUserBeforeConfirmation,
        temporary_error_shown_);
  } else if (server_request_succeeded) {
    AutofillMetrics::LogOtpInputDialogResult(
        AutofillMetrics::OtpInputDialogResult::
            kDialogClosedAfterVerificationSucceeded,
        temporary_error_shown_);
  } else {
    AutofillMetrics::LogOtpInputDialogResult(
        AutofillMetrics::OtpInputDialogResult::
            kDialogClosedAfterVerificationFailed,
        temporary_error_shown_);
  }

  // Resets the variables to their initial states since the controller will stay
  // even if the view is gone.
  dialog_view_ = nullptr;
  temporary_error_shown_ = false;
  ok_button_clicked_ = false;
}

void CardUnmaskOtpInputDialogControllerImpl::OnOkButtonClicked(
    const std::u16string& otp) {
  ok_button_clicked_ = true;
  if (delegate_)
    delegate_->OnUnmaskPromptAccepted(otp);
}

void CardUnmaskOtpInputDialogControllerImpl::OnNewCodeLinkClicked() {
  if (delegate_)
    delegate_->OnNewOtpRequested();

  AutofillMetrics::LogOtpInputDialogNewOtpRequested();
}

std::u16string CardUnmaskOtpInputDialogControllerImpl::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(
      IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_TITLE);
}

std::u16string
CardUnmaskOtpInputDialogControllerImpl::GetTextfieldPlaceholderText() const {
  return l10n_util::GetStringFUTF16(
      IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_TEXTFIELD_PLACEHOLDER_MESSAGE,
      base::NumberToString16(otp_length_));
}

#if defined(OS_ANDROID)
int CardUnmaskOtpInputDialogControllerImpl::GetExpectedOtpLength() const {
  return otp_length_;
}
#endif  // OS_ANDROID

bool CardUnmaskOtpInputDialogControllerImpl::IsValidOtp(
    const std::u16string& otp) const {
  return otp.length() == otp_length_ &&
         base::ContainsOnlyChars(otp,
                                 /*characters=*/u"0123456789");
}

FooterText CardUnmaskOtpInputDialogControllerImpl::GetFooterText(
    const std::u16string& link_text) const {
  size_t link_offset;
  std::u16string text = l10n_util::GetStringFUTF16(
      IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_FOOTER_MESSAGE, link_text,
      &link_offset);
  return {text, link_offset};
}

std::u16string CardUnmaskOtpInputDialogControllerImpl::GetNewCodeLinkText()
    const {
  return l10n_util::GetStringUTF16(
      IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_NEW_CODE_MESSAGE);
}

std::u16string CardUnmaskOtpInputDialogControllerImpl::GetOkButtonLabel()
    const {
  return l10n_util::GetStringUTF16(IDS_AUTOFILL_CARD_UNMASK_CONFIRM_BUTTON);
}

std::u16string CardUnmaskOtpInputDialogControllerImpl::GetProgressLabel()
    const {
  return l10n_util::GetStringUTF16(
      IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_PENDING_MESSAGE);
}

std::u16string CardUnmaskOtpInputDialogControllerImpl::GetConfirmationMessage()
    const {
  return l10n_util::GetStringUTF16(
      IDS_AUTOFILL_CARD_UNMASK_VERIFICATION_SUCCESS);
}

CardUnmaskOtpInputDialogControllerImpl::CardUnmaskOtpInputDialogControllerImpl(
    content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      content::WebContentsUserData<CardUnmaskOtpInputDialogControllerImpl>(
          *web_contents) {}

void CardUnmaskOtpInputDialogControllerImpl::ShowInvalidState(
    OtpUnmaskResult otp_unmask_result) {
  if (!dialog_view_)
    return;

  switch (otp_unmask_result) {
    case OtpUnmaskResult::kOtpExpired:
      dialog_view_->ShowInvalidState(l10n_util::GetStringUTF16(
          IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_VERIFICATION_CODE_EXPIRED_LABEL));
      break;
    case OtpUnmaskResult::kOtpMismatch:
      dialog_view_->ShowInvalidState(l10n_util::GetStringUTF16(
          IDS_AUTOFILL_CARD_UNMASK_OTP_INPUT_DIALOG_ENTER_CORRECT_CODE_LABEL));
      break;
    case OtpUnmaskResult::kSuccess:
    case OtpUnmaskResult::kPermanentFailure:
    case OtpUnmaskResult::kUnknownType:
      NOTREACHED();
  }
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(CardUnmaskOtpInputDialogControllerImpl);

}  // namespace autofill


text:
var redtape = require('redtape'),
    fs = require('fs'),
    path = require('path'),
    jpeg = require('..');

var it = redtape({
  asserts: {
    bufferEqual: function (a, b) {
      if (a.length != b.length) return false;
      for (var i = 0, len = a.length; i < len; i++) {
        if (a[i] !== b[i]) return false;
      }
      return true;
    }
  }
});

function fixture(name) {
  return fs.readFileSync(path.join(__dirname, 'fixtures', name));
}

it('should be able to decode a JPEG', function(t) {
  var jpegData = fixture('grumpycat.jpg');
  var rawImageData = jpeg.decode(jpegData);
  t.equal(rawImageData.width, 320);
  t.equal(rawImageData.height, 180);
  var expected = fixture('grumpycat.rgba');
  t.deepEqual(rawImageData.data, expected);
  t.end();
});

it('should be able to decode a JPEG with RST intervals', function(t) {
  var jpegData = fixture('redbox-with-rst.jpg');
  var rawImageData = jpeg.decode(jpegData);
  var expected = fixture('redbox.jpg');
  var rawExpectedImageData = jpeg.decode(expected);
  t.deepEqual(rawImageData.data, rawExpectedImageData.data);
  t.end();
});

it('should be able to decode a grayscale JPEG', function(t) {
  var jpegData = fixture('apsara.jpg');
  var rawImageData = jpeg.decode(jpegData);
  t.equal(rawImageData.width, 580);
  t.equal(rawImageData.height, 599);
  var expected = fixture('apsara.rgba');
  t.deepEqual(rawImageData.data, expected);
  t.end();
});

it('should be able to decode a unconventional table JPEG', function (t) {
  var jpegData = fixture('unconventional-table.jpg');
  var rawImageData = jpeg.decode(jpegData);
  t.equal(rawImageData.width, 1920);
  t.equal(rawImageData.height, 1200);
  t.end();
});

it('should be able to encode a JPEG', function (t) {
  var frameData = fixture('grumpycat.rgba');
  var rawImageData = {
    data: frameData,
    width: 320,
    height: 180
  };
  var jpegImageData = jpeg.encode(rawImageData, 50);
  t.equal(jpegImageData.width, 320);
  t.equal(jpegImageData.height, 180);
  var expected = fixture('grumpycat-50.jpg');
  t.deepEqual(jpegImageData.data, expected);
  t.end();
});

it('should be able to create a JPEG from an array', function (t) {
  var width = 320, height = 180;
  var frameData = new Buffer(width * height * 4);
  var i = 0;
  while (i < frameData.length) {
    frameData[i++] = 0xFF; // red
    frameData[i++] = 0x00; // green
    frameData[i++] = 0x00; // blue
    frameData[i++] = 0xFF; // alpha - ignored in JPEGs
  }
  var rawImageData = {
    data: frameData,
    width: width,
    height: height
  };
  var jpegImageData = jpeg.encode(rawImageData, 50);
  t.equal(jpegImageData.width, width);
  t.equal(jpegImageData.height, height);
  var expected = fixture('redbox.jpg');
  t.bufferEqual(jpegImageData.data, expected);
  t.end();
});


text:
/* Author: Dave Coleman, Michael 'v4hn' Goerner */

// Qt
#include <QVBoxLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QApplication>
#include <QSplitter>
// ROS
#include "author_information_widget.h"
#include <srdfdom/model.h>  // use their struct datastructures
#include <ros/ros.h>
// Boost
#include <boost/algorithm/string.hpp>  // for trimming whitespace from user input
#include <boost/filesystem.hpp>        // for creating folders/files
// Read write files
#include <iostream>  // For writing yaml and launch files
#include <fstream>

namespace moveit_setup_assistant
{
// Boost file system
namespace fs = boost::filesystem;

// ******************************************************************************************
// Outer User Interface for MoveIt Configuration Assistant
// ******************************************************************************************
AuthorInformationWidget::AuthorInformationWidget(QWidget* parent,
                                                 moveit_setup_assistant::MoveItConfigDataPtr config_data)
  : SetupScreenWidget(parent), config_data_(config_data)
{
  // Basic widget container
  QVBoxLayout* layout = new QVBoxLayout();
  layout->setAlignment(Qt::AlignTop);

  // Top Header Area ------------------------------------------------

  HeaderWidget* header =
      new HeaderWidget("Author Information", "Specify contact information of the author and initial maintainer of the "
                                             "generated package. catkin requires valid details in the package's "
                                             "package.xml",
                       this);
  layout->addWidget(header);

  QLabel* name_title = new QLabel(this);
  name_title->setText("Name of the maintainer this MoveIt! configuration:");
  layout->addWidget(name_title);

  name_edit_ = new QLineEdit(this);
  connect(name_edit_, SIGNAL(editingFinished()), this, SLOT(edited_name()));
  layout->addWidget(name_edit_);

  QLabel* email_title = new QLabel(this);
  email_title->setText("Email of the maintainer of this MoveIt! configuration:");
  layout->addWidget(email_title);

  email_edit_ = new QLineEdit(this);
  connect(email_edit_, SIGNAL(editingFinished()), this, SLOT(edited_email()));
  layout->addWidget(email_edit_);

  // Finish Layout --------------------------------------------------
  this->setLayout(layout);
}

// ******************************************************************************************
// Called when setup assistant navigation switches to this screen
// ******************************************************************************************
void AuthorInformationWidget::focusGiven()
{
  // Allow list box to populate
  this->name_edit_->setText(QString::fromStdString(config_data_->author_name_));
  this->email_edit_->setText(QString::fromStdString(config_data_->author_email_));
}

void AuthorInformationWidget::edited_name()
{
  config_data_->author_name_ = this->name_edit_->text().toStdString();
  config_data_->changes |= MoveItConfigData::AUTHOR_INFO;
}

void AuthorInformationWidget::edited_email()
{
  config_data_->author_email_ = this->email_edit_->text().toStdString();
  config_data_->changes |= MoveItConfigData::AUTHOR_INFO;
}

}  // namespace


text:
<?php

namespace Checkout\Models\Payments;

use Checkout\Models\Product;

/**
 * Payment method Fawry.
 *
 * @category SDK
 * @package  Checkout.com
 * @author   Platforms Development Team <platforms@checkout.com>
 * @license  https://opensource.org/licenses/mit-license.html MIT License
 * @link     https://docs.checkout.com/
 */
class FawrySource extends Source
{

    /**
     * Qualified name of the class.
     *
     * @var string
     */
    const QUALIFIED_NAME = __CLASS__;

    /**
     * Name of the model.
     *
     * @var string
     */
    const MODEL_NAME = 'fawry';

    /**
     * Magic Methods
     */

    /**
     * Initialise payment Fawry.
     *
     * @param      string       $email          The customer's email address.
     * @param      string       $mobile         The customer's mobile number.
     * @param      string       $description    The description of the payment.
     * @param      Product[]    $products       This object is passed directly to Fawry as products.
     */
    public function __construct($email, $mobile, $description, array $products)
    {
        $this->type = static::MODEL_NAME;
        $this->customer_email = $email;
        $this->customer_mobile = $mobile;
        $this->description = $description;
        $this->products = $products;
    }
}


text:
// EasyHook (File: EasyHookDll\driver.cpp)
//
// Copyright (c) 2009 Christoph Husse & Copyright (c) 2015 Justin Stenning
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Please visit https://easyhook.github.io for more information
// about the project and latest updates.

#include "stdafx.h"

EASYHOOK_NT_EXPORT RhInstallDriver(
			WCHAR* InDriverPath,
			WCHAR* InDriverName)
{
/*
Description:

	Installs the given driver.

Parameters:

	- InDriverPath

		A relative or full path to the driver's executable

	- InDriverName

		A name to register the driver in the service control manager.

*/
	WCHAR				DriverPath[MAX_PATH + 1];
	SC_HANDLE			hSCManager = NULL;
	SC_HANDLE			hService = NULL;
	NTSTATUS			NtStatus;

	GetFullPathNameW(InDriverPath, MAX_PATH, DriverPath, NULL);

	if(!RtlFileExists(DriverPath))
		THROW(STATUS_NOT_FOUND, L"The EasyHook driver file does not exist.");

	if((hSCManager = OpenSCManagerW(
			NULL,
			NULL,
			SC_MANAGER_ALL_ACCESS)) == NULL)
		THROW(STATUS_ACCESS_DENIED, L"Unable to open service control manager. Are you running as administrator?");

	// does service exist?
	if((hService = OpenService(
			hSCManager,
			InDriverName,
			SERVICE_ALL_ACCESS)) == NULL)
	{
		if(GetLastError() != ERROR_SERVICE_DOES_NOT_EXIST)
			THROW(STATUS_INTERNAL_ERROR, L"An unknown error has occurred during driver installation.");

		// Create the service
		if((hService = CreateServiceW(
				hSCManager,
				InDriverName,
				InDriverName,
				SERVICE_ALL_ACCESS,
				SERVICE_KERNEL_DRIVER,
				SERVICE_DEMAND_START,
				SERVICE_ERROR_NORMAL,
				DriverPath,
				NULL, NULL, NULL, NULL, NULL)) == NULL)
			THROW(STATUS_INTERNAL_ERROR, L"Unable to install driver.");
	}

	// start and connect service...
	if(!StartServiceW(hService, 0, NULL) && (GetLastError() != ERROR_SERVICE_ALREADY_RUNNING)
			&& (GetLastError() != ERROR_SERVICE_DISABLED))
		THROW(STATUS_INTERNAL_ERROR, L"Unable to start driver!");

	RETURN;

THROW_OUTRO:
FINALLY_OUTRO:
	{
		if(hService != NULL)
		{
			DeleteService(hService);

			CloseServiceHandle(hService);
		}

		if(hSCManager != NULL)
			CloseServiceHandle(hSCManager);

		return NtStatus;
	}
}

EASYHOOK_NT_EXPORT RhInstallSupportDriver()
{
/*
Description:

    Installs the EasyHook support driver.
	This will allow your driver to successfully obtain the EasyHook driver
	API using EasyHookQueryInterface().

*/
	WCHAR*				DriverName = L"EasyHook32Drv.sys";

	if(RhIsX64System())
		DriverName = L"EasyHook64Drv.sys";

	return RhInstallDriver(DriverName, DriverName);
}


text:
layout: post
title:  Baby steps with Ruby/CocoaPods for iOS and Swift
date:   2016-09-23 04:00:29
categories: iOS
subclass: 'post'
navigation: True
logo: 'assets/images/ghost.png'
---

Ruby was such a sweat to install. In the end I opted to use rvm to install and manage Ruby.

In terminal, type the following to download and install rvm (Ruby Version Manager)
```
  $ curl -sSL https://get.rvm.io | bash -s stable --ruby
```

check installed with `rvm list`

```
  $ rvm list
  rvm rubies
  =* ruby-2.3.0 [ x86_64 ]
  # => - current
  # =* - current && default
  #  * - default
```

if you switch versions, use the following to set a default
```
  $ rvm use 2.3.0 --default
```

In your terminal session you should then be able to check your rby and gem versions. For CocoaPods, you'll need at least version 2.2 of Ruby.
```
  $ ruby -v
  ruby 2.3.0p0 (2015-12-25 revision
  $ gem -v
  2.5.1
```

Install CocoaPods with
```
  $ sudo gem install cocoapods
```

cd into your project directly and ensure there is a PodFile. You can now run the pod install (or pod update) command
```
  $ pod install
```

Open up your project in xcode and you should be good to go!!