text:
package com.facebook.buck.dalvik;

import com.facebook.buck.jvm.java.classes.AbstractFileLike;
import com.facebook.buck.jvm.java.classes.FileLike;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * Helper to create a "canary" class for the secondary DEX. See {@link #create}.
 */
public class CanaryFactory {

  private static final String CANARY_PATH_FORMAT = "secondary/dex%02d/Canary.class";

  /**
   * Produced by compiling the following Java file with JDK 7 with "-target 6 -source 6".
   * <pre>
   * package secondary.dex01;
   * public interface Canary {}
   * </pre>
   */
  private static final byte[] CANARY_TEMPLATE = {
      -54,   -2,  -70,  -66, 0x00, 0x00, 0x00, 0x32,
      0x00, 0x05, 0x07, 0x00, 0x03, 0x07, 0x00, 0x04,
      0x01, 0x00, 0x16, 0x73, 0x65, 0x63, 0x6f, 0x6e,
      0x64, 0x61, 0x72, 0x79, 0x2f, 0x64, 0x65, 0x78,
      0x30, 0x31, 0x2f, 0x43, 0x61, 0x6e, 0x61, 0x72,
      0x79, 0x01, 0x00, 0x10, 0x6a, 0x61, 0x76, 0x61,
      0x2f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x4f, 0x62,
      0x6a, 0x65, 0x63, 0x74, 0x06, 0x01, 0x00, 0x01,
      0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00
  };

  /**
   * Offset into {@link #CANARY_TEMPLATE} where we find the 2-byte UTF-8 index that must be
   * updated for each canary class to change the package.
   */
  private static final int CANARY_INDEX_OFFSET = 32;

  /** Utility class: do not instantiate */
  private CanaryFactory() {}

  /**
   * Adds a "canary" class to a secondary dex that can be safely loaded on any system.
   * This avoids an issue where, during secondary dex loading, we attempt to verify a
   * secondary dex by loading an arbitrary class, but the class we try to load isn't
   * valid on that system (e.g., it depends on Google Maps, but we are on AOSP).
   *
   * @param index Index of the current zip (to ensure unique names).
   */
  public static FileLike create(final int index) {
    final byte[] canaryClass = Arrays.copyOf(CANARY_TEMPLATE, CANARY_TEMPLATE.length);
    final String canaryIndexStr = String.format("%02d", index);
    byte[] canaryIndexBytes = canaryIndexStr.getBytes(Charsets.UTF_8);
    Preconditions.checkState(canaryIndexBytes.length == 2,
        "Formatted index string should always be 2 bytes.");
    System.arraycopy(canaryIndexBytes, 0, canaryClass, CANARY_INDEX_OFFSET, 2);
    String relativePath = String.format(CANARY_PATH_FORMAT, index);
    return getCanaryClass(relativePath, canaryClass);
  }

  private static FileLike getCanaryClass(final String relativePath, final byte[] canaryClass) {
    return new AbstractFileLike() {
      @Override
      public Path getContainer() {
        return Paths.get(":memory:");
      }

      @Override
      public String getRelativePath() {
        return relativePath;
      }

      @Override
      public long getSize() {
        return canaryClass.length;
      }

      @Override
      public InputStream getInput() {
        return new ByteArrayInputStream(canaryClass);
      }
    };
  }
}


text:
#import "ORKSurveyAnswerCellForText.h"

#import "ORKAnswerTextField.h"
#import "ORKAnswerTextView.h"

#import "ORKAnswerFormat_Internal.h"
#import "ORKQuestionStep_Internal.h"

#import "ORKHelpers_Internal.h"
#import "ORKSkin.h"

static const CGFloat TextViewTopPadding = 8.0;
static const CGFloat TextViewBottomPadding = 16.0;
static const CGFloat TextViewMinimumHeight = 140.0;
static const CGFloat ClearTextButtonMinimumHeight = 20.0;
static const CGFloat ErrorLabelTopPadding = 4.0;
static const CGFloat ErrorLabelBottomPadding = 10.0;
static const CGFloat StandardSpacing = 8.0;
static const CGFloat CellBottomPadding = 5.0;

@interface ORKSurveyAnswerCellForText () <UITextViewDelegate>

@property (nonatomic, strong) ORKAnswerTextView *textView;
@property (nonatomic, strong) UILabel *errorLabel;

@end

@implementation ORKSurveyAnswerCellForText {
    NSInteger _maxLength;
    NSString *_defaultTextAnswer;
    UILabel *_textCountLabel;
    UIButton *_clearTextViewButton;
    UIView *_bottomSeperatorView;
    NSMutableArray *_constraints;
    BOOL _hideClearButton;
    BOOL _hideCharacterCountLabel;
}

- (void)applyAnswerFormat {
    ORKAnswerFormat *answerFormat = [self.step impliedAnswerFormat];

    if ([answerFormat isKindOfClass:[ORKTextAnswerFormat class]]) {
        ORKTextAnswerFormat *textAnswerFormat = (ORKTextAnswerFormat *)answerFormat;
        _maxLength = [textAnswerFormat maximumLength];
        _hideClearButton = [textAnswerFormat hideClearButton];
        _hideCharacterCountLabel = [textAnswerFormat hideCharacterCountLabel];
        _defaultTextAnswer = textAnswerFormat.defaultTextAnswer;
        self.textView.autocorrectionType = textAnswerFormat.autocorrectionType;
        self.textView.autocapitalizationType = textAnswerFormat.autocapitalizationType;
        self.textView.spellCheckingType = textAnswerFormat.spellCheckingType;
        self.textView.keyboardType = textAnswerFormat.keyboardType;
        self.textView.secureTextEntry = textAnswerFormat.secureTextEntry;
        self.textView.textContentType = textAnswerFormat.textContentType;

        if (@available(iOS 12.0, *)) {
            self.textView.passwordRules = textAnswerFormat.passwordRules;
        }
    } else {
        _maxLength = 0;
    }
}

- (BOOL)becomeFirstResponder {
    return [self.textView becomeFirstResponder];
}

- (void)setStep:(ORKQuestionStep *)step {
    [super setStep:step];
    [self applyAnswerFormat];
}

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    self.layoutMargins = ORKStandardLayoutMarginsForTableViewCell(self);
}

- (void)prepareView {

    NSMutableArray *accessibilityElements = [NSMutableArray new];

    if (self.textView == nil ) {
        self.preservesSuperviewLayoutMargins = NO;
        self.layoutMargins = ORKStandardLayoutMarginsForTableViewCell(self);

        self.textView = [[ORKAnswerTextView alloc] initWithFrame:CGRectZero];

        self.textView.delegate = self;
        self.textView.editable = YES;
        if (@available(iOS 13.0, *)) {
            self.textView.backgroundColor = [UIColor secondarySystemGroupedBackgroundColor];
        }

        [self addSubview:self.textView];

        self.textView.placeholder = self.step.placeholder;

        ORKEnableAutoLayoutForViews(@[_textView]);

        [self applyAnswerFormat];

        [self answerDidChange];

        // Avoid exposing both this cell and its inner text view as elements to accessibility
        // See also ORKCustomStepView -accessibilityElements
        [accessibilityElements addObject:self.textView];
    }

    if (_bottomSeperatorView == nil) {
        _bottomSeperatorView = [UIView new];

        if (@available(iOS 13.0, *)) {
            [_bottomSeperatorView setBackgroundColor:[UIColor separatorColor]];
        } else {
            [_bottomSeperatorView setBackgroundColor:[UIColor lightGrayColor]];
        }
        _bottomSeperatorView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_bottomSeperatorView];
    }

    if (_textCountLabel == nil && _maxLength > 0) {
        _textCountLabel = [UILabel new];
        if (@available(iOS 13.0, *)) {
            [_textCountLabel setTextColor:[UIColor labelColor]];
        } else {
            [_textCountLabel setTextColor:[UIColor grayColor]];
        }

        if (!_hideCharacterCountLabel) {
            [accessibilityElements addObject:_textCountLabel];
            [self updateTextCountLabel];
        }

        [_textCountLabel setHidden: _hideCharacterCountLabel];

        _textCountLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview: _textCountLabel];
    }

    if (_clearTextViewButton == nil && !_hideClearButton) {
        _clearTextViewButton = [UIButton new];
        [_clearTextViewButton setTitle:ORKLocalizedString(@"BUTTON_CLEAR", nil) forState:UIControlStateNormal];
        [_clearTextViewButton setBackgroundColor:[UIColor clearColor]];
        [_clearTextViewButton setTitleColor:self.tintColor forState:UIControlStateNormal];
        [_clearTextViewButton addTarget:self action:@selector(clearTextView) forControlEvents:UIControlEventTouchUpInside];
        _clearTextViewButton.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview: _clearTextViewButton];

        [accessibilityElements addObject:_clearTextViewButton];
    }

    if (_errorLabel == nil) {
        _errorLabel = [UILabel new];
        [_errorLabel setTextColor: [UIColor orangeColor]];
        [self.errorLabel setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
        _errorLabel.numberOfLines = 0;
        _errorLabel.lineBreakMode = NSLineBreakByWordWrapping;
        [_errorLabel setAdjustsFontForContentSizeCategory:YES];
        _errorLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_errorLabel];
    }

    self.accessibilityElements = [accessibilityElements copy];
    accessibilityElements = nil;

    [self setUpConstraints];
    [super prepareView];
}

- (void)assignDefaultAnswer {
    if (_defaultTextAnswer) {
        [self ork_setAnswer:_defaultTextAnswer];
        if (self.textView) {
            self.textView.text = _defaultTextAnswer;
        }
    }
}

- (void)answerDidChange {
    id answer = self.answer;
    self.textView.text = (answer == ORKNullAnswerValue()) ? nil : self.answer;
    [self assignDefaultAnswer];
}

- (void)setUpConstraints {

    if (_constraints) {
        [NSLayoutConstraint deactivateConstraints:_constraints];
    }

    _constraints = [NSMutableArray array];

    //TextView Constraints
    [_constraints addObject:[_textView.topAnchor constraintEqualToAnchor:self.topAnchor constant:TextViewTopPadding]];
    [_constraints addObject:[_textView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:StandardSpacing]];
    [_constraints addObject:[_textView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-StandardSpacing]];
    NSLayoutConstraint *heightConstraint = [_textView.heightAnchor constraintGreaterThanOrEqualToConstant:TextViewMinimumHeight];
    [heightConstraint setPriority:UILayoutPriorityRequired];
    [_constraints addObject:heightConstraint];

    UIView *bottomMostElement;

    if (_textCountLabel && !_textCountLabel.isHidden) {
        bottomMostElement = _textCountLabel;
    }

    if (_clearTextViewButton && !_clearTextViewButton.isHidden) {
        bottomMostElement = _clearTextViewButton;
    }

    if (_errorLabel.attributedText && (!_textCountLabel || _textCountLabel.isHidden)) {
        bottomMostElement = _errorLabel;
    }

    BOOL createEmptySpaceForPossibleErrorMessage = NO;
    if (!bottomMostElement && _textCountLabel) {
        bottomMostElement = _bottomSeperatorView;
        createEmptySpaceForPossibleErrorMessage = YES;
    }

    if (_bottomSeperatorView && (bottomMostElement || createEmptySpaceForPossibleErrorMessage)) {
        //SeperatorView Constraints
        [_constraints addObject:[_bottomSeperatorView.topAnchor constraintEqualToAnchor:_textView.bottomAnchor constant:TextViewTopPadding]];
        [_constraints addObject:[_bottomSeperatorView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor]];
        [_constraints addObject:[_bottomSeperatorView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor]];
        [_constraints addObject:[_bottomSeperatorView.heightAnchor constraintEqualToConstant:1.0 / [UIScreen mainScreen].scale]];
    }

    if (bottomMostElement && !createEmptySpaceForPossibleErrorMessage) {
        //TextCountLabel Constraints
        if (_textCountLabel && !_textCountLabel.isHidden) {
            [_constraints addObject:[_textCountLabel.topAnchor constraintEqualToAnchor:_bottomSeperatorView.bottomAnchor constant:TextViewBottomPadding]];
            [_constraints addObject:[_textCountLabel.leadingAnchor constraintEqualToAnchor:_textView.leadingAnchor]];
            [_constraints addObject:[_textCountLabel.heightAnchor constraintGreaterThanOrEqualToConstant:ClearTextButtonMinimumHeight]];
        }

        //ClearTextViewButton Constraints
        if (_clearTextViewButton) {
            [_constraints addObject:[_clearTextViewButton.topAnchor constraintEqualToAnchor:_bottomSeperatorView.bottomAnchor constant:TextViewBottomPadding]];
            [_constraints addObject:[_clearTextViewButton.trailingAnchor constraintEqualToAnchor:_textView.trailingAnchor]];
            [_constraints addObject:[_clearTextViewButton.heightAnchor constraintGreaterThanOrEqualToConstant:ClearTextButtonMinimumHeight]];
        }

        //ErrorLabel Constraints
        if (_errorLabel.attributedText && (_textCountLabel && _textCountLabel.isHidden)) {
            [_constraints addObject:[_errorLabel.leadingAnchor constraintEqualToAnchor:_textView.leadingAnchor]];
            [_constraints addObject:[_errorLabel.topAnchor constraintEqualToAnchor:_bottomSeperatorView.bottomAnchor constant:TextViewBottomPadding]];
            [_errorLabel setContentCompressionResistancePriority:1000 forAxis:UILayoutConstraintAxisVertical];
            [_constraints addObject:[_errorLabel.heightAnchor constraintGreaterThanOrEqualToConstant:ClearTextButtonMinimumHeight]];

            if (_clearTextViewButton) {
                [_constraints addObject:[_errorLabel.trailingAnchor constraintEqualToAnchor:_clearTextViewButton.leadingAnchor constant: -5.0]];
                [_clearTextViewButton setContentCompressionResistancePriority:1000 forAxis:UILayoutConstraintAxisHorizontal];
            } else {
                [_constraints addObject:[_errorLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor]];
            }
        }
    } else if (!createEmptySpaceForPossibleErrorMessage) {
        bottomMostElement = _textView;
    }

    if (createEmptySpaceForPossibleErrorMessage) {
        [_constraints addObject:[self.bottomAnchor constraintGreaterThanOrEqualToAnchor:bottomMostElement.bottomAnchor constant:CellBottomPadding + TextViewBottomPadding + ClearTextButtonMinimumHeight]];
    } else {
        [_constraints addObject:[self.bottomAnchor constraintGreaterThanOrEqualToAnchor:bottomMostElement.bottomAnchor constant:CellBottomPadding]];
    }

    // Get full width layout
    [_constraints addObject:[self.class fullWidthLayoutConstraint:_textView]];

    [NSLayoutConstraint activateConstraints:_constraints];
}

+ (BOOL)shouldDisplayWithSeparators {
    return NO;
}

- (void)textDidChange {
    [self ork_setAnswer:(self.textView.text.length > 0) ? self.textView.text : ORKNullAnswerValue()];
}

- (void)updateTextCountLabel {
    if (_maxLength > 0) {
        NSString *text = [[self.textView.text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
        NSString *textCountLabelText = [[NSString alloc] initWithFormat:@"%lu/%li", (unsigned long)text.length, (long)_maxLength];
        _textCountLabel.text = textCountLabelText;

        if (_errorLabel && _errorLabel.attributedText) {
            [self removeErrorMessage];
        }
    }
}

- (void)clearTextView {
    self.textView.text = @"";
    [self textDidChange];
    [self updateTextCountLabel];
}

- (BOOL)shouldContinue {
    ORKTextAnswerFormat *answerFormat = (ORKTextAnswerFormat *)[self.step impliedAnswerFormat];
    if (![answerFormat isAnswerValidWithString:self.textView.text]) {
        [self showValidityAlertWithMessage:[[self.step impliedAnswerFormat] localizedInvalidValueStringWithAnswerString:self.answer]];
        return NO;
    }
    return YES;
}

- (void)updateErrorLabelWithMessage:(NSString *)message {
    NSString *separatorString = @":";
    NSString *stringtoParse = message ? : ORKLocalizedString(@"RANGE_ALERT_TITLE", @"");
    NSString *parsedString = [stringtoParse componentsSeparatedByString:separatorString].firstObject;

    if (![self.accessibilityElements containsObject:self.errorLabel]) {
        self.accessibilityElements = [self.accessibilityElements arrayByAddingObject:self.errorLabel];
    }

    if (@available(iOS 13.0, *)) {

        NSString *errorMessage = [NSString stringWithFormat:@" %@", parsedString];
        NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithString:errorMessage];
        NSTextAttachment *imageAttachment = [NSTextAttachment new];

        UIImage *exclamationMarkImage = [UIImage systemImageNamed:@"exclamationmark.circle.fill"];

        UIImageSymbolConfiguration *imageConfig = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleFootnote];
        UIImage *configuredImage = [exclamationMarkImage imageByApplyingSymbolConfiguration:imageConfig];

        imageAttachment.image = [configuredImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:imageAttachment];

        [fullString insertAttributedString:imageString atIndex:0];

        self.errorLabel.attributedText = fullString;
    } else {
        NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithString:parsedString];
        self.errorLabel.attributedText = fullString;
    }

    [self setUpConstraints];
}

- (void)removeErrorMessage {
    self.errorLabel.attributedText = nil;
    if ([self.accessibilityElements containsObject:self.errorLabel]) {
        NSMutableArray *tempArray = [self.accessibilityElements mutableCopy];
        [tempArray removeObject:self.errorLabel];
        self.accessibilityElements = [tempArray copy];
    }
    [self setUpConstraints];
}

#pragma mark - UITextViewDelegate

- (void)textViewDidEndEditing:(UITextView *)textView {
    [self textDidChange];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    NSString *string = [textView.text stringByReplacingCharactersInRange:range withString:text];

    // Only need to validate the text if the user enters a character other than a backspace.
    // For example, if the `textView.text = researchki` and the `string = researchkit`.
    if (textView.text.length < string.length) {

        string = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];

        if (_maxLength > 0 && string.length > _maxLength) {

            if (_textCountLabel.isHidden) {
                [self updateErrorLabelWithMessage:ORKLocalizedString(@"MAX_WORD_COUNT_ERROR", @"")];
            } else {
                [self showValidityAlertWithMessage:[[self.step impliedAnswerFormat] localizedInvalidValueStringWithAnswerString:string]];
            }

            return NO;
        } else if (_errorLabel.attributedText) {
            [self removeErrorMessage];
        }
    }

    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
    [self textDidChange];
    [self updateTextCountLabel];
}

+ (CGFloat)suggestedCellHeightForView:(UIView *)view {
    return 180.0;
}

@end

@interface ORKSurveyAnswerCellForTextField ()

@property (nonatomic, strong) ORKAnswerTextField *textField;
@property (nonatomic, strong) UILabel *errorLabel;

@end

@implementation ORKSurveyAnswerCellForTextField {
    NSMutableArray *constraints;
    NSString *_defaultTextAnswer;
}

- (BOOL)becomeFirstResponder {
    return [self.textField becomeFirstResponder];
}

- (void)textFieldCell_initialize {
    ORKAnswerFormat *answerFormat = [self.step impliedAnswerFormat];
    ORKTextAnswerFormat *textAnswerFormat = ORKDynamicCast(answerFormat, ORKTextAnswerFormat);

    _defaultTextAnswer = textAnswerFormat.defaultTextAnswer;

    _textField = [[ORKAnswerTextField alloc] initWithFrame:CGRectZero];
    _textField.text = @"";

    NSString *placeholder = textAnswerFormat.placeholder ? :
        (self.step.placeholder ? : ORKLocalizedString(@"PLACEHOLDER_TEXT_OR_NUMBER", nil));
    _textField.placeholder = placeholder;
    _textField.textAlignment = NSTextAlignmentNatural;
    _textField.delegate = self;
    _textField.keyboardType = UIKeyboardTypeDefault;

    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.accessibilityElements = @[_textField];

    [self addSubview:_textField];
    ORKEnableAutoLayoutForViews(@[_textField]);

    if (_errorLabel == nil) {
        _errorLabel = [UILabel new];
        [_errorLabel setTextColor: [UIColor redColor]];
        [self.errorLabel setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]];
        _errorLabel.numberOfLines = 0;
        _errorLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_errorLabel];
    }

    [self setUpConstraints];
}

- (void)assignDefaultAnswer {
    if (_defaultTextAnswer) {
        [self ork_setAnswer:_defaultTextAnswer];
        if (self.textField) {
            self.textField.text = _defaultTextAnswer;
        }
    }
}

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    self.contentView.layoutMargins = ORKStandardLayoutMarginsForTableViewCell(self);
}

- (void)setUpConstraints {
    if (constraints != nil) {
        [NSLayoutConstraint deactivateConstraints:constraints];
    }

    constraints = [NSMutableArray new];

    [[_textField.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:StandardSpacing] setActive:YES];
    [[_textField.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-StandardSpacing] setActive:YES];
    [[_textField.topAnchor constraintEqualToAnchor:self.topAnchor constant:0.0] setActive:YES];
    [[_textField.bottomAnchor constraintEqualToAnchor:_errorLabel.topAnchor constant:ErrorLabelTopPadding] setActive:YES];

    [[_errorLabel.leadingAnchor constraintEqualToAnchor:_textField.leadingAnchor constant:0.0] setActive:YES];
    [[_errorLabel.trailingAnchor constraintEqualToAnchor:_textField.trailingAnchor constant:0.0] setActive:YES];

    [[self.bottomAnchor constraintEqualToAnchor:_errorLabel.bottomAnchor constant:ErrorLabelBottomPadding] setActive:YES];

    // Get a full width layout
    [constraints addObject:[self.class fullWidthLayoutConstraint:_textField]];
    [NSLayoutConstraint activateConstraints:constraints];
}

+ (BOOL)shouldDisplayWithSeparators {
    return NO;
}

- (void)prepareView {
    if (self.textField == nil ) {
        [self textFieldCell_initialize];
    }

    [self answerDidChange];

    [super prepareView];
}

- (BOOL)shouldContinue {
    ORKTextAnswerFormat *answerFormat = (ORKTextAnswerFormat *)[self.step impliedAnswerFormat];
    if (![answerFormat isAnswerValidWithString:self.textField.text]) {
        [self updateErrorLabelWithMessage:[[self.step impliedAnswerFormat] localizedInvalidValueStringWithAnswerString:self.textField.text]];
        return NO;
    }

    return YES;
}

- (void)answerDidChange {
    id answer = self.answer;
    ORKAnswerFormat *answerFormat = [self.step impliedAnswerFormat];
    ORKTextAnswerFormat *textFormat = (ORKTextAnswerFormat *)answerFormat;
    if (textFormat) {
        self.textField.autocorrectionType = textFormat.autocorrectionType;
        self.textField.autocapitalizationType = textFormat.autocapitalizationType;
        self.textField.spellCheckingType = textFormat.spellCheckingType;
        self.textField.keyboardType = textFormat.keyboardType;
        self.textField.secureTextEntry = textFormat.secureTextEntry;
        self.textField.textContentType = textFormat.textContentType;

        if (@available(iOS 12.0, *)) {
            self.textField.passwordRules = textFormat.passwordRules;
        }
    }
    NSString *displayValue = (answer && answer != ORKNullAnswerValue()) ? answer : nil;

    if (displayValue == nil && _defaultTextAnswer) {
        [self assignDefaultAnswer];
    } else {
        self.textField.text = displayValue;
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    [self checkTextAndSetAnswer];
}

- (void)checkTextAndSetAnswer {
    NSString *text = self.textField.text;
    ORKTextAnswerFormat *answerFormat = (ORKTextAnswerFormat *)[self.step impliedAnswerFormat];

    if (text.length && [answerFormat isAnswerValidWithString:text]) {
        [self ork_setAnswer:text];
    } else {
        [self ork_setAnswer:ORKNullAnswerValue()];
        [self removeErrorMessage];
    }
}

- (void)updateErrorLabelWithMessage:(NSString *)message {
    NSString *separatorString = @":";
    NSString *stringtoParse = message ? : ORKLocalizedString(@"RANGE_ALERT_TITLE", @"");
    NSString *parsedString = [stringtoParse componentsSeparatedByString:separatorString].firstObject;

    if (![self.accessibilityElements containsObject:self.errorLabel]) {
        self.accessibilityElements = [self.accessibilityElements arrayByAddingObject:self.errorLabel];
    }

    if (@available(iOS 13.0, *)) {

        NSString *errorMessage = [NSString stringWithFormat:@" %@", parsedString];
        NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithString:errorMessage];
        NSTextAttachment *imageAttachment = [NSTextAttachment new];

        UIImageSymbolConfiguration *imageConfig = [UIImageSymbolConfiguration configurationWithPointSize:12 weight:UIImageSymbolWeightRegular scale:UIImageSymbolScaleMedium];
        UIImage *exclamationMarkImage = [UIImage systemImageNamed:@"exclamationmark.circle"];
        UIImage *configuredImage = [exclamationMarkImage imageByApplyingSymbolConfiguration:imageConfig];

        imageAttachment.image = [configuredImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:imageAttachment];

        [fullString insertAttributedString:imageString atIndex:0];

        self.errorLabel.attributedText = fullString;
    } else {
        NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithString:parsedString];
        self.errorLabel.attributedText = fullString;
    }

    [self setUpConstraints];
}

- (void)removeErrorMessage {
    self.errorLabel.attributedText = nil;
    if ([self.accessibilityElements containsObject:self.errorLabel]) {
        NSMutableArray *tempArray = [self.accessibilityElements mutableCopy];
        [tempArray removeObject:self.errorLabel];
        self.accessibilityElements = [tempArray copy];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    ORKAnswerFormat *impliedFormat = [self.step impliedAnswerFormat];
    NSAssert([impliedFormat isKindOfClass:[ORKTextAnswerFormat class]], @"answerFormat should be ORKTextAnswerFormat type instance.");

    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Only need to validate the text if the user enters a character other than a backspace.
    // For example, if the `textField.text = researchki` and the `text = researchkit`.
    if (textField.text.length < text.length) {

        text = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];

        NSInteger maxLength = [(ORKTextAnswerFormat *)impliedFormat maximumLength];

        if (maxLength > 0 && text.length > maxLength) {
            [self updateErrorLabelWithMessage:[[self.step impliedAnswerFormat] localizedInvalidValueStringWithAnswerString:text]];
            return NO;
        }
    }

    [self checkTextAndSetAnswer];

    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.textField resignFirstResponder];

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSString *text = self.textField.text;
    ORKTextAnswerFormat *answerFormat = (ORKTextAnswerFormat *)[self.step impliedAnswerFormat];

    if (text.length && ![answerFormat isAnswerValidWithString:text]) {
        [self updateErrorLabelWithMessage:[[self.step impliedAnswerFormat] localizedInvalidValueStringWithAnswerString:self.textField.text]];
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { render } from 'react-dom';
import Home from './../../../src/scenes/Home/Home.jsx';

it('render Home', () => {
  const h3 = document.createElement('h3');
  render(<Home />, h3);
});


text:
#include "textbuffer.h"
#include "misc.h"
#include "byte_pattern.h"

namespace TextBuffer
{
    CString * CTextBuffer::GetString()
    {
        return field<CString, 0x1C>();
    }

    BitmapFont::CBitmapFont * CTextBuffer::GetFont()
    {
        return get_field<BitmapFont::CBitmapFont *, 0x70>();
    }

    bool CTextBuffer::GetUseSpecialChar()
    {
        return get_field<bool, 0xAC>();
    }

    unsigned short CTextBuffer::GetLineWidth()
    {
        return get_field<unsigned short, 0x48>();
    }

    int __fastcall CTextBuffer::GetLineCharSize(CTextBuffer *pBuffer, int edx, const CString *szText)
    {
        int result = 0;
        int width = 0;
        int maxWidth = pBuffer->GetLineWidth() - pBuffer->GetFont()->GetPaddingWidth(true);

        libcxx_strviewclone::string_view view{ szText->c_str() };
        auto it = view.begin();
        auto endit = view.end();

        while (it != endit)
        {
            auto len = eu4utf8::internal::sequence_length(it);

            width += pBuffer->GetFont()->GetWidthOfString(it, len, pBuffer->GetUseSpecialChar());

            if (width > maxWidth)
                return result;
            else
            {
                eu4utf8::next(it, endit);
                result += len;
            }
        }

        return result;
    }

    //
    //
    struct CTextBufferWrite_RemoveSpecials
    {
        void operator()(injector::reg_pack &regs) const
        {

        }
    };

    //
    //
    struct CTextBuffer_
    {
        void operator()(injector::reg_pack &regs) const
        {

        }
    };

    struct CSdlEvents_HandlePdxEvents_ReadInputs
    {
        void operator()(injector::reg_pack &regs) const
        {
            CInputEvent temp;
            char *pText = (char *)(regs.ebp.i - 0x48);

            temp.Init(pText);
            injector::thiscall<void(void *, const CInputEvent *)>::vtbl<3>(regs.ebx, &temp);

            memset(pText, 0, 32);

            regs.ecx.i = 0;
            regs.eax.i = 0;
        }
    };

    CString *__fastcall sub_112CEE0(const char *cstr, int edx, CString *result)
    {
        //初始化
        result->_sso_head[0] = 0;
        result->_length = 0;
        result->_capacity = 15;

        Misc::assign_string(result, cstr);
        return result;
    }

    void InitAndPatch()
    {
        //从输入接受整个字符串
        //mov ecx, [ebp - 0x48]; xor al, al
        byte_pattern::temp_instance().find_pattern("8B 4D B8 32 C0 88 45 0B");
        if (byte_pattern::temp_instance().has_size(1))
            injector::MakeInline<CSdlEvents_HandlePdxEvents_ReadInputs>(byte_pattern::temp_instance().get_first().address());

        //构造整个字符串
        byte_pattern::temp_instance().find_pattern("75 C6 8D 45 DC 8B CF 50 E8");
        if (byte_pattern::temp_instance().has_size(1))
            injector::MakeCALL(byte_pattern::temp_instance().get_first().address(8), sub_112CEE0);

        byte_pattern::temp_instance().find_pattern("6A 01 8B 4F 70 8B 01");
        if (byte_pattern::temp_instance().has_size(1))
            injector::MakeJMP(byte_pattern::temp_instance().get_first().address(-0xB), CTextBuffer::GetLineCharSize);
    }
}


text:
package ee.scanner.tablet.exception;

public class DeviceDuplicateException extends Throwable {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/historic/pilate-pontius" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/historic/pilate-pontius</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Pilate, Pontius</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/historic/pilate-pontius</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/historic/pilate-pontius</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
namespace GrizzenServer
{
    public class WhimperCmd : Cmd
    {
        public WhimperCmd(Client client) : base(client) { }

        public override void Run()
        {
            if (HasAccess)
            {
                Clients.TellScene(Scene, "Whimper", Actor);
            }
        }
    }
}


text:
using System;
using System.IO;
using System.Text;
using MasterExtensionKit.Core.Objects.Validations;
using MasterExtensionKit.Core.Strings.Validations;

namespace MasterExtensionKit.Core.Strings.Helpers
{
	/// <summary>
	///     String Helper Static Class
	/// </summary>
	public static class StringHelpers
	{
		/// <summary>
		///     Reads all data from a given file
		/// </summary>
		/// <param name="returnValue">String that is returned (OUT)</param>
		/// <param name="fileName">Location and File Name</param>
		/// <param name="encodingType">Optional: Encoding Type</param>
		public static void ReadFromFile(out string returnValue, string fileName, Encoding encodingType = null)
		{
			if (!fileName.HasValue())
			{
				throw new ArgumentNullException(nameof(fileName));
			}

			if (encodingType.IsNull())
			{
				encodingType = Encoding.Default;
			}

			try
			{
				using (var streamReader = new StreamReader(fileName, encodingType))
				{
					returnValue = streamReader.ReadToEnd();
					streamReader.Close();
				}
			}
			catch (Exception)
			{
				// TODO: Do better Exception Handling
				throw;
			}
		}
	}
}


text:
import { textToBuffer } from 'dimensions/utils';
import * as utf8 from 'utf8';
import NetworkText from 'dimensions/packets/networktext';
import Writer from 'dimensions/packets/writer';

class BufferWriter implements Writer {
    protected _buffer: Buffer;
    protected _offset: number = 0;

    constructor(size: number) {
        this._buffer = Buffer.allocUnsafe(size);
    }

    public changeOffset(offset: number) {
        this._offset = offset;
    }

    public packInt16(int16: number) {
        this._buffer.writeInt16LE(int16, this._offset);
        this._offset += 2;
        return this;
    }

    public packUInt16(uint16: number) {
        this._buffer.writeUInt16LE(uint16, this._offset);
        this._offset += 2;
        return this;
    }

    public packInt32(int32: number) {
        this._buffer.writeInt32LE(int32, this._offset);
        this._offset += 4;
        return this;
    }

    public packUInt32(uint32: number) {
        this._buffer.writeUInt32LE(uint32, this._offset);
        this._offset += 4;
        return this;
    }

    public packUInt64(uint64: number) {
        this.packUInt32(uint64 >> 8);
        this.packUInt32(uint64 & 0x00ff);
        return this;
    }

    public packSingle(single: number) {
        this._buffer.writeFloatLE(single, this._offset);
        this._offset += 4;
        return this;
    }

    public packByte(byte: number) {
        if (byte < 0) byte = -byte;
        this._buffer.writeUInt8(byte, this._offset);
        this._offset += 1;
        return this;
    }

    public packSByte(byte: number) {
        this._buffer.writeInt8(byte, this._offset);
        this._offset += 1;
        return this;
    }

    public packBytes(bytes: number[]) {
        for (const byte of bytes) {
            this.packByte(byte);
        }

        return this;
    }

    public packHex(hex: string) {
        const buf = Buffer.from(hex, "hex");
        buf.copy(this._buffer, this._offset, 0);
        this._offset += buf.length;
        return this;
    }

    public packBuffer(buffer: Buffer) {
        buffer.copy(this._buffer, this._offset, 0);
        this._offset += buffer.length;
        return this;
    }

    public packString(str: string) {
        const packedStr = textToBuffer(utf8.encode(str));
        const strLen = packedStr.length;

        if (strLen >= 128) {
            this.packByte((strLen % 128) + 128);
            this.packByte(Math.floor(strLen / 128));
        } else {
            this.packByte(strLen);
        }

        this.packBuffer(packedStr);
        return this;
    }

    public packColor(color: {R:number;G:number;B:number}) {
        this.packByte(color.R);
        this.packByte(color.G);
        this.packByte(color.B);
        return this;
    }

    public packNetworkText(networkText: NetworkText) {
        this.packByte(networkText.mode);
        this.packString(networkText.text);

        if (networkText.substitutionList) {
            this.packByte(networkText.substitutionList.length);
            for (let i = 0; i < networkText.substitutionList.length; i++)
            {
                this.packNetworkText(networkText.substitutionList[i]);
            }
        } else if (networkText.mode != 0) {
            this.packByte(0);
        }

        return this;
    }

    public get data() {
        return this._buffer;
    }

    public get slicedData() {
        return this._buffer.slice(0, this._offset);
    }
}

export default BufferWriter;


text:
package com.basho.dynamodb.integ;

import java.io.PrintStream;

public class ConsoleRedirector extends PrintStream {
    public ConsoleRedirector(String level) {
        super(new LogOutputStream(level));
    }
}


text:
package com.mailgun.api.domain;

public class Campaign {
   // no op
}


text: MathJax.Localization.addTranslation("diq","HTML-CSS",{version:"2.7.0",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/diq/HTML-CSS.js");


text:
package edu.sjsu.cmpe275.lab3.dao;

import edu.sjsu.cmpe275.lab3.model.Player;
import edu.sjsu.cmpe275.lab3.model.Sponsor;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.util.List;

public class JpaSponsorDAO implements SponsorDAO {

    private EntityManagerFactory entityManagerFactory;

    //set jpa entity manager
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory){
        this.entityManagerFactory = entityManagerFactory;
    }

    @Override
    public void insert(Sponsor sponsor) {
        EntityManager manager = entityManagerFactory.createEntityManager();
        EntityTransaction tx = manager.getTransaction();
        try {
            tx.begin();
            manager.persist(sponsor);//insert new sponsor
            tx.commit();
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            manager.close();
        }
    }

    @Override
    public Sponsor findBySponsorId(Long sponsorId) {
        EntityManager manager = entityManagerFactory.createEntityManager();
        EntityTransaction tx = manager.getTransaction();
        try {
            tx.begin();
            Sponsor sponsor = manager.find(Sponsor.class, sponsorId);
            tx.commit();
            return sponsor; //return null if not found
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            manager.close();
        }
    }

    @Override
    public List<Sponsor> allSponsors() {
        String query = "SELECT s FROM Sponsor s"; //select all row from the table
        EntityManager manager = entityManagerFactory.createEntityManager();
        EntityTransaction tx = manager.getTransaction();
        try {
            tx.begin();
            List<Sponsor> listSponsors = manager.createQuery(query).getResultList();
            tx.commit();
            return listSponsors; //return null if empty
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            manager.close();
        }
    }

    @Override
    public void update(Sponsor sponsor) {
        EntityManager manager = entityManagerFactory.createEntityManager();
        Sponsor sponsor1 = manager.find(Sponsor.class, sponsor.getId());
        EntityTransaction tx = manager.getTransaction();
        try {
            tx.begin();
            if(sponsor.getName() != null) {
                sponsor1.setName(sponsor.getName());
            }
            if(sponsor.getDescription() != null){
                sponsor1.setDescription(sponsor.getDescription());
            }
            if(sponsor.getAddress() != null){
                sponsor1.setAddress(sponsor.getAddress());
            }
            tx.commit();
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            manager.close();
        }
    }

    @Override
    public boolean delete(long sponsorId) {
        String query = "SELECT p FROM Player p WHERE Sponsor_idSponsor =" + sponsorId; //select all players under sponse with sponsor

        EntityManager manager = entityManagerFactory.createEntityManager();
        Sponsor sponsor1 = manager.find(Sponsor.class, sponsorId);
        EntityTransaction tx = manager.getTransaction();
        try {
            tx.begin();
            manager.refresh(sponsor1);//for cascading remove address
            manager.remove(sponsor1);

            //check players with sponsor1, set all to null
            List<Player> listPlayers = manager.createQuery(query).getResultList();
            if(listPlayers != null){
                for(Player p :listPlayers){
                    p.setSponsor(null);
                }
            }

            tx.commit();
            return true;
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            manager.close();
        }
    }

}


text:
module Ruby
  module ModuleExt
    # token is value
    def name
    end

    def includes
    end

    def methods
    end

    def body
    end
  end
end

module Ruby
  class Module
     include Ruby::ModuleExt
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="_Emulation Programming_" />
<meta name="keywords" content="_Emulation,Chip8,Gameboy,NES,SNES,Genesis,Master,System,Mega,Drive_" />
<meta name="author" content="CodeSlinger /" />
<link rel="stylesheet" type="text/css" href="css.css" media="screen,projection" title="CodeSlinger (screen)" />
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
<title>codeslinger.co.uk</title>

codeslinger.co.uk

Site menu:

Home |
Basics |
Zuko |
Mega Drive/Genesis |
Master System |
Gameboy |
Chip8 |
Blog |

Welcome to codeslinger.co.uk

Dedicated to the art of emulation programming

About:

 This website is intended to help newcomers to emulation programming understand the logic behind making an emulator. As you can see from my development blog I am no emulation expert but hopefully beginners should find a lot of useful material here. The idea of this website is to break down the system I am working on and decide the best way to emulate each part. My completed emulators also have their own section of the website so you can look back at the troubles I had emulating the system and how I succeeded. Although I try to teach programming logic this is not a general programming site, so you will need to know at least one programming language. All examples on this site including the source code are in C++. Im not gonna post the source code for all my emulators just some.

Please note: I do not host copyrighted Roms on this website and I never will, so please dont ask.

Update: 17th March 2009

Well after a fem months break I am back and ready to continue with my emulation development. My SMS tutorials are complete and can be found by navigating the top of this page. I'll probably optimize my gameboy emulator and add sound next before starting a mega drive emulator.

Update: 18th December 2008

My Sega Master System Emulator has approximately 95% compatibility including sound emulation. Over the next few days I shall write the tutorials for SMS emulation and shall upload them to this site. Check back in a few days.

Update: 9th August 2008

I have finally finished the gameboy tutorial section of the site. Use the navigation bar at the top to go to it. Next I will be coding a Sega Master System emulator.

Update: 29th July 2008

My gameboy emulator has approximately 95% compatibility which is enough for me to create the Gameboy howto section. I shall start writing this today and hopefully over the next few weeks I'll have this section of the site complete. However I have not emulated sound yet.

Update: 1st July 2008

Please bare with me while I get all features of this site up and running. I'll start with getting my Chip8 emulator tutorials up and then I'll start to upload my Gameboy resources which is the system I am currently emulating.

Links:

Emulation links will be up when the rest of the site is up and running

Links Coming Soon |
Links Coming Soon |
Links Coming Soon |
Links Coming Soon |
Links Coming Soon |
Links Coming Soon |
Links Coming Soon |

Copyright © 2008 codeslinger.co.uk


text:
import optparse
import sys

import m5
from m5.defines import buildEnv
from m5.objects import *
from m5.util import addToPath, fatal
addToPath('../dramsim2')
import dramsim2_base
from dramsim2_base import *

###############################################################################
# System Configuration
###############################################################################

#All the functions called in this section are in dramsim2_base.py

#Incorporate all the options available do dramsim2_base.py
options = add_options()

#Use a magic noninterfering zero latency memory
np = options.num_cpus
p2cores = int(pow( 2, ceil(log(np)/log(2)) ))
memorysize = str(1024*p2cores) + 'MB'
DRAM = MagicMemory( range = AddrRange(memorysize) )

#Setup benchmarks
multiprocesses = setup_workloads(options)
#Setup CPUs
(CPUClass,test_mem_mode,FutureClass) = setup_cpus(options)
# Use a shared RR_Noncoherent bus for the system bus
systembus = setup_systembus(options)

system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(options.num_cpus)],
                physmem = DRAM,
                membus =  systembus,
                mem_mode = test_mem_mode,
                numPids = options.numpids,
                fast_forward = (options.fast_forward != None),
                fixAddr = options.fixaddr)

for i in xrange(options.num_cpus):
    system.cpu[i].workload = multiprocesses[i]

    if options.checker:
        system.cpu[i].addCheckerCpu()

system.system_port = system.membus.slave
system.physmem.port = system.membus.master

# Setup L1i and L1d.
# The call to config_l1 builds these caches and then stores them in a stack of
# caches pending connection. Then, connectAllPorts checks this stack and
# connects the ports properly.
CacheConfig.config_l1( options, system )
for i in xrange( options.num_cpus ):
    system.cpu[i].connectAllPorts( system.membus )

#Start the simulation
root = Root(full_system = False, system = system)
Simulation.run(options, root, system, FutureClass, options.numpids)


text:
FOUNDATION_EXPORT double Pods_SWSocketManager_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_SWSocketManager_ExampleVersionString[];


text:
// Float.cs
// Copyright (c) Nikhil Kothari, 2008. All Rights Reserved.
// http://www.nikhilk.net
//
// Silverlight.FX is an application framework for building RIAs with Silverlight.
// This project is licensed under the BSD license. See the accompanying License.txt
// file for more information.
// For updated project information please visit http://projects.nikhilk.net/SilverlightFX.
//

using System;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Glitz;
using System.Windows;

namespace SilverlightFX.UserInterface.Effects {

    /// <summary>
    /// Represents an effect that floats an element by projecting it forward and
    /// adding a shadow.
    /// </summary>
    public class Float : AnimationEffect {

        private double _distance;
        private double _shadowLength;

        private DropShadowEffect _dropShadow;
        private PlaneProjection _projection;

        /// <summary>
        /// Gets or sets the distance by which the element is floated.
        /// </summary>
        public double Distance {
            get {
                return _distance;
            }
            set {
                _distance = value;
            }
        }

        /// <summary>
        /// Gets or sets the length of the shadow to create when the element
        /// is floated.
        /// </summary>
        public double ShadowLength {
            get {
                return _shadowLength;
            }
            set {
                _shadowLength = value;
            }
        }

        /// <internalonly />
        protected internal override ProceduralAnimation CreateEffectAnimation(AnimationEffectDirection direction) {
            FrameworkElement target = GetTarget();

            if (_projection == null) {
                _projection = target.Projection as PlaneProjection;
                if (_projection == null) {
                    _projection = new PlaneProjection();
                    _projection.CenterOfRotationX = 0.5;
                    _projection.CenterOfRotationY = 0.5;
                    _projection.CenterOfRotationZ = 0.5;

                    target.Projection = _projection;
                }
            }

            DoubleAnimation zOffsetAnimation =
                new DoubleAnimation(_projection, PlaneProjection.GlobalOffsetZProperty, Duration,
                                    (direction == AnimationEffectDirection.Forward ? Distance : 0));
            zOffsetAnimation.Interpolation = GetEffectiveInterpolation();

            if (_shadowLength == 0) {
                zOffsetAnimation.AutoReverse = AutoReverse;

                return zOffsetAnimation;
            }

            if (_dropShadow == null) {
                _dropShadow = target.Effect as DropShadowEffect;
                if (_dropShadow == null) {
                    _dropShadow = new DropShadowEffect();
                    _dropShadow.BlurRadius = 0;
                    _dropShadow.ShadowDepth = 0;
                    _dropShadow.Color = Colors.Black;
                    _dropShadow.Opacity = 0.5;

                    target.Effect = _dropShadow;
                }
            }

            DoubleAnimation shadowAnimation =
                new DoubleAnimation(_dropShadow, DropShadowEffect.BlurRadiusProperty, Duration,
                                    (direction == AnimationEffectDirection.Forward ? _shadowLength : 0));
            shadowAnimation.Interpolation = GetEffectiveInterpolation();

            ProceduralAnimationSet animationSet = new ProceduralAnimationSet(zOffsetAnimation, shadowAnimation);
            animationSet.AutoReverse = AutoReverse;

            return animationSet;
        }
    }
}


text:
'use strict';

angular.module('todoApp')
  .directive('autofocus', function () {
    return {
      link: function (scope, element, attrs) {
        scope.$watch(attrs.autofocus, function (val) {
          if (angular.isDefined(val) && val) {
            //    $timeout(function() {
            element[0].focus();
            //    });
          }
        }, true);

        element.bind('blur', function () {
          if (angular.isDefined(attrs.autofocusLost)) {
            scope.$apply(attrs.autofocusLost);
          }
        });
      }
    };
  });


text:
package xerrors

import (
	"errors"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestDefaultErrorIfNil(t *testing.T) {
	assert.Equal(t, DefaultErrorIfNil(nil, "Cool"), "Cool")
	assert.Equal(t, DefaultErrorIfNil(errors.New("Oops"), "Cool"), "Oops")
}


text:
CREATE PROCEDURE [dbo].[SamplingPoint_Get]
	@Id UNIQUEIDENTIFIER = null,
	@ParentId UNIQUEIDENTIFIER = null,
	@All BIT = null
AS
	SET NOCOUNT ON;

	SELECT LocationId,
		LocationName,
		Longitude,
		Latitude,
		ParentLocationId
	FROM dbo.SamplingPoint
	WHERE LocationId = @Id
		OR ParentLocationId = @ParentId
		OR @All = 1
	ORDER BY LocationName;
RETURN 0

GO
GRANT EXECUTE
    ON OBJECT::[dbo].[SamplingPoint_Get] TO [IbaAccounts]
    AS [dbo];


text:
define("./comlink-f69ccfb7.js",['exports'], function (exports) { 'use strict';

    const proxyMarker = Symbol("Comlink.proxy");
    const createEndpoint = Symbol("Comlink.endpoint");
    const releaseProxy = Symbol("Comlink.releaseProxy");
    const throwSet = new WeakSet();
    const transferHandlers = new Map([
        [
            "proxy",
            {
                canHandle: obj => obj && obj[proxyMarker],
                serialize(obj) {
                    const { port1, port2 } = new MessageChannel();
                    expose(obj, port1);
                    return [port2, [port2]];
                },
                deserialize: (port) => {
                    port.start();
                    return wrap(port);
                }
            }
        ],
        [
            "throw",
            {
                canHandle: obj => throwSet.has(obj),
                serialize(obj) {
                    const isError = obj instanceof Error;
                    let serialized = obj;
                    if (isError) {
                        serialized = {
                            isError,
                            message: obj.message,
                            stack: obj.stack
                        };
                    }
                    return [serialized, []];
                },
                deserialize(obj) {
                    if (obj.isError) {
                        throw Object.assign(new Error(), obj);
                    }
                    throw obj;
                }
            }
        ]
    ]);
    function expose(obj, ep = self) {
        ep.addEventListener("message", function callback(ev) {
            if (!ev || !ev.data) {
                return;
            }
            const { id, type, path } = Object.assign({ path: [] }, ev.data);
            const argumentList = (ev.data.argumentList || []).map(fromWireValue);
            let returnValue;
            try {
                const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);
                const rawValue = path.reduce((obj, prop) => obj[prop], obj);
                switch (type) {
                    case 0 /* GET */:
                        {
                            returnValue = rawValue;
                        }
                        break;
                    case 1 /* SET */:
                        {
                            parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
                            returnValue = true;
                        }
                        break;
                    case 2 /* APPLY */:
                        {
                            returnValue = rawValue.apply(parent, argumentList);
                        }
                        break;
                    case 3 /* CONSTRUCT */:
                        {
                            const value = new rawValue(...argumentList);
                            returnValue = proxy(value);
                        }
                        break;
                    case 4 /* ENDPOINT */:
                        {
                            const { port1, port2 } = new MessageChannel();
                            expose(obj, port2);
                            returnValue = transfer(port1, [port1]);
                        }
                        break;
                    case 5 /* RELEASE */:
                        {
                            returnValue = undefined;
                        }
                        break;
                }
            }
            catch (e) {
                returnValue = e;
                throwSet.add(e);
            }
            Promise.resolve(returnValue)
                .catch(e => {
                throwSet.add(e);
                return e;
            })
                .then(returnValue => {
                const [wireValue, transferables] = toWireValue(returnValue);
                ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
                if (type === 5 /* RELEASE */) {
                    // detach and deactive after sending release response above.
                    ep.removeEventListener("message", callback);
                    closeEndPoint(ep);
                }
            });
        });
        if (ep.start) {
            ep.start();
        }
    }
    function isMessagePort(endpoint) {
        return endpoint.constructor.name === "MessagePort";
    }
    function closeEndPoint(endpoint) {
        if (isMessagePort(endpoint))
            endpoint.close();
    }
    function wrap(ep, target) {
        return createProxy(ep, [], target);
    }
    function throwIfProxyReleased(isReleased) {
        if (isReleased) {
            throw new Error("Proxy has been released and is not useable");
        }
    }
    function createProxy(ep, path = [], target = function () { }) {
        let isProxyReleased = false;
        const proxy = new Proxy(target, {
            get(_target, prop) {
                throwIfProxyReleased(isProxyReleased);
                if (prop === releaseProxy) {
                    return () => {
                        return requestResponseMessage(ep, {
                            type: 5 /* RELEASE */,
                            path: path.map(p => p.toString())
                        }).then(() => {
                            closeEndPoint(ep);
                            isProxyReleased = true;
                        });
                    };
                }
                if (prop === "then") {
                    if (path.length === 0) {
                        return { then: () => proxy };
                    }
                    const r = requestResponseMessage(ep, {
                        type: 0 /* GET */,
                        path: path.map(p => p.toString())
                    }).then(fromWireValue);
                    return r.then.bind(r);
                }
                return createProxy(ep, [...path, prop]);
            },
            set(_target, prop, rawValue) {
                throwIfProxyReleased(isProxyReleased);
                // FIXME: ES6 Proxy Handler `set` methods are supposed to return a
                // boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯
                const [value, transferables] = toWireValue(rawValue);
                return requestResponseMessage(ep, {
                    type: 1 /* SET */,
                    path: [...path, prop].map(p => p.toString()),
                    value
                }, transferables).then(fromWireValue);
            },
            apply(_target, _thisArg, rawArgumentList) {
                throwIfProxyReleased(isProxyReleased);
                const last = path[path.length - 1];
                if (last === createEndpoint) {
                    return requestResponseMessage(ep, {
                        type: 4 /* ENDPOINT */
                    }).then(fromWireValue);
                }
                // We just pretend that `bind()` didn't happen.
                if (last === "bind") {
                    return createProxy(ep, path.slice(0, -1));
                }
                const [argumentList, transferables] = processArguments(rawArgumentList);
                return requestResponseMessage(ep, {
                    type: 2 /* APPLY */,
                    path: path.map(p => p.toString()),
                    argumentList
                }, transferables).then(fromWireValue);
            },
            construct(_target, rawArgumentList) {
                throwIfProxyReleased(isProxyReleased);
                const [argumentList, transferables] = processArguments(rawArgumentList);
                return requestResponseMessage(ep, {
                    type: 3 /* CONSTRUCT */,
                    path: path.map(p => p.toString()),
                    argumentList
                }, transferables).then(fromWireValue);
            }
        });
        return proxy;
    }
    function myFlat(arr) {
        return Array.prototype.concat.apply([], arr);
    }
    function processArguments(argumentList) {
        const processed = argumentList.map(toWireValue);
        return [processed.map(v => v[0]), myFlat(processed.map(v => v[1]))];
    }
    const transferCache = new WeakMap();
    function transfer(obj, transfers) {
        transferCache.set(obj, transfers);
        return obj;
    }
    function proxy(obj) {
        return Object.assign(obj, { [proxyMarker]: true });
    }
    function toWireValue(value) {
        for (const [name, handler] of transferHandlers) {
            if (handler.canHandle(value)) {
                const [serializedValue, transferables] = handler.serialize(value);
                return [
                    {
                        type: 3 /* HANDLER */,
                        name,
                        value: serializedValue
                    },
                    transferables
                ];
            }
        }
        return [
            {
                type: 0 /* RAW */,
                value
            },
            transferCache.get(value) || []
        ];
    }
    function fromWireValue(value) {
        switch (value.type) {
            case 3 /* HANDLER */:
                return transferHandlers.get(value.name).deserialize(value.value);
            case 0 /* RAW */:
                return value.value;
        }
    }
    function requestResponseMessage(ep, msg, transfers) {
        return new Promise(resolve => {
            const id = generateUUID();
            ep.addEventListener("message", function l(ev) {
                if (!ev.data || !ev.data.id || ev.data.id !== id) {
                    return;
                }
                ep.removeEventListener("message", l);
                resolve(ev.data);
            });
            if (ep.start) {
                ep.start();
            }
            ep.postMessage(Object.assign({ id }, msg), transfers);
        });
    }
    function generateUUID() {
        return new Array(4)
            .fill(0)
            .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
            .join("-");
    }

    exports.expose = expose;
    exports.transfer = transfer;
    exports.wrap = wrap;

});


text:
  Aubérive est
       un village
       localisé dans le département de Marne en Champagne-Ardenne. On dénombrait 194 habitants en 2008.

À proximité de Aubérive sont localisées les villes de
Sainte-Marie-à-Py à 7 km, 198 habitants,
Vaudesincourt située à 2 km, 116 habitants,
Mourmelon-le-Grand située à 7 km, 5 138 habitants,
Saint-Martin-l'Heureux située à 5 km, 77 habitants,
Baconnes localisée à 7 km, 278 habitants,
Dontrien localisée à 4 km, 199 habitants,
 entre autres. De plus, Aubérive est située à seulement 28 km de Reims.

Le parc d'habitations, à Aubérive, était réparti en 2011 en un appartements et 98 maisons soit
 un marché plutôt équilibré.

Si vous pensez venir habiter à Aubérive, vous pourrez aisément trouver une maison à acheter.


text:
<?php namespace App\Repositories\Backend\User;

use App\Models\Access\User\User;
use App\Exceptions\GeneralException;
use App\Repositories\Backend\Role\RoleRepositoryContract;
use App\Repositories\Frontend\Auth\AuthenticationContract;
use App\Exceptions\Backend\Access\User\UserNeedsRolesException;

/**
 * Class EloquentUserRepository
 * @package App\Repositories\User
 */
class EloquentUserRepository implements UserContract {

	/**
	 * @var RoleRepositoryContract
	 */
	protected $role;

	/**
	 * @var AuthenticationContract
	 */
	protected $auth;

	/**
	 * @param RoleRepositoryContract $role
	 * @param AuthenticationContract $auth
	 */
	public function __construct(RoleRepositoryContract $role, AuthenticationContract $auth) {
		$this->role = $role;
		$this->auth = $auth;
	}

	/**
	 * @param $id
	 * @param bool $withRoles
	 * @return mixed
	 * @throws GeneralException
	 */
	public function findOrThrowException($id, $withRoles = false) {
		if ($withRoles)
			$user = User::with('roles')->withTrashed()->find($id);
		else
			$user = User::withTrashed()->find($id);

		if (! is_null($user)) return $user;

		throw new GeneralException('That user does not exist.');
	}

	/**
	 * @param $per_page
	 * @param string $order_by
	 * @param string $sort
	 * @param int $status
	 * @return mixed
	 */
	public function getUsersPaginated($per_page, $status = 1, $order_by = 'id', $sort = 'asc') {
		return User::where('status', $status)->orderBy($order_by, $sort)->paginate($per_page);
	}

	/**
	 * @param $per_page
	 * @return \Illuminate\Pagination\Paginator
	 */
	public function getDeletedUsersPaginated($per_page) {
		return User::onlyTrashed()->paginate($per_page);
	}

	/**
	 * @param string $order_by
	 * @param string $sort
	 * @return mixed
	 */
	public function getAllUsers($order_by = 'id', $sort = 'asc') {
		return User::orderBy($order_by, $sort)->get();
	}

	/**
	 * @param $input
	 * @param $roles
	 * @param $permissions
	 * @return bool
	 * @throws GeneralException
	 * @throws UserNeedsRolesException
	 */
	public function create($input, $roles, $permissions) {
		$user = $this->createUserStub($input);

		if ($user->save()) {
			//User Created, Validate Roles
			$this->validateRoleAmount($user, $roles['assignees_roles']);

			//Attach new roles
			$user->attachRoles($roles['assignees_roles']);

			//Attach other permissions
			$user->attachPermissions($permissions['permission_user']);

			//Send confirmation email if requested
			if (isset($input['confirmation_email']) && $user->confirmed == 0)
				$this->auth->resendConfirmationEmail($user->id);

			return true;
		}

		throw new GeneralException('There was a problem creating this user. Please try again.');
	}

	/**
	 * @param $id
	 * @param $input
	 * @param $roles
	 * @return bool
	 * @throws GeneralException
	 */
	public function update($id, $input, $roles, $permissions) {
		$user = $this->findOrThrowException($id);
		$this->checkUserByEmail($input, $user);

		if ($user->update($input)) {
			//For whatever reason this just wont work in the above call, so a second is needed for now
			$user->status = isset($input['status']) ? 1 : 0;
			$user->confirmed = isset($input['confirmed']) ? 1 : 0;
			$user->save();

			$this->checkUserRolesCount($roles);
			$this->flushRoles($roles, $user);
			$this->flushPermissions($permissions, $user);

			return true;
		}

		throw new GeneralException('There was a problem updating this user. Please try again.');
	}

	/**
	 * @param $id
	 * @param $input
	 * @return bool
	 * @throws GeneralException
	 */
	public function updatePassword($id, $input) {
		$user = $this->findOrThrowException($id);

		//Passwords are hashed on the model
		$user->password = $input['password'];
		if ($user->save())
			return true;

		throw new GeneralException('There was a problem changing this users password. Please try again.');
	}

	/**
	 * @param $id
	 * @return bool
	 * @throws GeneralException
	 */
	public function destroy($id) {
		if (auth()->id() == $id)
			throw new GeneralException("You can not delete yourself.");

		$user = $this->findOrThrowException($id);
		if ($user->delete())
			return true;

		throw new GeneralException("There was a problem deleting this user. Please try again.");
	}

	/**
	 * @param $id
	 * @return boolean|null
	 * @throws GeneralException
	 */
	public function delete($id) {
		$user = $this->findOrThrowException($id, true);

		//Detach all roles & permissions
		$user->detachRoles($user->roles);
		$user->detachPermissions($user->permissions);

		try {
			$user->forceDelete();
		} catch (\Exception $e) {
			throw new GeneralException($e->getMessage());
		}
	}

	/**
	 * @param $id
	 * @return bool
	 * @throws GeneralException
	 */
	public function restore($id) {
		$user = $this->findOrThrowException($id);

		if ($user->restore())
			return true;

		throw new GeneralException("There was a problem restoring this user. Please try again.");
	}

	/**
	 * @param $id
	 * @param $status
	 * @return bool
	 * @throws GeneralException
	 */
	public function mark($id, $status) {
		if (auth()->id() == $id && ($status == 0 || $status == 2))
			throw new GeneralException("You can not do that to yourself.");

		$user = $this->findOrThrowException($id);
		$user->status = $status;

		if ($user->save())
			return true;

		throw new GeneralException("There was a problem updating this user. Please try again.");
	}

	/**
	 * Check to make sure at lease one role is being applied or deactivate user
	 * @param $user
	 * @param $roles
	 * @throws UserNeedsRolesException
	 */
	private function validateRoleAmount($user, $roles) {
		//Validate that there's at least one role chosen, placing this here so
		//at lease the user can be updated first, if this fails the roles will be
		//kept the same as before the user was updated
		if (count($roles) == 0) {
			//Deactivate user
			$user->status = 0;
			$user->save();

			$exception = new UserNeedsRolesException();
			$exception->setValidationErrors('You must choose at lease one role. User has been created but deactivated.');

			//Grab the user id in the controller
			$exception->setUserID($user->id);
			throw $exception;
		}
	}

	/**
	 * @param $input
	 * @param $user
	 * @throws GeneralException
	 */
	private function checkUserByEmail($input, $user)
	{
		//Figure out if email is not the same
		if ($user->email != $input['email'])
		{
			//Check to see if email exists
			if (User::where('email', '=', $input['email'])->first())
				throw new GeneralException('That email address belongs to a different user.');
		}
	}

	/**
	 * @param $roles
	 * @param $user
	 */
	private function flushRoles($roles, $user)
	{
		//Flush roles out, then add array of new ones
		$user->detachRoles($user->roles);
		$user->attachRoles($roles['assignees_roles']);
	}

	/**
	 * @param $permissions
	 * @param $user
	 */
	private function flushPermissions($permissions, $user)
	{
		//Flush permissions out, then add array of new ones if any
		$user->detachPermissions($user->permissions);
		if (count($permissions['permission_user']) > 0)
			$user->attachPermissions($permissions['permission_user']);
	}

	/**
	 * @param $roles
	 * @throws GeneralException
	 */
	private function checkUserRolesCount($roles)
	{
		//User Updated, Update Roles
		//Validate that there's at least one role chosen
		if (count($roles['assignees_roles']) == 0)
			throw new GeneralException('You must choose at least one role.');
	}

	/**
	 * @param $input
	 * @return mixed
	 */
	private function createUserStub($input)
	{
		$user = new User;
		$user->name = $input['name'];
		$user->email = $input['email'];
		$user->password = $input['password'];
		$user->status = isset($input['status']) ? 1 : 0;
		$user->confirmation_code = md5(uniqid(mt_rand(), true));
		$user->confirmed = isset($input['confirmed']) ? 1 : 0;
		return $user;
	}
}


text:
***Request name***: `latest-revisions-since`

***Request parameters***: empty

***Request headers***: empty

***Request body***: This request is very similar to the request of the ["Latest Revision" message](latest_revision.md). This contains information about the SCM configuration provided by the user. The keys in the maps correspond to the keys provided by the plugin, as a part of the response to ["SCM Configuration"](scm_configuration.md) messages.

Along with that information, this request contains information about the previous revision of the SCM that GoCD knows about. Compare the "previous-revision" data of the example request shown below, with the response of the ["Latest Revision" message](latest_revision.md#response---from-the-plugin) to understand this.

Note: It is prudent to validate these details before using them, because direct editing of GoCD's configuration XML file does not cause ["Validate SCM Configuration"](validate_scm_configuration.md) to be sent to the plugin. So, the information sent to this call might not be validated by the plugin.

***Example request***:

```json
{
    "scm-configuration": {
        "SCM_URL": {
            "value": "http://localhost.com"
        },
        "USERNAME": {
            "value": "user"
        },
        "PASSWORD": {
            "value": "password"
        }
    },
    "scm-data": {
        "dataKeyOne": "data-value-one",
        "dataKeyTwo": "data-value-two"
    },
    "flyweight-folder": "/var/lib/go-server/pipelines/flyweight-for-this-material",
    "previous-revision": {
        "revision": "revision-1",
        "timestamp": "2011-07-14T19:43:37.100Z",
        "data": {
          "dataKeyOne": "data-value-one",
          "dataKeyTwo": "data-value-two"
        }
    }
}
```

### Response - From the plugin

***Expected response body***: Just as with the "Lastest Revision" message, the plugin is expected to send a response, which contains information about the latest revision it can find of the SCM specified by the information in the request. The difference here, is that it needs to find a revisions of the SCM which is greater than the one specified in the request - previous-revision. It can send an empty response ({}) to specify that it could not find revisions (for instance, if there has been no change, and the latest revision is still the one specified in the request).

Almost all the fields expected in this response are explained in this [part of the user documentation](https://docs.gocd.org/current/extension_points/scm_extension.html#scm-information-display). The extra map, named "data" in the response, can be filled with custom key-value pairs, which will be made available to the agent, as environment variables, when a job contains this plugin as a material.

***Example response***:

```json
{
    "revisions" : [
        {
            "revision": "revision-2",
            "timestamp": "2011-07-14T19:45:37.100Z",
            "user": "some-user",
            "revisionComment": "comment 2",
            "data": {
                "dataKeyOne": "data-value-one-1",
                "dataKeyTwo": "data-value-two-2"
            },
            "modifiedFiles": [
                {
                    "fileName": "file-2",
                    "action": "modified"
                }
            ]
        }
    ],
    "scm-data": {
        "dataKeyOne": "data-value-one",
        "dataKeyTwo": "data-value-three"
    }
}
```

### Schema information

***[JSON schema](http://json-schema.org) of request from the server***:

```json
{
    "title": "Latest revisions since request schema",
    "description": "Schema for latest revisions since request Json",
    "type": "object",
    "properties": {
        "scm-configuration": {
             "type": "object",
             "patternProperties": {
                 "^[a-zA-Z0-9_-]+$": {
                     "type": [
                         "object",
                         "null"
                     ],
                     "properties": {
                         "value": {
                             "type": "string",
                             "pattern": "^[a-zA-Z0-9_-]+$"
                         }
                     },
                     "additionalProperties": false
                 }
             },
             "additionalProperties": false
         },
        "flyweight-folder" : {
            "type": "string",
            "required": true
        },
        "previous-revision": {
            "type": "object",
            "properties": {
                "revision": {
                    "type": "string"
                },
                "timestamp": {
                    "type": "string"
                },
                "data": {
                    "type": "object",
                    "patternProperties": {
                        "^[a-zA-Z0-9_-]+$": {
                            "type": "string"
                        },
                        "additionalProperties": false
                    }
                }
            }
        }
    },
    "additionalProperties": false
}
```

***[JSON schema](http://json-schema.org) of expected response***:

```json
{
    "title": "Latest revisions since response schema",
    "description": "Schema for latest revisions since response Json",
    "type":"object",
    "required":false,
    "properties":{
        "revisions": {
            "required": false,
            "type": "array",
            "items": {
                "type": "object",
                "data": {
                    "type":"object",
                    "required":false,
                    "patternProperties":{
                        "^[a-zA-Z0-9_-]+$":{
                            "type":"string",
                            "required":false
                        }
                    },
                    "additionalProperties": false
                },
                "revisionComment": {
                    "type":"string",
                    "required":false
                },
                "revision": {
                    "type":"string",
                    "required":false
                },
                "timestamp": {
                    "type":"string",
                    "required":false
                },
                "user": {
                    "type":"string",
                    "required":false
                },
                "modifiedFiles": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "fileName": {
                                "type": "string",
                                "required": true
                            },
                            "action": {
                                "type": "string",
                                "required": true
                            }
                        },
                        "additionalProperties": false
                    },
                    "minItems": 0,
                    "uniqueItems": true,
                    "additionalItems": false
                }
            },
            "scm-data": {
                "type":"object",
                "required":false,
                "patternProperties":{
                    "^[a-zA-Z0-9_-]+$":{
                        "type":"string",
                        "required":false
                    }
                }
            }
            "minItems": 0,
            "uniqueItems": true
        }
    },
    "additionalProperties": false
}
```


text:
package com.ivyis.di.trans.steps.git.command.impl;

import java.io.File;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.pentaho.di.i18n.BaseMessages;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.ivyis.di.trans.steps.git.GitCommandType;
import com.ivyis.di.trans.steps.git.command.GitCommand;
import com.ivyis.di.trans.steps.git.command.GitOperationsCommand;
import com.ivyis.di.trans.steps.git.operations.GitOperationsStep;

/**
 * Init Git command implementation.
 *
 * @author Joel Latino
 * @since 1.0.0
 */
public class InitGitCommand implements GitOperationsCommand {
  private static final Class<?> PKG = InitGitCommand.class; // for i18n
  private static final Logger LOGGER = Logger.getLogger(PKG);

  private boolean bare;

  public InitGitCommand() {}

  public InitGitCommand(String description) {
    if ("".equals(description)) {
      throw new IllegalArgumentException("Unkomnown config fields.");
    }
    final String[] stringProps = description.split(" / ");
    for (String stringProp : stringProps) {
      if (BaseMessages.getString(PKG, "Git.Bare.Label").equals(
          stringProp.split(":")[0].trim())) {
        this.bare = Boolean.parseBoolean(stringProp.split(":")[1]
            .trim());
      }
    }
  }

  public InitGitCommand(Node xml, String stepName) {
    try {
      final XPathFactory xPathFactory = XPathFactory.newInstance();
      final XPath xpath = xPathFactory.newXPath();
      final XPathExpression xPathExpr = xpath.compile("//step[name='"
          + stepName + "']/gitCommands//" + GitCommand.MAIN_NODE
          + "/bare/text()");
      this.bare = Boolean.parseBoolean((String) xPathExpr.evaluate(xml,
          XPathConstants.STRING));

    } catch (XPathExpressionException e) {
      LOGGER.error(e.getMessage(), e);
    }
  }

  public String getDescription() {
    return BaseMessages.getString(PKG, "Git.Bare.Label") + ": " + bare;
  }

  public GitCommandType getCommandType() {
    return GitCommandType.INIT;
  }

  public String getXML() {
    try {
      final DocumentBuilderFactory dFact = DocumentBuilderFactory
          .newInstance();
      final DocumentBuilder build = dFact.newDocumentBuilder();
      final Document doc = build.newDocument();
      final Element root = doc.createElement(MAIN_NODE);
      doc.appendChild(root);
      final Element commandName = doc.createElement(COMMAND_NAME_NODE);
      commandName.appendChild(doc.createTextNode(GitCommandType.INIT
          .getOperationName()));
      root.appendChild(commandName);

      final Element bareNode = doc.createElement("bare");
      bareNode.appendChild(doc.createTextNode(String.valueOf(bare)));
      root.appendChild(bareNode);

      final Transformer tf = TransformerFactory.newInstance()
          .newTransformer();
      tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      tf.setOutputProperty(OutputKeys.INDENT, "yes");
      tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      final Writer out = new StringWriter();
      tf.transform(new DOMSource(doc), new StreamResult(out));
      return out.toString();

    } catch (ParserConfigurationException pce) {
      LOGGER.error(pce.getMessage(), pce);
      return "";
    } catch (TransformerException e) {
      LOGGER.error(e.getMessage(), e);
      return "";
    }
  }

  public Git call(final GitOperationsStep gitOperationsStep, Git git,
      CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder)
      throws GitAPIException {
    return Git.init().setBare(bare).setDirectory(gitRepoFolder).call();
  }

  public boolean isBare() {
    return bare;
  }

  public void setBare(boolean bare) {
    this.bare = bare;
  }

}


text:
package com.github.e13mort.stf.console;

import com.github.e13mort.stf.client.FarmClient;
import com.github.e13mort.stf.client.FarmInfo;
import com.github.e13mort.stf.console.commands.cache.DeviceListCache;
import io.reactivex.Single;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.util.logging.Logger;

public class StfCommanderContext {
    private static final String DEFAULT_PROPERTY_FILE_NAME = "farm.properties";

    private final FarmClient client;
    private final AdbRunner adbRunner;
    private DeviceListCache cache;
    private OutputStream output;
    private Logger logger;

    StfCommanderContext(FarmClient client, AdbRunner adbRunner, DeviceListCache cache, OutputStream output, Logger logger) {
        this.client = client;
        this.adbRunner = adbRunner;
        this.cache = cache;
        this.output = output;
        this.logger = logger;
    }

    public FarmClient getClient() {
        return client;
    }

    public AdbRunner getAdbRunner() {
        return adbRunner;
    }

    public DeviceListCache getCache() {
        return cache;
    }

    public OutputStream getOutput() {
        return output;
    }

    public Logger getLogger() {
        return logger;
    }

    static Single<StfCommanderContext> create(Logger logger) {
        return Single.create(e -> e.onSuccess(createInternal(logger)));
    }

    private static StfCommanderContext createInternal(Logger logger) throws IOException {
        FarmInfo farmInfo = createFarmInfo();
        FarmClient client = FarmClient.create(farmInfo);
        AdbRunner adbRunner = new AdbRunner(farmInfo.getSdkPath(), logger);
        DeviceListCache cache = DeviceListCache.getCache();
        final OutputStream output = System.out;
        return new StfCommanderContext(client, adbRunner, cache, output, logger);
    }

    private static FarmInfo createFarmInfo() throws IOException {
        File properties = getPropertiesFile(DEFAULT_PROPERTY_FILE_NAME);
        return readFarmInfo(properties);
    }

    private static FarmInfo readFarmInfo(File propertiesFile) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileReader(propertiesFile));
        String farmUrl = properties.getProperty("stf.url");
        String apiKey = properties.getProperty("stf.key");
        if (farmUrl == null || apiKey == null) {
            throw new IllegalArgumentException("Property file is invalid");
        }
        String sdk = properties.getProperty("android_sdk");
        int timeout = getTimeout(properties);
        return new FarmInfo(farmUrl, apiKey, sdk, timeout);
    }

    private static File getPropertiesFile(String propertiesFileName) {
        File file = new File(propertiesFileName);

        if (!file.exists()) {
            File homeFile = new File(System.getProperty("user.home"), propertiesFileName);
            if (homeFile.exists()) {
                return homeFile;
            } else {
                throw new IllegalArgumentException("Property file does not exists");
            }
        }
        return file;
    }

    private static int getTimeout(Properties properties) {
        String timeoutProperty = properties.getProperty("stf.timeout");
        return Integer.parseInt(timeoutProperty);
    }
}


text:
require "wp2corpus/version"
require "wp2corpus/cli"
require "wp2corpus/nlp"
require "wp2txt"
require "wp2txt/utils"
require "pry"

$leave_template = true
$leave_table    = true
$leave_ref      = true

module Wp2corpus
  class Control
    def make options
      parent = Wp2txt::CmdProgbar.new
      wpconv = Wp2txt::Runner.new(parent, options.input_file, options.output_dir, 100, true, true)
      element_whitelist = [:mw_paragraph, :mw_unordered, :mw_ordered, :mw_definition]
      title_blacklist   = /(曖昧さの回避|曖昧さ回避|一覧)/
      nlp = Wp2corpus::NLP.new(
        stem:          options[:stem],
        categorematic: options[:categorematic]
      )
      wpconv.extract_text do |article|
        wpconv.format_wiki!(article.title)
        title = article.title
        contents = ""
        unless title =~ title_blacklist
          article.elements.each do |e|
            if element_whitelist.include? e.first
              wpconv.format_wiki!(e.last) if [:mw_paragraph].include? e.first
              line    = e.last
              content = nlp.parse(line)
              contents << "#{content} " if content
            end
          end
          contents.gsub!("\n", " ")
          title.gsub!(" ", "_")
          if contents.split(' ').length >= 10
            contents = "doc:#{title}\t#{contents}\n"
          else
            contents = ""
          end
        end
        contents
      end
    end
  end
end


text:
var env = require("./env"),
	jquery = require("./jquery"), // first require
	logger = require("../libs/logger");

logger.log("Starting...");

if (env.isValid()) {
	jquery.load(function ($) {
		logger.log("Running with jQuery", $.fn.jquery);
		// Is "interactive" enough to ensure everything would be OK?
		if (document.readyState == "complete" /*  || document.readyState == "interactive" */) {
			runScript();
		} else {
			logger.log("Waiting for document to be ready...");
			$(document).ready(runScript);
		}
		function runScript() {
			logger.log("Document is ready");
			if (env.detectOnReady()) {
				require("./run");
			}
		}
	});
}


text:
package com.linkedin.thirdeye.dashboard.views;

import io.dropwizard.views.View;

public class DefaultView extends View {

  public DefaultView(String templateName) {
    super(templateName);
  }

}


text:
"use strict";
//# sourceMappingURL=cart-item.model.js.map