text:
CGFloat SVProgressHUDRingRadius = 14;
CGFloat SVProgressHUDRingThickness = 6;

@interface SVProgressHUD ()

@property (nonatomic, readwrite) SVProgressHUDMaskType maskType;
@property (nonatomic, strong, readonly) NSTimer *fadeOutTimer;

@property (nonatomic, strong, readonly) UIWindow *overlayWindow;
@property (nonatomic, strong, readonly) UIView *hudView;
@property (nonatomic, strong, readonly) UILabel *stringLabel;
@property (nonatomic, strong, readonly) UIImageView *imageView;
@property (nonatomic, strong, readonly) UIActivityIndicatorView *spinnerView;

@property (nonatomic, readwrite) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *backgroundRingLayer;
@property (nonatomic, strong) CAShapeLayer *ringLayer;

@property (nonatomic, readonly) CGFloat visibleKeyboardHeight;

- (void)showProgress:(CGFloat)progress
              status:(NSString*)string
            maskType:(SVProgressHUDMaskType)hudMaskType;

- (void)showImage:(UIImage*)image
           status:(id)status
         duration:(NSTimeInterval)duration;

- (void)dismiss;

- (void)setStatus:(NSString*)string;
- (void)registerNotifications;
- (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle;
- (void)positionHUD:(NSNotification*)notification;

#if __IPHONE_OS_VERSION_MIN_REQUIRED < 50000
- (UIColor *)hudBackgroundColor;
- (UIColor *)hudForegroundColor;
- (UIColor *)hudStatusShadowColor;
- (UIFont *)hudFont;
#endif

@end

@implementation SVProgressHUD

@synthesize overlayWindow, hudView, maskType, fadeOutTimer, stringLabel, imageView, spinnerView, visibleKeyboardHeight;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
@synthesize hudBackgroundColor = _uiHudBgColor;
@synthesize hudForegroundColor = _uiHudFgColor;
@synthesize hudStatusShadowColor = _uiHudStatusShColor;
@synthesize hudFont = _uiHudFont;
#endif

+ (SVProgressHUD*)sharedView {
    static dispatch_once_t once;
    static SVProgressHUD *sharedView;
    dispatch_once(&once, ^ { sharedView = [[SVProgressHUD alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; });
    return sharedView;
}

+ (void)setStatus:(NSString *)string {
	[[SVProgressHUD sharedView] setStatus:string];
}

#pragma mark - Show Methods

+ (void)show {
    [[SVProgressHUD sharedView] showProgress:-1 status:nil maskType:SVProgressHUDMaskTypeNone];
}

+ (void)showWithStatus:(NSString *)status {
    [[SVProgressHUD sharedView] showProgress:-1 status:status maskType:SVProgressHUDMaskTypeNone];
}

+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType {
    [[SVProgressHUD sharedView] showProgress:-1 status:nil maskType:maskType];
}

+ (void)showWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {
    [[SVProgressHUD sharedView] showProgress:-1 status:status maskType:maskType];
}

+ (void)showProgress:(CGFloat)progress {
    [[SVProgressHUD sharedView] showProgress:progress status:nil maskType:SVProgressHUDMaskTypeNone];
}

+ (void)showProgress:(CGFloat)progress status:(NSString *)status {
    [[SVProgressHUD sharedView] showProgress:progress status:status maskType:SVProgressHUDMaskTypeNone];
}

+ (void)showProgress:(CGFloat)progress status:(NSString *)status maskType:(SVProgressHUDMaskType)maskType {
    [[SVProgressHUD sharedView] showProgress:progress status:status maskType:maskType];
}

#pragma mark - Show then dismiss methods

+ (void)showSuccessWithStatus:(id)string {
    [SVProgressHUD showImage:[UIImage imageNamed:@"HUD Success"] status:string];
}

+ (void)showErrorWithStatus:(id)string {
    [SVProgressHUD showImage:[UIImage imageNamed:@"HUD Error"] status:string];
}

+ (void)showImage:(UIImage *)image status:(id)string {
    [SVProgressHUD showImage:image status:string duration:1.0];
}

+ (void)showImage:(UIImage *)image status:(id)status duration:(NSTimeInterval)duration {
    [[SVProgressHUD sharedView] showImage:image status:status duration:duration];
}

#pragma mark - Dismiss Methods

+ (void)dismiss {
	[[SVProgressHUD sharedView] dismiss];
}

#pragma mark - Instance Methods

- (id)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {
		self.userInteractionEnabled = NO;
        self.backgroundColor = [UIColor clearColor];
		self.alpha = 0;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }

    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    switch (self.maskType) {

        case SVProgressHUDMaskTypeBlack: {
            [[UIColor colorWithWhite:0 alpha:0.5] set];
            CGContextFillRect(context, self.bounds);
            break;
        }

        case SVProgressHUDMaskTypeGradient: {

            size_t locationsCount = 2;
            CGFloat locations[2] = {0.0f, 1.0f};
            CGFloat colors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f};
            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, locationsCount);
            CGColorSpaceRelease(colorSpace);

            CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
            float radius = MIN(self.bounds.size.width , self.bounds.size.height) ;
            CGContextDrawRadialGradient (context, gradient, center, 0, center, radius, kCGGradientDrawsAfterEndLocation);
            CGGradientRelease(gradient);

            break;
        }
    }
}

- (void)updatePosition {

    CGFloat hudWidth = 100;
    CGFloat hudHeight = 100;
    CGFloat stringWidth = 0;
    CGFloat stringHeight = 0;
    CGRect labelRect = CGRectZero;

    NSString *string = self.stringLabel.text;
    // False if it's text-only
    BOOL imageUsed = (self.imageView.image) || (self.imageView.hidden);

    if(string) {
        CGSize stringSize = [string boundingRectWithSize:CGSizeMake(200, 300)
                                                 options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                              attributes:@{ NSFontAttributeName : self.stringLabel.font }
                                                 context:nil].size;
        stringWidth = stringSize.width;
        stringHeight = stringSize.height;
        if (imageUsed)
            hudHeight = 110+stringHeight;
        else
            hudHeight = 20+stringHeight;

        if(stringWidth > hudWidth)
            hudWidth = ceil(stringWidth/2)*2;

        CGFloat labelRectY = imageUsed ? 86 : 9;

        if(hudHeight > 100) {
            labelRect = CGRectMake(12, labelRectY, hudWidth, stringHeight);
            hudWidth+=24;
        } else {
            hudWidth+=24;
            labelRect = CGRectMake(0, labelRectY, hudWidth, stringHeight);
        }
    }

	self.hudView.bounds = CGRectMake(0, 0, hudWidth, hudHeight);

    if(string)
        self.imageView.center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, 50);
	else
       	self.imageView.center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, CGRectGetHeight(self.hudView.bounds)/2);

	self.stringLabel.hidden = NO;
	self.stringLabel.frame = labelRect;

	if(string) {
		self.spinnerView.center = CGPointMake(ceil(CGRectGetWidth(self.hudView.bounds)/2)+0.5, 40.5);

        if(self.progress != -1)
            self.backgroundRingLayer.position = self.ringLayer.position = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), 36);
	}
    else {
		self.spinnerView.center = CGPointMake(ceil(CGRectGetWidth(self.hudView.bounds)/2)+0.5, ceil(self.hudView.bounds.size.height/2)+0.5);

        if(self.progress != -1)
            self.backgroundRingLayer.position = self.ringLayer.position = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), CGRectGetHeight(self.hudView.bounds)/2);
    }

}

- (void)setStatus:(NSString *)string {

	self.stringLabel.text = string;
    [self updatePosition];

}

- (void)setFadeOutTimer:(NSTimer *)newTimer {

    if(fadeOutTimer)
        [fadeOutTimer invalidate], fadeOutTimer = nil;

    if(newTimer)
        fadeOutTimer = newTimer;
}

- (void)registerNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(positionHUD:)
                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(positionHUD:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(positionHUD:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(positionHUD:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(positionHUD:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
}

- (void)positionHUD:(NSNotification*)notification {

    CGFloat keyboardHeight;
    double animationDuration;

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    if(notification) {
        NSDictionary* keyboardInfo = [notification userInfo];
        CGRect keyboardFrame = [[keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
        animationDuration = [[keyboardInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

        if(notification.name == UIKeyboardWillShowNotification || notification.name == UIKeyboardDidShowNotification) {
            if(UIInterfaceOrientationIsPortrait(orientation))
                keyboardHeight = keyboardFrame.size.height;
            else
                keyboardHeight = keyboardFrame.size.width;
        } else
            keyboardHeight = 0;
    } else {
        keyboardHeight = self.visibleKeyboardHeight;
    }

    CGRect orientationFrame = [UIScreen mainScreen].bounds;
    CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;

    if(UIInterfaceOrientationIsLandscape(orientation)) {
        float temp = orientationFrame.size.width;
        orientationFrame.size.width = orientationFrame.size.height;
        orientationFrame.size.height = temp;

        temp = statusBarFrame.size.width;
        statusBarFrame.size.width = statusBarFrame.size.height;
        statusBarFrame.size.height = temp;
    }

    CGFloat activeHeight = orientationFrame.size.height;

    if(keyboardHeight > 0)
        activeHeight += statusBarFrame.size.height*2;

    activeHeight -= keyboardHeight;
    CGFloat posY = floor(activeHeight*0.45);
    CGFloat posX = orientationFrame.size.width/2;

    CGPoint newCenter;
    CGFloat rotateAngle;

    switch (orientation) {
        case UIInterfaceOrientationPortraitUpsideDown:
            rotateAngle = M_PI;
            newCenter = CGPointMake(posX, orientationFrame.size.height-posY);
            break;
        case UIInterfaceOrientationLandscapeLeft:
            rotateAngle = -M_PI/2.0f;
            newCenter = CGPointMake(posY, posX);
            break;
        case UIInterfaceOrientationLandscapeRight:
            rotateAngle = M_PI/2.0f;
            newCenter = CGPointMake(orientationFrame.size.height-posY, posX);
            break;
        default: // as UIInterfaceOrientationPortrait
            rotateAngle = 0.0;
            newCenter = CGPointMake(posX, posY);
            break;
    }

    if(notification) {
        [UIView animateWithDuration:animationDuration
                              delay:0
                            options:UIViewAnimationOptionAllowUserInteraction
                         animations:^{
                             [self moveToPoint:newCenter rotateAngle:rotateAngle];
                         } completion:NULL];
    }

    else {
        [self moveToPoint:newCenter rotateAngle:rotateAngle];
    }

}

- (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle {
    self.hudView.transform = CGAffineTransformMakeRotation(angle);
    self.hudView.center = newCenter;
}

#pragma mark - Master show/dismiss methods

- (void)showProgress:(CGFloat)progress status:(NSString*)string maskType:(SVProgressHUDMaskType)hudMaskType {
    if(!self.superview)
        [self.overlayWindow addSubview:self];

    self.fadeOutTimer = nil;
    self.imageView.hidden = YES;
    self.maskType = hudMaskType;
    self.progress = progress;

    self.stringLabel.text = string;
    [self updatePosition];

    if(progress >= 0) {
        self.imageView.image = nil;
        self.imageView.hidden = NO;
        [self.spinnerView stopAnimating];
        self.ringLayer.strokeEnd = progress;
    }
    else {
        [self cancelRingLayerAnimation];
        [self.spinnerView startAnimating];
    }

    if(self.maskType != SVProgressHUDMaskTypeNone) {
        self.overlayWindow.userInteractionEnabled = YES;
        self.accessibilityLabel = string;
        self.isAccessibilityElement = YES;
    }
    else {
        self.overlayWindow.userInteractionEnabled = NO;
        self.hudView.accessibilityLabel = string;
        self.hudView.isAccessibilityElement = YES;
    }

    [self.overlayWindow setHidden:NO];
    [self positionHUD:nil];

    if(self.alpha != 1) {
        [self registerNotifications];
        self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1.3, 1.3);

        [UIView animateWithDuration:0.15
                              delay:0
                            options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1/1.3, 1/1.3);
                             self.alpha = 1;
                         }
                         completion:^(BOOL finished){
                             UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, string);
                         }];

        [self setNeedsDisplay];
    }
}

- (void)showImage:(UIImage *)image status:(id)string duration:(NSTimeInterval)duration {
    self.progress = -1;
    [self cancelRingLayerAnimation];

    if(![SVProgressHUD isVisible])
        [SVProgressHUD show];

    self.maskType = SVProgressHUDMaskTypeClear;
    self.overlayWindow.userInteractionEnabled = YES;

    self.imageView.image = image;
    self.imageView.hidden = NO;
    if ([string isKindOfClass:[NSAttributedString class]]) {
        self.stringLabel.attributedText = string;
    } else {
        self.stringLabel.text = string;
    }
    [self updatePosition];
    [self.spinnerView stopAnimating];

    self.fadeOutTimer = [NSTimer timerWithTimeInterval:duration target:self selector:@selector(dismiss) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:self.fadeOutTimer forMode:NSRunLoopCommonModes];
}

- (void)dismiss {
    [UIView animateWithDuration:0.15
                          delay:0
                        options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8, 0.8);
                         self.alpha = 0;
                     }
                     completion:^(BOOL finished){
                         if(self.alpha == 0) {
                             [[NSNotificationCenter defaultCenter] removeObserver:self];
                             [self cancelRingLayerAnimation];
                             [hudView removeFromSuperview];
                             hudView = nil;

                             [overlayWindow removeFromSuperview];
                             overlayWindow = nil;

                             // fixes bug where keyboard wouldn't return as keyWindow upon dismissal of HUD
                             [[UIApplication sharedApplication].windows enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id window, NSUInteger idx, BOOL *stop) {
                                 if([window isMemberOfClass:[UIWindow class]]) {
                                     [window makeKeyWindow];
                                     *stop = YES;
                                 }
                             }];

                             UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                             // uncomment to make sure UIWindow is gone from app.windows
                             //NSLog(@"%@", [UIApplication sharedApplication].windows);
                             //NSLog(@"keyWindow = %@", [UIApplication sharedApplication].keyWindow);
                         }
                     }];
}

#pragma mark -
#pragma mark Ring progress animation

- (CAShapeLayer *)ringLayer {
    if(!_ringLayer) {
        CGPoint center = CGPointMake(CGRectGetWidth(hudView.frame)/2, CGRectGetHeight(hudView.frame)/2);
        _ringLayer = [self createRingLayerWithCenter:center radius:SVProgressHUDRingRadius lineWidth:SVProgressHUDRingThickness color:[UIColor whiteColor]];
        [self.hudView.layer addSublayer:_ringLayer];
    }
    return _ringLayer;
}

- (CAShapeLayer *)backgroundRingLayer {
    if(!_backgroundRingLayer) {
        CGPoint center = CGPointMake(CGRectGetWidth(hudView.frame)/2, CGRectGetHeight(hudView.frame)/2);
        _backgroundRingLayer = [self createRingLayerWithCenter:center radius:SVProgressHUDRingRadius lineWidth:SVProgressHUDRingThickness color:[UIColor darkGrayColor]];
        _backgroundRingLayer.strokeEnd = 1;
        [self.hudView.layer addSublayer:_backgroundRingLayer];
    }
    return _backgroundRingLayer;
}

- (void)cancelRingLayerAnimation {
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    [hudView.layer removeAllAnimations];

    _ringLayer.strokeEnd = 0.0f;
    if (_ringLayer.superlayer) {
        [_ringLayer removeFromSuperlayer];
    }
    _ringLayer = nil;

    if (_backgroundRingLayer.superlayer) {
        [_backgroundRingLayer removeFromSuperlayer];
    }
    _backgroundRingLayer = nil;

    [CATransaction commit];
}

- (CGPoint)pointOnCircleWithCenter:(CGPoint)center radius:(double)radius angleInDegrees:(double)angleInDegrees {
    float x = (float)(radius * cos(angleInDegrees * M_PI / 180)) + radius;
    float y = (float)(radius * sin(angleInDegrees * M_PI / 180)) + radius;
    return CGPointMake(x, y);
}

- (UIBezierPath *)createCirclePathWithCenter:(CGPoint)center radius:(CGFloat)radius sampleCount:(NSInteger)sampleCount {

    UIBezierPath *smoothedPath = [UIBezierPath bezierPath];
    CGPoint startPoint = [self pointOnCircleWithCenter:center radius:radius angleInDegrees:-90];

    [smoothedPath moveToPoint:startPoint];

    CGFloat delta = 360.0f/sampleCount;
    CGFloat angleInDegrees = -90;
    for (NSInteger i=1; i<sampleCount; i++) {
        angleInDegrees += delta;
        CGPoint point = [self pointOnCircleWithCenter:center radius:radius angleInDegrees:angleInDegrees];
        [smoothedPath addLineToPoint:point];
    }

    [smoothedPath addLineToPoint:startPoint];

    return smoothedPath;
}

- (CAShapeLayer *)createRingLayerWithCenter:(CGPoint)center radius:(CGFloat)radius lineWidth:(CGFloat)lineWidth color:(UIColor *)color {

    UIBezierPath *smoothedPath = [self createCirclePathWithCenter:center radius:radius sampleCount:72];

    CAShapeLayer *slice = [CAShapeLayer layer];
    slice.frame = CGRectMake(center.x-radius, center.y-radius, radius*2, radius*2);
    slice.fillColor = [UIColor clearColor].CGColor;
    slice.strokeColor = color.CGColor;
    slice.lineWidth = lineWidth;
    slice.lineCap = kCALineJoinBevel;
    slice.lineJoin = kCALineJoinBevel;
    slice.path = smoothedPath.CGPath;
    return slice;
}

#pragma mark - Utilities

+ (BOOL)isVisible {
    return ([SVProgressHUD sharedView].alpha == 1);
}

#pragma mark - Getters

- (UIWindow *)overlayWindow {
    if(!overlayWindow) {
        overlayWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        overlayWindow.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        overlayWindow.backgroundColor = [UIColor clearColor];
        overlayWindow.userInteractionEnabled = NO;
        overlayWindow.windowLevel = UIWindowLevelStatusBar;
    }
    return overlayWindow;
}

- (UIView *)hudView {
    if(!hudView) {
        hudView = [[UIView alloc] initWithFrame:CGRectZero];
        hudView.layer.cornerRadius = 10;

        // UIAppearance is used when iOS >= 5.0
		hudView.backgroundColor = self.hudBackgroundColor;

        hudView.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin |
                                    UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin);

        [self addSubview:hudView];
    }
    return hudView;
}

- (UILabel *)stringLabel {
    if (stringLabel == nil) {
        stringLabel = [[UILabel alloc] initWithFrame:CGRectZero];
		stringLabel.backgroundColor = [UIColor clearColor];
		stringLabel.adjustsFontSizeToFitWidth = YES;
		#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000
			stringLabel.textAlignment = UITextAlignmentCenter;
		#else
			stringLabel.textAlignment = NSTextAlignmentCenter;
		#endif
		stringLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

        // UIAppearance is used when iOS >= 5.0
		stringLabel.textColor = self.hudForegroundColor;
		stringLabel.font = self.hudFont;
		stringLabel.shadowColor = self.hudStatusShadowColor;

		stringLabel.shadowOffset = CGSizeMake(0, -1);
        stringLabel.numberOfLines = 0;
    }

    if(!stringLabel.superview)
        [self.hudView addSubview:stringLabel];

    return stringLabel;
}

- (UIImageView *)imageView {
    if (imageView == nil)
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

    if(!imageView.superview)
        [self.hudView addSubview:imageView];

    return imageView;
}

- (UIActivityIndicatorView *)spinnerView {
    if (spinnerView == nil) {
        spinnerView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		spinnerView.hidesWhenStopped = YES;
		spinnerView.bounds = CGRectMake(0, 0, 37, 37);

        // UIAppearance is used when iOS >= 5.0
        spinnerView.color = self.hudForegroundColor;
    }

    if(!spinnerView.superview)
        [self.hudView addSubview:spinnerView];

    return spinnerView;
}

- (CGFloat)visibleKeyboardHeight {

    UIWindow *keyboardWindow = nil;
    for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
        if(![[testWindow class] isEqual:[UIWindow class]]) {
            keyboardWindow = testWindow;
            break;
        }
    }

    for (__strong UIView *possibleKeyboard in [keyboardWindow subviews]) {
        if([possibleKeyboard isKindOfClass:NSClassFromString(@"UIPeripheralHostView")] || [possibleKeyboard isKindOfClass:NSClassFromString(@"UIKeyboard")])
            return possibleKeyboard.bounds.size.height;
    }

    return 0;
}

#pragma mark - UIAppearance getters

- (UIColor *)hudBackgroundColor {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
    if(_uiHudBgColor == nil) {
        _uiHudBgColor = [[[self class] appearance] hudBackgroundColor];
    }

    if(_uiHudBgColor != nil) {
        return _uiHudBgColor;
    }
#endif

    return [UIColor colorWithWhite:0 alpha:0.8];
}

- (UIColor *)hudForegroundColor {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
    if(_uiHudFgColor == nil) {
        _uiHudFgColor = [[[self class] appearance] hudForegroundColor];
    }

    if(_uiHudFgColor != nil) {
        return _uiHudFgColor;
    }
#endif

    return [UIColor whiteColor];
}

- (UIColor *)hudStatusShadowColor {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
    if(_uiHudStatusShColor == nil) {
        _uiHudStatusShColor = [[[self class] appearance] hudStatusShadowColor];
    }

    if(_uiHudStatusShColor != nil) {
        return _uiHudStatusShColor;
    }
#endif

    return [UIColor blackColor];
}

- (UIFont *)hudFont {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
    if(_uiHudFont == nil) {
        _uiHudFont = [[[self class] appearance] hudFont];
    }

    if(_uiHudFont != nil) {
        return _uiHudFont;
    }
#endif

    return [UIFont boldSystemFontOfSize:16];
}

@end


text:
/*
 * @test
 * @bug 8025290
 * @summary javac implicit versus explicit lambda compilation error
 * @compile ExplicitVSImplicitLambdaTest.java
 */

import java.util.function.*;

public class ExplicitVSImplicitLambdaTest {
    private void test()
    {
        /* in the explicit case "e" is inferred to String so we can use a String
         * only method.
         */
        MyComparator.mycomparing1((String e) -> e.concat(""));
        MyComparator.mycomparing2((String e) -> e.concat(""));
        MyComparator.mycomparing3((String e) -> e.concat(""));
        MyComparator.mycomparing4((String e) -> e.concat(""));

        /* in the implicit case "e" is inferred to Object so toString() is OK.
         */
        MyComparator.mycomparing1((e) -> e.toString());
        MyComparator.mycomparing2((e) -> e.toString());
        MyComparator.mycomparing3((e) -> e.toString());
        MyComparator.mycomparing4((e) -> e.toString());
    }
}

interface MyComparator<T> {
    public static <T, U extends Comparable<? super U>> MyComparator<T> mycomparing1(
            Function<? super T, ? extends U> keyExtractor) {
        return null;
    }

    public static <T, U extends Comparable<? super U>> MyComparator<T> mycomparing2(
            Function<? super T, ? super U> keyExtractor) {
        return null;
    }

    public static <T, U extends Comparable<? super U>> MyComparator<T> mycomparing3(
            Function<? extends T, ? extends U> keyExtractor) {
        return null;
    }

    public static <T, U extends Comparable<? super U>> MyComparator<T> mycomparing4(
            Function<? extends T, ? super U> keyExtractor) {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
public class Shirt
{
	private int collarSize;
	private int sleeveLength;
	private int shirtPockets;
	private String material;

	public Shirt(int collar, int sleeve, int pockets)
	{
		collarSize = collar;
		sleeveLength = sleeve;
		shirtPockets = pockets;
		material = "cotton";
	}

	public void showShirt()
	{
		System.out.println("T-Shirt Size: " + collarSize + " T-Shirt length: " + sleeveLength + " T-Shirt has " + shirtPockets + " pockets, and is made of " + material + "\n");
	}
}


text:
package tdem.TDEM_TOPICS;

/**
 *	Generated from IDL definition of struct "actuatorSpace"
 *	@author JacORB IDL compiler
 */

public final class actuatorSpace
	implements org.omg.CORBA.portable.IDLEntity
{
	public actuatorSpace(){}
	public double[] ptt;
	public actuatorSpace(double[] ptt)
	{
		this.ptt = ptt;
	}
}


text:
$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'test/unit'

begin
  RAILS_ENV = "test"
  require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
  require 'action_controller/test_process'
rescue LoadError
  puts "\n[!] Tests only run when the plugin is installed in the plugins directory, running the tests against anything other than your particular Rails version doesn't really serve a purpose."
  exit
end


text:
{{title}}

Second partial content.


text:
<?php

namespace SofaChamps\Bundle\SquaresBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GameInviteFormType extends GameFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('invites', 'textarea', array(
                'label' => 'Email Addresses',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
        ));
    }

    public function getName()
    {
        return 'invite';
    }
}


text: Course work for cloud computing


text:
import sys

reload(sys)
sys.setdefaultencoding("utf8")

import tornado.web
import re
import pickle
from tornado.escape import to_unicode
from tornado import web, escape

class FlashHandler(object):
    """
    Extends Tornado's RequestHandler by adding flash functionality.
    and GetFlash in UIModule
    """

    def flash(self, message, category='info'):
        """write by Flask.Flash
        Flashes a message to the next request.  In order to remove the
        flashed message from the session and to display it to the user

        :param message: the message to be flashed.
        :param category: the category for the message.  The following values
                     are recommended: ``'error'`` for errors, ``'info'`` for
                      information messages,``'success'`` for success info and
                       ``'warning'`` for warnings.  However any kind of string
                        can be used as category.
        """
        # get request._flashes
        self._flashes = self._flashes or []
        self._flashes.append((category,message))
        result = pickle.dumps(self._flashes)
        self.set_cookie('flashes_cookies', tornado.escape.url_escape(result))


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>me.footlights</groupId>
		<artifactId>android</artifactId>
		<version>HEAD</version>
	</parent>

	<artifactId>android-app</artifactId>
	<name>Android App</name>

	<packaging>apk</packaging>

	<dependencies>
		<dependency>
			<groupId>me.footlights</groupId>
			<artifactId>footlights-core</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>me.footlights</groupId>
			<artifactId>api</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.roboguice</groupId>
			<artifactId>roboguice</artifactId>
		</dependency>
		<dependency>
			<groupId>android.support</groupId>
			<artifactId>compatibility-v4</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>com.jayway.maven.plugins.android.generation2</groupId>
				<artifactId>android-maven-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<proguard>
						<skip>false</skip>
					</proguard>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
"""
byceps.signals.page
~~~~~~~~~~~~~~~~~~~

:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from blinker import Namespace

page_signals = Namespace()

page_created = page_signals.signal('page-created')
page_updated = page_signals.signal('page-updated')
page_deleted = page_signals.signal('page-deleted')


text:
  - MongoDB
  - AngularJS
  - Hapi
  - Raspberry Pi
  - Ionic
  - Oauth

This open-source projects aims at building a seed project with shared code between web and mobile app. It includes a server instance connected to a database along with token-based and Oauth authentication. The Raspberry Pi mini computer is to be determined.

## OSX Development - Software Installations
These instructions are for quick setup. Instructions are for OSX but should work fine on Linux too. Windows not tested.
### Node
Check version installed

    $: node -v

Download and install

    http://nodejs.org/dist/v0.10.33/node-v0.10.33.pkg

Note: node comes with npm, to check npm version use

    $: npm -v

### MongoDB
Check version installed

    $: mongod --version

Install mongodb using brew

    http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

### Git
Check version installed

    $: git --version

Install git using installer

    http://git-scm.com/downloads

## WebApp Setup and Run
### Checkout and Environment Setup
Clone git repository. On your operating system create a directory where this project will live and clone this repo.

    $: git clone https://github.com/JesusGuerrero/MAHRIO.git

Install global modules

    $: sudo npm install supervisor grunt bower -g

Install local application modules. Change into MAHRIO directory and ensure package.json is there. Then run command.

    $: npm install

You should now have a folder 'node_modules' in same location as the package.json, these are the modules required to run the server/api.

Install bower packaged libraries. Change into MAHRIO directory and ensure bower.json is there. Then run command.

    $: bower install

You should now have a folder 'bower_components' in sam elocation as the bower.json, these are the libraries required to run front-end/UI of the app.

### Run MongoDb
In order to leverage the database, ensure that mongod is running before the WebApp. To run mongod with custom config
ensure you are still in the directory, next to the package.json, and run startup the dameon using

    mongod --config mongoDB/config/mongod.conf

The configuration file is meant to have the data for development contained in your local workspace and the logs too.
This is never checked in, and ignored by .gitignore

### Run WebApp
Having the database running, and all the node_modules (including global) installed, you can run application by
using supervisor

    $: supervisor server/index.js

or by using node

    $: node server/index.js

Supervisor allows for monitoring changes to the code and auto-rebuilding for faster functional testing. Node on the
other hand can be configured in WebStorm and fully-debuggable with IDE

### Bower and Grunt
Bower is used to add new front-end libraries and keep track by using bower.json, so for example when any jquery plugins
needed you can log their requirement by installing via bower so that it gets saved to bower.json every time. When you
install in using bower you also need to update Gruntfile so that it takes the necessary files from bower package and
includes them in the build. This helps to keep libraries managed, and a task-runner to build the app is updated to any
new libraries. Some examples added through bower are angular, bootstrap and jquery.

Grunt is used to jslint any files modified, also copy from client to server folder, and finally build less files to css.

To run grunt watcher, ensure you are at the top-level next to the Gruntfile.json

    $: grunt

To run grunt once to build the system, ensure you are at the top-level next to the Gruntfile.json

    $: grunt build

### Run Tests
TODO, this is a work in progress but the basic setup is there. To run testing use

    $: grunt karma

and also

    npm test
## Notes - Things to consider

Node.JS changes frequently, and it's suggested you load the PPA in order to grab the stable latest version.  Work is in progress on customizing a Vagrantfile for this purpose, with instructions forthcoming.

## Troubleshooting
have any questions or troubke with the setup? email rocha.jesus@hotmail.com

## References
### Hapi [http://hapijs.com]
### AngularJS [https://angularjs.org]
### MongoDB [http://www.mongodb.org]

### Utilities
#### Back-End

    Jade [http://jade-lang.com]

#### Front-End

    Bootstrap 3.3.2 [http://getbootstrap.com]
    Font-Awesome 4.2.0 [http://fortawesome.github.io/Font-Awesome]
    jQuery 2.1.1 [http://jquery.com]


text:
(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "pioneer-checkers-goal") {
     checkVersion(design, name, value);
  }
}

var checkGoals = Dagaz.Model.checkGoals;

Dagaz.Model.checkGoals = function(design, board, player) {
  var e = 0; var f = 0;
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece === null) return;
      if (!design.inZone(1, piece.player, pos)) return;
      if (piece.player != player) {
          e++;
      } else {
          f++;
      }
  });
  if (e > 0) return -1;
  if (f > 0) return 1;
  return checkGoals(design, board, player);
}

})();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.3"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Kernel Tuning Toolkit: ktt::EnableBitfieldOperators< ValidationMode > Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Kernel Tuning Toolkit 2.1

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Static Public Attributes |
List of all members

ktt::EnableBitfieldOperators< ValidationMode > Struct Reference

#include <ValidationMode.h>

Static Public Attributes

static const bool 	m_Enable = true

Detailed Description

Validation mode enum supports bitwise operations.

Member Data Documentation

◆ m_Enable

          const bool ktt::EnableBitfieldOperators< ValidationMode >::m_Enable = true

static

Bitwise operations are enabled.

The documentation for this struct was generated from the following file:

Source/KernelRunner/ValidationMode.h

ktt

EnableBitfieldOperators< ValidationMode >

Generated by  1.9.3


text:
% Run KDE code on a set of fragments

% Variables used in this test script:
%     ( x, y ) - the location of the characters (user and expert)
%     chars - character at that location
%     peaks - unique set of locations of the consensus characters
%     peak_heights - intensity of the density peak of a consensus location
%     peak_labels  - maps the characters to their corresponding peaks
%     user_ids - user ids of all who transcribed the fragment
%     consensus_chars - list of consensus characters (locations are peaks)
%     is_visible - true if plot is to be displayed, as well as printed to a file

% Other Matlab routines called in this script:

%   run_kde
%   generate_consensus_characters
%   generate_consensus_report

warning('off','all');
load fraglist.txt;                                  % list of fragments w/o consensus yet
frags_to_run = fraglist;
num_frags_to_run = length( frags_to_run );

% load the database
load ../markers_db2.mat                             % Copy of markers.txt in matlab form
                                                    % Data: fragment_ids, user_ids, x, y, chars

for i = 1 : num_frags_to_run
    k = fragment_ids == frags_to_run( i );          % Match where this fragment occurs in main database
    frag_user_ids = user_ids( k );                  % Find corresponding user, x, y, char data
    frag_x = x( k );
    frag_y = y( k );
    frag_chars = chars( k );
    disp( frags_to_run( i ) );                      % Print the fragment being run
%    for h = [ 8 6 5 3 ]
    for h = [ 8 ]                                   % Kernel width
        binsize = 2 * h;
        peak_merge_threshold = h;
        [ frag_x frag_y peaks peak_heights peak_labels frag_chars frag_user_ids ] = run_kde( h, binsize, peak_merge_threshold, frag_x, frag_y, frag_chars, frag_user_ids );
        consensus_filename = sprintf( 'fragment_%d_consensus_%d.txt', frags_to_run( i ), h );
        consensus_results = generate_consensus_characters( peaks, peak_labels, frag_chars );
        generate_consensus_report( consensus_filename, consensus_results );

    % Plot the consensus characters
    is_visible = false;
    %plot_filename = sprintf( 'fragment_%d_plot_%d.pdf', frags_to_run( i ), h );
    %plot_consensus_chars( plot_filename, frags_to_run( i ), is_visible, ...
    %s                      consensus_results.consensus, peaks );
    end
end
%fclose( fp );


text:
layout: post
title: "Time is Money. At Least That's What I'm Told"
categories: journal, travel, time
tags: [travel]
image:
  # Feature: 1024x600 pixels
  # Teaser: 1024x380 pixels
  feature:
  teaser:
  credit: Josh Soucie
  creditlink: ""
---

One of the biggest tradeoffs we make in life is time for money.

> Time is Money.
> -Benjamin Franklin

### You Can Never Have Enough Vacation Days

The money-time tradeoff that has been the biggest concern to me lately has been in regards to travel. In the past, I've mostly been able to travel semi-cheaply by finding fare sales/discounts or tacking on vacation days from work to make a longer holiday. But it was always a struggle to budget my seemingly insufficient number of vacation days, of which the US requires no minimum. So I was stuck with trying to maximize my travel days while also carefully managing my financial budget.

I've always tried to keep an eye out for fare deals, but one of the other best strategies I've found to find cheap flights is to fly on a Tuesday or Wednesday - days that most people don't or choose not to fly since they're less convenient. [Find more strategies here.](https://qz.com/169299/how-to-avoid-every-common-mistake-when-booking-a-flight/) Find a cheap flight and tack a few vacation days onto a long weekend, and it's possible to have an incredible vacation for a song. Of course, traveling to countries where your dollar is maximized helps as well.

But at the moment, my time feels nearly limitless - I am, for the time being and for all intents and purposes, funemployed. And the wonderful thing about being funemployed and on the road means that I can afford to travel the (often) longer yet cheaper route - although, sometimes, I must say this is at the further expense of my own comfort, but that's another discussion!

### Overnight Trains & Buses

Traveling cheap and slow most often means trains and buses instead of flights. Another added benefit that often manifests itself with these types of travel is the possibility of an overnight trip. Although this can mean an uncomfortable bus trip, it frequently means a "free" place to sleep on the train if you book a sleeper ticket. Sleeper trains have got to be my absolute favorite means of transportation!

Sleeper trains are wonderful because they couple a decently comfortable place to sleep with transportation to your next destination. I've never flown business class, but I imagine sleeper cars are somewhat similar to business class international without, of course, a giant TV or free booze throughout your flight.

That said, you are more than welcome to bring booze (as much as you can carry seems to be about the limit) on *most* sleeper trains. It has the added benefit of making you immediate friends with anyone wanting to share with you. Plus, it helps in any countries where there may be a language barrier.

> There's no such thing as bad Russian, just not enough vodka.
> -Tianshi Ji

I must also say that I'd never heard of "sleeper buses" until my recent trip to Mongolia during which I ended up on a sleeper bus twice (seemingly, the only route for them?). Welp, it was not nearly as comfortable as a sleeper on a train, so I can't say I recommend it if there's a sleeper car available on a train, but I can say that it was much more comfortable than sitting for...well, overnight.

### So What's the Point?

Well, I feel the entire point of even quitting my latest job in the first place was that I didn't feel the tradeoff in time to money worth it. Of course, there are many more metrics to liking or staying in your job than just how much you're paid for how much time you need to put in, but in the simplistic sense, I finally realized that what I was getting from my last employer wasn't worth the money I was being paid or the time I was getting off to spend the "hard-earned" money I was receiving.

> It's just money. We'll make some more tomorrow.
> -Craig Allen

Something had to give, and so, for now, it makes sense for me to buy as much free time as I can. And to live every single minute of it.

Time is money, but **time** is the only resource you **can't get back**.

So spend it wisely.

Safe travels and happy surfing!

Josh S =P

ps. Welp, I let that one get away from me a bit. Happy to be writing though...I'll be dragging more things out of my journal in the near future...and perhaps bringing some older writings from my old blog back to the new site. Cheers!


text:
var jive = require('jive-sdk');
var q = require('q');

function DataAccessObject() {
}

module.exports = DataAccessObject;

/**
 * Template function for correct sql execution.
 * 1. acquire a client - throw an error if non can be found
 * 2. run the operation (the parameter to this function)
 * 3. release the client
 * @param operation a function that MUST return a promise!
 * @returns {*}
 */
DataAccessObject.prototype.query = function(operation) {
    var db = jive.service.persistence();

    // fetch a db connection from the pool
    var pClient = db.getQueryClient();

    return pClient.then( function(dbClient) {
        // die if one comes back empty
        if ( !dbClient ) {
            throwError("Can't query, invalid client");
        }

        // die if the operation doesn't return a promise
        var result = operation(dbClient);
        if ( !result ) {
            throwError("Operation must return a promise.");
        }

        // always try to release the client, if it exists
        result.finally(function() {
            if ( dbClient ) {
                // always try to release the client, if it exists
                dbClient.release();
            }
        });

        return result;
    })
    // failed to get a db connection
    .fail( function(e) {
        jive.logger.error(e.stack);
        return q.reject(e);
    });
};

DataAccessObject.prototype.throwError = throwError;

function throwError(detail) {
    var error = typeof detail === 'string' ? new Error(detail) : detail;
    jive.logger.error(error.stack);
    throw error;
}


text:
<!doctype html>

  <meta charset="utf-8">
  <base href="/examples/angular-1/phone-kitten/">

  <title>Google Phone Gallery</title>

  <link rel="stylesheet" href="css/bootstrap.css">
  <link rel="stylesheet" href="css/app.css">
  <link rel="stylesheet" href="css/animations.css">


text:
module CompositePrimaryKeys
  ID_SEP = ','
  ID_SET_SEP = ';'
  module ArrayExtension
    def to_composite_keys
      CompositeKeys.new(self)
    end

    def to_composite_ids
      CompositeIds.new(self)
    end
  end

  class CompositeArray < Array
    def to_s
      join(ID_SEP)
    end
  end

  class CompositeKeys < CompositeArray

  end

  class CompositeIds < CompositeArray

  end
end

Array.send(:include, CompositePrimaryKeys::ArrayExtension)


text:
package lightstep

import (
	"context"

	"github.com/opentracing/opentracing-go"
)

// Tracerv0_14 matches the Tracer interface from v0.14.0
// DEPRECATED
type Tracerv0_14 interface {
	opentracing.Tracer

	// DEPRECATED: error is always nil. Equivalent to Tracer.Close(context.Background())
	Close() error
	// DEPRECATED: error is always nil. Equivalent to Tracer.Flush(context.Background())
	Flush() error
	// Options gets the Options used in New().
	Options() Options
	// Disable prevents the tracer from recording spans or flushing.
	Disable()
}

type tracerv0_14 struct {
	Tracer
}

// NewTracerv0_14 returns a tracer which conforms to the Tracer interface from v0.14.0,
// for backwards compatibility.
// DEPRECATED
func NewTracerv0_14(opts Options) Tracerv0_14 {
	return &tracerv0_14{
		Tracer: NewTracer(opts),
	}
}

func (t *tracerv0_14) Close() error {
	t.Tracer.Close(context.Background())
	return nil
}

func (t *tracerv0_14) Flush() error {
	t.Tracer.Flush(context.Background())
	return nil
}


text:
package serialapi

import (
	"errors"

	"github.com/gozwave/gozw/frame"
	"github.com/gozwave/gozw/protocol"
	"github.com/gozwave/gozw/session"
)

// IsFailedNode Will return if a node has failed.
func (s *Layer) IsFailedNode(nodeID byte) (failed bool, err error) {

	done := make(chan *frame.Frame)

	request := &session.Request{
		FunctionID: protocol.FnIsNodeFailed,
		Payload:    []byte{nodeID},
		HasReturn:  true,
		ReturnCallback: func(err error, ret *frame.Frame) bool {
			done <- ret
			return false
		},
	}

	s.sessionLayer.MakeRequest(request)
	ret := <-done

	if ret == nil {
		err = errors.New("Error checking failure status")
		return
	}

	failed = ret.Payload[1] == 1

	return
}


text:
#include "gd32f4xx.h"
#include "cmsis.h"
#include "hal_tick.h"

int mbed_sdk_inited = 0;

#if TICKER_TIMER_WIDTH_BIT == 16
extern void ticker_16bits_timer_init(void);
#else
extern void ticker_32bits_timer_init(void);
#endif

/**
 * SDK hook for running code before ctors or OS
 *
 * This is a weak function which can be overridden by a target's
 * SDK to allow code to run after ram is initialized but before
 * the OS has been started or constructors have run.
 *
 * Preconditions:
 * - Ram is initialized
 * - NVIC is setup
 */
/**
 * This function is called after RAM initialization and before main.
 */
void mbed_sdk_init()
{
    /* Update the SystemCoreClock */
    SystemCoreClockUpdate();
    nvic_priority_group_set(NVIC_PRIGROUP_PRE4_SUB0);

    /* configure 1ms tick */
#if TICKER_TIMER_WIDTH_BIT == 16
    ticker_16bits_timer_init();
#else
    ticker_32bits_timer_init();
#endif

    SystemInit();

    SystemCoreClockUpdate();

    mbed_sdk_inited = 1;
}