text:
#import "PFOAuth1FlowDialog.h"

#import <Parse/PFNetworkActivityIndicatorManager.h>

@implementation PFOAuth1FlowDialog

@synthesize dataSource = _dataSource;
@synthesize completion = _completion;

@synthesize queryParameters = _queryParameters;
@synthesize redirectURLPrefix = _redirectURLPrefix;

static NSString *const PFOAuth1FlowDialogDefaultTitle = @"Connect to Service";

static const CGFloat PFOAuth1FlowDialogBorderGreyColorComponents[4] = {0.3f, 0.3f, 0.3f, 0.8f};
static const CGFloat PFOAuth1FlowDialogBorderBlackColorComponents[4] = {0.3f, 0.3f, 0.3f, 1.0f};

static const NSTimeInterval PFOAuth1FlowDialogAnimationDuration = 0.3;

static const UIEdgeInsets PFOAuth1FlowDialogContentInsets = {
    .top = 10.0f,
    .left = 10.0f,
    .bottom = 10.0f,
    .right = 10.0f,
};

static const UIEdgeInsets PFOAuth1FlowDialogTitleInsets = {.top = 4.0f, .left = 8.0f, .bottom = 4.0f, .right = 8.0f};

static const CGFloat PFOAuth1FlowDialogScreenInset = 10.0f;

static BOOL PFOAuth1FlowDialogScreenHasAutomaticRotation() {
    static BOOL automaticRotation;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        automaticRotation = [[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"coordinateSpace")];
    });
    return automaticRotation;
}

static BOOL PFOAuth1FlowDialogIsDevicePad() {
    static BOOL isPad;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        isPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
    });
    return isPad;
}

static CGFloat PFTFloatRound(CGFloat value, NSRoundingMode mode) {
    switch (mode) {
        case NSRoundPlain:
        case NSRoundBankers:
#if CGFLOAT_IS_DOUBLE
            value = round(value);
#else
            value = roundf(value);
#endif
        case NSRoundDown:
#if CGFLOAT_IS_DOUBLE
            value = floor(value);
#else
            value = floorf(value);
#endif
        case NSRoundUp:
#if CGFLOAT_IS_DOUBLE
            value = ceil(value);
#else
            value = ceilf(value);
#endif
        default: break;
    }
    return value;
}

#pragma mark -
#pragma mark Class

+ (void)_fillRect:(CGRect)rect withColorComponents:(const CGFloat *)colorComponents radius:(CGFloat)radius {
    CGContextRef context = UIGraphicsGetCurrentContext();

    if (colorComponents) {
        CGContextSaveGState(context);
        CGContextSetFillColor(context, colorComponents);
        if (radius != 0.0f) {
            UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
            CGContextAddPath(context, [bezierPath CGPath]);
            CGContextFillPath(context);
        } else {
            CGContextFillRect(context, rect);
        }
        CGContextRestoreGState(context);
    }
}

+ (void)_strokeRect:(CGRect)rect withColorComponents:(const CGFloat *)strokeColor {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    {
        CGContextSetStrokeColor(context, strokeColor);
        CGContextSetLineWidth(context, 1.0f);
        CGContextStrokeRect(context, rect);
    }
    CGContextRestoreGState(context);
}

+ (NSURL *)_urlFromBaseURL:(NSURL *)baseURL queryParameters:(NSDictionary *)params {
    if ([params count] > 0) {
        NSMutableArray *parameterPairs = [NSMutableArray array];
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            CFStringRef escapedString = CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL, /* allocator */
                                                                                (CFStringRef)obj,
                                                                                NULL, /* charactersToLeaveUnescaped */
                                                                                (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                kCFStringEncodingUTF8);
            [parameterPairs addObject:[NSString stringWithFormat:@"%@=%@", key, CFBridgingRelease(escapedString)]];
        }];

        NSString *query = [parameterPairs componentsJoinedByString:@"&"];
        NSString *url = [NSString stringWithFormat:@"%@?%@", [baseURL absoluteString], query];

        return [NSURL URLWithString:url];
    }

    return baseURL;
}

+ (UIImage *)_closeButtonImage {
    CGRect imageRect = CGRectZero;
    imageRect.size = CGSizeMake(30.0f, 30.0f);

    UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect outerRingRect = CGRectInset(imageRect, 2.0f, 2.0f);

    [[UIColor whiteColor] set];
    CGContextFillEllipseInRect(context, outerRingRect);

    CGRect innerRingRect = CGRectInset(outerRingRect, 2.0f, 2.0f);

    [[UIColor blackColor] set];
    CGContextFillEllipseInRect(context, innerRingRect);

    CGRect crossRect = CGRectInset(innerRingRect, 6.0f, 6.0f);

    CGContextBeginPath(context);

    [[UIColor whiteColor] setStroke];
    CGContextSetLineWidth(context, 3.0f);

    CGContextMoveToPoint(context, CGRectGetMinX(crossRect), CGRectGetMinY(crossRect));
    CGContextAddLineToPoint(context, CGRectGetMaxX(crossRect), CGRectGetMaxY(crossRect));

    CGContextMoveToPoint(context, CGRectGetMaxX(crossRect), CGRectGetMinY(crossRect));
    CGContextAddLineToPoint(context, CGRectGetMinX(crossRect), CGRectGetMaxY(crossRect));

    CGContextStrokePath(context);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

#pragma mark -
#pragma mark Init

- (instancetype)init {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.autoresizesSubviews = YES;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.contentMode = UIViewContentModeRedraw;

        _orientation = UIInterfaceOrientationPortrait;

        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeButton.showsTouchWhenHighlighted = YES;
        _closeButton.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin);
        [_closeButton setImage:[[self class] _closeButtonImage] forState:UIControlStateNormal];
        [_closeButton addTarget:self
                         action:@selector(_cancelButtonAction)
               forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_closeButton];

        CGFloat titleLabelFontSize = (PFOAuth1FlowDialogIsDevicePad() ? 18.0f : 14.0f);
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.text = PFOAuth1FlowDialogDefaultTitle;
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont boldSystemFontOfSize:titleLabelFontSize];
        [self addSubview:_titleLabel];

        _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _webView.delegate = self;
        [self addSubview:_webView];

        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
                              UIActivityIndicatorViewStyleWhiteLarge];
        _activityIndicator.color = [UIColor grayColor];
        _activityIndicator.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin |
                                               UIViewAutoresizingFlexibleBottomMargin |
                                               UIViewAutoresizingFlexibleLeftMargin |
                                               UIViewAutoresizingFlexibleRightMargin);
        [self addSubview:_activityIndicator];

        _modalBackgroundView = [[UIView alloc] init];
    }
    return self;
}

- (instancetype)initWithURL:(NSURL *)url queryParameters:(NSDictionary *)parameters {
    self = [self init];
    if (self) {
        _baseURL = url;
        _queryParameters = [parameters mutableCopy];
    }
    return self;
}

+ (instancetype)dialogWithURL:(NSURL *)url queryParameters:(NSDictionary *)queryParameters {
    return [[self alloc] initWithURL:url queryParameters:queryParameters];
}

#pragma mark -
#pragma mark Dealloc

- (void)dealloc {
    _webView.delegate = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark UIView

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    [[self class] _fillRect:self.bounds withColorComponents:PFOAuth1FlowDialogBorderGreyColorComponents radius:10.0f];
    [[self class] _strokeRect:_webView.frame withColorComponents:PFOAuth1FlowDialogBorderBlackColorComponents];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    const CGRect bounds = self.bounds;
    const CGRect contentRect = UIEdgeInsetsInsetRect(bounds, PFOAuth1FlowDialogContentInsets);

    CGRect titleLabelBoundingRect = UIEdgeInsetsInsetRect(contentRect, PFOAuth1FlowDialogTitleInsets);
    CGSize titleLabelSize = [_titleLabel sizeThatFits:titleLabelBoundingRect.size];
    titleLabelBoundingRect.size.width = (CGRectGetMaxX(contentRect) -
                                         PFOAuth1FlowDialogTitleInsets.right -
                                         titleLabelSize.height);
    titleLabelSize = [_titleLabel sizeThatFits:titleLabelBoundingRect.size];

    CGRect titleLabelFrame = titleLabelBoundingRect;
    titleLabelFrame.size.height = titleLabelSize.height;
    titleLabelFrame.size.width = CGRectGetWidth(titleLabelBoundingRect);
    _titleLabel.frame = titleLabelFrame;

    CGRect closeButtonFrame = contentRect;
    closeButtonFrame.size.height = (CGRectGetHeight(titleLabelFrame) +
                                    PFOAuth1FlowDialogTitleInsets.top +
                                    PFOAuth1FlowDialogTitleInsets.bottom);
    closeButtonFrame.size.width = CGRectGetHeight(closeButtonFrame);
    closeButtonFrame.origin.x = CGRectGetMaxX(contentRect) - CGRectGetWidth(closeButtonFrame);
    _closeButton.frame = closeButtonFrame;

    CGRect webViewFrame = contentRect;
    if (!_showingKeyboard || PFOAuth1FlowDialogIsDevicePad() || UIInterfaceOrientationIsPortrait(_orientation)) {
        webViewFrame.origin.y = CGRectGetMaxY(titleLabelFrame) + PFOAuth1FlowDialogTitleInsets.bottom;
        webViewFrame.size.height = CGRectGetMaxY(contentRect) - CGRectGetMinY(webViewFrame);
    }
    _webView.frame = webViewFrame;

    [_activityIndicator sizeToFit];
    _activityIndicator.center = _webView.center;
}

#pragma mark -
#pragma mark Accessors

- (NSString *)title {
    return _titleLabel.text;
}

- (void)setTitle:(NSString *)title {
    _titleLabel.text = title;

    [self setNeedsLayout];
}

#pragma mark -
#pragma mark Present / Dismiss

- (void)showAnimated:(BOOL)animated {
    [self load];
    [self _sizeToFitOrientation];

    [_activityIndicator startAnimating];

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    _modalBackgroundView.frame = window.bounds;
    [_modalBackgroundView addSubview:self];
    [window addSubview:_modalBackgroundView];

    CGAffineTransform transform = [self _transformForOrientation:_orientation];
    if (animated) {
        self.transform = CGAffineTransformScale(transform, 0.001f, 0.001f);

        NSTimeInterval animationStepDuration = PFOAuth1FlowDialogAnimationDuration / 2.0f;

        [UIView animateWithDuration:animationStepDuration
                         animations:^{
                             self.transform = CGAffineTransformScale(transform, 1.1f, 1.1f);
                         }
                         completion:^(BOOL finished) {
                             [UIView animateWithDuration:animationStepDuration
                                              animations:^{
                                                  self.transform = CGAffineTransformScale(transform, 0.9f, 0.9f);
                                              }
                                              completion:^(BOOL finished) {
                                                  [UIView animateWithDuration:animationStepDuration
                                                                   animations:^{
                                                                       self.transform = transform;
                                                                   }];
                                              }];

                         }];
    } else {
        self.transform = transform;
    }

    [self _addObservers];
}

- (void)dismissAnimated:(BOOL)animated {
    _loadingURL = nil;

    __weak typeof(self) wself = self;
    dispatch_block_t completionBlock = ^{
        __strong typeof(wself) sself = wself;
        [sself _removeObservers];
        [sself removeFromSuperview];
        [_modalBackgroundView removeFromSuperview];
    };

    if (animated) {
        [UIView animateWithDuration:PFOAuth1FlowDialogAnimationDuration
                         animations:^{
                             typeof(wself) sself = wself;
                             sself.alpha = 0.0f;
                         }
                         completion:^(BOOL finished) {
                             completionBlock();
                         }];
    } else {
        completionBlock();
    }
}

- (void)_dismissWithSuccess:(BOOL)success url:(NSURL *)url error:(NSError *)error {
    if (!self.completion) {
        return;
    }

    PFOAuth1FlowDialogCompletion completion = self.completion;
    self.completion = nil;

    dispatch_async(dispatch_get_main_queue(), ^{
        completion(success, url, error);
    });

    [self dismissAnimated:YES];
}

- (void)_cancelButtonAction {
    [self _dismissWithSuccess:NO url:nil error:nil];
}

#pragma mark -
#pragma mark Public

- (void)load {
    [self loadURL:_baseURL queryParameters:self.queryParameters];
}

- (void)loadURL:(NSURL *)url queryParameters:(NSDictionary *)parameters {
    _loadingURL = [[self class] _urlFromBaseURL:url queryParameters:parameters];

    NSURLRequest *request = [NSURLRequest requestWithURL:_loadingURL];
    [_webView loadRequest:request];
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;

    if ([url.absoluteString hasPrefix:self.redirectURLPrefix]) {
        [self _dismissWithSuccess:YES url:url error:nil];
        return NO;
    } else if ([_loadingURL isEqual:url]) {
        return YES;
    } else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        if ([self.dataSource dialog:self shouldOpenURLInExternalBrowser:url]) {
            [[UIApplication sharedApplication] openURL:url];
        } else {
            return YES;
        }
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[PFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[PFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

    [_activityIndicator stopAnimating];
    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [[PFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

    // 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
    if (!([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102)) {
        [self _dismissWithSuccess:NO url:nil error:error];
    }
}

#pragma mark -
#pragma mark Observers

- (void)_addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_deviceOrientationDidChange:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)_removeObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIDeviceOrientationDidChangeNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

#pragma mark -
#pragma mark UIDeviceOrientationDidChangeNotification

- (void)_deviceOrientationDidChange:(NSNotification *)notification {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if ([self _shouldRotateToOrientation:orientation]) {
        NSTimeInterval duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
        [UIView animateWithDuration:duration
                         animations:^{
                             [self _sizeToFitOrientation];
                         }];
    }
}

- (BOOL)_shouldRotateToOrientation:(UIInterfaceOrientation)orientation {
    if (orientation == _orientation) {
        return NO;
    }

    return (orientation == UIDeviceOrientationLandscapeLeft ||
            orientation == UIDeviceOrientationLandscapeRight ||
            orientation == UIDeviceOrientationPortrait ||
            orientation == UIDeviceOrientationPortraitUpsideDown);
}

- (CGAffineTransform)_transformForOrientation:(UIInterfaceOrientation)orientation {
    // No manual rotation required on iOS 8
    // There is coordinateSpace method, since iOS 8
    if (PFOAuth1FlowDialogScreenHasAutomaticRotation()) {
        return CGAffineTransformIdentity;
    }

    switch (orientation) {
        case UIInterfaceOrientationLandscapeLeft:
            return CGAffineTransformMakeRotation((CGFloat)(-M_PI / 2.0f));
            break;
        case UIInterfaceOrientationLandscapeRight:
            return CGAffineTransformMakeRotation((CGFloat)(M_PI / 2.0f));
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            return CGAffineTransformMakeRotation((CGFloat)-M_PI);
            break;
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationUnknown:
        default:
            break;
    }

    return CGAffineTransformIdentity;
}

- (void)_sizeToFitOrientation {
    _orientation = [UIApplication sharedApplication].statusBarOrientation;
    CGAffineTransform transform = [self _transformForOrientation:_orientation];

    CGRect bounds = [UIScreen mainScreen].applicationFrame;
    CGRect transformedBounds = CGRectApplyAffineTransform(bounds, transform);
    transformedBounds.origin = CGPointZero;

    CGPoint center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

    CGFloat scale = (PFOAuth1FlowDialogIsDevicePad() ? 0.6f : 1.0f);

    CGFloat width = PFTFloatRound((scale * CGRectGetWidth(transformedBounds)) - PFOAuth1FlowDialogScreenInset * 2.0f, NSRoundDown);
    CGFloat height = PFTFloatRound((scale * CGRectGetHeight(transformedBounds)) - PFOAuth1FlowDialogScreenInset * 2.0f, NSRoundDown);

    self.transform = transform;
    self.center = center;
    self.bounds = CGRectMake(0.0f, 0.0f, width, height);

    [self setNeedsLayout];
}

#pragma mark -
#pragma mark UIKeyboardNotifications

- (void)_keyboardWillShow:(NSNotification *)notification {
    _showingKeyboard = YES;

    if (PFOAuth1FlowDialogIsDevicePad()) {
        // On the iPad the screen is large enough that we don't need to
        // resize the dialog to accomodate the keyboard popping up
        return;
    }

    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        NSDictionary *userInfo = [notification userInfo];
        NSTimeInterval animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        UIViewAnimationCurve animationCurve = [[notification userInfo][UIKeyboardAnimationCurveUserInfoKey] intValue];

        [UIView animateWithDuration:animationDuration
                              delay:0.0
                            options:animationCurve << 16 | UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [self setNeedsLayout];
                             [self layoutIfNeeded];

                             [self setNeedsDisplay];
                         }
                         completion:nil];
    }
}

- (void)_keyboardWillHide:(NSNotification *)notification {
    _showingKeyboard = NO;

    if (PFOAuth1FlowDialogIsDevicePad()) {
        return;
    }
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        NSDictionary *userInfo = [notification userInfo];
        NSTimeInterval animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        UIViewAnimationCurve animationCurve = [[notification userInfo][UIKeyboardAnimationCurveUserInfoKey] intValue];

        [UIView animateWithDuration:animationDuration
                              delay:0.0
                            options:animationCurve << 16 | UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [self setNeedsLayout];
                             [self layoutIfNeeded];

                             [self setNeedsDisplay];
                         }
                         completion:nil];
    }
}

@end


text:
namespace net {

namespace der {
struct GeneralizedTime;
}

struct ParseCertificateOptions;
class SignaturePolicy;

// Represents a trust anchor (i.e. a trusted root certificate).
class NET_EXPORT TrustAnchor {
 public:
  // The certificate data for this trust anchor may either be owned internally
  // (INTERNAL_COPY) or owned externally (EXTERNAL_REFERENCE). When it is
  // owned internally the data is held by |cert_data_|
  enum class DataSource {
    INTERNAL_COPY,
    EXTERNAL_REFERENCE,
  };

  TrustAnchor();
  ~TrustAnchor();

  // Creates a TrustAnchor given a DER-encoded certificate. Returns nullptr on
  // failure. Failure will occur if the certificate data cannot be parsed to
  // find a subject.
  //
  // The provided certificate data is either copied, or aliased, depending on
  // the value of |source|. See the comments for DataSource for details.
  static std::unique_ptr<TrustAnchor> CreateFromCertificateData(
      const uint8_t* data,
      size_t length,
      const ParseCertificateOptions& options,
      DataSource source);

  // Returns true if the trust anchor matches |name|. In other words, returns
  // true if the certificate's subject matches |name|.
  bool MatchesName(const der::Input& name) const;

  // Returns the DER-encoded certificate data for this trust anchor.
  const der::Input& cert() const { return cert_; }

 private:
  // The backing store for the certificate data. This is only applicable when
  // the trust anchor was initialized using DataSource::INTERNAL_COPY.
  std::vector<uint8_t> cert_data_;

  // Note that the backing data for |cert_| and |name_| may come either form
  // |cert_data_| or some external buffer (depending on how the anchor was
  // created).

  // Points to the raw certificate DER.
  der::Input cert_;

  // Points to the subject TLV for the certificate.
  der::Input name_;

  DISALLOW_COPY_AND_ASSIGN(TrustAnchor);
};

// A very simple implementation of a TrustStore, which contains a set of
// trusted certificates.
class NET_EXPORT TrustStore {
 public:
  TrustStore();
  ~TrustStore();

  // Empties the trust store, resetting it to original state.
  void Clear();

  // Adds a trusted certificate to the store. The trust store makes a copy of
  // the provided certificate data.
  bool AddTrustedCertificate(const uint8_t* data,
                             size_t length) WARN_UNUSED_RESULT;
  bool AddTrustedCertificate(const base::StringPiece& data) WARN_UNUSED_RESULT;

  // This function is the same as AddTrustedCertificate() except the underlying
  // data is not copied. The caller is responsible for ensuring that the data
  // pointer remains alive and is not mutated for the lifetime of the
  // TrustStore.
  bool AddTrustedCertificateWithoutCopying(const uint8_t* data,
                                           size_t length) WARN_UNUSED_RESULT;

  // Returns the trust anchor that matches |name|, or nullptr if there is none.
  // TODO(eroman): There may be multiple matches.
  const TrustAnchor* FindTrustAnchorByName(const der::Input& name) const
      WARN_UNUSED_RESULT;

  // Returns true if |cert_der| matches a certificate in the TrustStore.
  bool IsTrustedCertificate(const der::Input& cert_der) const
      WARN_UNUSED_RESULT;

 private:
  bool AddTrustedCertificate(const uint8_t* data,
                             size_t length,
                             TrustAnchor::DataSource source) WARN_UNUSED_RESULT;

  std::vector<std::unique_ptr<TrustAnchor>> anchors_;

  DISALLOW_COPY_AND_ASSIGN(TrustStore);
};

// VerifyCertificateChain() verifies a certificate path (chain) based on the
// rules in RFC 5280.
//
// WARNING: This implementation is in progress, and is currently incomplete.
// Consult an OWNER before using it.
//
// ---------
// Inputs
// ---------
//
//   cert_chain:
//     A non-empty chain of N DER-encoded certificates, listed in the
//     "forward" direction.
//
//      * cert_chain[0] is the target certificate to verify.
//      * cert_chain[i+1] holds the certificate that issued cert_chain[i].
//      * cert_chain[N-1] must be the trust anchor, or have been directly
//        issued by a trust anchor.
//
//   trust_store:
//     Contains the set of trusted public keys (and their names).
//
//   signature_policy:
//     The policy to use when verifying signatures (what hash algorithms are
//     allowed, what length keys, what named curves, etc).
//
//   time:
//     The UTC time to use for expiration checks.
//
// ---------
// Outputs
// ---------
//
//   Returns true if the target certificate can be verified.
NET_EXPORT bool VerifyCertificateChain(const std::vector<der::Input>& certs_der,
                                       const ParseCertificateOptions& options,
                                       const TrustStore& trust_store,
                                       const SignaturePolicy* signature_policy,
                                       const der::GeneralizedTime& time)
    WARN_UNUSED_RESULT;

}  // namespace net

#endif  // NET_CERT_INTERNAL_VERIFY_CERTIFICATE_CHAIN_H_

redpajama_set_name: RedPajamaGithub


text:
package com.atlassian.plugin.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AbstractFileServerServlet extends HttpServlet
{
    public static final String PATH_SEPARATOR = "/";
    public static final String RESOURCE_URL_PREFIX = "resources";
    public static final String SERVLET_PATH = "download";
    private static final Logger log = LoggerFactory.getLogger(AbstractFileServerServlet.class);

    @Override
    protected final void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException
    {
        final DownloadStrategy downloadStrategy = getDownloadStrategy(httpServletRequest);
        if (downloadStrategy == null)
        {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "The file you were looking for was not found");
            return;
        }

        try
        {
            downloadStrategy.serveFile(httpServletRequest, httpServletResponse);
        }
        catch (final DownloadException e)
        {
            log.debug("Error while serving file for request:" + httpServletRequest.getRequestURI(), e);
            if (!httpServletResponse.isCommitted())
            {
                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while serving file");
            }
        }
    }

    /**
     * Returns a list of {@link DownloadStrategy} objects in the order that they will be matched against.
     * The list returned should be cached as this method is called for every request.
     */
    protected abstract List<DownloadStrategy> getDownloadStrategies();

    private DownloadStrategy getDownloadStrategy(final HttpServletRequest httpServletRequest)
    {
        final String url = httpServletRequest.getRequestURI();
        DownloadStrategy strategy = findStrategy(url);

        if(strategy==null){
            strategy = findStrategy(url.toLowerCase());
        }

        return strategy;
    }

    private DownloadStrategy findStrategy(String url){
        for (final DownloadStrategy downloadStrategy : getDownloadStrategies())
        {
            if (downloadStrategy.matches(url))
            {
                return downloadStrategy;
            }
        }
        return null;
    }
}


text:
set SERVER=127.0.0.1:1099
set USER=workshopcommandline@gmail.com
set /p PW=<password.txt
set FROMNAME=workshopcommandline@gmail.com
set TO=""
set SUBJECT="Command Line WorkShop"
set BODY="Send from the command line. Download zip file containing all materials for the workshop here {URL}"
blat -server %SERVER% -f %FROMNAME% -u %USER% -pw %PW% -to %TO% -subject %SUBJECT% -body %BODY%


text:
//
//  SearchController.m
//  sgSalerReport
//
//  Created by 朱巩拓 on 16/5/6.
//  Copyright © 2016年 dwolf. All rights reserved.
//

#import "SearchController.h"
#import "StoreDetailsController.h"

@interface SearchController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (strong,nonatomic)UITextField     *homeTextF;
@property (strong,nonatomic)UITableView     *tableView_2;
@end

//--------------------------城市内搜索商店------------------------

@implementation SearchController
{
    UIView          *nvcView1;//加载在导航栏上的view
    NSMutableArray  *cell_nameAry;
    NSMutableArray  *cell_idAry;
}

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self.delegate.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, nil]];//导航栏字体颜色
    [self.delegate.navigationController setNavigationBarHidden:NO];
    [self.delegate.navigationController.navigationItem setHidesBackButton:YES];
    [self.delegate.navigationItem setHidesBackButton:YES];
    [self.delegate.navigationController.navigationBar.backItem setHidesBackButton:YES];

    [self initnvc];

}

-(void)initnvc
{
    nvcView1=[[UIView alloc]initWithFrame:CGRectMake(60, 7, 210, 32)];

    UIView *colorView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 210, 32)];

    colorView.layer.masksToBounds=YES;
    colorView.layer.cornerRadius=5;
    //搜索框里的放大镜
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(10,8,14, 14)];
    [imgView setImage:[UIImage imageNamed:@"search_Icon"]];
    [colorView addSubview:imgView];

    self.homeTextF=[[UITextField alloc]initWithFrame:CGRectMake(29,2,WIN_WIDTH-110, 32)];
    self.homeTextF.placeholder=@"请输入要搜索的商城名";
     self.homeTextF.delegate=self;
    self.homeTextF.font=DESC_FONT;
    [colorView addSubview:imgView];
    [colorView addSubview:self.homeTextF];

    [nvcView1 addSubview:colorView];
    [self.delegate.navigationController.navigationBar addSubview:nvcView1];
    [self initTableview];

}
#pragma mark ---请求网络---
-(void)NetWorkRequest
{
    [SVProgressHUD showWithStatus:@"正在努力加载中"];
     NSUserDefaults *userCity=[NSUserDefaults standardUserDefaults];
     NSString *strid=[userCity objectForKey:@"city"];

    if ([Util isNull:strid]) {
        strid=@"1";
    }
    NSString *memberID=[Global sharedClient].member_id;
    if ([Util isNull:memberID]) {
        memberID=@"";
    }

    [HttpClient requestWithMethod:@"POST" path:[Util makeRequestUrl:@"mallshoplist" tp:@"loadmalllist"] parameters:[[NSDictionary alloc]initWithObjectsAndKeys:strid,@"city",memberID,@"member_id",@"10",@"pageSize",@(1),@"Page",nil ]  target:self success:^(NSDictionary *dic){
        dispatch_async(dispatch_get_main_queue(), ^{

            [SVProgressHUD dismiss];
        });
    }failue:^(NSDictionary *dic){
        [SVProgressHUD dismiss];
    }];

}

-(void)initTableview
{

    self.tableView_2=[[UITableView alloc]initWithFrame:CGRectMake(0,64, WIN_WIDTH, self.view.frame.size.height-64) style:UITableViewStylePlain];
    self.tableView_2.delegate=self;
    self.tableView_2.dataSource=self;
    self.tableView_2.scrollEnabled=YES;
    self.tableView_2.separatorStyle=UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.tableView_2];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 42;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return cell_nameAry.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID=@"cellID";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

    }
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(14, 11, 240,20)];
    lab.textAlignment=NSTextAlignmentLeft;
    lab.text=cell_nameAry[indexPath.row];
    lab.font=COMMON_FONT;

    UILabel *juliLab=[[UILabel alloc]initWithFrame:CGRectMake(WIN_WIDTH-67, 15, 53, 12)];
    juliLab.textAlignment=NSTextAlignmentRight;
    juliLab.textColor=COLOR_FONT_SECOND;
    juliLab.font=DESC_FONT;
    juliLab.text=@"13.2公里";

    [cell addSubview:lab];
    [cell addSubview:juliLab];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    StoreDetailsController *sVC=[[StoreDetailsController alloc]init];

    [self.delegate.navigationController pushViewController:sVC animated:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.nameArray=[[NSMutableArray alloc]init];
//    self.idArray  =[[NSMutableArray alloc]init];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [nvcView1 removeFromSuperview];

}

-(void)textFieldDidChange:(id)sender
{

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans 'Your account was activated' %}{% endblock %}

{% block content %}

{% trans 'Thank you!' %}

{% trans 'Your account was activated, now you can to log in our site via link below.' %}

{% trans 'Login' %}

{% trans 'To index page' %}

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;

namespace IdefavOAuth2Client
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // 在应用程序启动时运行的代码
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


text:
      <form method="POST" action="." novalidate>
        {{form.csrf_token}}
        {{forms.number_field(form.rank)}}
        {{forms.text_field(form.name, autofocus=True)}}
        {{forms.select_field(form.album_key)}}
        {{forms.select_field(form.writer_key)}}
        {{forms.date_field(form.release_date)}}
        {{forms.text_field(form.soundcloud_id)}}
        {{forms.text_field(form.youtube_id)}}
        {{forms.text_field(form.tags)}}
        {{forms.text_field(form.artist)}}
        {{forms.textarea_field(form.lyrics)}}
        <button type="submit" class="btn btn-primary btn-block btn-loading" {{forms.data_loading_text()}}>
          # if song_db.key
            Update
          # else
            Create
          # endif
        </button>
      </form>

# endblock


text:
package org.apache.catalina.mbeans;

import java.util.ArrayList;
import java.util.List;

import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.apache.catalina.Container;
import org.apache.catalina.ContainerListener;
import org.apache.catalina.JmxEnabled;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Valve;
import org.apache.catalina.core.ContainerBase;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.ContextConfig;
import org.apache.catalina.startup.HostConfig;

public class ContainerMBean extends BaseCatalinaMBean<ContainerBase> {

    /**
     * Add a new child Container to those associated with this Container,
     * if supported. Won't start the child yet. Has to be started with a call to
     * Start method after necessary configurations are done.
     *
     * @param type ClassName of the child to be added
     * @param name Name of the child to be added
     *
     * @exception MBeanException if the child cannot be added
     */
    public void addChild(String type, String name) throws MBeanException{

        Container contained = (Container) newInstance(type);
        contained.setName(name);

        if(contained instanceof StandardHost){
            HostConfig config = new HostConfig();
            contained.addLifecycleListener(config);
        } else if(contained instanceof StandardContext){
            ContextConfig config = new ContextConfig();
            contained.addLifecycleListener(config);
        }

        boolean oldValue= true;

        ContainerBase container = doGetManagedResource();
        try {
            oldValue = container.getStartChildren();
            container.setStartChildren(false);
            container.addChild(contained);
            contained.init();
        } catch (LifecycleException e){
            throw new MBeanException(e);
        } finally {
            if(container != null) {
                container.setStartChildren(oldValue);
            }
        }
    }

    /**
     * Remove an existing child Container from association with this parent
     * Container.
     *
     * @param name Name of the existing child Container to be removed
     * @throws MBeanException if the child cannot be removed
     */
    public void removeChild(String name) throws MBeanException{
        if (name != null) {
            Container container = doGetManagedResource();
            Container contained = container.findChild(name);
            container.removeChild(contained);
        }
    }

    /**
     * Adds a valve to this Container instance.
     *
     * @param valveType ClassName of the valve to be added
     * @return the MBean name of the new valve
     * @throws MBeanException if adding the valve failed
     */
    public String addValve(String valveType) throws MBeanException{
        Valve valve = (Valve) newInstance(valveType);

        Container container = doGetManagedResource();
        container.getPipeline().addValve(valve);

        if (valve instanceof JmxEnabled) {
            return ((JmxEnabled)valve).getObjectName().toString();
        } else {
            return null;
        }
    }

    /**
     * Remove an existing Valve.
     *
     * @param valveName MBean Name of the Valve to remove
     *
     * @exception MBeanException if a component cannot be removed
     */
    public void removeValve(String valveName) throws MBeanException{
        Container container = doGetManagedResource();

        ObjectName oname;
        try {
            oname = new ObjectName(valveName);
        } catch (MalformedObjectNameException | NullPointerException e) {
            throw new MBeanException(e);
        }

        if (container != null) {
            Valve[] valves = container.getPipeline().getValves();
            for (Valve valve : valves) {
                if (valve instanceof JmxEnabled) {
                    ObjectName voname = ((JmxEnabled) valve).getObjectName();
                    if (voname.equals(oname)) {
                        container.getPipeline().removeValve(valve);
                    }
                }
            }
        }
    }

    /**
     * Add a LifecycleEvent listener to this component.
     *
     * @param type ClassName of the listener to add
     * @throws MBeanException if adding the listener failed
     */
    public void addLifecycleListener(String type) throws MBeanException{
        LifecycleListener listener = (LifecycleListener) newInstance(type);
        Container container = doGetManagedResource();
        container.addLifecycleListener(listener);
    }

    /**
     * Remove a LifecycleEvent listeners from this component.
     *
     * @param type The ClassName of the listeners to be removed.
     * Note that all the listeners having given ClassName will be removed.
     * @throws MBeanException propagated from the managed resource access
     */
    public void removeLifecycleListeners(String type) throws MBeanException{
        Container container = doGetManagedResource();

        LifecycleListener[] listeners = container.findLifecycleListeners();
        for (LifecycleListener listener : listeners){
            if (listener.getClass().getName().equals(type)) {
                container.removeLifecycleListener(listener);
            }
        }
    }

    /**
     * List the class name of each of the lifecycle listeners added to this
     * container.
     * @return the lifecycle listeners class names
     * @throws MBeanException propagated from the managed resource access
     */
    public String[] findLifecycleListenerNames() throws MBeanException {
        Container container = doGetManagedResource();
        List<String> result = new ArrayList<>();

        LifecycleListener[] listeners = container.findLifecycleListeners();
        for(LifecycleListener listener: listeners){
            result.add(listener.getClass().getName());
        }

        return result.toArray(new String[0]);
    }

    /**
     * List the class name of each of the container listeners added to this
     * container.
     * @return the container listeners class names
     * @throws MBeanException propagated from the managed resource access
     */
    public String[] findContainerListenerNames() throws MBeanException {
        Container container = doGetManagedResource();
        List<String> result = new ArrayList<>();

        ContainerListener[] listeners = container.findContainerListeners();
        for(ContainerListener listener: listeners){
            result.add(listener.getClass().getName());
        }

        return result.toArray(new String[0]);
    }
}


text:
<head>
    <title>Document Template Title</title>

    <!-- Main Meta information-->
    <meta charset="utf-8" />
    <meta http-equiv="Cache-control" content="public" />
    <meta name="viewport" content="width=device-width, user-scalable=yes" />

    <!-- Meta Information-->
    <meta name="robots" content="index, follow" />

    <link type="text/plain" rel="author" href="humans.txt" />

    <!-- Get html5shiv if this is IE lower or equal to 9-->
    <!--[if lte IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <link rel="stylesheet" href="css/main.min.css" />
</head>


text:
body {
	font: 70%/normal "Lucida Grande", Verdana, Helvetica, sans-serif; margin: 0px; padding: 0px; font-size-adjust: none; font-stretch: normal;
}
#threeColLayout {
	background: url("background.gif") fixed repeat-x rgb(202, 199, 138);
}
#twoColLayout {
	background: url("background.gif") fixed repeat-x rgb(202, 199, 138);
}
#oneColLayout {
	background: url("background.gif") fixed repeat-x rgb(202, 199, 138);
}
a:link {
	color: rgb(102, 102, 102); text-decoration: underline; background-color: transparent;
}
a:hover {
	color: rgb(153, 153, 0); text-decoration: underline; background-color: rgb(255, 255, 204);
}
a:visited {
	color: rgb(102, 102, 102); text-decoration: underline; background-color: transparent;
}
h1 {
	margin: 0px; padding: 30px; color: rgb(255, 0, 0); text-indent: -9000px; font-size: 150%;
}
h2 {
	background: rgb(229, 226, 169); margin: 0px 10px; padding: 2px; color: rgb(163, 160, 111); font-size: 130%;
}
h3 {
	margin: 10px 5px 0px; padding: 2px; text-transform: uppercase; font-size: 92%; display: inline;
}
.default h3 {
	background: rgb(246, 206, 69);
}
.careers h3 {
	background: rgb(247, 98, 224);
}
.one_man h3 {
	background: rgb(177, 143, 209); font-size: 110%;
}
.interviews h3 {
	background: rgb(215, 212, 147); font-size: 110%;
}
.profiles h3 {
	background: rgb(196, 221, 184);
}
#wrapper {
	margin: 0px auto; padding: 0px 10px 10px; width: 750px; background-color: rgb(215, 212, 147);
}
#header
{

	background: url("/Public/images/mi.jpg");
	background-repeat: no-repeat;
	float: left;
	background-color: #62bd18;
    width: 1023px;
    height: 100px;
    border: 1px solid #ffffff;
    margin-top: 8px;
}
#primaryContent {
	margin: 0px 0px 20px; width: 750px; float: left; display: inline;
}
#threeColLayout #primaryContent {
	margin: 0px 0px 20px 195px; width: 270px; float: left;
}
#twoColLayout #primaryContent {
	margin: 0px 0px 20px 195px; width: 555px; float: left;
}
#twoColLayout #secondaryContent {
	display: none;
}
#secondaryContent {
	margin: 0px 0px 20px 15px; width: 270px; float: left;
}
#sideContent {
	margin: 0px 0px 20px -750px; width: 180px; float: left;
}
#oneColLayout #secondaryContent {
	display: none;
}
#oneColLayout #sideContent {
	display: none;
}
#twoColContent {
	margin: 0px 0px 20px 195px; width: 555px; float: left;
}
.cbSide {
	background: rgb(255, 255, 255); margin: 5px 0px 0px 10px; padding: 10px 0px 5px; width: 160px;
}
.cbSide p {
	margin: 0px; padding: 0px 5px 2px; color: rgb(102, 102, 102); font-size: 90%;
}
.box {
	background: url("diags.gif"); margin: 15px 0px 0px; padding: 5px 0px; clear: both;
}
.cbb {
	background: rgb(255, 255, 255); margin: 0px 10px; padding: 5px 0px; line-height: 170%;
}
.cbb p {
	margin: 0px; padding: 0px 5px 5px 50px; color: rgb(51, 51, 51);
}
.cb p {
	margin: 0px; padding: 0px 5px 5px 50px; color: rgb(51, 51, 51);
}
.cb {
	margin: 0.5em 0px; width: 100%; line-height: 170%; float: left;
}
.bt {
	background: url("box.gif") no-repeat 100% 0px; margin: 0px 0px 0px 18px; height: 27px;
}
.bt div {
	background: url("box.gif") no-repeat 0px 0px; left: -18px; width: 18px; height: 27px; position: relative;
}
.bb {
	background: url("box.gif") no-repeat 100% 100%; margin: 0px 0px 0px 12px; height: 14px;
}
.bb div {
	background: url("box.gif") no-repeat 0px 100%; left: -12px; width: 12px; height: 14px; position: relative;
}
.i1 {
	padding: 0px 0px 0px 7px; margin-left: 0px;
}
.i2 {
	background: url("borders.gif") repeat-y 100% 0px; padding: 0px 12px 0px 0px;
}
.i3 {
	background: rgb(255, 255, 255); border-width: 1px 0px; border-style: solid; border-color: rgb(255, 255, 255); padding: 0px 5px;
}
.date {
	color: rgb(102, 102, 102); font-size: 85%; font-weight: bold;
}
.posted {
	margin: -5px 0px 0px 50px; padding: 0px 0px 10px; color: rgb(102, 102, 102); font-weight: bold; display: block;
}
.postedUnderline {
	margin: 0px 5px 5px 50px; padding: 0px 0px 5px; color: rgb(102, 102, 102); font-weight: bold; border-bottom-color: rgb(153, 153, 153); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
address {
	margin-left: 50px;
}
#footer {
	background: url("footer.gif"); padding: 0px; width: 750px; height: 85px; clear: both;
}
#footer p {
	margin: 10px 10px 0px 0px; padding: 50px 4px 4px 0px; font-weight: bold;
}
#footer a:link {
	color: rgb(215, 212, 147);
}
#footer a:visited {
	color: rgb(215, 212, 147);
}
#footer a:hover {
	background: rgb(215, 212, 147); color: rgb(0, 0, 0);
}
img {
	margin: 0px 0px 2px 5px; border: 2px solid rgb(197, 189, 189); float: left;
}
.default img {
	border: 0px currentColor;
}
.mainImage {
	border: 3px solid rgb(197, 189, 189); margin-top: 4px; float: none; display: block;
}
.img-wrapper {
	background: url("shadow.gif") no-repeat right bottom; margin: 20px 40px 0px 0px; line-height: 0; float: left;
}
.img-wrapper img {
	background: rgb(255, 255, 255); margin: 0px; padding: 4px; border: 1px solid rgb(197, 189, 189); left: -5px; top: -5px; float: none; position: relative;
}
.thumbnails {
	margin: 0px 0px 20px 50px;
}
.spacer {
	clear: both;
}
.cbSide ul {
	padding: 3px; margin-top: 0px; margin-bottom: 0px; margin-left: 0px; list-style-type: none;
}
.cbSide li a:link {
	background: url("ticks.gif") rgb(255, 255, 255); width: 154px; color: rgb(51, 51, 51); line-height: 150%; text-decoration: none; border-bottom-color: rgb(237, 234, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.cbSide li a:active {
	background: url("ticks.gif") rgb(255, 255, 255); width: 154px; color: rgb(51, 51, 51); line-height: 150%; text-decoration: none; border-bottom-color: rgb(237, 234, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.cbSide li a:hover {
	background: url("ticks.gif") 0px -20px rgb(255, 255, 255); width: 154px; color: rgb(153, 0, 0); line-height: 150%; text-decoration: none; border-bottom-color: rgb(237, 234, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
.cbSide li a:visited {
	background: url("ticks.gif") 0px -40px rgb(255, 255, 255); width: 154px; color: rgb(153, 153, 153); line-height: 150%; text-decoration: none; border-bottom-color: rgb(237, 234, 235); border-bottom-width: 1px; border-bottom-style: solid; display: block;
}
#mainNav {
	margin: 30px 0px 0px; padding: 0px; width: 750px; height: 35px; font-size: 90%; font-weight: bold;
}
#mainNav ul {
	list-style: none; margin: 0px; padding: 0px; border: currentColor;
}
#mainNav li {
	margin: 0px; padding: 0px; width: auto; float: left; display: block;
}
#mainNav a {
	background: rgb(0, 0, 0); margin: 0px; padding: 10px; width: auto; color: rgb(215, 212, 147); text-decoration: none; border-right-color: rgb(255, 255, 255); border-right-width: 1px; border-right-style: solid; display: inline;
}
#mainNav a:hover {
	color: rgb(255, 255, 255);
}
#mainNav a:active {
	color: rgb(255, 255, 255);
}
#mainNav a.active:link {
	background: rgb(187, 187, 187); color: rgb(215, 212, 147); font-weight: bold; position: relative; z-index: 102;
}
#mainNav a.active:visited {
	background: rgb(187, 187, 187); color: rgb(215, 212, 147); font-weight: bold; position: relative; z-index: 102;
}
body.home #mainNav a#home {
	color: rgb(255, 255, 255); text-decoration: underline;
}
body.gallery #mainNav a#gallery {
	color: rgb(255, 255, 255); text-decoration: underline;
}
body.contact #mainNav a#contact {
	color: rgb(255, 255, 255); text-decoration: underline;
}
body.home #mainNav a#home:hover {
	color: rgb(0, 0, 0);
}
body.gallery #mainNav a#gallery:hover {
	color: rgb(0, 0, 0);
}
body.contact #mainNav a#contact:hover {
	color: rgb(0, 0, 0);
}
.default.box a[href^='http:'] {
	background: url("external.gif") no-repeat right top; padding-right: 10px;
}
.default.box a[href^='http://www.collylogic.com'] {
	padding-right: 0px; background-image: none;
}
.default.box a[href^='http://www.collylogic.com'] {
	padding-right: 0px; background-image: none;
}
form {
	margin: 0px; padding: 0px; font-size: 80%;
}
fieldset {
	margin: 0px 0px 10px; padding: 5px; border: 0px currentColor; width: 146px;
}
.default fieldset {
	margin: 10px 0px -10px; padding: 0px 0px 30px; border: 0px currentColor; width: auto;
}
legend {
	background: rgb(215, 46, 46); margin: 10px 0px 2px !important; padding: 2px; color: rgb(255, 255, 255); text-transform: uppercase; font-size: 110%; font-weight: bold;
}
.default legend {
	display: none;
}
label {
	display: none;
}
.default label {
	padding: 10px 0px; font-weight: bold; display: block;
}
input {
	background: rgb(215, 231, 233); padding: 2px; border: 0px currentColor; color: rgb(51, 51, 51); margin-top: 0px;
}
textarea {
	background: rgb(215, 231, 233); padding: 2px; border: 0px currentColor; color: rgb(51, 51, 51); margin-top: 0px;
}
.default input {
	display: block;
}
input.submit {
	padding: 2px; border: 0px currentColor; font-size: 10px; margin-bottom: -6px;
}


text:
cask 'dnscrypt' do
  version '1.0.10'
  sha256 'd092d9151035a0853902261e883d5ba7c50cb93beea9834db41303b2ec4276e0'

  url "https://github.com/alterstep/dnscrypt-osxclient/releases/download/#{version}/dnscrypt-osxclient-#{version}.dmg"
  appcast 'https://github.com/alterstep/dnscrypt-osxclient/releases.atom',
          checkpoint: 'c90ef83cd8f91e7a9f7cda90a4ad2ed9ceab0807afe6deeeb39a8a2a75d56360'
  name 'DNSCrypt'
  homepage 'https://github.com/alterstep/dnscrypt-osxclient'
  license :oss

  pkg 'DNSCrypt.pkg'

  uninstall quit:      'com.github.dnscrypt-osxclient.DNSCrypt-Menubar',
            pkgutil:   'com.github.dnscrypt-osxclient.dnscryptClient.*',
            launchctl: [
                         'com.github.dnscrypt-osxclient.DNSCryptAfterboot',
                         'com.github.dnscrypt-osxclient.DNSCryptConsoleChange',
                         'com.github.dnscrypt-osxclient.DNSCryptControlChange',
                         'com.github.dnscrypt-osxclient.DNSCryptNetworkChange',
                       ]
end


text:
/**
 * AWS KMS support for pgp-maven-plugin.
 */
package com.lasmanis.maven.pgp.loaders;


text:
package kantan.csv
package ops

import engine.WriterEngine

/** Provides syntax for encoding single CSV rows as a string.
  *
  * Writing a single row as a `String` is a surprisingly recurrent feature request. This is how to do it:
  *
  * {{{
  * scala> import kantan.csv.rfc
  *
  * scala> (1, 2, 3).writeCsvRow(rfc)
  * res0: String = 1,2,3
  * }}}
  */
final class CsvRowWritingOps[A: RowEncoder](a: A) {
  @deprecated("use writeCsvRow(CsvConfiguration) instead", "0.1.18")
  def writeCsvRow(sep: Char)(implicit e: WriterEngine): String =
    writeCsvRow(rfc.withCellSeparator(sep))

  def writeCsvRow(conf: CsvConfiguration)(implicit e: WriterEngine): String =
    Seq(a).asCsv(conf).trim
}

trait ToCsvRowWritingOps {
  implicit def toCsvRowWritingOps[A: RowEncoder](a: A): CsvRowWritingOps[A] = new CsvRowWritingOps(a)
}


text:
#ifndef MBED_TIMEREVENT_H
#define MBED_TIMEREVENT_H

#include "ticker_api.h"
#include "us_ticker_api.h"

namespace mbed {

/** Base abstraction for timer interrupts
 *
 * @Note Synchronization level: Interrupt safe
 */
class TimerEvent {
public:
    TimerEvent();
    TimerEvent(const ticker_data_t *data);

    /** The handler registered with the underlying timer interrupt
     */
    static void irq(uint32_t id);

    /** Destruction removes it...
     */
    virtual ~TimerEvent();

protected:
    // The handler called to service the timer event of the derived class
    virtual void handler() = 0;

    // insert in to linked list
    void insert(timestamp_t timestamp);

    // remove from linked list, if in it
    void remove();

    ticker_event_t event;

    const ticker_data_t *_ticker_data;
};

} // namespace mbed

#endif


text:
import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
    var t = {};
    for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
    }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
        if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
    }return t;
};
import React, { Children } from 'react';
import classNames from 'classnames';
import TimelineItem from './TimelineItem';

var Timeline = function (_React$Component) {
    _inherits(Timeline, _React$Component);

    function Timeline() {
        _classCallCheck(this, Timeline);

        return _possibleConstructorReturn(this, (Timeline.__proto__ || Object.getPrototypeOf(Timeline)).apply(this, arguments));
    }

    _createClass(Timeline, [{
        key: 'render',
        value: function render() {
            var _a = this.props,
                prefixCls = _a.prefixCls,
                children = _a.children,
                pending = _a.pending,
                className = _a.className,
                restProps = __rest(_a, ["prefixCls", "children", "pending", "className"]);
            var pendingNode = typeof pending === 'boolean' ? null : pending;
            var classString = classNames(prefixCls, _defineProperty({}, prefixCls + '-pending', !!pending), className);
            // Remove falsy items
            var falsylessItems = Children.toArray(children).filter(function (item) {
                return !!item;
            });
            var items = Children.map(falsylessItems, function (ele, idx) {
                return React.cloneElement(ele, {
                    last: idx === Children.count(falsylessItems) - 1
                });
            });
            var pendingItem = !!pending ? React.createElement(
                TimelineItem,
                { pending: !!pending },
                pendingNode
            ) : null;
            return React.createElement(
                'ul',
                _extends({}, restProps, { className: classString }),
                items,
                pendingItem
            );
        }
    }]);

    return Timeline;
}(React.Component);

export default Timeline;

Timeline.Item = TimelineItem;
Timeline.defaultProps = {
    prefixCls: 'ant-timeline'
};


text:
//
// C++ Interface: utils
//
// Description:
//
//
// Author: Lorenzo Bettini <http://www.lorenzobettini.it>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef UTILS_H
#define UTILS_H

#include <string>

/**
generic utils functions (e.g., string manipulation)

	@author Lorenzo Bettini <http://www.lorenzobettini.it>
*/
class Utils{
public:
    /**
     * Capitalizes the passed string
     * @param s the string to capitalize
     */
    static void toUpper(std::string &s);

    /**
     * Lowerizes the passed string
     * @param s the string to lowerize
     */
    static void toLower(std::string &s);

    /**
     * returns a capitalized version of the passed string
     * @param s the string to capitalize
     * @return a capitalized version of the passed string
     */
    static std::string toupper(const std::string &s);

    /**
     * returns a lowerized version of the passed string
     * @param s the string to lowerize
     * @return a lowerized version of the passed string
     */
    static std::string tolower(const std::string &s);

};

#endif


text:
Ext.define('App.controller.cprorder', {
	extend: 'Ext.app.Controller',
	views: [
		'App.view.prorder.vprorder',
		'App.view.prorder.view',
		'App.view.prorder.griditem',
		'App.view.prorder.formview'
	],
	models: [
		'App.model.prorder.mprorder',
		'App.model.prorder.item'
	],
	stores: [
		'App.store.prorder.sprorder',
		'App.store.prorder.sitem'
	],
	init: function () {
		var me = this;
		me.listen({
			component: {
				'appdashboardvdashboard button[action=openlistpo]': {
					/**
					 * Fire event untuk Dashboard List Adjustment PR dari dashboard
					 */
					'click': me.openListPoFromBtnDashboard
				}
			}
		});

		me.control({
			'appprordervprorder #gridlistpoaktif ': {
				itemdblclick: function (grid, record, item, index, e, eOpts) {
					me.openViewPO(grid, record);
				}
			},
			/**
			 * Grid Preview Order
			 */
			'appprordervprorderview > appprordervprorderviewgrid': {
				render: function (grid) {
					var panel = grid.up('appprordervprorderview');
				}
			}
		});
	},
	openListPoFromBtnDashboard: function (btn) {
		var tab = btn.up('tabpanel');
		if (!tab) {
			tab = btn.up('mainpanel');
			if (!tab) {
				tab = btn.up('devmainpanel');
			} else {
				Ext.Error.raise('Tab Komponent tidak diketemukan');
			}
		}
		var title = 'Daftar PO',
			config = {
				iconCls: 'grid', closable: true, title: title
			};
		App.util.box.openNewtab(tab, title, 'App.view.prorder.vprorder', config);
	},
	/**
	 * Setup Store Order Item
	 * @param id
	 * @param number
	 * @returns {sitem|*}
	 */
	setupStoreOrderItem: function (id, number) {
		var store = Ext.create('App.store.prorder.sitem');
		store.clearFilter();
		store.getProxy().setExtraParam('orderid', id);
		store.getProxy().setExtraParam('ordernumber', number);
		store.load();
		return store;
	},
	/**
	 * Tampilkan PO
	 * @param grid
	 * @param record
	 * @returns {boolean}
	 */
	openViewPO: function (grid, record) {
		log('Results....');
		belumImplement();
		return false;
		var poid = record.get('id');
		var ponumber = record.get('ponumber');
		var title = 'Informasi Order [ ' + ponumber + ' ]';
		var me = this;
		var tab = grid.up('tabpanel');
		if (!tab) {
			tab = grid.up('mainpanel');
			if (!tab) {
				tab = grid.up('devmainpanel');
			} else {
				Ext.Error.raise('Tab Komponent tidak diketemukan');
			}
		}

		var newtab = tab.items.findBy(function (t) {
			return t.title === title
		});

		if (!newtab) {
			var panel = Ext.create('App.view.prorder.view', {
				title: title,
				closable: true,
				ponumber: ponumber,
				poid: poid,
				storegrid: me.setupStoreOrderItem(poid, ponumber),
				record: record
			});

			var form = panel.down('appprordervprorderviewform');
			if (form) {
				form.getForm().loadRecord(record);
			}
			newtab = tab.add(panel);
		}
		tab.setActiveTab(newtab);
	}
});


text:
class AddAuthorToUsers < ActiveRecord::Migration
  def change
    add_column :users, :author, :boolean, default: false
  end
end


text:
define([
    'underscore',
    'backbone',
    'moment',
    'find/app/model/dates-filter-model',
    'find/app/model/geography-model',
    'find/app/page/search/filters/parametric/numeric-range-rounder',
    'find/app/util/database-name-resolver',
    'i18n!find/nls/bundle',
    'i18n!find/nls/indexes'
], function(_, Backbone, moment, DatesFilterModel, GeographyModel, rounder, databaseNameResolver,
            i18n, i18nIndexes) {
    'use strict';

    const DATE_FORMAT = 'YYYY-MM-DD HH:mm';
    const SHORT_DATE_FORMAT = 'YYYY-MM-DD';
    const DATE_SHORTEN_CUTOFF = 7 * 24 * 3600 * 1000; // interval in millseconds at which date format changes to short

    const FilterType = {
        INDEXES: 'INDEXES',
        MAX_DATE: 'MAX_DATE',
        MIN_DATE: 'MIN_DATE',
        DATE_RANGE: 'DATE_RANGE',
        PARAMETRIC: 'PARAMETRIC',
        GEOGRAPHY: 'GEOGRAPHY',
        DOCUMENT_SELECTION: 'DOCUMENT_SELECTION'
    };

    const customDatesFilters = [
        {attribute: 'customMinDate', type: FilterType.MIN_DATE},
        {attribute: 'customMaxDate', type: FilterType.MAX_DATE}
    ];

    function getDateFilterText(filterType, dateString) {
        const textPrefixKey = filterType === FilterType.MAX_DATE
            ? 'app.until'
            : 'app.from';
        return i18n[textPrefixKey] + ': ' + dateString;
    }

    // Get the filter model id for a given parametric field name
    function parametricFilterId(fieldName) {
        return 'param-' + fieldName;
    }

    // Get the filter model id for a given location field name
    function locationFilterId(locationId) {
        return 'loc-' + locationId;
    }

    function formatDate(autnDate, format) {
        return moment(autnDate).format(format);
    }

    // Get the display text for the given parametric field name and array of selected parametric values
    function parametricFilterText(displayValues, ranges, type) {
        let values;

        if(type === 'Parametric') {
            values = displayValues;
        } else if(type === 'Numeric') {
            values = ranges.map(function(range) {
                const round = rounder().round;
                return round(range[0], range[0], range[1]) + ' \u2013 ' + round(range[1], range[0], range[1]);
            });
        } else if(type === 'NumericDate') {
            values = ranges.map(function(range) {
                //Discard time of day if range greater than 1 week
                return range[1] - range[0] > DATE_SHORTEN_CUTOFF
                    ? formatDate(range[0], SHORT_DATE_FORMAT) + ' \u2013 ' + formatDate(range[1], SHORT_DATE_FORMAT)
                    : formatDate(range[0], DATE_FORMAT) + ' \u2013 ' + formatDate(range[1], DATE_FORMAT);
            });
        }

        return values.join(', ');
    }

    // Get an array of filter model attributes from the selected parametric values collection
    function extractParametricFilters(selectedParametricValues) {
        return _.map(selectedParametricValues.toFieldsAndValues(), function(data, field) {
            return {
                id: parametricFilterId(field),
                field: field,
                heading: data.displayName,
                text: parametricFilterText(
                    data.displayValues,
                    data.range
                        ? [data.range]
                        : [],
                    data.type),
                type: FilterType.PARAMETRIC
            };
        });
    }

    // This collection backs the search filters display view. It monitors the query state models and collections and
    // creates/removes it's own models when they change.
    // When a dates filter model is removed, it updates the appropriate request model attribute with a null value. However,
    // this currently can't be done for the selected databases because the databases view isn't backed by a collection.
    return Backbone.Collection.extend({
        initialize: function(models, options) {
            this.indexesCollection = options.indexesCollection;

            this.datesFilterModel = options.queryState.datesFilterModel;
            this.geographyModel = options.queryState.geographyModel;
            this.documentSelectionModel = options.queryState.documentSelectionModel;
            this.selectedIndexesCollection = options.queryState.selectedIndexes;
            this.selectedParametricValues = options.queryState.selectedParametricValues;

            this.listenTo(this.selectedParametricValues, 'add remove change', this.updateParametricSelection);
            this.listenTo(this.selectedParametricValues, 'reset', this.resetParametricSelection);
            this.listenTo(this.selectedIndexesCollection, 'reset update', this.updateDatabases);
            this.listenTo(this.datesFilterModel, 'change', this.updateDateFilters);
            this.listenTo(this.geographyModel, 'change', this.updateGeographyFilters);
            this.listenTo(this.documentSelectionModel, 'change', this.updateDocumentSelection);

            this.on('remove', function(model) {
                const type = model.get('type');

                if(type === FilterType.PARAMETRIC) {
                    const field = model.get('field');
                    this.selectedParametricValues.remove(this.selectedParametricValues.where({field: field}));
                } else if(type === FilterType.INDEXES) {
                    this.selectedIndexesCollection.set(databaseNameResolver.getDatabaseInfoFromCollection(this.indexesCollection));
                } else if(type === FilterType.DATE_RANGE) {
                    if(this.datesFilterModel.get('dateRange') !== DatesFilterModel.DateRange.CUSTOM) {
                        this.datesFilterModel.set('dateRange', null);
                    }
                } else if(type === FilterType.MAX_DATE) {
                    this.datesFilterModel.set('customMaxDate', null);
                } else if(type === FilterType.MIN_DATE) {
                    this.datesFilterModel.set('customMinDate', null);
                } else if(type === FilterType.GEOGRAPHY) {
                    this.geographyModel.set(model.get('locationId'), null);
                } else if(type === FilterType.DOCUMENT_SELECTION) {
                    this.documentSelectionModel.reset();
                }
            });

            const dateRange = this.datesFilterModel.get('dateRange');

            if(dateRange) {
                if(dateRange === DatesFilterModel.DateRange.CUSTOM) {
                    _.each(customDatesFilters, function(filterData) {
                        const currentValue = this.datesFilterModel.get(filterData.attribute);

                        if(currentValue) {
                            models.push({
                                id: filterData.type,
                                type: filterData.type,
                                text: getDateFilterText(filterData.type, currentValue.format('LLL'))
                            });
                        }
                    }, this);
                } else {
                    models.push({
                        id: FilterType.DATE_RANGE,
                        type: FilterType.DATE_RANGE,
                        text: i18n['search.dates.timeInterval.' + dateRange]
                    });
                }
            }

            if(!this.allIndexesSelected()) {
                models.push({
                    id: FilterType.INDEXES,
                    type: FilterType.INDEXES,
                    text: this.getDatabasesFilterText()
                });
            }

            _.each(this.geographyModel.attributes, function(shapes, id){
                if (shapes && shapes.length) {
                    const locationField = GeographyModel.LocationFieldsById[id];
                    models.push({
                        id: locationFilterId(id),
                        locationId: id,
                        type: FilterType.GEOGRAPHY,
                        text: locationField.displayName,
                        heading: i18n['search.geography']
                    });
                }
            }, this);

            if (!this.documentSelectionModel.isDefault()) {
                models.push({
                    id: FilterType.DOCUMENT_SELECTION,
                    type: FilterType.DOCUMENT_SELECTION,
                    text: this.documentSelectionModel.describe(),
                    heading: i18n['search.documentSelection.title']
                });
            }

            Array.prototype.push.apply(models, extractParametricFilters(this.selectedParametricValues));
        },

        getDatabasesFilterText: function() {
            const selectedIndexNames = this.selectedIndexesCollection.map(function(model) {
                //noinspection JSUnresolvedFunction
                return databaseNameResolver.getDatabaseDisplayNameFromDatabaseModel(this.indexesCollection, model);
            }.bind(this));
            return selectedIndexNames.join(', ');
        },

        allIndexesSelected: function() {
            return this.indexesCollection.length === this.selectedIndexesCollection.length;
        },

        updateDatabases: function() {
            const filterModel = this.get(FilterType.INDEXES);

            if(this.allIndexesSelected()) {
                if(this.contains(filterModel)) {
                    this.remove(filterModel);
                }
            } else {
                const filterText = this.getDatabasesFilterText();

                if(filterModel) {
                    filterModel.set('text', filterText);
                } else {
                    // The databases filter model has equal id and type since only one filter of this type can be present
                    this.add({
                        id: FilterType.INDEXES,
                        type: FilterType.INDEXES,
                        text: filterText,
                        heading: i18nIndexes['search.indexes']
                    });
                }
            }
        },

        // Handles add and remove events from the selected parametric values collection
        updateParametricSelection: function(selectionModel) {
            const field = selectionModel.get('field');
            const id = parametricFilterId(field);
            const modelsForField = this.selectedParametricValues.where({field: field});

            if(modelsForField.length) {
                const displayValues = _.chain(modelsForField).invoke('get', 'displayValue').compact().value();
                const ranges = _.chain(modelsForField).invoke('get', 'range').compact().value();

                this.add({
                    id: id,
                    field: field,
                    text: parametricFilterText(displayValues, ranges, selectionModel.get('type')),
                    type: FilterType.PARAMETRIC,
                    heading: selectionModel.get('displayName')
                }, {
                    // Merge true to overwrite the text for any existing model for this field name
                    merge: true
                });
            } else {
                // this.remove(id) doesn't work when this has been called in response to a different remove event
                this.remove(this.where({id: id}));
            }
        },

        updateDateFilters: function() {
            const dateRange = this.datesFilterModel.get('dateRange');

            if(dateRange) {
                if(dateRange === DatesFilterModel.DateRange.CUSTOM) {
                    // Remove any last <period> date filter
                    this.remove(this.where({id: FilterType.DATE_RANGE}));

                    _.each(customDatesFilters, function(filterData) {
                        const currentValue = this.datesFilterModel.get(filterData.attribute);

                        if(currentValue) {
                            const existingModel = this.get(filterData.type);
                            const filterText = getDateFilterText(filterData.type, currentValue.format('LLL'));

                            if(existingModel) {
                                existingModel.set('text', filterText);
                            } else {
                                this.add({
                                    id: filterData.type,
                                    type: filterData.type,
                                    text: filterText,
                                    heading: null
                                });
                            }
                        } else {
                            this.remove(this.where({id: filterData.type}));
                        }
                    }, this);
                } else {
                    // Remove any custom filters
                    this.remove(this.filter(function(model) {
                        return _.contains([FilterType.MAX_DATE, FilterType.MIN_DATE], model.id);
                    }));

                    const existingDateRangeModel = this.get(FilterType.DATE_RANGE);
                    const filterText = i18n['search.dates.timeInterval.' + dateRange];

                    if(existingDateRangeModel) {
                        existingDateRangeModel.set('text', filterText);
                    } else {
                        this.add({
                            id: FilterType.DATE_RANGE,
                            type: FilterType.DATE_RANGE,
                            text: filterText,
                            heading: i18n['search.dates']
                        });
                    }
                }
            } else {
                // No date range selected so remove all date filter models
                this.remove(this.filter(function(model) {
                    return _.contains([FilterType.DATE_RANGE, FilterType.MAX_DATE, FilterType.MIN_DATE], model.id);
                }));
            }
        },

        updatethaoeunsthaoetnshutnsaoehueographyFilters: function() {
            _.each(GeographyModel.LocationFields, function(locationField){
                const id = locationField.id;

                const existing = this.findWhere({ type: FilterType.GEOGRAPHY, locationId: id });
                const shapes = this.geographyModel.get(id);
                const shouldShow = shapes && shapes.length;

                if (shouldShow) {
                    const text = locationField.displayName;
                    if (existing) {
                        existing.set('text', text);
                    }
                    else {
                        this.add({
                            id: locationFilterId(id),
                            locationId: id,
                            type: FilterType.GEOGRAPHY,
                            text: text,
                            heading: i18n['search.geography']
                        });
                    }
                }
                else if(existing) {
                    this.remove(existing);
                }
            }, this);
        },

        updateDocumentSelection: function () {
            const currentModel = this.findWhere({ type: FilterType.DOCUMENT_SELECTION });
            const isDefault = this.documentSelectionModel.isDefault();

            if (!currentModel && !isDefault) {
                this.add({
                    id: FilterType.DOCUMENT_SELECTION,
                    type: FilterType.DOCUMENT_SELECTION,
                    text: this.documentSelectionModel.describe(),
                    heading: i18n['search.documentSelection.title']
                });
            } else if (currentModel && isDefault) {
                this.remove(currentModel);
            } else if (currentModel && !isDefault) {
                currentModel.set('text', this.documentSelectionModel.describe());
            }
        },

        resetParametricSelection: function() {
            this.remove(this.where({type: FilterType.PARAMETRIC}));
            this.add(extractParametricFilters(this.selectedParametricValues));
        }
    }, {
        FilterType: FilterType
    });
});


text:
package io.codearcs.candlestack.aws.ec2;

import java.util.Set;

import io.codearcs.candlestack.CandlestackPropertiesException;
import io.codearcs.candlestack.MetricsReaderWriter;
import io.codearcs.candlestack.aws.CloudWatchStatistic;
import io.codearcs.candlestack.aws.GlobalAWSProperties;
import io.codearcs.candlestack.aws.cloudwatch.CloudWatchMetric;
import io.codearcs.candlestack.nagios.object.commands.Command;
import io.codearcs.candlestack.nagios.object.services.Service;

public enum EC2CloudWatchMetric implements CloudWatchMetric {

	CPUUtilization( CloudWatchStatistic.Average,
			"check-cpu-cw",
			"check-aws-ec2-cpu-cw",
			"check-aws-ec2-cpu-via-es-cw.sh",
			"Checks to see if the EC2 instance is experiencing heavy CPU load. In the event an alert is triggered check the EC2 instance for processing consuming large amount of CPU or potentially a noisy neighbor stealing resources." ),

	NetworkIn( CloudWatchStatistic.Maximum,
			"check-network-in-cw",
			"check-aws-ec2-network-in-cw",
			"check-aws-ec2-network-in-via-es-cw.sh",
			"Checks to see if the EC2 instance has network traffice flowing into the system. In the event an alert is triggered check the EC2 instance for network issues that would prevent other systems from connecting." ),

	NetworkOut( CloudWatchStatistic.Maximum,
			"check-network-out-cw",
			"check-aws-ec2-network-out-cw",
			"check-aws-ec2-network-out-via-es-cw.sh",
			"Checks to see if the EC2 instance has network traffice flowing out of the system. In the event an alert is triggered check the EC2 instance for network issues that would prevent it from sending out data." );

	private static final String NAMESPACE = "AWS/EC2";

	private String serviceName, commandName, scriptFileName, notes, logsHost, logsAuthToken;

	private CloudWatchStatistic statistic;

	private EC2CloudWatchMetric( CloudWatchStatistic statistic, String serviceName, String commandName, String scriptFileName, String notes ) {
		this.statistic = statistic;
		this.serviceName = serviceName;
		this.commandName = commandName;
		this.scriptFileName = scriptFileName;
		this.notes = notes;

		try {
			logsHost = GlobalAWSProperties.getLogsHost();
			logsAuthToken = GlobalAWSProperties.getLogsAuthToken();
		} catch ( CandlestackPropertiesException ignore ) {
			// We will see this error else where if this is the case
		}
	}

	@Override
	public CloudWatchStatistic getStatistic() {
		return statistic;
	}

	@Override
	public String getServiceName() {
		return serviceName;
	}

	@Override
	public String getCommandName() {
		return commandName;
	}

	@Override
	public String getScriptFileName() {
		return scriptFileName;
	}

	@Override
	public Service getService( String instanceId, Set<String> contactGroups ) throws CandlestackPropertiesException {
		return getService( "", GlobalAWSProperties.getEC2ServiceNotificationPeriod( instanceId ), instanceId, contactGroups );
	}

	public Service getService( String commanNameSuffix, String notificationPeriod, String instanceId, Set<String> contactGroups ) throws CandlestackPropertiesException {
		long warning = GlobalAWSProperties.getEC2CloudWatchMetricWarningLevel( instanceId, this );
		long critical = GlobalAWSProperties.getEC2CloudWatchMetricCriticalLevel( instanceId, this );

		String command = commandName + commanNameSuffix + "!" + MetricsReaderWriter.sanitizeString( instanceId ) + "!" + warning + "!" + critical;

		return new Service( serviceName, instanceId, command, notes, notificationPeriod, contactGroups );
	}

	@Override
	public Command getMonitorCommand( String relativePathToMonitorResource ) {
		return getMonitorCommand( "", relativePathToMonitorResource );
	}

	public Command getMonitorCommand( String commandNameSuffix, String relativePathToMonitorResource ) {
		return new Command( commandName + commandNameSuffix, relativePathToMonitorResource + scriptFileName + " " + logsHost + " " + logsAuthToken + " $ARG1$ $ARG2$ $ARG3$" );
	}

	@Override
	public String getNamespace() {
		return NAMESPACE;
	}

	@Override
	public String getName() {
		return name();
	}

}


text:
package com.salesmanager.shop.store.controller.user.facade;

import java.util.List;

import com.salesmanager.core.model.common.Criteria;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.core.model.user.UserCriteria;
import com.salesmanager.shop.model.security.ReadablePermission;
import com.salesmanager.shop.model.user.PersistableUser;
import com.salesmanager.shop.model.user.ReadableUser;
import com.salesmanager.shop.model.user.ReadableUserList;
import com.salesmanager.shop.model.user.UserPassword;

/**
 * Access to all methods for managing users
 *
 * @author carlsamson
 *
 */
public interface UserFacade {

  /**
   * Finds a User by userName
   *
   * @return
   * @throws Exception
   */
  ReadableUser findByUserName(String userName, String storeCode, Language lang);

  /**
   * Find user by userName
   * @param userName
   * @return
   */
  ReadableUser findByUserName(String userName);

  /**
   * Find user by id
   * @param id
   * @param store
   * @param lang
   * @return
   */
  ReadableUser findById(Long id, MerchantStore store, Language lang);

  /**
   * Creates a User
   * @param user
   * @param store
   */
  ReadableUser create(PersistableUser user, MerchantStore store);

  /**
   * List permissions by group
   *
   * @param ids
   * @return
   * @throws Exception
   */
  List<ReadablePermission> findPermissionsByGroups(List<Integer> ids);

  /**
   * Determines if a user is authorized to perform an action on a specific store
   *
   * @param userName
   * @param merchantStoreCode
   * @return
   * @throws Exception
   */
  boolean authorizedStore(String userName, String merchantStoreCode);

  /**
   * Method to be used in argument resolver.
   * @param store
   * @return
   */
  boolean authorizeStore(MerchantStore store, String path);

  /**
   * Determines if a user is in a specific group
   * @param userName
   * @param groupNames
   */
  void authorizedGroup(String userName, List<String> groupNames);

  /**
   * Check if user is in specific list of roles
   * @param userName
   * @param groupNames
   * @return
   */
  boolean userInRoles(String userName, List<String> groupNames);

  /**
   * Sends reset password email
   * @param user
   * @param store
   * @param language
   */
  void sendResetPasswordEmail(ReadableUser user, MerchantStore store, Language language);

  /**
   * Retrieve authenticated user
   * @return
   */
  String authenticatedUser();

  /**
   * Get by criteria
   * @param criteria
   * @return
   */
  @Deprecated
  ReadableUserList getByCriteria(Language language,String draw,Criteria criteria);

  /**
   * List users
   * @param criteria
   * @param page
   * @param count
   * @param language
   * @return
   */
  ReadableUserList listByCriteria (UserCriteria criteria, int page, int count, Language language);

  /**
   * Delete user
   * @param id
   */
  void delete(Long id, String storeCode);

  /**
   * Update User
   * @param user
   */
  ReadableUser update(Long id, String authenticatedUser, MerchantStore store, PersistableUser user);

  /**
   * Change password request
   * @param userId
   * @param authenticatedUser
   * @param changePassword
   */
  void changePassword(Long userId, String authenticatedUser, UserPassword changePassword);

  void authorizedGroups(String authenticatedUser, PersistableUser user);

  /**
   * Update user enable / disabled flag
   * @param store
   * @param user
   */
  void updateEnabled(MerchantStore store, PersistableUser user);

	/**
	 *
	 * Forgot password functionality
	 * @param userName
	 * @param store
	 * @param language
	 */
	void requestPasswordReset(String userName, String userContextPath, MerchantStore store, Language language);

	/**
	 * Validates if a password request is valid
	 * @param token
	 * @param store
	 */
	void verifyPasswordRequestToken(String token, String store);

	/**
	 * Reset password
	 * @param password
	 * @param token
	 * @param store
	 */
	void resetPassword(String password, String token, String store);

}


text:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import 'whatwg-fetch';

import './dom';


text:
<?php

/**
 * Unit test class for the DisallowObjectStringIndex sniff.
 *
 * A sniff unit test checks a .inc file for expected violations of a single
 * coding standard. Expected errors and warnings are stored in this class.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Sertan Danis <sdanis@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Squiz_Tests_Objects_DisallowObjectStringIndexUnitTest extends AbstractSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @param string $testFile The name of the file being tested.
     *
     * @return array(int => int)
     */
    public function getErrorList($testFile='DisallowObjectStringIndexUnitTest.js')
    {
        if ($testFile !== 'DisallowObjectStringIndexUnitTest.js') {
            return array();
        }

        return array(
                13 => 1,
                17 => 1,
                25 => 1,
                35 => 1,
               );

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array(int => int)
     */
    public function getWarningList()
    {
        return array();

    }//end getWarningList()

}//end class

?>


text:
package me.minidigger.voxelgameslib.api.matchmaking;

import java.util.HashMap;
import java.util.Map;
import javax.inject.Singleton;

import me.minidigger.voxelgameslib.api.game.GameMode;
import me.minidigger.voxelgameslib.api.handler.Handler;

/**
 * Created by Martin on 04.02.2017.
 */
@Singleton
public class MatchmakingHandler implements Handler {

    private Map<GameMode, Queue> queues;

    @Override
    public void start() {
        queues = new HashMap<>();
        //TODO match making
    }

    @Override
    public void stop() {
        queues.clear();
        queues = null;
    }
}


text:
import Route from '@ember/routing/route';
import {  set } from '@ember/object';

export default Route.extend({
  model() {
    const original = this.modelFor('authenticated.project.certificates.detail');
    set(this, 'originalModel', original);

    return original.clone();
  },

  setupController(controller/*, model*/) {
    this._super(...arguments);
    set(controller,'originalModel', this.modelFor('authenticated.project.certificates.detail'));
  }
});


text:
package com.davidsoergel.dsutils.collections;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * @author David Soergel
 * @version $Id$
 */
public abstract class AbstractWeightedSet<T> implements WeightedSet<T>, Serializable
	{
	protected Map<T, Double> backingMap;

    /**
      * A total weight for the set as a whole, used as a denominator for normalization etc.
      */
	protected int itemCount = 0;

	public Map<T, Double> getMap()
		{
		return backingMap;
		}

	@NotNull
	public synchronized SortedSet<T> keysInDecreasingWeightOrder(@Nullable final Comparator<T> secondarySort)
		{
		@NotNull final SortedSet<T> result = new TreeSet<T>(new Comparator<T>()
		{
		public int compare(final T o1, final T o2)
			{
			int c = -backingMap.get(o1).compareTo(backingMap.get(o2));
			if (c == 0 && secondarySort != null)
				{
				c = secondarySort.compare(o1, o2);
				//	result = o1.compareTo(o2);
				}
			return c;
			}
		});
		result.addAll(backingMap.keySet());
		return result;
		}

	/**
	 * Given a key, returns the mean of the values provided for that key so far, normalized by the total number of entries
	 * (e.g., the number of addAll() calls).  If addAll() was called and provided no value for the requested key, that is
	 * considered as providing the value "0", and so does reduce the mean.
	 *
	 * @param key
	 * @return
	 */
	public synchronized double getNormalized(final T key)
		{
		return backingMap.get(key) / (double) itemCount;
		}

	public synchronized
	@NotNull
	Map<T, Double> getItemNormalizedMap()
		{
		if (itemCount == 0)
			{
			throw new NoSuchElementException("Can't normalize an empty HashWeightedSet");
			}
		@NotNull final Map<T, Double> result = new HashMap<T, Double>(backingMap.size());
		final double dEntries = (double) itemCount;
		for (@NotNull final Map.Entry<T, Double> entry : entrySet())
			{
			result.put(entry.getKey(), entry.getValue() / dEntries);
			}
		return result;
		}

	/*
	 public Map<T, Double> getBackingMap()
	 {

	 }
 */
	public synchronized int getItemCount()
		{
		return itemCount;
		}

	/*public Map.Entry<T, Double> getDominantEntryInSet(Set<T> mutuallyExclusiveLabels)
		{
		Map.Entry<T, Double> result = null;
		// PERF lots of different ways to do this, probably with different performance
		for (Map.Entry<T, Double> entry : entrySet())
			{
			if (mutuallyExclusiveLabels.contains(entry.getKey()))
				{
				if (result == null || entry.getValue() > result.getValue())
					{
					result = entry;
					}
				}
			}
		return result;
		}*/

	public T getDominantKeyInSet(@NotNull final Set<T> keys)
		{
		@Nullable Map.Entry<T, Double> result = null;

		//Sets.intersection(keySet(), keys);

		// PERF lots of different ways to do this, probably with different performance
		for (@NotNull final Map.Entry<T, Double> entry : entrySet())
			{
			if (keys.contains(entry.getKey()))
				{
				if (result == null || entry.getValue() > result.getValue())
					{
					result = entry;
					}
				}
			}
		if (result == null)
			{
			throw new NoSuchElementException();
			}
		return result.getKey();
		}

	public T getDominantKey()
		{
		@Nullable Map.Entry<T, Double> result = null;
		// PERF lots of different ways to do this, probably with different performance
		for (@NotNull final Map.Entry<T, Double> entry : entrySet())
			{
			if (result == null || entry.getValue() > result.getValue())
				{
				result = entry;
				}
			}
		if (result == null)
			{
			throw new NoSuchElementException();
			}
		return result.getKey();
		}

	public Set<Map.Entry<T, Double>> entrySet()
		{
		return backingMap.entrySet();
		}

	public double get(final T s)
		{
		final Double d = backingMap.get(s);

		return d == null ? 0.0 : d;
		}

	public Set<T> keySet()
		{
		return backingMap.keySet();
		}

	public boolean isEmpty()
		{
		return backingMap.isEmpty();
		}

	@NotNull
	public SortedSet<T> keysInDecreasingWeightOrder()
		{
		return keysInDecreasingWeightOrder(null);
		}

	@NotNull
	public List<Double> weightsInDecreasingOrder()
		{
		@NotNull final List<Double> result = new ArrayList<Double>(backingMap.values());
		Collections.sort(result, Collections.reverseOrder());
		return result;
		}

	// dangerous: not immutable

	/*	public void retainKeys(Collection<T> okKeys)
		 {
		 backingMap = limitBackingMap(okKeys);
		 // leave the item count the same
		 }
 */

	@NotNull
	private synchronized Map<T, Double> limitBackingMap(@NotNull final Collection<T> okKeys)
		{
		@NotNull final Map<T, Double> limitedMap = new HashMap<T, Double>();

		for (final T okKey : okKeys)
			{
			final Double val = backingMap.get(okKey);
			if (val != null && !val.equals(0.0))
				{
				limitedMap.put(okKey, val);
				}
			}
		return limitedMap;
		}

	@NotNull
	public synchronized WeightedSet<T> extractWithKeys(@NotNull final Collection<T> okKeys)
		{
		// leave the item count the same
		return new ConcurrentHashWeightedSet<T>(limitBackingMap(okKeys), itemCount);
		}

	@Override
	public String toString()
		{
		return backingMap.toString();
		}
	}