text:
package lila.round

import chess.format.Forsyth
import chess.variant._
import chess.{ Game => ChessGame, Board, Color => ChessColor, Castles, Clock, Situation, History }
import ChessColor.{ Black, White }
import com.github.blemale.scaffeine.Cache
import lila.memo.CacheApi
import scala.concurrent.duration._

import lila.common.Bus
import lila.game.{ AnonCookie, Event, Game, GameRepo, PerfPicker, Pov, Rematches, Source }
import lila.memo.ExpireSetMemo
import lila.user.{ User, UserRepo }
import lila.i18n.{ I18nKeys => trans, defaultLang }

final private class Rematcher(
    gameRepo: GameRepo,
    userRepo: UserRepo,
    idGenerator: lila.game.IdGenerator,
    messenger: Messenger,
    onStart: OnStart,
    rematches: Rematches
)(implicit ec: scala.concurrent.ExecutionContext) {

  implicit private val chatLang = defaultLang

  private val declined = new lila.memo.ExpireSetMemo(1 minute)

  private val rateLimit = new lila.memo.RateLimit[String](
    credits = 2,
    duration = 1 minute,
    key = "round.rematch",
    log = false
  )

  import Rematcher.Offers

  private val offers: Cache[Game.ID, Offers] = CacheApi.scaffeineNoScheduler
    .expireAfterWrite(20 minutes)
    .build[Game.ID, Offers]()

  private val chess960 = new ExpireSetMemo(3 hours)

  def isOffering(pov: Pov): Boolean = offers.getIfPresent(pov.gameId).exists(_(pov.color))

  def yes(pov: Pov): Fu[Events] =
    pov match {
      case Pov(game, color) if game.playerCouldRematch =>
        if (isOffering(!pov) || game.opponent(color).isAi)
          rematches.of(game.id).fold(rematchJoin(pov))(rematchExists(pov))
        else if (!declined.get(pov.flip.fullId) && rateLimit(pov.fullId)(true)(false))
          fuccess(rematchCreate(pov))
        else fuccess(List(Event.RematchOffer(by = none)))
      case _ => fuccess(List(Event.ReloadOwner))
    }

  def no(pov: Pov): Fu[Events] = {
    if (isOffering(pov)) messenger.system(pov.game, trans.rematchOfferCanceled.txt())
    else if (isOffering(!pov)) {
      declined put pov.fullId
      messenger.system(pov.game, trans.rematchOfferDeclined.txt())
    }
    offers invalidate pov.game.id
    fuccess(List(Event.RematchOffer(by = none)))
  }

  private def rematchExists(pov: Pov)(nextId: Game.ID): Fu[Events] =
    gameRepo game nextId flatMap {
      _.fold(rematchJoin(pov))(g => fuccess(redirectEvents(g)))
    }

  private def rematchJoin(pov: Pov): Fu[Events] =
    rematches.of(pov.gameId) match {
      case None =>
        for {
          nextGame <- returnGame(pov) map (_.start)
          _ = offers invalidate pov.game.id
          _ = rematches.cache.put(pov.gameId, nextGame.id)
          _ = if (pov.game.variant == Chess960 && !chess960.get(pov.gameId)) chess960.put(nextGame.id)
          _ <- gameRepo insertDenormalized nextGame
        } yield {
          messenger.system(pov.game, trans.rematchOfferAccepted.txt())
          onStart(nextGame.id)
          redirectEvents(nextGame)
        }
      case Some(rematchId) => gameRepo game rematchId map { _ ?? redirectEvents }
    }

  private def rematchCreate(pov: Pov): Events = {
    messenger.system(pov.game, trans.rematchOfferSent.txt())
    pov.opponent.userId foreach { forId =>
      Bus.publish(lila.hub.actorApi.round.RematchOffer(pov.gameId), s"rematchFor:$forId")
    }
    offers.put(pov.gameId, Offers(white = pov.color.white, black = pov.color.black))
    List(Event.RematchOffer(by = pov.color.some))
  }

  private def returnGame(pov: Pov): Fu[Game] =
    for {
      initialFen <- gameRepo initialFen pov.game
      situation = initialFen flatMap Forsyth.<<<
      pieces = pov.game.variant match {
        case Chess960 =>
          if (chess960 get pov.gameId) Chess960.pieces
          else situation.fold(Chess960.pieces)(_.situation.board.pieces)
        case FromPosition => situation.fold(Standard.pieces)(_.situation.board.pieces)
        case variant      => variant.pieces
      }
      users <- userRepo byIds pov.game.userIds
      board = Board(pieces, variant = pov.game.variant).withHistory(
        History(
          lastMove = situation.flatMap(_.situation.board.history.lastMove),
          castles = situation.fold(Castles.init)(_.situation.board.history.castles)
        )
      )
      game <- Game.make(
        chess = ChessGame(
          situation = Situation(
            board = board,
            color = situation.fold[chess.Color](White)(_.situation.color)
          ),
          clock = pov.game.clock map { c =>
            Clock(c.config)
          },
          turns = situation ?? (_.turns),
          startedAtTurn = situation ?? (_.turns)
        ),
        whitePlayer = returnPlayer(pov.game, White, users),
        blackPlayer = returnPlayer(pov.game, Black, users),
        mode = if (users.exists(_.lame)) chess.Mode.Casual else pov.game.mode,
        source = pov.game.source | Source.Lobby,
        daysPerTurn = pov.game.daysPerTurn,
        pgnImport = None
      ) withUniqueId idGenerator
    } yield game

  private def returnPlayer(game: Game, color: ChessColor, users: List[User]): lila.game.Player =
    game.opponent(color).aiLevel match {
      case Some(ai) => lila.game.Player.make(color, ai.some)
      case None =>
        lila.game.Player.make(
          color,
          game.opponent(color).userId.flatMap { id =>
            users.find(_.id == id)
          },
          PerfPicker.mainOrDefault(game)
        )
    }

  private def redirectEvents(game: Game): Events = {
    val whiteId = game fullIdOf White
    val blackId = game fullIdOf Black
    List(
      Event.RedirectOwner(White, blackId, AnonCookie.json(game pov Black)),
      Event.RedirectOwner(Black, whiteId, AnonCookie.json(game pov White)),
      // tell spectators about the rematch
      Event.RematchTaken(game.id)
    )
  }
}

private object Rematcher {

  case class Offers(white: Boolean, black: Boolean) {
    def apply(color: chess.Color) = color.fold(white, black)
  }
}


text:
<?php

class ImmutableTest extends UnitTestCase
{

  // TODO: Look at writing a helper test to use reflection to make sure the "setX" method is not available
  public function test_Immutable()
  {
    $door = new DoorC("1",2,3.4,date(1234),time(1235),false,new DoorB(5));

    $this->assertEqual("1",$door->getId());
    // $this->assertEqual(false,$door->setId("2"));
    // $this->assertEqual("1",$door->getId());

    $this->assertEqual(2,$door->getIntId());
    // $this->assertEqual(false,$door->setIntId(22));
    // $this->assertEqual(2,$door->getIntId());

    $this->assertEqual(3.4,$door->getDoubleId(),0.01);
    // $this->assertEqual(false,$door->setDoubleId(33.44));
    // $this->assertEqual(3.4,$door->getDoubleId(),0.01);

    $this->assertEqual(date(1234),$door->getDateId());
    // $this->assertEqual(false,$door->setDateId(date(4321)));
    // $this->assertEqual(date(1234),$door->getDateId());

    $this->assertEqual(time(1235),$door->getTimeId());
    // $this->assertEqual(false,$door->setTimeId(date(5321)));
    // $this->assertEqual(time(1235),$door->getTimeId());

    $this->assertEqual(false,$door->getBooleanId());
    // $this->assertEqual(false,$door->setBooleanId(true));
    // $this->assertEqual(false,$door->getBooleanId());

    $this->assertEqual(new DoorB(5),$door->getDoorId());
    // $this->assertEqual(false,$door->setDoorId(new DoorB(6)));
    // $this->assertEqual(new DoorB(5),$door->getDoorId());
  }

  //TODO: Look at writing a helper test to use reflection to make sure the "setX" method is not available
  public function test_ImmutableInitialized()
  {
    $door = new DoorA();
    $this->assertEqual("1",$door->getId());
    // $this->assertEqual(false,$door->setId("2"));
    // $this->assertEqual("1",$door->getId());

    $this->assertEqual(2,$door->getIntId());
    // $this->assertEqual(false,$door->setIntId(22));
    // $this->assertEqual(2,$door->getIntId());

    $this->assertEqual(3.4,$door->getDoubleId(),0.01);
    // $this->assertEqual(false,$door->setDoubleId(33.44));
    // $this->assertEqual(3.4,$door->getDoubleId(),0.01);

    $this->assertEqual(date(1234),$door->getDateId());
    // $this->assertEqual(false,$door->setDateId(date(4321)));
    // $this->assertEqual(date(1234),$door->getDateId());

    $this->assertEqual(time(1235),$door->getTimeId());
    // $this->assertEqual(false,$door->setTimeId(date(5321)));
    // $this->assertEqual(time(1235),$door->getTimeId());

    $this->assertEqual(false,$door->getBooleanId());
    // $this->assertEqual(false,$door->setBooleanId(true));
    // $this->assertEqual(false,$door->getBooleanId());

    $this->assertEqual(new DoorB(5),$door->getDoorId());
    // $this->assertEqual(false,$door->setDoorId(new DoorB(6)));
    // $this->assertEqual(new DoorB(5),$door->getDoorId());

  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Differential Speckle Survey Instrument</AwardTitle>
    <AwardEffectiveDate>08/01/2007</AwardEffectiveDate>
    <AwardExpirationDate>08/31/2009</AwardExpirationDate>
    <AwardAmount>126513</AwardAmount>
    <AwardInstrument>
      <Value>Continuing grant</Value>
    </AwardInstrument>
    <Organization>
      03020518
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Astronomical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Jeffrey R. Pier</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>AST-0504010 -- Horch/U Mass Dartmouth<br/><br/>The award covers the development and construction of the Differential Speckle Survey Instrument. This instrument builds upon a previous speckle imager developed by the investigators that is compatible with any large format CCD and uses the large area of such a CCD as a memory cache of many speckle images prior to a full-frame readout. The Differential Speckle Survey Instrument will use the same idea, but will collect speckle patterns in two colors simultaneously in order to obtain image information below the diffraction limit of a large telescope. The Differential Speckle Survey Instrument will be an important tool for ongoing long baseline interferometer projects.</AbstractNarration>
    <MinAmdLetterDate>09/06/2007</MinAmdLetterDate>
    <MaxAmdLetterDate>11/09/2007</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0751361</AwardID>
    <Investigator>
      <FirstName>Elliott</FirstName>
      <LastName>Horch</LastName>
      <EmailAddress>horche2@southernct.edu</EmailAddress>
      <StartDate>09/06/2007</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Grant</FirstName>
      <LastName>O'Rielly</LastName>
      <EmailAddress>grant.orielly@umassd.edu</EmailAddress>
      <StartDate>11/09/2007</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Southern Connecticut State University</Name>
      <CityName>New Haven</CityName>
      <ZipCode>065151330</ZipCode>
      <PhoneNumber>2033925151</PhoneNumber>
      <StreetAddress>501 Crescent Street</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Connecticut</StateName>
      <StateCode>CT</StateCode>
    </Institution>
    <ProgramElement>
      1218
      <Text>ADVANCED TECHNOLOGIES & INSTRM</Text>
    </ProgramElement>
    <ProgramReference>
      0000
      <Text>UNASSIGNED</Text>
    </ProgramReference>
    <ProgramReference>
      1207
      <Text>OBSERVATIONAL ASTRONOMY</Text>
    </ProgramReference>
    <ProgramReference>
      OTHR
      <Text>OTHER RESEARCH OR EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
//
//  postDetailTVC.m
//  TakeMeHome
//
//  Created by Nigel on 2015/8/28.
//  Copyright (c) 2015年 Josh. All rights reserved.
//

#import "editDetailTVC.h"
#import "SSBouncyButton.h"
#import "UIColor+FlatUI.h"
#import "FUIAlertView.h"
#import "MBProgressHUD.h"
#import "adoptView.h"
#import "HHAlertView.h"

@interface editDetailTVC ()
<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate,MBProgressHUDDelegate>
{
	MBProgressHUD *HUD;
    UIPickerView *areaPickView;
    NSArray *areaArray ;
    NSString *getAreaNumStr;
    UIView   *maskView;
    NSMutableArray *getphotoImgArray;
    PFFile *imageFile;
    PFUser *currentUser;

}
@property (weak, nonatomic) IBOutlet UITextField *areaTxtField;
@property (weak, nonatomic) IBOutlet UITextField *sexTxtField;
@property (weak, nonatomic) IBOutlet UITextField *typeTxtField;
@property (weak, nonatomic) IBOutlet UITextField *ageTxtField;
@property (weak, nonatomic) IBOutlet UITextField *colorTxtField;
@property (weak, nonatomic) IBOutlet UITextField *mixTypeTxtField;
@property (weak, nonatomic) IBOutlet UITextField *sterilizationTxtField;
@property (weak, nonatomic) IBOutlet UITextField *bacterinTxtField;
@property (weak, nonatomic) IBOutlet UITextField *contactTxtField;
@property (weak, nonatomic) IBOutlet UITextField *howToContactTxtField;
@property (weak, nonatomic) IBOutlet UITextField *foundTxtFiled;
@property (weak, nonatomic) IBOutlet UITextView *traitTxtField;
@property (weak, nonatomic) IBOutlet SSBouncyButton *OKbtn;
@property (weak, nonatomic) IBOutlet SSBouncyButton *cancelBtn;

@end

@implementation editDetailTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //btn setting
    [self BtnsSetting];
    [self areaArrSettings];
    //NSLog(@"%@",self.adoptData);
    currentUser = [PFUser currentUser];
    NSString *userName = currentUser[@"name"];
    NSString *userContactMethod = currentUser[@"email"];
    NSInteger index =[self.adoptData[@"area"] integerValue];
    NSString *areaStr = [areaArray objectAtIndex:index-1];

    _contactTxtField.text = userName;
    _howToContactTxtField.text = userContactMethod;
    _ageTxtField.text = self.adoptData[@"age"];
    _areaTxtField.text = @"";
    _bacterinTxtField.text = self.adoptData[@"bacterin"];
    _colorTxtField.text = self.adoptData[@"color"];
    _foundTxtFiled.text = self.adoptData[@"found"];
    _mixTypeTxtField.text = self.adoptData[@"mixType"];
    _sexTxtField.text = self.adoptData[@"sex"];
    _sterilizationTxtField.text = self.adoptData[@"sterilization"];
    _traitTxtField.text = self.adoptData[@"trait"];
    _typeTxtField.text = self.adoptData[@"type"];

    //NSLog(@"currentUser: %@",currentUser);
    //getphotoImgArray = [NSMutableArray new];

    //如果user有放照片 則觸發此notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addImgData:) name:USER_POST_PHOTO_NOTIFICATION object:nil];

}

- (void)addImgData:(NSNotification*)notify{

    NSData *imageData = UIImagePNGRepresentation(notify.object);
    NSString *imgfileNameStr = [NSString stringWithFormat:@"%ld.png",(unsigned long)imageData.hash];
    imageFile = [PFFile fileWithName:imgfileNameStr data:imageData];

    [getphotoImgArray insertObject:imageFile atIndex:0];
    if (getphotoImgArray.count >= 2) {
        //僅能放2張img 之前po過的就del掉
        [getphotoImgArray removeObjectAtIndex:2];
    }

    //NSLog(@"%@",notify.object);
}

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

- (void)BtnsSetting{

    _OKbtn.adjustsImageWhenHighlighted = NO;
    _OKbtn.tintColor = [UIColor turquoiseColor];
    _OKbtn.cornerRadius = SSBouncyButtonDefaultCornerRadius;
    _OKbtn.titleLabel.font = [UIFont systemFontOfSize:SSBouncyButtonDefaultTitleLabelFontSize];
    [_OKbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [_OKbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected | UIControlStateHighlighted];

    _cancelBtn.adjustsImageWhenHighlighted = NO;
    _cancelBtn.tintColor = [UIColor alizarinColor];
    _cancelBtn.cornerRadius = SSBouncyButtonDefaultCornerRadius;
    _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:SSBouncyButtonDefaultTitleLabelFontSize];
    [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected | UIControlStateHighlighted];

}

- (IBAction)submitBtn:(UIButton*)button {
    //button.selected = !button.selected;

    //必填沒填 -> 跳警告
    //必填正常 -> 上傳資料

    if (_areaTxtField.text.length == 0 || _sexTxtField.text.length == 0 ||
        _ageTxtField.text.length == 0 ||  _contactTxtField.text.length == 0 ||
        _howToContactTxtField.text.length == 0) {
        [self doAlert];
    }else{

        [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
        [self pushDataToParse];
    }

}

- (void)pushDataToParse{

    if ([_sexTxtField.text isEqualToString:@"公"]) {//公
        _sexTxtField.text = @"M";
    }else{
        _sexTxtField.text = @"F";
    }

    if ([_ageTxtField.text isEqualToString:@"成年"]) {
        _ageTxtField.text = @"ADULT";
    }else{
        _ageTxtField.text = @"CHILD";
    }
    //拿po文者的大頭貼
    PFFile *userIcon = currentUser[@"userPhoto"];

    PFQuery *queryPostAdopt = [PFQuery queryWithClassName:ADOPT_PETS_PARSE_TABLE_NAME];
    [queryPostAdopt getObjectInBackgroundWithId:self.adoptData.objectId block:^(PFObject *postAdopt ,NSError *err){
        if (!err) {
            postAdopt[AREA_PARSE_TITLE] = getAreaNumStr;
            postAdopt[TYPE_PARSE_TITLE] = _typeTxtField.text;
            postAdopt[SEX_PARSE_TITLE] = _sexTxtField.text;
            postAdopt[AGE_PARSE_TITLE] = _ageTxtField.text;
            postAdopt[MIX_TYPE_PARSE_TITLE] = _mixTypeTxtField.text;
            postAdopt[COLOR_PARSE_TITLE] = _colorTxtField.text;
            postAdopt[STERILIZATION_PARSE_TITLE] = _sterilizationTxtField.text;
            postAdopt[BACTERIN_PARSE_TITLE] = _bacterinTxtField.text;
            postAdopt[CONTACT_PARSE_TITLE] = _contactTxtField.text;
            postAdopt[HOW_TO_CONTACT_PARSE_TITLE] = _howToContactTxtField.text;
            postAdopt[FOUND_PARSE_TITLE] = _foundTxtFiled.text;
            postAdopt[TRAIT_PARSE_TITLE] = _traitTxtField.text;

            if (imageFile != nil) {
                postAdopt[USER_ICON_PARSE_TITLE] =  userIcon;
            }
            if (imageFile != nil) {
                postAdopt[USER_POST_IMG_PHOTO_PARSE_TITLE] = imageFile;
            }

            [postAdopt save];

            [MBProgressHUD hideHUDForView:self.view.window animated:YES];

            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"adopt" bundle:nil];

            adoptView *nextVC = [storyBoard instantiateViewControllerWithIdentifier:@"adoptView"];
            nextVC.getUserOptionsFilterDoneStr = [NSString stringWithFormat:@"(animal_area_pkid == '%@') AND (animal_kind == '%@') AND (animal_sex == '%@') AND (animal_age == '%@')",getAreaNumStr,_typeTxtField.text,_sexTxtField.text,_ageTxtField.text];
            [self.navigationController pushViewController:nextVC animated:true];
        }else{
            [self.view.window addSubview:self.addmaskView];
            [[HHAlertView shared]
             showAlertWithStyle:HHAlertStyleWraning
             inView:self.view.window
             Title:@"注意"
             detail:@"請檢查您的網路狀況"
             cancelButton:nil
             Okbutton:@"關閉"
             block:^(HHAlertButton buttonindex) {
                 [maskView removeFromSuperview];

             }];
        }
    }];

}

- (void)areaArrSettings{
    areaArray = [NSArray arrayWithObjects:
                 @"",@"臺北市",@"新北市",@"基隆市",@"宜蘭縣",@"桃園縣",@"新竹縣",@"新竹市",@"苗栗縣",
                 @"臺中市",@"彰化縣",@"南投縣",@"雲林縣",@"嘉義縣",@"嘉義市",@"臺南市",@"臺南市",
                 @"高雄市",@"屏東縣",@"花蓮縣",@"臺東縣",@"澎湖縣",@"金門縣",@"連江縣",nil];
}

//建立一個霧透的背景
- (UIView *)addmaskView
{
    if (!maskView) {
        maskView = [[UIView alloc] initWithFrame:self.view.window.frame];
        [maskView setBackgroundColor:[UIColor blackColor]];
        [maskView setAlpha:0.2];
    }
    return maskView;

}

- (void)doAlert{
    [self.view.window addSubview:self.addmaskView];
    [[HHAlertView shared]showAlertWithStyle:HHAlertStyleWraning
                                     inView:self.view.window
                                      Title:nil
                                     detail:@"請確認必填欄位"
                               cancelButton:nil
                                   Okbutton:@"確定"
                                    block:^(HHAlertButton buttonindex) {
                                        [maskView removeFromSuperview];
                                    }
     ];
    /*
    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:@"請確認必填欄位"
                                                          message:nil
                                                         delegate:nil cancelButtonTitle:@"確定"
                                                otherButtonTitles:nil, nil];
    alertView.titleLabel.textColor = [UIColor cloudsColor];
    alertView.messageLabel.textColor = [UIColor cloudsColor];
    alertView.backgroundOverlay.backgroundColor = [[UIColor cloudsColor] colorWithAlphaComponent:0.8];
    alertView.alertContainer.backgroundColor = [UIColor midnightBlueColor];
    alertView.defaultButtonColor = [UIColor cloudsColor];
    alertView.defaultButtonShadowColor = [UIColor asbestosColor];
    alertView.defaultButtonTitleColor = [UIColor asbestosColor];
    [alertView show];
     */
}

- (void)setAreaPickerVIew{

    areaPickView = [UIPickerView new];
    areaPickView.delegate = self;

    [self.areaTxtField setInputView:areaPickView];
    [areaPickView setBackgroundColor:[UIColor colorWithRed: 1.0 green: 1.0 blue: 1.0 alpha: 1.0]];

    CGFloat screenWidth = self.view.frame.size.width;
    UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,screenWidth,44)];
    [toolBar setBarStyle:UIBarStyleBlackOpaque];
    UIBarButtonItem *cancelBarBtn =[[UIBarButtonItem alloc]
                                    initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                    target:self
                                    action:@selector(barBtnItemPressed:)];

    UIBarButtonItem *spanBarBtn = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                   target:self
                                   action:nil];

    UIBarButtonItem *doneBarBtn = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                   target:self
                                   action:@selector(barBtnItemPressed:)];

    toolBar.items = [[NSArray alloc] initWithObjects:cancelBarBtn,spanBarBtn, doneBarBtn,nil];
    cancelBarBtn.tintColor=[UIColor blackColor];
    doneBarBtn.tintColor=[UIColor blackColor];
    self.areaTxtField.inputAccessoryView = toolBar;
}

- (void)barBtnItemPressed:(UIBarButtonItem*)sender{
     [self.view endEditing:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 1000://area
            [self setAreaPickerVIew];
            break;
        case 1001://sex
            [self setOptionsAlert:@"公" secondOption:@"母" txtField:_sexTxtField];
            return false;
            break;
        case 1002://age
            [self setOptionsAlert:@"幼年" secondOption:@"成年" txtField:_ageTxtField];
            return false;
            break;
        case 1010://type
            [self setOptionsAlert:@"貓" secondOption:@"狗" txtField:_typeTxtField];
            return false;
        default:
            break;
    }
    return true;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    return areaArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    return [areaArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    getAreaNumStr = [NSString stringWithFormat:@"%d",row + 1] ;//編碼起始號碼為2號
    _areaTxtField.text = [areaArray objectAtIndex:row];
}

- (void)setOptionsAlert:(NSString*)firstOption secondOption:(NSString*)secondOptions txtField:(UITextField*)txtfield{

    UIAlertController *optionsAlert=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *optionFirst = [UIAlertAction actionWithTitle:firstOption style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        txtfield.text = firstOption;
    }];

    UIAlertAction *optionSecond=[UIAlertAction actionWithTitle:secondOptions style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        txtfield.text= secondOptions;
    }];
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];

    [optionsAlert addAction:optionFirst];
    [optionsAlert addAction:optionSecond];
    [optionsAlert addAction:cancle];
    [self presentViewController:optionsAlert animated:YES completion:nil];
}

- (IBAction)btnCancelPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end


text:
package bootstrap;

import com.ltsllc.miranda.miranda.Miranda;
import com.ltsllc.miranda.test.TestCase;
import com.ltsllc.miranda.user.BootstrapUsersFile;
import org.junit.Test;

/**
 * Created by clarkhobbie on 6/16/17.
 */
public class TestCreateUser extends TestCase {
    @Test
    public void testBootstrap () throws Exception {
        String usersFilename = "data/users.json";
        setupMiranda();
        createKeyStore(TEMP_KEYSTORE, TEMP_KEYSTORE_PASSWORD, TEMP_ALIAS);
        BootstrapUsersFile bootstrapUsersFile = new BootstrapUsersFile(usersFilename, TEMP_KEYSTORE, TEMP_KEYSTORE_PASSWORD, TEMP_ALIAS);
        bootstrapUsersFile.createUser("admin", "the admin user");
        bootstrapUsersFile.write();
    }
}


text:
<component name="libraryTable">
  <library name="support-vector-drawable-25.3.0">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/6ccaa61977650e0fcba0016e201768cf811df3a4/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/6ccaa61977650e0fcba0016e201768cf811df3a4/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://E:/devicesdk/extras/android/m2repository/com/android/support/support-vector-drawable/25.3.0/support-vector-drawable-25.3.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
'use strict';

var assign = require('es5-ext/object/assign')
  , mano   = require('mano');

assign(exports, require('eregistrations/controller/user'));

// Translations
mano.i18nScanMap = require('../../../i18n-scan-map.generated');
exports['save-translations'] = require('eregistrations/controller/save-translations');


text:
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;

namespace NetOffice.OWC10Api
{
	/// <summary>
	/// Name
	/// </summary>
	[SyntaxBypass]
 	public class Name_ : COMObject
	{
		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public Name_(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public Name_(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        /// <param name="parentObject">object there has created the proxy</param>
        /// <param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		/// <param name="parentObject">object there has created the proxy</param>
        /// <param name="comProxy">inner wrapped COM proxy</param>
        /// <param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		/// <param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		/// <summary>
        /// Hidden stub .ctor
        /// </summary>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name_(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get/Set
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public string Name
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "Name");
			}
			set
			{
				Factory.ExecuteValuePropertySet(this, "Name", value);
			}
		}

		#endregion

		#region Methods

		#endregion
	}

	/// <summary>
	/// DispatchInterface Name
	/// SupportByVersion OWC10, 1
	/// </summary>
	[SupportByVersion("OWC10", 1)]
	[EntityType(EntityType.IsDispatchInterface)]
 	public class Name : Name_
	{
		#pragma warning disable

		#region Type Information

		/// <summary>
		/// Instance Type
		/// </summary>
		[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
		public override Type InstanceType
		{
			get
			{
				return LateBindingApiWrapperType;
			}
		}

        private static Type _type;

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public static Type LateBindingApiWrapperType
        {
            get
            {
                if (null == _type)
                    _type = typeof(Name);
                return _type;
            }
        }

        #endregion

		#region Ctor

		/// <param name="factory">current used factory core</param>
		/// <param name="parentObject">object there has created the proxy</param>
		/// <param name="proxyShare">proxy share instead if com proxy</param>
		public Name(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
		public Name(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
		{

		}

        ///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
		{
		}

		///<param name="factory">current used factory core</param>
		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
		{

		}

		///<param name="parentObject">object there has created the proxy</param>
        ///<param name="comProxy">inner wrapped COM proxy</param>
        ///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
		{
		}

		///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name(ICOMObject replacedObject) : base(replacedObject)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name() : base()
		{
		}

		/// <param name="progId">registered progID</param>
		[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
		public Name(string progId) : base(progId)
		{
		}

		#endregion

		#region Properties

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		[BaseResult]
		public NetOffice.OWC10Api.ISpreadsheet Application
		{
			get
			{
				return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OWC10Api.ISpreadsheet>(this, "Application");
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public Int32 Index
		{
			get
			{
				return Factory.ExecuteInt32PropertyGet(this, "Index");
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get
		/// Unknown COM Proxy
		/// </summary>
		[SupportByVersion("OWC10", 1), ProxyResult]
		public object Parent
		{
			get
			{
				return Factory.ExecuteReferencePropertyGet(this, "Parent");
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get/Set
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public object RefersTo
		{
			get
			{
				return Factory.ExecuteVariantPropertyGet(this, "RefersTo");
			}
			set
			{
				Factory.ExecuteVariantPropertySet(this, "RefersTo", value);
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get/Set
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public object RefersToLocal
		{
			get
			{
				return Factory.ExecuteVariantPropertyGet(this, "RefersToLocal");
			}
			set
			{
				Factory.ExecuteVariantPropertySet(this, "RefersToLocal", value);
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		[BaseResult]
		public NetOffice.OWC10Api._Range RefersToRange
		{
			get
			{
				return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OWC10Api._Range>(this, "RefersToRange");
			}
		}

		/// <summary>
		/// SupportByVersion OWC10 1
		/// Get
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public string Value
		{
			get
			{
				return Factory.ExecuteStringPropertyGet(this, "Value");
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// SupportByVersion OWC10 1
		/// </summary>
		[SupportByVersion("OWC10", 1)]
		public void Delete()
		{
			 Factory.ExecuteMethod(this, "Delete");
		}

		#endregion

		#pragma warning restore
	}
}


text:
* Updated to Xcode 8.0 and Swift 3.0. Please update your book and get the  latest source code from GitHub.

### 03/24/2016
* Project settings now specify "Requires full screen"
* Updated gravity settings in switchToRunning() function of GameScene
* Updated fly() function in Player


text:
#include "view.hpp"
#include "plotter.hpp"
#include "handler.hpp"
#include <pangolin/plot/plotter.h>

namespace py_pangolin {

  template<typename P>
  void bind_range(pybind11::module& m, const char* python_name_postfix)
  {
      pybind11::class_<pangolin::Range<P>>(m, (std::string("Range") + python_name_postfix).c_str() )
          .def_readwrite("min", &pangolin::Range<P>::min)
          .def_readwrite("max", &pangolin::Range<P>::max);

      pybind11::class_<pangolin::XYRange<P>>(m, (std::string("XYRange") + python_name_postfix).c_str() )
          .def_readwrite("x", &pangolin::XYRange<P>::x)
          .def_readwrite("y", &pangolin::XYRange<P>::y);
  }

  void bind_plotter(pybind11::module& m){
  //   pybind11::class_<pangolin::Handler, PyHandler> handler1(m, "Handler1");
  //   handler1
  //     .def(pybind11::init<>())
  //     .def("Keyboard", &pangolin::Handler::Keyboard)
  //     .def("Mouse", &pangolin::Handler::Mouse)
  //     .def("MouseMotion", &pangolin::Handler::MouseMotion)
  //     .def("PassiveMouseMotion", &pangolin::Handler::PassiveMouseMotion)
  //     .def("Special", &pangolin::Handler::Special);

    bind_range<float>(m, "f");

    pybind11::enum_<pangolin::DrawingMode>(m, "DrawingMode")
      .value("DrawingModePoints", pangolin::DrawingMode::DrawingModePoints)
      .value("DrawingModeDashed", pangolin::DrawingMode::DrawingModeDashed)
      .value("DrawingModeLine", pangolin::DrawingMode::DrawingModeLine)
      .value("DrawingModeNone", pangolin::DrawingMode::DrawingModeNone)
      .export_values();

    pybind11::class_<pangolin::Marker> marker(m, "Marker");

    pybind11::enum_<pangolin::Marker::Direction>(marker, "Direction")
      .value("Horizontal", pangolin::Marker::Direction::Horizontal)
      .value("Vertical", pangolin::Marker::Direction::Vertical)
      .export_values();

    pybind11::enum_<pangolin::Marker::Equality>(marker, "Equality")
      .value("LessThan", pangolin::Marker::Equality::LessThan)
      .value("Equal", pangolin::Marker::Equality::Equal)
      .value("GreaterThan", pangolin::Marker::Equality::GreaterThan)
      .export_values();

    marker.def(pybind11::init<pangolin::Marker::Direction, float, pangolin::Marker::Equality, pangolin::Colour>(), pybind11::arg("d"), pybind11::arg("value"), pybind11::arg("leg") = pangolin::Marker::Equality::Equal, pybind11::arg("c")=pangolin::Colour())
      .def(pybind11::init<const pangolin::XYRangef&, const pangolin::Colour&>(), pybind11::arg("range"), pybind11::arg("c")=pangolin::Colour())
      .def_readwrite("range", &pangolin::Marker::range)
      .def_readwrite("colour", &pangolin::Marker::colour);

    pybind11::class_<pangolin::Plotter,pangolin::View>(m, "Plotter")
      .def(pybind11::init<pangolin::DataLog*, float, float, float, float, float, float, pangolin::Plotter*, pangolin::Plotter*>(),
           pybind11::arg("default_log"),
           pybind11::arg("left")=0,
           pybind11::arg("right")=600,
           pybind11::arg("bottom")=-1,
           pybind11::arg("top")=1,
           pybind11::arg("tickx")=30,
           pybind11::arg("ticky")=0.5,
           pybind11::arg("linked_plotter_x")=NULL,
           pybind11::arg("linked_plotter_y")=NULL)
      .def(pybind11::init([](pangolin::DataLog* log, float left, float right, float bottom, float top, float tickx, float ticky){return new pangolin::Plotter(log, left, right, bottom, top,tickx, ticky);}),
           pybind11::arg("default_log"),
           pybind11::arg("left")=0,
           pybind11::arg("right")=600,
           pybind11::arg("bottom")=-1,
           pybind11::arg("top")=1,
           pybind11::arg("tickx")=30,
           pybind11::arg("ticky")=0.5)

      .def("Render", &pangolin::Plotter::Render)
      .def("GetSelection", &pangolin::Plotter::GetSelection)
      .def("GetDefaultView", &pangolin::Plotter::GetDefaultView)
      .def("SetDefaultView", &pangolin::Plotter::SetDefaultView)
      .def("GetView", &pangolin::Plotter::GetView)
      .def("SetView", &pangolin::Plotter::SetView)
      .def("SetViewSmooth", &pangolin::Plotter::SetViewSmooth)
      .def("ScrollView", &pangolin::Plotter::ScrollView)
      .def("ScrollViewSmooth", &pangolin::Plotter::ScrollViewSmooth)
      .def("ScaleView", &pangolin::Plotter::ScaleView)
      .def("ScaleViewSmooth", &pangolin::Plotter::ScaleViewSmooth)
      .def("SetTicks", &pangolin::Plotter::SetTicks)
      .def("Track", &pangolin::Plotter::Track, pybind11::arg("x")="$i", pybind11::arg("y")="")
      .def("ToggleTracking", &pangolin::Plotter::ToggleTracking)
      .def("Trigger", &pangolin::Plotter::Trigger, pybind11::arg("x")="$0", pybind11::arg("edge")=-1, pybind11::arg("value")=0.0f)
      .def("ToggleTrigger", &pangolin::Plotter::ToggleTrigger)
      .def("SetBackgroundColour", &pangolin::Plotter::SetBackgroundColour)
      .def("SetAxisColour", &pangolin::Plotter::SetAxisColour)
      .def("SetTickColour", &pangolin::Plotter::SetTickColour)
      .def("Keyboard", &pangolin::Plotter::Keyboard)
      .def("Mouse", &pangolin::Plotter::Mouse)
      .def("MouseMotion", &pangolin::Plotter::MouseMotion)
      .def("PassiveMouseMotion", &pangolin::Plotter::PassiveMouseMotion)
      .def("Special", &pangolin::Plotter::Special)
      .def("ClearSeries", &pangolin::Plotter::ClearSeries)
      .def("AddSeries", &pangolin::Plotter::AddSeries)
      .def("PlotTitleFromExpr", &pangolin::Plotter::PlotTitleFromExpr)
      .def("ClearMarkers", &pangolin::Plotter::ClearMarkers)
      .def("AddMarker", (pangolin::Marker& (pangolin::Plotter::*)(pangolin::Marker::Direction, float, pangolin::Marker::Equality, pangolin::Colour))&pangolin::Plotter::AddMarker, pybind11::arg("d"), pybind11::arg("value"), pybind11::arg("leg") = pangolin::Marker::Equality::Equal, pybind11::arg("c")=pangolin::Colour())
      .def("AddMarker", (pangolin::Marker& (pangolin::Plotter::*)(const pangolin::Marker&))&pangolin::Plotter::AddMarker)
    //      .def("ClearImplicitPlots", &pangolin::Plotter::ClearImplicitPlots);
      //   .def("AddImplicitPlot", &pangolin::Plotter::AddImplicitPlot);
      .def("SetBounds", (pangolin::View& (pangolin::Plotter::*)(pangolin::Attach, pangolin::Attach, pangolin::Attach, pangolin::Attach))&pangolin::Plotter::SetBounds)
      .def("SetBounds", (pangolin::View& (pangolin::Plotter::*)(pangolin::Attach, pangolin::Attach, pangolin::Attach, pangolin::Attach, bool))&pangolin::Plotter::SetBounds)
      .def("SetBounds", (pangolin::View& (pangolin::Plotter::*)(pangolin::Attach, pangolin::Attach, pangolin::Attach, pangolin::Attach, double))&pangolin::Plotter::SetBounds);

  }

}  // py_pangolin


text:
<?xml version="1.0" encoding="utf-8"?><!--
   Copyright (C) 2013 Lucas Rocha

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<resources xmlns:tools="http://schemas.android.com/tools">

    <declare-styleable name="twowayview_TwoWayLayoutManager">
        <attr name="android:orientation" tools:ignore="ResourceName" />
    </declare-styleable>

</resources>


text:
FROM klakegg/hugo:0.101.0-ext-alpine as docsy-user-guide

RUN apk update
RUN apk add git
COPY package.json /app/docsy/userguide/
WORKDIR /app/docsy/userguide/
RUN npm install --production=false
RUN git config --global --add safe.directory /app/docsy

CMD ["serve", "--cleanDestinationDir", "--themesDir", "../..", "--baseURL",  "http://localhost:1313/", "--buildDrafts", "--buildFuture", "--disableFastRender", "--ignoreCache", "--watch"]


text:
(function(){
var t = setInterval(function(){
[].forEach.call(document.querySelectorAll('#YaDirectLine,#rb-direct-left-slot,#AdLeftInformer,.b-slot_left_banner'),function(el) {
el.remove();});
},400);
})();


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif

[System.Serializable]
public class UIChatSprites : MonoBehaviour
{
    [SerializeField]
    public List<Sprite> AllsSprites;

    public Dictionary<string, Sprite> font;

    void Awake()
    {
        Init();

    }

    // Use this for initialization
    void Start()
    {
        Init();
    }

    public void Init()
    {
        if (font != null)
        {
            return;
        }
        font = new Dictionary<string, Sprite>();
        for (int i = 0; i < AllsSprites.Count; i++)
        {
            if (!font.ContainsKey(AllsSprites[i].name))
            {
                font.Add(AllsSprites[i].name, AllsSprites[i]);
            }
        }
    }

    public Sprite GetSprite(string key)
    {
        Init();
        Sprite sprite = null;
        if (font != null)
        {
            font.TryGetValue(key, out sprite);
        }
        return sprite;
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(UIChatSprites))]
public class UIChatSpritesEditor : Editor
{
    public UIChatSprites obj;
    public override void OnInspectorGUI()
    {
        obj = target as UIChatSprites;
        base.OnInspectorGUI();
        GUILayout.Label("使用说明");
        GUILayout.Label("1.拖放全部的Sprite到Sprites");
        GUILayout.Label("2.点击自动填充Key");
        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("自动填充Key"))
        {
            obj.Init();
        }
        if (GUILayout.Button("清空所有Key"))
        {
            obj.font.Clear();
        }

        EditorGUILayout.EndHorizontal();
    }
}
#endif


text:
'use strict';

const models = require('./index');

/**
 * The condition that results in the alert rule being activated.
 *
 */
class RuleCondition {
  /**
   * Create a RuleCondition.
   * @member {object} [dataSource] the resource from which the rule collects
   * its data. For this type dataSource will always be of type
   * RuleMetricDataSource.
   * @member {string} [dataSource.resourceUri] the resource identifier of the
   * resource the rule monitors. **NOTE**: this property cannot be updated for
   * an existing rule.
   * @member {string} [dataSource.odatatype] Polymorphic Discriminator
   * @member {string} odatatype Polymorphic Discriminator
   */
  constructor() {
  }

  /**
   * Defines the metadata of RuleCondition
   *
   * @returns {object} metadata of RuleCondition
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'RuleCondition',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: 'odata.type',
          clientName: 'odatatype'
        },
        uberParent: 'RuleCondition',
        className: 'RuleCondition',
        modelProperties: {
          dataSource: {
            required: false,
            serializedName: 'dataSource',
            type: {
              name: 'Composite',
              polymorphicDiscriminator: {
                serializedName: 'odata.type',
                clientName: 'odatatype'
              },
              uberParent: 'RuleDataSource',
              className: 'RuleDataSource'
            }
          },
          odatatype: {
            required: true,
            serializedName: 'odata\\.type',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = RuleCondition;


text:
import Vue from 'vue'
import VueRouter from 'vue-router'
import TodoList from './TodoList.vue'
Vue.use(VueRouter);

const App = {
	template: `

		<form>
			<input class="todo-input" type="text" placeholder="please enter your todos..." autofocus autocomplete="off"
			@keydown.enter.prevent="addTodo"
			v-model="todo" />
		</form>

			All
			Active
			Completed

		<todo-list :filter="filter" :todos="todos"></todo-list>

`,
	components: {
		TodoList
	},
	data () {
		return {
			todos: [{
				content: 'eat breakfast',
				complete: false
			}, {
				content: 'go to school',
				complete: false
			}, {
				content: 'take a rest',
				complete: false
			}],
			todo: '',
			filter: 'ALL'
		}
	},
	computed: {
		validateTodo () {
			return this.todo.trim();
		}
	},
	methods: {
		addTodo () {
			if (this.validateTodo) {
				this.todos.push({content: this.validateTodo, complete: false});
				this.todo = '';
			}
		}
	}
}

const routes = [{
	path: '/', component: App
}]

const router = new VueRouter({
	mode: 'history',
	base: __dirname,
	routes
})

const vm = new Vue({
	router,
	el: '#app'
});


text:
package ch21concurrency;

import java.util.concurrent.locks.*;

/**
 * Using explicit Lock objects to create critical sections.
 *
 * <pre>
 * Output: (Sample)
 * pm1: Pair: x: 15, y: 15 checkCounter = 174035
 * pm2: Pair: x: 16, y: 16 checkCounter = 2608588
 * </pre>
 *
 * 线程在进行ExplicitPairManager2中的increment()方法时,并不会影响PairManager中的另一个synchronized方法getPair()获得锁,因此,getPair().checkState()方法可能读取到共享资源p.x和p.y非同步状态的值。
 */
// Synchronize the entire method:
class ExplicitPairManager1 extends PairManager {
	private Lock lock = new ReentrantLock();

	public synchronized void increment() {
		lock.lock();
		try {
			p.incrementX();
			p.incrementY();
			store(getPair());
		} finally {
			lock.unlock();
		}
	}
}

// Use a critical section:
class ExplicitPairManager2 extends PairManager {
	private Lock lock = new ReentrantLock();

	public void increment() {
		Pair temp;
		lock.lock();
		try {
			p.incrementX();
			p.incrementY();
			temp = getPair();
		} finally {
			lock.unlock();
		}
		store(temp);
	}
}

public class D36_ExplicitCriticalSection {
	public static void main(String[] args) throws Exception {
		PairManager pman1 = new ExplicitPairManager1(), pman2 = new ExplicitPairManager2();
		D35_CriticalSection.testApproaches(pman1, pman2);
	}
}


text:
'use strict';

const browsers = [
  'last 2 Chrome versions',
  'last 2 Firefox versions',
  'last 2 Safari versions'
];

module.exports = {
  browsers
};


text:
var st = [
    { //JACE BEGINS
        "q": '"Muslim" is a single ethnic group.',
        "a": 'UK Media has been representing "Muslim" as a single ethnic group, however it is a religion with members from diverse background',
        'correct': 0
    },
    {
        "q": "Muslims are potential Terrorists",
        'a': "United States media has portrayed "Muslims" as the potential terrorists, instead of being factual and neutral about the 9/11 incident. In turn encouraging stereotype towards the specific social group.",
        'correct': 0
    },
    {
        "q":"About 80 percent of Americans disapprove Muslims",
        'a':"American Media FOX, stated ⅘ Americans disapprove Muslim, the Pew Global Attitude Project conducted independent research and survey about the public opinion towards Muslims. from 2004 and 2008, there was rise in disapproval rate from (48% to 56%), but no where close to 80% like the media Fox Suggested.",
        'correct': 0
    },
    {
        "q": "There are diversity in Muslim and certain group of Muslims should be blamed for the terrorism incidence (i.e. 9/11)",
        'a': "Majority blames the whole religion of Islam as the cause of destruction and violence, although the truth is terrorist groups are extreme radicals",
        'correct': 1
    },
    {
        "q": "Muslim groups encounters danger due to hatred expressed through threat and violence",
        'a': "Anti-Muslim act as well as crimes that shows hate towards Muslims group has increased drastically. For example, in the anniversary of 9/11, Americans publicly  burned copies of Quran. The stereotype is that we perceive "Muslims" as threat, but the threat and anxiety can be mutually shared emotion.",
        'correct': 1
    },
    {
        "q": " More than half of the Americans believe there should be discrimination against Muslims",
        'a': "58% of Americans favored a requirement that Arabs have more strict inspection at the airport. In addition, more barriers for Muslims entering the country. This influence more social division and discrimination. ",
        'correct': 1
    },
    { //SOHINI BEGINS
        "q": "For crimes such as rape, murder, manslaughter, drunkenness, liquor laws, sex offences, weapons holding, are Mexicans accountable for the larger percentage?",
        "a": "In comparison to their population and taking in account of their involvement in crimes. Mexicans constitute of a much lower portion than the whopping 7 million by the Caucasian population while Mexicans only consisted of a 3 million. Cuts down more than half the of the impact caused by the Caucasian community according to the FBI crime report in 2013 of the United States",
        "correct": 0
    },
    {
        "q": "Is it true the Mexicans immigrants/Hispanics who are looking for employment in US are the reason for the wage decline in the United States. Or the reason for the lack of job opportunities present?",
        "a": "Mexican immigrants are more likely to get and or focus on menial jobs such as janitorial, home care, or cleaning jobs because of their lack of expertise for salary jobs. The only reason for the decrease in wage is due of the exploitation of workers by their business employers. Making immigration and citizenship easier would enable Mexicans and the Hispanic community to force these employers into inclination of wages discovered by the Service Employees International Union. Also not all Hispanics are immigrants. They could be born in the soil of the nation as well.",
        "correct": 0
    },
    {
        "q": " Is it true that in major illicit drug abuse cases it is shown to be predominantly Mexicans?",
        "a": "This is a manifestation of the media to focus on the worst aspects of all other races in a way to prove their superiority. This however, is proven wrong when the actual evidence is put forward. The highest amount of cases in drug abuse are concerned with the population that is not Hispanic or Latino.",
        "correct": 1
    },
    {
        "q": "By demographic, Marijuana abuse and usage is shown to be more dominant in Hispanic community than in any others?",
        "a": "Even though the media portrays a huge amount of Hispanics in illicit drug abuse. It doesn't so much as focus on Marijuana. Although according to the news report by CNN increase and spread in abusive marijuana use or 'pot' is shown to be predominantly by Caucasian Americans",
        "correct": 0
    },
    {
        "q":  "Hispanics or Latinos can't hold down jobs unless they are the daily wage type.",
        "a":  "Focusing on them being "unable" to hold down jobs other than the minimum wage ones. Not true. Why is it not true. This issue focuses on the often believed stereotype that Hispanics cannot hold down high paying jobs and are therefore "stuck" with jobs that are "more suited" to their abilities. The people of the Hispanic community are known to be extraordinary entrepreneurs and are targeted as the future of the business world.",
        "correct": 0
    },
    { // Kayla Begins
      "q": "Black people commit the most amount of overall crime in the U.S.",
      "a": "According to the statistics, white people commit more overall crime than black people in the U.S. White people commit 68.9% of total crimes, while black people commit 28.3%. This suggests that the stereotype, "black people are violent and commit a significant amount of crime", is not true.",
      "correct": 0
    },
    {
      "q": "Black people in Canada are less likely to be unemployed than the rest of the population.",
      "a": "People in the African community in Canada are slightly less likely to be employed than the rest of the population. In 2001, 60% of all African people aged 15 and over were employed, compared with 62% of those in this age range in the overall Canadian population.",
      "correct": 1
    },
    {
      "q": "Black people in Canada are significantly less likely than the rest of the population to be university graduates.",
      "a": "Black people in Canada are more likely than the rest of the population to be university graduates. Those in the African community in Canada are somewhat more likely than the rest of the population to be university graduates. In 2001, 19% of African people aged 15 and over were university graduates, compared with 15% of those in the overall adult population.",
      "correct": 0
    },
    {
      "q": "Black people in the U.S. are usually unemployed due to the fact that they are uneducated or unqualified.",
      "a": "Black people in the U.S. are usually unemployed due to prejudices against them by employers. In one study, employers were far more likely to view African American workers in a negative light, describing them as 'having an attitude', i.e. the 'wrong' attitude towards work.",
      "correct": 0
    },
    {
      "q": "Black people in the U.S. commit crime due to unemployment, economic deprivation, and family disruption.",
      "a": "One study states that black violence is linked to unemployment, economic deprivation and family disruption but not to Black culture. Another study examined reciprocal effects between violent crime and racial composition and concluded that the association between them is due, in part, to the strong effect of violent crime on racial composition.",
      "correct": 1
    },
    {
      "q": "Black people commit 68.9% of crime in the U.S., whereas white people only commit 28.3% of crime in the U.S.",
      "a": "It is the opposite, white people commit 68.9% of crime in the U.S., whereas black people only commit 28.3% of crime in the U.S.",
      "correct": 0
    },
    {
      "q": "Black people do not commit crime simply because 'it is part of their culture'",
      "a": "Black violence is linked to unemployment, economic deprivation and family disruption, but not to Black culture.",
      "correct": 1
    },
    {
      "q": "Black people in the U.S. do not face any prejudices against them by employers. ",
      "a": "Black people in the U.S. face a lot of prejudice against them by employers. The data from Los Angeles document that employers systematically differentiate between African American and Latino immigrant candidates on the basis of race, nativity and gender.",
      "correct": 0
    }
    ];


text:
package mil.nga.giat.geowave.core.store.config;

public class ConfigOption
{
	private final String name;
	private final String description;
	private final boolean optional;
	private boolean password;
	private Class type;

	public ConfigOption(
			final String name,
			final String description,
			final boolean optional,
			final Class type ) {
		this.name = name;
		this.description = description;
		this.optional = optional;
		this.type = type;
	}

	public Class getType() {
		return type;
	}

	public void setType(
			Class type ) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public String getDescription() {
		return description;
	}

	public boolean isOptional() {
		return optional;
	}

	public boolean isPassword() {
		return password;
	}

	public void setPassword(
			boolean password ) {
		this.password = password;
	}
}


text:
<?php

namespace Drupal\Tests\file\Kernel;

/**
 * Tests the file url.
 *
 * @group file
 */
class FileUrlTest extends FileManagedUnitTestBase {

  /**
   * Test public files with a different host name from settings.
   */
  public function testFilesUrlWithDifferentHostName() {
    $test_base_url = 'http://www.example.com/cdn';
    $this->setSetting('file_public_base_url', $test_base_url);
    $filepath = file_create_filename('test.txt', '');
    $directory_uri = 'public://' . dirname($filepath);
    file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
    $file = $this->createFile($filepath, NULL, 'public');
    $url = file_create_url($file->getFileUri());
    $expected_url = $test_base_url . '/' . basename($filepath);
    $this->assertSame($url, $expected_url);
  }

}


text:
/**
 * @fileoverview
This module provides generic logging support for Ringo
 * applications. It uses SLF4J or
 * Apache log4j if either is
 * detected in the classpath, and will fall back to java.util.logging
 * otherwise.

 *
 *
If the first argument passed to any of the logging methods is a string
 * containing any number of curly bracket pairs ({}), the logger will interpret
 * it as format string and use any following arguments to replace the curly
 * bracket pairs. If an argument is an Error or Java Exception object, the
 * logger will render a stack trace for it and append it to the log message.

 *
 *
This module's exports object implements the [EventEmitter](../events/)
 * interface and emits logged messages using the log level name as event type.

 */

var strings = require('ringo/utils/strings');
var {EventEmitter} = require('ringo/events');

export('getLogger', 'setConfig', 'getScriptStack', 'getJavaStack');

// Use singleton to share flag across workers to avoid unwanted reconfiguration
var configured = module.singleton("configured");
// interval id for configuration watcher
var configWatcher;

var verbose = require('ringo/engine').getRhinoEngine().getConfig().isVerbose();

// Make exports object emit log events
EventEmitter.call(exports);

/**
 * Logger class. This constructor is not exported, use this module's
 * {@link getLogger} to get a logger instance.
 * @param name the Logger name
 * @param impl the logger implementation
 * @constructor
 * @name Logger
 * @see #getLogger()
 */
function Logger(name, impl) {

    this.trace = function() {
        if (impl.isTraceEnabled()) {
            var msg = formatMessage(arguments);
            impl.trace(msg);
            exports.emit("trace", name, msg);
        }
    };

    this.debug = function() {
        if (impl.isDebugEnabled()) {
            var msg = formatMessage(arguments);
            impl.debug(msg);
            exports.emit("debug", name, msg);
        }
    };

    this.info = function() {
        if (impl.isInfoEnabled()) {
            var msg = formatMessage(arguments);
            impl.info(msg);
            exports.emit("info", name, msg);
        }
    };

    this.warn = function() {
        if (impl.isWarnEnabled()) {
            var msg = formatMessage(arguments);
            impl.warn(msg);
            exports.emit("warn", name, msg);
        }
    };

    this.error = function() {
        if (impl.isErrorEnabled()) {
            var msg = formatMessage(arguments);
            impl.error(msg);
            exports.emit("error", name, msg);
        }
    };

    /**
     * @function
     */
    this.isTraceEnabled = impl.isTraceEnabled.bind(impl);

    /**
     * @function
     */
    this.isDebugEnabled = impl.isDebugEnabled.bind(impl);

    /**
     * @function
     */
    this.isInfoEnabled = impl.isInfoEnabled.bind(impl);

    /**
     * @function
     */
    this.isWarnEnabled = impl.isWarnEnabled.bind(impl);

    /**
     * @function
     */
    this.isErrorEnabled = impl.isErrorEnabled.bind(impl);
}

/**
 * Configure log4j using the given file resource.
 *
 * If you plan to update the configuration make sure to set the
 * reset property to true in your configuration file.
 *
 * @param {Resource} resource the configuration resource in XML or properties format
 * @param {Boolean} watchForUpdates if true a scheduler thread is started that
 * repeatedly checks the resource for updates.
 */
function setConfig(resource, watchForUpdates) {
    var {path, url} = resource;
    var PropertyConfigurator = org.apache.log4j.PropertyConfigurator;
    var DOMConfigurator = org.apache.log4j.xml.DOMConfigurator;
    var configurator = strings.endsWith(path, '.properties') || strings.endsWith(path, '.props') ?
                       PropertyConfigurator : DOMConfigurator;
    if (typeof configurator.configure === "function") {
        configurator.configure(url);
        if (watchForUpdates) {
            try {
                // set up a scheduler to watch the configuration file for changes
                var lastModified = resource.lastModified();
                if (configWatcher) {
                    clearInterval(configWatcher);
                }
                configWatcher = setInterval(function() {
                    if (resource.exists() && resource.lastModified() != lastModified) {
                        lastModified = resource.lastModified();
                        configurator.configure(url);
                    }
                }, 3000);
            } catch (e) {
                print("Error watching log configuration file:", e);
            }
        }
    }
    configured = module.singleton("configured", function() true);
}

/**
 * Get a logger for the given name.
 * @param {string} name the name of the logger
 * @returns {Logger} a logger instance for the given name
 */
function getLogger(name) {
    name = name.replace(/\//g, '.');
    var impl = new LoggerImpl(name);
    return new Logger(name, impl);
}

function formatMessage(args) {
    var message = strings.format.apply(null, args);
    for each (var arg in args) {
        if (arg instanceof Error || arg instanceof java.lang.Throwable) {
            message  = [
                message,
                getScriptStack(arg, "\nScript stack:\n"),
                verbose ? getJavaStack(arg, "Java stack:\n") : null
            ].join('');
        }
    }
    return message;
}

/**
 * Get a rendered JavaScript stack trace from a caught error.
 * @param {Error} error an error object
 * @param {String} prefix to prepend to result if available
 * @return {String} the rendered JavaScript stack trace
 */
function getScriptStack(error, prefix) {
    prefix = prefix || "";
    if (error && error.stack)
        return prefix + error.stack;
    return "";
}

/**
 * Get a rendered JavaScript stack trace from a caught error.
 * @param {Error} error an error object
 * @param {String} prefix to prepend to result if available
 * @return {String} the rendered JavaScript stack trace
 */
function getJavaStack(error, prefix) {
    prefix = prefix || "";
    var exception = error && error.rhinoException ?
        error.rhinoException : error;
    if (exception instanceof java.lang.Throwable) {
        var writer = new java.io.StringWriter();
        var printer = new java.io.PrintWriter(writer);
        exception.printStackTrace(printer);
        return prefix + writer.toString();
    }
    return "";
}

/**
 * Logger implementation based on java.util.logging
 * @param name the logger name
 */
function JdkLogger(name) {

    var log = java.util.logging.Logger.getLogger(name);
    var Level = java.util.logging.Level;

    this.trace = function(msg) {
        log.logp(Level.FINEST, null, null, msg);
    };

    this.debug = function(msg) {
        log.logp(Level.FINE, null, null, msg);
    };

    this.info = function(msg) {
        log.logp(Level.INFO, null, null, msg);
    };

    this.warn = function(msg) {
        log.logp(Level.WARNING, null, null, msg);
    };

    this.error = function(msg) {
        log.logp(Level.SEVERE, null, null, msg);
    };

    this.isTraceEnabled = function() {
        return log.isLoggable(Level.FINEST);
    };

    this.isDebugEnabled = function() {
        return log.isLoggable(Level.FINE);
    };

    this.isInfoEnabled = function() {
        return log.isLoggable(Level.INFO);
    };

    this.isWarnEnabled = function() {
        return log.isLoggable(Level.WARNING);
    };

    this.isErrorEnabled = function() {
        return log.isLoggable(Level.SEVERE);
    };
}

/**
 * Logger implementation based on log4j
 * @param name the logger name
 */
function Log4jLogger(name) {

    if (!configured) {
        setConfig(getResource('config/log4j.properties'));
        configured = module.singleton("configured", function() true);
    }
    var Level = org.apache.log4j.Level;
    var log = org.apache.log4j.LogManager.getLogger(name);

    this.trace = function(msg) {
        // TODO: older versions of log4j don't support trace
        log.trace(msg);
    };

    this.debug = function(msg) {
        log.debug(msg);
    };

    this.info = function(msg) {
        log.info(msg);
    };

    this.warn = function(msg) {
        log.warn(msg);
    };

    this.error = function(msg) {
        log.error(msg);
    };

    this.isTraceEnabled = function() {
        return log.isTraceEnabled();
    };

    this.isDebugEnabled = function() {
        return log.isDebugEnabled();
    };

    this.isInfoEnabled = function() {
        return log.isInfoEnabled();
    };

    this.isWarnEnabled = function() {
        return log.isEnabledFor(Level.WARN);
    };

    this.isErrorEnabled = function() {
        return log.isEnabledFor(Level.ERROR);
    };
}

/**
 * Logger implementation based on SLF4J
 * @param name the logger name
 */
function Slf4jLogger(name) {

    if (!configured) {
        setConfig(getResource('config/log4j.properties'));
        configured = module.singleton("configured", function() true);
    }
    var log = org.slf4j.LoggerFactory.getLogger(name);

    this.trace = function(msg) {
        log.trace(msg);
    };

    this.debug = function(msg) {
        log.debug(msg);
    };

    this.info = function(msg) {
        log.info(msg);
    };

    this.warn = function(msg) {
        log.warn(msg);
    };

    this.error = function(msg) {
        log.error(msg);
    };

    this.isTraceEnabled = function() {
        return log.isTraceEnabled();
    };

    this.isDebugEnabled = function() {
        return log.isDebugEnabled();
    };

    this.isInfoEnabled = function() {
        return log.isInfoEnabled();
    };

    this.isWarnEnabled = function() {
        return log.isWarnEnabled();
    };

    this.isErrorEnabled = function() {
        return log.isErrorEnabled();
    };
}

var LoggerImpl;
if (typeof org.slf4j.LoggerFactory.getLogger === "function") {
    LoggerImpl = Slf4jLogger;
} else if (typeof org.apache.log4j.LogManager.getLogger === "function") {
    LoggerImpl = Log4jLogger;
} else {
    LoggerImpl = JdkLogger;
}


text:
package project

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	kapi "k8s.io/kubernetes/pkg/api"
)

// ProjectList is a list of Project objects.
type ProjectList struct {
	metav1.TypeMeta
	metav1.ListMeta
	Items []Project
}

const (
	// These are internal finalizer values to Origin
	FinalizerOrigin kapi.FinalizerName = "openshift.io/origin"
)

// ProjectSpec describes the attributes on a Project
type ProjectSpec struct {
	// Finalizers is an opaque list of values that must be empty to permanently remove object from storage
	Finalizers []kapi.FinalizerName
}

// ProjectStatus is information about the current status of a Project
type ProjectStatus struct {
	Phase kapi.NamespacePhase
}

// +genclient
// +genclient:nonNamespaced

// Project is a logical top-level container for a set of origin resources
type Project struct {
	metav1.TypeMeta
	metav1.ObjectMeta

	Spec   ProjectSpec
	Status ProjectStatus
}

type ProjectRequest struct {
	metav1.TypeMeta
	metav1.ObjectMeta
	DisplayName string
	Description string
}

// These constants represent annotations keys affixed to projects
const (
	// ProjectNodeSelector is an annotation that holds the node selector;
	// the node selector annotation determines which nodes will have pods from this project scheduled to them
	ProjectNodeSelector = "openshift.io/node-selector"
	// ProjectRequester is the username that requested a given project.  Its not guaranteed to be present,
	// but it is set by the default project template.
	ProjectRequester = "openshift.io/requester"
)


text:
import * as moment from 'moment'
import * as $ from 'jquery'
import { viewHash } from './ViewRegistry'
import { mergeProps, unitsDesc, computeDurationGreatestUnit } from './util'
import { mergeOptions, globalDefaults } from './options'
import { populateInstanceComputableOptions } from './locale'

export default class ViewSpecManager {

  _calendar: any // avoid
  optionsManager: any
  viewSpecCache: any // cache of view definitions (initialized in Calendar.js)

  constructor(optionsManager, _calendar) {
    this.optionsManager = optionsManager
    this._calendar = _calendar

    this.clearCache()
  }

  clearCache() {
    this.viewSpecCache = {}
  }

  // Gets information about how to create a view. Will use a cache.
  getViewSpec(viewType) {
    let cache = this.viewSpecCache

    return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType))
  }

  // Given a duration singular unit, like "week" or "day", finds a matching view spec.
  // Preference is given to views that have corresponding buttons.
  getUnitViewSpec(unit) {
    let viewTypes
    let i
    let spec

    if ($.inArray(unit, unitsDesc) !== -1) {

      // put views that have buttons first. there will be duplicates, but oh well
      viewTypes = this._calendar.header.getViewsWithButtons() // TODO: include footer as well?
      $.each(viewHash, function(viewType) { // all views
        viewTypes.push(viewType)
      })

      for (i = 0; i < viewTypes.length; i++) {
        spec = this.getViewSpec(viewTypes[i])
        if (spec) {
          if (spec.singleUnit === unit) {
            return spec
          }
        }
      }
    }
  }

  // Builds an object with information on how to create a given view
  buildViewSpec(requestedViewType) {
    let viewOverrides = this.optionsManager.overrides.views || {}
    let specChain = [] // for the view. lowest to highest priority
    let defaultsChain = [] // for the view. lowest to highest priority
    let overridesChain = [] // for the view. lowest to highest priority
    let viewType = requestedViewType
    let spec // for the view
    let overrides // for the view
    let durationInput
    let duration
    let unit

    // iterate from the specific view definition to a more general one until we hit an actual View class
    while (viewType) {
      spec = viewHash[viewType]
      overrides = viewOverrides[viewType]
      viewType = null // clear. might repopulate for another iteration

      if (typeof spec === 'function') { // TODO: deprecate
        spec = { 'class': spec }
      }

      if (spec) {
        specChain.unshift(spec)
        defaultsChain.unshift(spec.defaults || {})
        durationInput = durationInput || spec.duration
        viewType = viewType || spec.type
      }

      if (overrides) {
        overridesChain.unshift(overrides) // view-specific option hashes have options at zero-level
        durationInput = durationInput || overrides.duration
        viewType = viewType || overrides.type
      }
    }

    spec = mergeProps(specChain)
    spec.type = requestedViewType
    if (!spec['class']) {
      return false
    }

    // fall back to top-level `duration` option
    durationInput = durationInput ||
      this.optionsManager.dynamicOverrides.duration ||
      this.optionsManager.overrides.duration

    if (durationInput) {
      duration = moment.duration(durationInput)

      if (duration.valueOf()) { // valid?

        unit = computeDurationGreatestUnit(duration, durationInput)

        spec.duration = duration
        spec.durationUnit = unit

        // view is a single-unit duration, like "week" or "day"
        // incorporate options for this. lowest priority
        if (duration.as(unit) === 1) {
          spec.singleUnit = unit
          overridesChain.unshift(viewOverrides[unit] || {})
        }
      }
    }

    spec.defaults = mergeOptions(defaultsChain)
    spec.overrides = mergeOptions(overridesChain)

    this.buildViewSpecOptions(spec)
    this.buildViewSpecButtonText(spec, requestedViewType)

    return spec
  }

  // Builds and assigns a view spec's options object from its already-assigned defaults and overrides
  buildViewSpecOptions(spec) {
    let optionsManager = this.optionsManager

    spec.options = mergeOptions([ // lowest to highest priority
      globalDefaults,
      spec.defaults, // view's defaults (from ViewSubclass.defaults)
      optionsManager.dirDefaults,
      optionsManager.localeDefaults, // locale and dir take precedence over view's defaults!
      optionsManager.overrides, // calendar's overrides (options given to constructor)
      spec.overrides, // view's overrides (view-specific options)
      optionsManager.dynamicOverrides // dynamically set via setter. highest precedence
    ])
    populateInstanceComputableOptions(spec.options)
  }

  // Computes and assigns a view spec's buttonText-related options
  buildViewSpecButtonText(spec, requestedViewType) {
    let optionsManager = this.optionsManager

    // given an options object with a possible `buttonText` hash, lookup the buttonText for the
    // requested view, falling back to a generic unit entry like "week" or "day"
    function queryButtonText(options) {
      let buttonText = options.buttonText || {}
      return buttonText[requestedViewType] ||
        // view can decide to look up a certain key
        (spec.buttonTextKey ? buttonText[spec.buttonTextKey] : null) ||
        // a key like "month"
        (spec.singleUnit ? buttonText[spec.singleUnit] : null)
    }

    // highest to lowest priority
    spec.buttonTextOverride =
      queryButtonText(optionsManager.dynamicOverrides) ||
      queryButtonText(optionsManager.overrides) || // constructor-specified buttonText lookup hash takes precedence
      spec.overrides.buttonText // `buttonText` for view-specific options is a string

    // highest to lowest priority. mirrors buildViewSpecOptions
    spec.buttonTextDefault =
      queryButtonText(optionsManager.localeDefaults) ||
      queryButtonText(optionsManager.dirDefaults) ||
      spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
      queryButtonText(globalDefaults) ||
      (spec.duration ? this._calendar.humanizeDuration(spec.duration) : null) || // like "3 days"
      requestedViewType // fall back to given view name
  }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Ryan Ringler</title>
  <meta name="author" content="Ryan Ringler">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="canonical" href="http://ryanringler.com">
  <link href="/favicon.ico" type="image/x-icon" rel="icon">
  <link href="/favicon.ico" type="image/x-icon" rel="shortcut icon">
  <link href="/atom.xml" rel="alternate" title="Ryan Ringler" type="application/atom+xml">

  <link href="/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="/assets/bootstrap/dist/css/bootstrap-cerulean.min.css" rel="stylesheet" type="text/css">
<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Nunito:300' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<meta name="google-site-verification" content="Vmxf8lrwDyqcKr7eJ0Nn8xkfs83B7XsS171hpNNRm_0" />

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-menu">

          </button>
          Ryan Ringler

Experience

Skills

Projects

Education

              Contact me

                  email: jobs@ryanringler.com

                   github: rringler

                   linked in: rringler

            Blog

Experience

      Zendesk
      (San Francisco, CA)

2016 - Present

      Software Engineer

2016 - Present

    Improving Zendesk’s customer billing experience every day:

        Writing new (and improving old) production Ruby/Rails & Ember.js
        code (and tests)

        Improving team and project processes:

            Optimizing our continuous-integration (Travis & Jenkins)
            configurations

            Implementing Rubocop & Reek static-analysis tools

            Adding and improving instrumentation to monitor our code performance
            and alerting

          Ruby contributor!

          Proposed and wrote the initial implementation of String#casecmp?

      Shuddle, Inc.
      (San Francisco, CA)

2015 - 2016

      Software Engineer

2015 - 2016

    Lead developer for several features of Shuddle’s monolithic
    Ruby on Rails API:

        Contributed production code (and tests) daily via Ruby on Rails,
        RSpec, Postgres, Redis, Git, Github and various third-party APIs.

        Improved collective code quality by participating in code reviews on
        all Github pull requests.

        Reduced similar-record database insertion times by 95%
        (over standard ActiveRecord) by implementing a bulk-record insertion
        feature.

      Raytheon Integrated Defenese Systems
      (San Diego, CA)

2006 - 2015

      Senior Electrical Engineer II, Platform Integration
      (w/ DoD SECRET Clearance)

2010 - 2015

    Integrated Product Team Lead for the

      GPS-based Position, Navigation, and Timing Service
     program:

         Customer/company POC for all procurement, production, and sell-off
         activities for multiple Engineering Development Model deliveries
         (approx. $43M in revenue).

        Utilized

          Earned Value Management
         to analyze cost & schedule performance, to forecast program
        performance, manage risk & opportunity, and plan & maintain an
        Integrated Master Schedule.

          Eight consecutive annual performance rankings in the top quartile of
          labor grade.

      Senior Electrical Engineer I, Platform Integration

2008 - 2010

    Control Account Manager for

        Zumwalt Class Destroyer
       program:

        Oversaw the planning, execution, and reporting of $50M in revenue and
        multiple hardware deliverables.

        Completed multiple successful internal and customer audits, and
        quarterly compliance reviews.

      Electrical Engineer II, Naval Platform E3

2006 - 2008

      Electromagnetic Interference/Compliance Lead
     for several government contracts:

        Developed tools in Excel and Mathcad to automate the analysis and
        sell-off of EMI/EMC/Lightning/EMP requirements (eg., MIL-STD-461,
        MIL-STD-464.)

          Assigned a “High Potential” designation by performing in the top 2%
          of salary grade.

Skills Inventory

Programming Skills

          Daily:
           Ruby, Ruby on
          Rails, Ember.js, RSpec, MiniTest, MySQL, Git, Github, Docker, Travis
          CI

          Occasionally:
          React, Redux, Test::Unit, Capybara, Selenium, PostgreSQL, HTML, CSS,
          JavaScript, Heroku

          Previously:
          PostGIS, Cucumber, Elasticsearch, Excel VBA

Management Skills

        Earned Value Management, Integrated Master Plan & Schedule
        Development, Microsoft Office Suite, Microsoft Project, Statement of
        Work Creation, Basis of Estimate Creation, Six Sigma Process Improvement

Online Learning

        CodeSchool:

          Treehouse:

9/9

Build a Simple Ruby on Rails Application

14/14

Ruby Foundations

6/6

JavaScript Foundations

7/7

HTML

          Codecademy:

Ruby

          100%

JavaScript

          16%

          Recent Readings

        Clean Ruby,
        The Pragmatic Programmer: From Journeyman to Master,
        Growing Object-Oriented Software, Guided by Tests,
        Practical Object-Oriented Design in Ruby: An Agile Primer,
        Design Patterns in Ruby,
        Everyday Rails Testing with RSpec,
        Ruby on Rails Tutorial: Learn Web Development with Rails,
        The Well-Grounded Rubyist,
        Eloquent Ruby,
        Head First HTML with CSS & XHTML,
        Head First SQL: Your Brain on SQL – A Learner’s Guide

Projects

                pi_plant

                tags:
                Ruby, Ruby on Rails, Raspberry Pi, Electrical Engineering

              Description:  A small rails webserver that runs on a
              Raspberry Pi Model B that will monitor a plant’s soil moisture and
              display the historical measurements. If the moisture level dips below a
              preset threshold, a rake task will trigger a small aquarium pump to
              water the plant

              Why it’s cool: I like this project because it’s an
              interesting mix of hardware and software.  The Raspberry Pi is fully
              capable of supporting Debian linux and running a rails server, while
              this project relies upon an analog moisture sensor, an ten-bit A2D
              converter, and a power relay to switch on the aquarium pump.

                whipped-cream (contributor)

                tags:
                Ruby, Sinatra, Raspberry Pi, dns-sd

              Description:  A Ruby gem that creates a simple DSL for
              creating a Raspberry Pi web server to monitor sensors, switches, and
              buttons via the Pi’s GPIO pins. Utilizes a simple, mobile-ready
              interface, and supports dns-sd/Bonjour discovery of other whipped-cream
              Pis on the local network.

              Why it’s cool: Anything on the Pi is fun, but this
              project was also my first significant open-source contribution.  It was
              also my first foray into ruby gems, and let me learn a bit about Travis
              CI and dns-sd.

                Voteline

                tags:
                Ruby, Ruby on Rails, Bootstrap, Devise, Highcharts

              Description:  Your typical public-facing rails
              prototype that implements real-time public voting (similar to real-time
              polling during political speeches.) Uses bootstrap for layout, devise
              for user authentication, and Highcharts for data plotting.

              Why it’s cool: This project was pretty simple, but fun
              because I got to experiment a bit with the JSON API for returning
              real-time votes, and the JavaScript for continually submitting votes.

                Lower Pines

                tags:
                Ruby, Padrino, Bootstrap, Haml, Mechanize

              Description:  A small weekend project to learn a bit
              about Sinatra/Padrino.  This site scrapes the recreation.gov website for
              open dates in Yosemite’s Lower Pines campground.  Utilizes the Padrino
              framework, ActiveRecord for data persistance, and bootstrap for
              appearance.

              Why it’s cool: This project was fun because it
              introduced me to an alternate MVC framework, and helped me realize what
              parts of rails really shine and what parts I could live without. It’s
              also super convenient.

Education

        University of Michigan
        (Ann Arbor, MI)

        Master of Science in Engineering
         Applied Electromagnetics

2005

        Bachelor of Science in Engineering
        Electrical Engineering (w/ Physics minor)

2004
Cum Laude

        Key Coursework:
        Electromagnetics I & II; Electromagnetic Theory; Numerical
        Electromagnetics; Antenna Theory & Design; Radiowave Propagation
        and Link Design; Advanced Solid State Microwave Circuits; Digital
        Communications, Digital Signal Processing and Analysis

  Copyright © 2017 - Ryan Ringler

      Powered by Octopress,
      customized with octostrap3.


text:
package com.datastax.oss.driver.internal.core.util.collection;

import com.datastax.oss.driver.api.core.metadata.Node;
import net.jcip.annotations.ThreadSafe;

/**
 * A query plan where nodes are computed lazily, when the plan is consumed for the first time.
 *
 *
This class can be useful when a query plan computation is heavy but the plan has a low chance
 * of ever being consumed, e.g. the last query plan in a {@link CompositeQueryPlan}.
 */
@ThreadSafe
public abstract class LazyQueryPlan extends QueryPlanBase {

  private volatile Object[] nodes;

  /**
   * Computes and returns the nodes to use for this query plan.
   *
   *
For efficiency, the declared return type is {@code Object[]} but all elements must be
   * instances of {@link Node}. See {@link #getNodes()} for details.
   *
   *
This method is guaranteed to be invoked only once, at the first call to {@link #poll()}.
   *
   *
Implementors must avoid blocking calls in this method as it will be invoked on the driver's
   * hot path.
   */
  protected abstract Object[] computeNodes();

  @Override
  protected Object[] getNodes() {
    if (nodes == null) {
      synchronized (this) {
        if (nodes == null) {
          nodes = computeNodes();
        }
      }
    }
    return nodes;
  }
}


text:
package org.opensingular.form.wicket.mapper.attachment;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.resource.AbstractResource;
import org.apache.wicket.request.resource.ContentDisposition;
import org.apache.wicket.util.string.StringValue;
import org.opensingular.form.type.core.attachment.IAttachmentRef;
import org.opensingular.lib.commons.util.Loggable;

/**
 * Shared Resource bound to application.
 *
 * @see DownloadSupportedBehavior
 */
public class AttachmentPublicResource extends AbstractResource implements Loggable {

    private Map<String, Attachment> attachments = new HashMap<>();
    public static final String APPLICATION_KEY = "public";

    public AttachmentPublicResource() { /*Blank constructor*/}

    @Override
    protected ResourceResponse newResourceResponse(Attributes attributes) {
        ResourceResponse resourceResponse = new ResourceResponse();
        StringValue attachmentKey = attributes.getParameters().get("attachmentKey");
        if (attachmentKey.isNull() || attachmentKey.isEmpty()) {
            return resourceResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
        }
        Attachment attachment = attachments.get(attachmentKey.toString());
        if (attachment == null) {
            return resourceResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
        }
        IAttachmentRef attachmentRef = attachment.attachmentRef;
        if (attachmentRef.getSize() > 0) {
            resourceResponse.setContentLength(attachmentRef.getSize());
        }

        resourceResponse.setFileName(attachment.filename);

        try {
            resourceResponse.setContentDisposition(attachment.contentDisposition);
            resourceResponse.setContentType(attachmentRef.getContentType());
            resourceResponse.setWriteCallback(new AttachmentResourceWriteCallback(resourceResponse, attachmentRef));
        } catch (Exception e) {
            getLogger().error("Erro ao recuperar arquivo.", e);
            resourceResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
        }

        return resourceResponse;
    }

    /**
     * @param name        the file name
     * @param disposition the disposition
     * @param ref         the reference
     * @return the URL for download
     */
    public String addAttachment(String name, ContentDisposition disposition, IAttachmentRef ref) {
        WebApplication app = WebApplication.get();
        attachments.put(ref.getId(), new Attachment(name, disposition, ref));
        String path = app.getServletContext().getContextPath() + '/' + app.getWicketFilter().getFilterPath() + getDownloadURL(ref.getId());
        return path.replaceAll("\\*", "").replaceAll("//", "/");
    }

    public static String getMountPathPublic() {
        return getDownloadURL("${attachmentKey}");
    }

    public static String getDownloadURL(String path) {
        return '/' + APPLICATION_KEY + "/download/" + path;
    }

}


text:
'use strict';

//Global service for global variables
angular.module('mean.system').factory('Global', [

  function() {
    var _this = this;
    _this._data = {
      user: window.user,
      authenticated: false,
      isAdmin: false
    };
    if (window.user && window.user.roles) {
      _this._data.authenticated = window.user.roles.length;
      _this._data.isAdmin = window.user.roles.indexOf('admin') !== -1;
    }
    return _this._data;
  }
]);


text:
package org.lightadmin.core.view.preparer.support;

import org.apache.tiles.beans.MenuItem;

import java.util.Comparator;

public class MenuItemComparator implements Comparator<MenuItem> {

    public static final MenuItemComparator INSTANCE = new MenuItemComparator();

    @Override
    public int compare(final MenuItem menuItem, final MenuItem menuItem2) {
        return menuItem.getValue().compareTo(menuItem2.getValue());
    }
}


text:
package nu.validator.htmlparser.test;

import java.util.LinkedList;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ListErrorHandler implements ErrorHandler {

    private boolean fatal = false;

    private LinkedList<String> errors = new LinkedList<String>();

    public void error(SAXParseException spe) throws SAXException {
        errors.add(Integer.toString(spe.getColumnNumber()) + ": " + spe.getMessage());
    }

    public void fatalError(SAXParseException arg0) throws SAXException {
        fatal = true;
    }

    public void warning(SAXParseException arg0) throws SAXException {
    }

    /**
     * Returns the errors.
     *
     * @return the errors
     */
    public LinkedList<String> getErrors() {
        return errors;
    }

    /**
     * Returns the fatal.
     *
     * @return the fatal
     */
    public boolean isFatal() {
        return fatal;
    }

}