text:
//
//  DGDownloadManagerFile.m
//  DGDownloadManager
//
//  Created by Daniel Cohen Gindi on 12/29/13.
//  Copyright (c) 2013 Daniel Cohen Gindi. All rights reserved.
//
//  https://github.com/danielgindi/DGDownloadManager
//
//  The MIT License (MIT)
//
//  Copyright (c) 2014 Daniel Cohen Gindi (danielgindi@gmail.com)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
//

#import "DGDownloadManagerFile.h"
#import "DGDownloadManager.h"

@interface DGDownloadManagerFile () <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
@end

@implementation DGDownloadManagerFile
{
    NSURLConnection *_connection;
    NSFileHandle *fileWriteHandle;
    BOOL resumeAllowed;
    BOOL connectionFinished;
    UIBackgroundTaskIdentifier bgTaskId;

    NSString *_downloadFilePath;
    BOOL _shouldDeleteOnDealloc;
    NSURLRequest *_currentUrlRequest;
}

- (void)initialize_DGDownloadManagerFile
{
    _requestTimeout = 60.0;
    _cachePolicy = NSURLRequestUseProtocolCachePolicy;
    bgTaskId = UIBackgroundTaskInvalid;
}

- (id)initWithUrl:(NSURL *)url
{
    self = [super init];
    if (self)
    {
        [self initialize_DGDownloadManagerFile];
        _url = url;
    }
    return self;
}

- (id)initWithUrl:(NSURL *)url context:(NSObject *)context
{
    self = [super init];
    if (self)
    {
        [self initialize_DGDownloadManagerFile];
        _url = url;
        _context = context;
    }
    return self;
}

- (id)initWithUrlRequest:(NSURLRequest *)urlRequest context:(NSObject *)context
{
    self = [super init];
    if (self)
    {
        [self initialize_DGDownloadManagerFile];
        _urlRequest = urlRequest;
        _context = context;
    }
    return self;
}

- (id)initWithUrlRequest:(NSURLRequest *)urlRequest
{
    self = [super init];
    if (self)
    {
        [self initialize_DGDownloadManagerFile];
        _urlRequest = urlRequest;
    }
    return self;
}

- (void)dealloc
{
    [self cancelDownloading];
    [fileWriteHandle closeFile];
    fileWriteHandle = nil;

    if (_downloadFilePath && _shouldDeleteOnDealloc)
    {
        [[NSFileManager defaultManager] removeItemAtPath:_downloadFilePath error:nil];
    }
}

- (NSString *)newTempFilePath
{
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"download-%@", uuidStr]];

    CFRelease(uuidStr);
    CFRelease(uuid);

    return path;
}

- (BOOL)prepareFileForDownloadWithResume:(BOOL)isResume error:(NSError **)outError
{
    BOOL shouldReturnError = NO;

    if (isResume && _downloadFilePath) return NO;

    if (!_downloadFilePath || !isResume)
    {
        _downloadFilePath = self.downloadDirectlyToPath;

        if (_downloadFilePath)
        {
            _shouldDeleteOnDealloc = NO;

            BOOL isDirectory = NO;
            if (!isResume || ![[NSFileManager defaultManager] fileExistsAtPath:_downloadFilePath isDirectory:&isDirectory] || isDirectory)
            {
                NSError *fileCreationError = nil;
                [[[NSData alloc] init] writeToFile:_downloadFilePath options:0 error:&fileCreationError];

                if (fileCreationError)
                {
                    _downloadFilePath = nil;
                    if (outError)
                    {
                        *outError = fileCreationError;
                    }
                    shouldReturnError = YES;
                }
            }
        }
        else
        {
            _shouldDeleteOnDealloc = YES;

            NSError *fileCreationError = nil;

            _downloadFilePath = [self newTempFilePath];
            int tries = 3;

            [[[NSData alloc] init] writeToFile:_downloadFilePath options:0 error:&fileCreationError];
            while (fileCreationError && --tries)
            {
                _downloadFilePath = [self newTempFilePath];

                fileCreationError = nil;
                [[[NSData alloc] init] writeToFile:_downloadFilePath options:0 error:&fileCreationError];
            }

            if (fileCreationError)
            {
                _downloadFilePath = nil;
                if (outError)
                {
                    *outError = fileCreationError;
                }
                shouldReturnError = YES;
            }
        }
    }

    // Now when we have a file (and truncated it if we needed to) open a handle for writing to it.
    // On UNIX the file can be moved or even deleted while the handle is still open - which is a nice feature because we can start reading from the temp file while downloading, and when we move that file to somewhere else we don't have to stop and resume reading.
    if (_downloadFilePath)
    {
        fileWriteHandle = [NSFileHandle fileHandleForWritingAtPath:_downloadFilePath];
        if (!fileWriteHandle)
        {
            _downloadFilePath = nil;
            if (outError)
            {
                *outError = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{NSLocalizedDescriptionKey: @"NSFileHandle fileHandleForWritingAtPath: failed and returned nil."}];
            }
            shouldReturnError = YES;
        }
    }

    return shouldReturnError;
}

- (void)startDownloadingNow
{
    if (_connection || (!_url && !_urlRequest)) return;

    _currentUrlRequest = _urlRequest;
    if (!_currentUrlRequest)
    {
        _currentUrlRequest = [[NSURLRequest alloc] initWithURL:_url cachePolicy:_cachePolicy timeoutInterval:_requestTimeout];
    }

    NSError *fileError = nil;
    [self prepareFileForDownloadWithResume:NO error:&fileError];

    if (fileError)
    {
        [self cleanupOnFailureWithError:fileError];
        return;
    }

    _connection = [[NSURLConnection alloc] initWithRequest:_currentUrlRequest delegate:self];
    connectionFinished = NO;
    [_connection start];

    if (!_isStandalone)
    {
        [[DGDownloadManager sharedInstance] downloadFile:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadStartedNotification object:self];
    if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFileStartedDownload:)])
    {
        [_delegate downloadManagerFileStartedDownload:self];
    }
}

- (void)pauseDownloading
{
    if (!_connection) return;
    [_connection cancel];
    _connection = nil;
    _currentUrlRequest = nil;

    if (!_isStandalone)
    {
        [[DGDownloadManager sharedInstance] cancelFileDownload:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadPausedNotification object:self];
    if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFilePausedDownload:)])
    {
        [_delegate downloadManagerFilePausedDownload:self];
    }

    if (bgTaskId)
    {
        [UIApplication.sharedApplication endBackgroundTask:bgTaskId];
        bgTaskId = UIBackgroundTaskInvalid;
    }
}

- (void)cancelDownloading
{
    if (!_connection) return;
    [_connection cancel];
    _connection = nil;
    _currentUrlRequest = nil;

    [fileWriteHandle closeFile];
    fileWriteHandle = nil;

    if (_downloadFilePath && _shouldDeleteOnDealloc)
    {
        [[NSFileManager defaultManager] removeItemAtPath:_downloadFilePath error:nil];
        _downloadFilePath = nil;
        _shouldDeleteOnDealloc = NO;
    }

    _downloadedDataLength = 0LL;

    if (!_isStandalone)
    {
        [[DGDownloadManager sharedInstance] cancelFileDownload:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadCancelledNotification object:self];
    if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFileCancelledDownload:)])
    {
        [_delegate downloadManagerFileCancelledDownload:self];
    }

    if (bgTaskId)
    {
        [UIApplication.sharedApplication endBackgroundTask:bgTaskId];
        bgTaskId = UIBackgroundTaskInvalid;
    }
}

- (void)resumeDownloadNow
{
    if (_connection || (!_url && !_urlRequest)) return;

    NSError *fileError = nil;
    [self prepareFileForDownloadWithResume:YES error:&fileError];

    if (fileError)
    {
        [self cleanupOnFailureWithError:fileError];
        return;
    }

    NSMutableURLRequest *request;

    if (_urlRequest)
    {
        request = [_urlRequest mutableCopy];
    }
    else
    {
        request = [NSMutableURLRequest requestWithURL:_url cachePolicy:_cachePolicy timeoutInterval:_requestTimeout];
    }

    unsigned long long currentFileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_downloadFilePath error:nil] fileSize];
    _downloadedDataLength = currentFileSize;

    if (resumeAllowed)
    {
        if ([request valueForHTTPHeaderField:@"Range"] == nil)
        {
            [request addValue:[NSString stringWithFormat:@"bytes=%lld-", _downloadedDataLength] forHTTPHeaderField:@"Range"];
        }
    }
    else
    {
        [request setValue:nil forHTTPHeaderField:@"Range"];
    }

    _currentUrlRequest = [request copy];

    bgTaskId = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{
        bgTaskId = UIBackgroundTaskInvalid;
        [self cancelDownloading];
    }];
    _connection = [[NSURLConnection alloc] initWithRequest:_currentUrlRequest delegate:self];
    connectionFinished = NO;
    [_connection start];

    if (!_isStandalone)
    {
        [[DGDownloadManager sharedInstance] resumeFileDownload:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadStartedNotification object:self];
    if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFileStartedDownload:)])
    {
        [_delegate downloadManagerFileStartedDownload:self];
    }
}

- (void)addToDownloadQueue
{
    [[DGDownloadManager sharedInstance] downloadFile:self];
}

- (void)addToDownloadQueueForResuming
{
    [[DGDownloadManager sharedInstance] resumeFileDownload:self];
}

- (void)postFailedMessageWithError:(NSError *)error
{
    [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadFailedNotification object:self userInfo:@{@"error": error}];

    if (_delegate)
    {
        if ([_delegate respondsToSelector:@selector(downloadManagerFileFailedDownload:error:)])
        {
            [_delegate downloadManagerFileFailedDownload:self error:error];
        }
        else if ([_delegate respondsToSelector:@selector(downloadManagerFileFailedDownload:)])
        {
            [_delegate downloadManagerFileFailedDownload:self];
        }
    }
}

- (void)cleanupOnFailureWithError:(NSError *)error
{
    _connection = nil;
    _currentUrlRequest = nil;

    if (!_isStandalone)
    {
        // Make it remove from us the known arrays
        [[DGDownloadManager sharedInstance] cancelFileDownload:self];
    }

    [self postFailedMessageWithError:error];

    if (bgTaskId)
    {
        [UIApplication.sharedApplication endBackgroundTask:bgTaskId];
        bgTaskId = UIBackgroundTaskInvalid;
    }
}

#pragma mark - Accessors

- (BOOL)isComplete
{
    return (_expectedContentLength == -1 || (unsigned long long)_expectedContentLength == _downloadedDataLength) && connectionFinished;
}

- (BOOL)isDownloading
{
    return _connection != nil;
}

- (NSString *)downloadedFilePath
{
    return _downloadFilePath;
}

#pragma mark - NSURLConnectionDelegate, NSURLConnectionDataDelegate

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    _suggestedFilename = response.suggestedFilename;
    if (response)
    {
        NSMutableURLRequest *goodRequest = [_currentUrlRequest mutableCopy];
        goodRequest.URL = request.URL;
        return goodRequest;
    }
    else
    {
        return request;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([response isKindOfClass:NSHTTPURLResponse.class])
    {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        if (statusCode >= 400)
        {
            [connection cancel];
            [self connection:connection didFailWithError:[NSError errorWithDomain:response.URL.absoluteString code:statusCode userInfo:@{ NSLocalizedFailureReasonErrorKey: @(statusCode)}]];
            return;
        }
    }

    _suggestedFilename = response.suggestedFilename;
    _expectedContentLength = response.expectedContentLength;

    NSHTTPURLResponse *httpResonse = (NSHTTPURLResponse *)response;
    NSDictionary *headers = [httpResonse allHeaderFields];

    resumeAllowed = [[headers valueForKey:@"Accept-Ranges"] hasSuffix:@"bytes"];

    long long start = 0;

    NSString *contentRange = [headers valueForKey:@"Content-Range"];
    if (contentRange && _downloadedDataLength > 0ULL)
    {
        NSScanner *contentRangeScanner = [NSScanner scannerWithString:contentRange];
        [contentRangeScanner scanString:@"bytes " intoString:nil];
        [contentRangeScanner scanLongLong:&start];

        _expectedContentLength += start;
    }

    if (start > 0L)
    {
        // This is a partial, from resuming the download. Seek to the start position.
        [fileWriteHandle seekToFileOffset:start];
    }
    else
    {
        /*! @discussion In rare cases, for example in the case of an HTTP load where the content type of the load data is multipart/x-mixed-replace, the delegate will receive more than one connection:didReceiveResponse: message. In the event this occurs, delegates should discard all data previously delivered by connection:didReceiveData:, and should be prepared to handle the, potentially different, MIME type reported by the newly reported URL response. */

        [fileWriteHandle truncateFileAtOffset:0];
        _downloadedDataLength = 0ULL;
    }

    if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFileHeadersReceived:)])
    {
        [_delegate downloadManagerFileHeadersReceived:self];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    @try
    {
        [fileWriteHandle writeData:data];
    }
    @catch (NSException *exception)
    {
        [connection cancel];

        NSMutableDictionary *userInfo = [exception.userInfo mutableCopy];
        userInfo[NSLocalizedFailureReasonErrorKey] = exception.reason;

        NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
                                             code:NSFileWriteUnknownError
                                         userInfo:userInfo];
        [self connection:connection didFailWithError:error];

        return;
    }
    @finally
    {

    }

    [fileWriteHandle synchronizeFile]; // Prevent memory presure by always flushing to disk
    _downloadedDataLength += (unsigned long long)data.length;

    if (_progressDelegate)
    {
        [_progressDelegate downloadManagerFileProgressChanged:self];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self cleanupOnFailureWithError:error];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    _connection = nil;
    _currentUrlRequest = nil;
    connectionFinished = YES;

    if (!_isStandalone)
    {
        // Make it remove from us the known arrays
        [[DGDownloadManager sharedInstance] cancelFileDownload:self];
    }

    if ([[[NSFileManager defaultManager] attributesOfItemAtPath:_downloadFilePath error:nil] fileSize] < _downloadedDataLength)
    {
        NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:@{NSLocalizedDescriptionKey: @"seems like we ran out of space and could not write to disk"}];

        [self postFailedMessageWithError:error];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:DGDownloadManagerDownloadFinishedNotification object:self];
        if (_delegate && [_delegate respondsToSelector:@selector(downloadManagerFileFinishedDownload:)])
        {
            [_delegate downloadManagerFileFinishedDownload:self];
        }
    }

    if (bgTaskId)
    {
        [UIApplication.sharedApplication endBackgroundTask:bgTaskId];
        bgTaskId = UIBackgroundTaskInvalid;
    }
}

@end


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

var HttpConflictException = require('../../errors/HttpConflictException');

'use strict';

/**
* 要求された操作を行えません。このISOイメージは不完全です。複製処理等の完了後に再度お試しください。
*/
var CdromIsIncompleteException = (function (_super) {
    __extends(CdromIsIncompleteException, _super);
    /**
    * @constructor
    * @public
    * @param {number} status
    * @param {string} code=null
    * @param {string} message=""
    */
    function CdromIsIncompleteException(status, code, message) {
        if (typeof code === "undefined") { code = null; }
        if (typeof message === "undefined") { message = ""; }
        _super.call(this, status, code, message == null || message == "" ? "要求された操作を行えません。このISOイメージは不完全です。複製処理等の完了後に再度お試しください。" : message);
    }
    return CdromIsIncompleteException;
})(HttpConflictException);
module.exports = CdromIsIncompleteException;

redpajama_set_name: RedPajamaGithub


text:
class BLOBNBOX_LIST;
class TO_BLOCK;
struct Pix;

namespace tesseract {

class ColPartitionGrid;
class ColPartitionSet;

class EquationDetectBase {
 public:
  EquationDetectBase();
  virtual ~EquationDetectBase();

  // Iterate over the blobs inside to_block, and set the blobs that we want to
  // process to BSTT_NONE. (By default, they should be BSTT_SKIP). The function
  // returns 0 upon success.
  virtual int LabelSpecialText(TO_BLOCK* to_block) = 0;

  // Interface to find possible equation partition grid from part_grid. This
  // should be called after IdentifySpecialText function.
  virtual int FindEquationParts(ColPartitionGrid* part_grid,
                                ColPartitionSet** best_columns) = 0;

  // Debug function: Render a bounding box on pix based on the value of its
  // special_text_type, specifically:
  // BSTT_MATH: red box
  // BSTT_DIGIT: cyan box
  // BSTT_ITALIC: green box
  // BSTT_UNCLEAR: blue box
  // All others: yellow box
  static void RenderSpecialText(Pix* pix, BLOBNBOX* blob);
};

};  // namespace tesseract

#endif  // TESSERACT_TEXTORD_EQUATIONDETECTBASE_H__


text:
from django.conf.urls import include, url
from django.contrib import admin

from .views import home

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allaccess.urls')),
    url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'),
    url(r'^$', home, name='home'),
]


text:
package reactivemongo.api

import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.duration.SECONDS

import akka.util.Timeout
import akka.actor.ActorRef

import shaded.netty.channel.ChannelFuture

import reactivemongo.core.protocol.Response
import reactivemongo.core.nodeset.{ Authenticate, NodeSet, Node }
import reactivemongo.core.actors, actors.{
  ChannelClosed,
  MongoDBSystem,
  RequestId,
  StandardDBSystem
}

import reactivemongo.bson.BSONDocument

package object tests {
  // Test alias
  def _failover2[A](c: MongoConnection, s: FailoverStrategy)(p: () => Future[A])(implicit ec: ExecutionContext): Failover2[A] = Failover2.apply(c, s)(p)(ec)

  def isAvailable(con: MongoConnection)(implicit ec: ExecutionContext): Future[Boolean] = con.probe.map(_.isEmpty)

  def waitIsAvailable(con: MongoConnection, failoverStrategy: FailoverStrategy)(implicit ec: ExecutionContext): Future[Unit] = con.waitIsAvailable(failoverStrategy)

  def standardDBSystem(supervisor: String, name: String, nodes: Seq[String], authenticates: Seq[Authenticate], options: MongoConnectionOptions) = new StandardDBSystem(supervisor, name, nodes, authenticates, options)

  def addConnection(d: MongoDriver, name: String, nodes: Seq[String], options: MongoConnectionOptions, mongosystem: ActorRef): Future[Any] = {
    import akka.pattern.ask

    def message = d.AddConnection(name, nodes, options, mongosystem)
    implicit def timeout = Timeout(10, SECONDS)

    d.supervisorActor ? message
  }

  def history(sys: MongoDBSystem): Traversable[(Long, String)] =
    sys.history.toArray.toList.collect {
      case (time: Long, event: String) => time -> event
    }

  def nodeSet(sys: MongoDBSystem): NodeSet = sys.getNodeSet

  def channelClosed(id: Int) = ChannelClosed(id)

  def makeRequest[T](cursor: Cursor[T], maxDocs: Int)(implicit ec: ExecutionContext): Future[Response] = cursor.asInstanceOf[CursorOps[T]].makeRequest(maxDocs)

  def fakeResponse(doc: BSONDocument, reqID: Int = 2, respTo: Int = 1, chanId: Int = 1): Response = {
    val reply = reactivemongo.core.protocol.Reply(
      flags = 1,
      cursorID = 1,
      startingFrom = 0,
      numberReturned = 1
    )

    val message = reactivemongo.core.netty.BufferSequence.single(doc).merged

    val header = reactivemongo.core.protocol.MessageHeader(
      messageLength = message.capacity,
      requestID = reqID,
      responseTo = respTo,
      opCode = -1
    )

    Response(
      header,
      reply,
      documents = message,
      info = reactivemongo.core.protocol.ResponseInfo(chanId)
    )
  }

  def foldResponses[T](
    makeRequest: ExecutionContext => Future[Response],
    next: (ExecutionContext, Response) => Future[Option[Response]],
    killCursors: (Long, String) => Unit,
    z: => T,
    maxDocs: Int,
    suc: (T, Response) => Future[Cursor.State[T]],
    err: Cursor.ErrorHandler[T]
  )(implicit sys: akka.actor.ActorSystem, ec: ExecutionContext): Future[T] =
    FoldResponses[T](
      z, makeRequest, next, killCursors, suc, err, maxDocs
    )(sys, ec)

  def bsonReadPref(pref: ReadPreference): BSONDocument =
    reactivemongo.api.collections.bson.BSONReadPreference.write(pref)

  @inline def RefreshAll = actors.RefreshAll

  @inline def updateNodeSet(sys: StandardDBSystem, event: String)(f: NodeSet => NodeSet) = sys.updateNodeSet(event)(f)

  @inline def nodeSet(sys: StandardDBSystem) = sys._nodeSet

  @inline def isMasterReqId: Int = RequestId.isMaster.next

  @inline def connectAll(sys: StandardDBSystem, ns: NodeSet, f: (Node, ChannelFuture) => (Node, ChannelFuture) = { _ -> _ }) = sys.connectAll(ns, f)
}


text:
package org.apache.fineract.portfolio.loanaccount.domain;

import java.math.BigDecimal;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.portfolio.loanaccount.data.LoanTermVariationsData;
import org.apache.fineract.portfolio.loanproduct.service.LoanEnumerations;
import org.joda.time.LocalDate;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Table(name = "m_loan_term_variations")
public class LoanTermVariations extends AbstractPersistable<Long> {

    @ManyToOne(optional = false)
    @JoinColumn(name = "loan_id", nullable = false)
    private Loan loan;

    @Column(name = "term_type", nullable = false)
    private Integer termType;

    @Temporal(TemporalType.DATE)
    @Column(name = "applicable_date", nullable = false)
    private Date termApplicableFrom;

    @Column(name = "decimal_value", scale = 6, precision = 19)
    private BigDecimal decimalValue;

    @Temporal(TemporalType.DATE)
    @Column(name = "date_value")
    private Date dateValue;

    @Column(name = "is_specific_to_installment", nullable = false)
    private boolean isSpecificToInstallment;

    @Column(name = "applied_on_loan_status", nullable = false)
    private Integer onLoanStatus;

    @Column(name = "is_active", nullable = false)
    private Boolean isActive;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private LoanTermVariations parent;

    public LoanTermVariations(final Integer termType, final Date termApplicableFrom, final BigDecimal decimalValue, final Date dateValue,
            final boolean isSpecificToInstallment, final Loan loan) {
        this.loan = loan;
        this.termApplicableFrom = termApplicableFrom;
        this.termType = termType;
        this.decimalValue = decimalValue;
        this.dateValue = dateValue;
        this.isSpecificToInstallment = isSpecificToInstallment;
        this.onLoanStatus = loan.status().getValue();
        this.isActive = true;
        this.parent = null;
    }

    public LoanTermVariations(final Integer termType, final Date termApplicableFrom, final BigDecimal decimalValue, final Date dateValue,
            final boolean isSpecificToInstallment, final Loan loan, final Integer loanStatus) {
        this.loan = loan;
        this.termApplicableFrom = termApplicableFrom;
        this.termType = termType;
        this.decimalValue = decimalValue;
        this.dateValue = dateValue;
        this.isSpecificToInstallment = isSpecificToInstallment;
        this.onLoanStatus = loanStatus;
        this.isActive = true;
        this.parent = null;
    }

    public LoanTermVariations(final Integer termType, final Date termApplicableFrom, final BigDecimal decimalValue, final Date dateValue,
            final boolean isSpecificToInstallment, final Loan loan, final Integer loanStatus, final Boolean isActive, final LoanTermVariations parent) {
        this.loan = loan;
        this.termApplicableFrom = termApplicableFrom;
        this.termType = termType;
        this.decimalValue = decimalValue;
        this.dateValue = dateValue;
        this.isSpecificToInstallment = isSpecificToInstallment;
        this.onLoanStatus = loanStatus;
        this.isActive = isActive;
        this.parent = parent;
    }

    protected LoanTermVariations() {

    }

    public LoanTermVariationType getTermType() {
        return LoanTermVariationType.fromInt(this.termType);
    }

    public LoanTermVariationsData toData() {
        LocalDate termStartDate = new LocalDate(this.termApplicableFrom);
        LocalDate dateValue = null;
        if (this.dateValue != null) {
            dateValue = new LocalDate(this.dateValue);
        }
        EnumOptionData type = LoanEnumerations.loanvariationType(this.termType);
        return new LoanTermVariationsData(getId(), type, termStartDate, this.decimalValue, dateValue, this.isSpecificToInstallment);
    }

    public Date getTermApplicableFrom() {
        return this.termApplicableFrom;
    }

    public LocalDate fetchTermApplicaDate() {
        return new LocalDate(this.termApplicableFrom);
    }

    public BigDecimal getTermValue() {
        return this.decimalValue;
    }

    public Date getDateValue() {
        return this.dateValue;
    }

    public LocalDate fetchDateValue() {
        return this.dateValue == null ? null : new LocalDate(this.dateValue);
    }

    public void setTermApplicableFrom(Date termApplicableFrom) {
        this.termApplicableFrom = termApplicableFrom;
    }

    public void setDecimalValue(BigDecimal decimalValue) {
        this.decimalValue = decimalValue;
    }

    public Integer getOnLoanStatus() {
        return this.onLoanStatus;
    }

    public Boolean isActive() {
        return this.isActive;
    }

    public LoanTermVariations parent() {
        return this.parent;
    }

    public void updateIsActive(final Boolean isActive){
        this.isActive = isActive;
    }

    public void markAsInactive() {
        this.isActive = false;
    }

}


text:
package org.innovateuk.ifs.project.status.viewmodel;

import org.innovateuk.ifs.competition.publiccontent.resource.FundingType;
import org.innovateuk.ifs.competition.resource.CompetitionThirdPartyConfigResource;
import org.innovateuk.ifs.competition.resource.PostAwardService;
import org.innovateuk.ifs.project.projectdetails.viewmodel.BasicProjectDetailsViewModel;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.resource.ProjectState;

import java.util.List;

/**
 * A view model that backs the Project Status page
 */
public class SetupStatusViewModel implements BasicProjectDetailsViewModel {

    private final long projectId;
    private final String projectName;
    private final boolean monitoringOfficer;
    private final ProjectState projectState;
    private final long applicationId;
    private final String competitionName;
    private final long competitionId;
    private final FundingType fundingType;
    private final boolean collaborativeProject;
    private final boolean showApplicationSummaryLink;
    private final List<SetupStatusStageViewModel> stages;
    private final boolean projectManager;
    private final boolean projectFinanceContact;
    private final PostAwardService postAwardService;
    private final String liveProjectsLandingPageUrl;
    private final boolean thirdPartyProcurement;
    private final CompetitionThirdPartyConfigResource thirdPartyConfig;
    private final boolean hasAssessmentStage;
    private final boolean isDirectAward;
    private final boolean ktpCompetition;

    public SetupStatusViewModel(ProjectResource project,
                                boolean monitoringOfficer,
                                List<SetupStatusStageViewModel> stages,
                                FundingType fundingType,
                                boolean showApplicationSummaryLink,
                                boolean projectManager,
                                boolean projectFinanceContact,
                                PostAwardService postAwardService,
                                String liveProjectsLandingPageUrl,
                                boolean thirdPartyProcurement,
                                CompetitionThirdPartyConfigResource thirdPartyConfig,
                                boolean hasAssessmentStage,
                                boolean isDirectAward,
                                boolean ktpCompetition) {
        this.projectId = project.getId();
        this.projectName = project.getName();
        this.monitoringOfficer = monitoringOfficer;
        this.projectState = project.getProjectState();
        this.applicationId = project.getApplication();
        this.competitionName = project.getCompetitionName();
        this.competitionId = project.getCompetition();
        this.stages = stages;
        this.fundingType = fundingType;
        this.collaborativeProject = project.isCollaborativeProject();
        this.showApplicationSummaryLink = showApplicationSummaryLink;
        this.projectManager = projectManager;
        this.projectFinanceContact = projectFinanceContact;
        this.postAwardService = postAwardService;
        this.liveProjectsLandingPageUrl = liveProjectsLandingPageUrl;
        this.thirdPartyProcurement = thirdPartyProcurement;
        this.thirdPartyConfig = thirdPartyConfig;
        this.hasAssessmentStage = hasAssessmentStage;
        this.isDirectAward = isDirectAward;
        this.ktpCompetition = ktpCompetition;
    }

    public Long getProjectId() {
        return projectId;
    }

    public String getProjectName() {
        return projectName;
    }

    public Long getApplicationId() {
        return applicationId;
    }

    public String getCompetitionName() {
        return competitionName;
    }

    public Long getCompetitionId() {
        return competitionId;
    }

    public ProjectState getProjectState() {
        return projectState;
    }

    public boolean isMonitoringOfficer() {
        return monitoringOfficer;
    }

    public boolean isLoanCompetition() {
        return this.fundingType == FundingType.LOAN;
    }

    public boolean isInvestorPartnershipCompetition() {
        return this.fundingType == FundingType.INVESTOR_PARTNERSHIPS;
    }

    public boolean isKtpCompetition() {
        return ktpCompetition;
    }

    public List<SetupStatusStageViewModel> getStages() {
        return stages;
    }

    public boolean isCollaborativeProject() {
        return collaborativeProject;
    }

    public boolean isShowApplicationSummaryLink() {
        return showApplicationSummaryLink;
    }

    public boolean shouldShowStatus(SetupStatusStageViewModel stage) {
        return isMonitoringOfficer() || !stage.getAccess().isNotAccessible();
    }

    public boolean isProjectManager() {
        return projectManager;
    }

    public boolean isProjectFinanceContact() {
        return projectFinanceContact;
    }

    public PostAwardService getPostAwardService() {
        return postAwardService;
    }

    public boolean isIfsPostAward() {
        return this.postAwardService == PostAwardService.IFS_POST_AWARD;
    }

    public String getLiveProjectsLandingPageUrl() {
        return liveProjectsLandingPageUrl;
    }

    public boolean isApplicationFeedbackAvailable() {
        return !isKtpCompetition();
    }

    public boolean isBannerVisible() {
        return !isLoanCompetition() && !isKtpCompetition() && getProjectState().isActive();
    }

    public boolean isLiveProjectMessageVisible() {
        return !isKtpCompetition() && getProjectState().isLive();
    }

    public boolean isThirdPartyProcurement() { return thirdPartyProcurement; }

    public CompetitionThirdPartyConfigResource getThirdPartyConfig() { return thirdPartyConfig; }

    public boolean isHasAssessmentStage() {
        return hasAssessmentStage;
    }

    public boolean isDirectAward() {
        return isDirectAward;
    }
}


text:
class Account < ActiveRecord::Base
  active_ingredients do
    mobile_phone PhoneNumber, validate: true, unique: true
    home_phone   PhoneNumber, validate: true, allow_nil: true
  end
end


text:
package main;

import game.MainMenu;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.ArrayList;
import java.util.ListIterator;

import javax.swing.JFrame;
import javax.swing.JPanel;

import abstracts.Renderable;

public class GameComponent extends Canvas implements Runnable {
	private static final long serialVersionUID = 1L;
	public static final double FRAMES_PER_SECOND = 60.0;
	public static final int WIDTH = 640;
	public static final int HEIGHT = 480;
	public static final int SCALE = 4;
	public static final int MAGNIFIED = WIDTH / SCALE;

	private Thread gameThread;
	protected boolean threadRunning;
	private boolean displayActive;

	public BufferedImage image;
	public int[] pixels;

	public BufferedImage display;
	public int[] displayPixels;

	public ArrayList<Renderable> objects;
	public ArrayList<Renderable> queue;
	public InputHandler inputHandler;

	public GameComponent() {
		threadRunning = false;

		Dimension d = new Dimension(WIDTH, HEIGHT);
		this.setPreferredSize(d);
		this.setMaximumSize(d);
		this.setMinimumSize(d);
		this.setSize(d);

		image = new BufferedImage(WIDTH / SCALE, HEIGHT / SCALE, BufferedImage.TYPE_INT_ARGB);
		pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

		display = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
		displayPixels = ((DataBufferInt) display.getRaster().getDataBuffer()).getData();

		this.displayActive = false;

		this.inputHandler = new InputHandler();
		this.addMouseListener(inputHandler);
		this.addMouseMotionListener(inputHandler);
		objects = new ArrayList<Renderable>();
		queue = new ArrayList<Renderable>();
		objects.add(new MainMenu(this));
	}

	@Override
	public void run() {
		long now = System.nanoTime();
		long lastTime = now;
		double unprocessedTime = 0.0;
		final double ticksPerSecond = 1000000000.0 / FRAMES_PER_SECOND;
		while (threadRunning) {
			now = System.nanoTime();
			unprocessedTime += (now - lastTime) / ticksPerSecond;
			lastTime = now;
			if (unprocessedTime > 1)
				unprocessedTime = 1.0;

			boolean render = false;
			while (unprocessedTime >= 1) {
				unprocessedTime -= 1;
				tick();
				render = true;
			}
			if (render)
				render();
			try {
				Thread.sleep(1);
			}
			catch (InterruptedException e) {
			}
		}
	}

	public synchronized void start() {
		if (!threadRunning) {
			threadRunning = true;
			gameThread = new Thread(this);
			gameThread.start();
		}
	}

	public synchronized void stop() {
		if (threadRunning) {
			threadRunning = false;
		}
	}

	public void tick() {
		for (ListIterator<Renderable> i = objects.listIterator(); i.hasNext();) {
			Renderable r = i.next();
			r.tick();
		}
		if (!queue.isEmpty()) {
			objects.addAll(queue);
			queue.clear();
		}
	}

	public void render() {
		BufferStrategy bs = this.getBufferStrategy();
		if (bs == null) {
			this.createBufferStrategy(3);
			bs = this.getBufferStrategy();
		}

		for (ListIterator<Renderable> it = objects.listIterator(); it.hasNext();) {
			Renderable r = it.next();
			r.render();
		}

		int w = this.getWidth();
		int h = this.getHeight();
		Graphics g = bs.getDrawGraphics();
		g.setColor(new Color(24, 100, 150));
		g.fillRect(0, 0, w, h);
		g.drawImage(image, 0, 0, w, h, null);
		if (this.displayActive)
			g.drawImage(display, 0, 0, w, h, null);
		g.dispose();
		bs.show();
	}

	public void setDisplayActive() {
		this.displayActive = true;
	}

	public void setDisplayInactive() {
		this.displayActive = false;
	}

	public static void main(String[] args) {
		GameComponent g = new GameComponent();
		JFrame frame = new JFrame("Pixavive Alpha - v0.07 (A* algorithm test)");
		frame.add(new JPanel().add(g));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);

		g.start();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_height="fill_parent"
  android:layout_width="fill_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent">
        <TextView android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textColor="#fff"
            android:textSize="30sp"
            android:paddingTop="10sp"
            android:paddingBottom="10sp"
            android:layout_weight="1"
            android:id="@+id/titleSeason"/>
    </LinearLayout>

  <ListView android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:id="@+id/listSeason"/>

</LinearLayout>


text:
<?php

namespace CommandPlanner\Tests\Pool;

use CommandPlanner\Pool\CommandPool;
use CommandPlanner\Tests\Data\TestCommand;
use CommandPlanner\Wrapper\CommandWrapper;
use Cron\CronExpression;
use Symfony\Component\Console\Application;

/**
 * Class CommandPoolTest
 *
 * @package CommandPlanner\Tests\Pool
 */
class CommandPoolTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers CommandPlanner\Pool\CommandPool::add
     */
    public function testAdd()
    {
        $commandPool = new CommandPool();

        $commandConfig = [
            'parameters' => [],
            'options'    => [],
            'log_file'   => []
        ];

        $uniqid = $commandPool->add(new CommandWrapper(get_class(new TestCommand()), get_class(new Application()), CronExpression::factory('* * * * * *'), $commandConfig));

        $this->assertEquals(13, strlen($uniqid));
    }

    /**
     * @covers CommandPlanner\Pool\CommandPool::get
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidGet()
    {
        $commandPool = new CommandPool();

        $commandPool->get(uniqid());
    }

    /**
     * @covers CommandPlanner\Pool\CommandPool::get
     */
    public function testValidGet()
    {
        $commandPool = new CommandPool();

        $commandConfig = [
            'parameters' => [],
            'options'    => [],
            'log_file'   => []
        ];

        $uniqid = $commandPool->add(new CommandWrapper(get_class(new TestCommand()), get_class(new Application()), CronExpression::factory('* * * * * *'), $commandConfig));

        $this->assertInstanceOf('CommandPlanner\Wrapper\CommandWrapper', $commandPool->get($uniqid));
    }

    /**
     * @covers CommandPlanner\Pool\CommandPool::remove
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidRemove()
    {
        $commandPool = new CommandPool();

        $commandPool->remove(uniqid());
    }

    /**
     * @covers CommandPlanner\Pool\CommandPool::remove
     * @expectedException \InvalidArgumentException
     */
    public function testValidRemove()
    {
        $commandPool = new CommandPool();

        $commandConfig = [
            'parameters' => [],
            'options'    => [],
            'log_file'   => []
        ];

        $uniqid = $commandPool->add(new CommandWrapper(get_class(new TestCommand()), get_class(new Application()), CronExpression::factory('* * * * * *'), $commandConfig));

        $commandPool->remove($uniqid);

        $commandPool->get($uniqid);
    }

    /**
     * @covers CommandPlanner\Pool\CommandPool::all
     */
    public function testAll()
    {
        $commandPool = new CommandPool();

        $commandConfig = [
            'parameters' => [],
            'options'    => [],
            'log_file'   => []
        ];

        $commandPool->add(new CommandWrapper(get_class(new TestCommand()), get_class(new Application()), CronExpression::factory('* * * * * *'), $commandConfig));
        $commandPool->add(new CommandWrapper(get_class(new TestCommand()), get_class(new Application()), CronExpression::factory('* * * * * *'), $commandConfig));

        $commandWrappers = $commandPool->all();

        $this->assertCount(2, $commandWrappers);

        foreach ($commandWrappers as $uniqid => $commandWrapper) {
            $this->assertInstanceOf('CommandPlanner\Wrapper\CommandWrapper', $commandWrapper);
            $this->assertEquals(13, strlen($uniqid));
        }
    }
}


text:
Facter.add(:install_server__copy_or_download) do
  setcode do
    result_string = 'not there'
    myfile = '/tmp/dynatrace_server_installation.info'
    if File.exists?(myfile)
      text=File.open(myfile).read
      text.gsub!(/\r\n?/, "\n")
      text.each_line do |line|
        line_noend = line.gsub(/\s+/, ',')
        #check if this step of manifest should be executed...
        if line_noend.include? "copy_or_download_file"
          key = line_noend.split(/=/).first
          value = line_noend.split(/=/).last
          value = value.gsub(/,/, '')                 #'/opt/puppetlabs/puppet/cache/dynatrace/dynatrace.jar'
          #check if file from 'value' exists
          if File.exists?(value)
            result_string = 'there'
          end
#          puts "#############!!!!!! key=#{key}  value=#{value}   result_string=#{result_string}"
        end
      end
      result_string
    else
      'not there'
    end
  end
end


text:
var mongoose = require('mongoose'),
    encryption = require('../utilities/encryption');

var userSchema = mongoose.Schema({
    username: { type: String, require: '{PATH} is required', unique: true },
    email: { type: String, require: "{PATH} is required", unique: true },
    representativeName: String,
    phoneNumber: String,
    salt: String,
    hashPass: String,
    roles: [String]
});

userSchema.method({
    authenticate: function(password) {
        return encryption.generateHashedPassword(this.salt, password) === this.hashPass;
    }
});

var User = mongoose.model('User', userSchema);

module.exports.seedInitialUsers = function() {
    User.find({}).exec(function(err, collection) {
        var salt,
            hashedPwd;

        if (err) {
            console.log('Cannot find users ' + err);
            return;
        }

        if (collection.length === 0) {
            salt = encryption.generateSalt();
            hashedPwd = encryption.generateHashedPassword(salt, "password");

            User.create({username: 'gosho', email: "zzz@z.c", phoneNumber: "+1888 332 544", salt: salt, hashPass: hashedPwd, roles: ['admin']});
            User.create({username: 'misho', email: "noemail@gmail.no", representativeName: "Seller", salt: salt, hashPass: hashedPwd, roles: ['standard']});
            User.create({username: 'pesho', email: "pesho@guzara.com", salt: salt, hashPass: hashedPwd});

            console.log('Users added to database...');
        }
    });
};


text:
class DianpingCrawlerSpiderMiddleware(object):
    def process_request(self, request, spider):
        cookies = spider.settings.get('COOKIES', {})
        request.cookies.update(cookies)


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Localization;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;

namespace OrchardCore.Workflows.UserTasks.Activities
{
    public class UserTaskEvent : EventActivity
    {
        private readonly IStringLocalizer S;

        public UserTaskEvent(IStringLocalizer<UserTaskEvent> localizer)
        {
            S = localizer;
        }

        public override string Name => nameof(UserTaskEvent);
        public override LocalizedString DisplayText => S["User Task Event"];
        public override LocalizedString Category => S["Content"];

        public IList<string> Actions
        {
            get => GetProperty(() => new List<string>());
            set => SetProperty(value);
        }

        public IList<string> Roles
        {
            get => GetProperty(() => new List<string>());
            set => SetProperty(value);
        }

        public override bool CanExecute(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        {
            var action = GetProvidedAction(workflowContext);
            return Actions.Contains(action);
        }

        public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        {
            return Actions.Select(x => Outcome(S[x]));
        }

        public override ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        {
            var action = GetProvidedAction(workflowContext);
            return Outcomes(action);
        }

        private string GetProvidedAction(WorkflowExecutionContext workflowContext)
        {
            return (string)workflowContext.Input["UserAction"];
        }
    }
}


text:
package gobblin.util;

import java.io.IOException;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;

import com.google.common.base.Preconditions;

import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.State;
import gobblin.configuration.WorkUnitState;
import gobblin.source.workunit.WorkUnit;

/**
 * Utility class for use with the {@link gobblin.writer.DataWriter} class.
 */
public class WriterUtils {

  /**
   * TABLENAME should be used for jobs that pull from multiple tables/topics and intend to write the records
   * in each table/topic to a separate folder. Otherwise, DEFAULT can be used.
   */
  public enum WriterFilePathType {
    TABLENAME,
    DEFAULT
  }

  /**
   * Get the {@link Path} corresponding the to the directory a given {@link gobblin.writer.DataWriter} should be writing
   * its staging data. The staging data directory is determined by combining the
   * {@link ConfigurationKeys#WRITER_STAGING_DIR} and the {@link ConfigurationKeys#WRITER_FILE_PATH}.
   * @param state is the {@link State} corresponding to a specific {@link gobblin.writer.DataWriter}.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {@link gobblin.writer.DataWriter} will write to.
   * @return a {@link Path} specifying the directory where the {@link gobblin.writer.DataWriter} will write to.
   */
  public static Path getWriterStagingDir(State state, int numBranches, int branchId) {
    String writerStagingDirKey = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_STAGING_DIR,
        numBranches, branchId);
    Preconditions.checkArgument(state.contains(writerStagingDirKey), "Missing required property " +
        writerStagingDirKey);

    return new Path(state.getProp(ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_STAGING_DIR,
        numBranches, branchId)), WriterUtils.getWriterFilePath(state, numBranches, branchId));
  }

  /**
   * Get the {@link Path} corresponding the to the directory a given {@link gobblin.writer.DataWriter} should be writing
   * its output data. The output data directory is determined by combining the
   * {@link ConfigurationKeys#WRITER_OUTPUT_DIR} and the {@link ConfigurationKeys#WRITER_FILE_PATH}.
   * @param state is the {@link State} corresponding to a specific {@link gobblin.writer.DataWriter}.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {@link gobblin.writer.DataWriter} will write to.
   * @return a {@link Path} specifying the directory where the {@link gobblin.writer.DataWriter} will write to.
   */
  public static Path getWriterOutputDir(State state, int numBranches, int branchId) {
    String writerOutputDirKey = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_OUTPUT_DIR,
        numBranches, branchId);
    Preconditions.checkArgument(state.contains(writerOutputDirKey), "Missing required property " +
        writerOutputDirKey);

    return new Path(state.getProp(ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_OUTPUT_DIR,
        numBranches, branchId)), WriterUtils.getWriterFilePath(state, numBranches, branchId));
  }

  /**
   * Get the {@link Path} corresponding the to the directory a given {@link gobblin.publisher.BaseDataPublisher} should
   * commits its output data. The final output data directory is determined by combining the
   * {@link ConfigurationKeys#DATA_PUBLISHER_FINAL_DIR} and the {@link ConfigurationKeys#WRITER_FILE_PATH}.
   * @param state is the {@link State} corresponding to a specific {@link gobblin.writer.DataWriter}.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {@link gobblin.publisher.BaseDataPublisher} will publish.
   * @return a {@link Path} specifying the directory where the {@link gobblin.publisher.BaseDataPublisher} will publish.
   */
  public static Path getDataPublisherFinalDir(State state, int numBranches, int branchId) {
    String dataPublisherFinalDirKey = ForkOperatorUtils.getPropertyNameForBranch(
        ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR, numBranches, branchId);
    Preconditions.checkArgument(state.contains(dataPublisherFinalDirKey), "Missing required property " +
        dataPublisherFinalDirKey);

    return new Path(state.getProp(ForkOperatorUtils.getPropertyNameForBranch(
        ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR, numBranches, branchId)), WriterUtils.getWriterFilePath(state,
        numBranches, branchId));
  }

  /**
   * Get the {@link Path} corresponding the the relative file path for a given {@link gobblin.writer.DataWriter}.
   * This method retrieves the value of {@link ConfigurationKeys#WRITER_FILE_PATH} from the given {@link State}. It also
   * constructs the default value of the {@link ConfigurationKeys#WRITER_FILE_PATH} if not is not specified in the given
   * {@link State}.
   * @param state is the {@link State} corresponding to a specific {@link gobblin.writer.DataWriter}.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {{@link gobblin.writer.DataWriter} will write to.
   * @return a {@link Path} specifying the relative directory where the {@link gobblin.writer.DataWriter} will write to.
   */
  public static Path getWriterFilePath(State state, int numBranches, int branchId) {
    if (state.contains(ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches,
        branchId))) {
      return new Path(state.getProp(ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH,
          numBranches, branchId)));
    }

    switch (getWriterFilePathType(state)) {
      case TABLENAME:
        return WriterUtils.getTableNameWriterFilePath(state);
      default:
        return WriterUtils.getDefaultWriterFilePath(state, numBranches, branchId);
    }
  }

  private static WriterFilePathType getWriterFilePathType(State state) {
    String pathTypeStr =
        state.getProp(ConfigurationKeys.WRITER_FILE_PATH_TYPE, ConfigurationKeys.DEFAULT_WRITER_FILE_PATH_TYPE);
    return WriterFilePathType.valueOf(pathTypeStr.toUpperCase());
  }

  /**
   * Creates {@link Path} for the {@link ConfigurationKeys#WRITER_FILE_PATH} key according to
   * {@link ConfigurationKeys#EXTRACT_TABLE_NAME_KEY}.
   * @param state
   * @return
   */
  public static Path getTableNameWriterFilePath(State state) {
    Preconditions.checkArgument(state.contains(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY));
    return new Path(state.getProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY));
  }

  /**
   * Creates the default {@link Path} for the {@link ConfigurationKeys#WRITER_FILE_PATH} key.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {@link gobblin.writer.DataWriter} will write to.
   * @return a {@link Path} specifying the directory where the {@link gobblin.writer.DataWriter} will write to.
   */
  public static Path getDefaultWriterFilePath(State state, int numBranches, int branchId) {
    if (state instanceof WorkUnitState) {
      WorkUnitState workUnitState = (WorkUnitState) state;
      return new Path(ForkOperatorUtils.getPathForBranch(workUnitState, workUnitState.getExtract().getOutputFilePath(),
          numBranches, branchId));

    } else if (state instanceof WorkUnit) {
      WorkUnit workUnit = (WorkUnit) state;
      return new Path(ForkOperatorUtils.getPathForBranch(workUnit, workUnit.getExtract().getOutputFilePath(),
          numBranches, branchId));
    }

    throw new RuntimeException("In order to get the default value for " + ConfigurationKeys.WRITER_FILE_PATH
        + " the given state must be of type " + WorkUnitState.class.getName() + " or " + WorkUnit.class.getName());
  }

  /**
   * Get the value of {@link ConfigurationKeys#WRITER_FILE_NAME} for the a given {@link gobblin.writer.DataWriter}. The
   * method also constructs the default value of the {@link ConfigurationKeys#WRITER_FILE_NAME} if it is not set in the
   * {@link State}
   * @param state is the {@link State} corresponding to a specific {@link gobblin.writer.DataWriter}.
   * @param numBranches is the total number of branches for the given {@link State}.
   * @param branchId is the id for the specific branch that the {{@link gobblin.writer.DataWriter} will write to.
   * @param writerId is the id for a specific {@link gobblin.writer.DataWriter}.
   * @param formatExtension is the format extension for the file (e.g. ".avro").
   * @return a {@link String} representation of the file name.
   */
  public static String getWriterFileName(State state, int numBranches, int branchId, String writerId,
      String formatExtension) {
    return state.getProp(
        ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_NAME, numBranches, branchId),
        String.format("%s.%s.%s", ConfigurationKeys.DEFAULT_WRITER_FILE_BASE_NAME, writerId, formatExtension));
  }

  /**
   * Set the following file attributes from a given State object
   * - WRITER_FILE_REPLICATION_FACTOR
   * - WRITER_FILE_PERMISSIONS
   * - WRITER_FILE_OWNER
   * - WRITER_FILE_GROUP
   *
   * @param properties The input state object from which the attributes are read from
   * @param fs The current Hadoop file system object
   * @param outputFile The output file into which these attributes are set into
   */
  public static void setFileAttributesFromState(final State properties,
                                                final FileSystem fs,
                                                final Path outputFile) throws IOException {
    if (properties.contains(ConfigurationKeys.WRITER_FILE_REPLICATION_FACTOR)) {
      fs.setReplication(outputFile, (short) properties.getPropAsInt(ConfigurationKeys.WRITER_FILE_REPLICATION_FACTOR));
    }
    if (properties.contains(ConfigurationKeys.WRITER_FILE_PERMISSIONS)) {
      final short permissions = (short) properties.getPropAsInt(ConfigurationKeys.WRITER_FILE_PERMISSIONS);
      fs.setPermission(outputFile, new FsPermission(permissions));
    }

    // If both owner and group is present. Only then, paste the ownership info on the file
    if (properties.contains(ConfigurationKeys.WRITER_FILE_OWNER) &&
        properties.contains(ConfigurationKeys.WRITER_FILE_GROUP)) {
      fs.setOwner(outputFile,
          properties.getProp(ConfigurationKeys.WRITER_FILE_OWNER),
          properties.getProp(ConfigurationKeys.WRITER_FILE_GROUP));
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chinesejoke"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light.NoActionBar" >
        <activity
            android:name="com.example.chinesejoke.activity.WelcomActivity"
            android:label="@string/title_activity_welcom"
            android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.chinesejoke.activity.MainActivity"
            android:label="@string/app_name" >

        </activity>
        <activity
            android:name="com.example.chinesejoke.activity.JokeDetailActivity"
            android:label="@string/title_activity_joke_detail" >
        </activity>

    </application>

</manifest>


text:
using content::BrowserThread;

namespace browser_sync {

class AndroidInvalidatorBridge::Core
    : public base::RefCountedThreadSafe<Core> {
 public:
  // Created on UI thread.
  explicit Core(
      const scoped_refptr<base::SequencedTaskRunner>& sync_task_runner);

  // All member functions below must be called on the sync task runner.

  void InitializeOnSyncThread();
  void CleanupOnSyncThread();

  void RegisterHandler(syncer::InvalidationHandler* handler);
  void UpdateRegisteredIds(syncer::InvalidationHandler* handler,
                           const syncer::ObjectIdSet& ids);
  void UnregisterHandler(syncer::InvalidationHandler* handler);

  void EmitInvalidation(
      const syncer::ObjectIdInvalidationMap& invalidation_map);

  bool IsHandlerRegisteredForTest(syncer::InvalidationHandler* handler) const;
  syncer::ObjectIdSet GetRegisteredIdsForTest(
      syncer::InvalidationHandler* handler) const;

 private:
  friend class base::RefCountedThreadSafe<Core>;

  // Destroyed on the UI thread or on |sync_task_runner_|.
  ~Core();

  const scoped_refptr<base::SequencedTaskRunner> sync_task_runner_;

  // Used only on |sync_task_runner_|.
  scoped_ptr<syncer::InvalidatorRegistrar> invalidator_registrar_;
};

AndroidInvalidatorBridge::Core::Core(
    const scoped_refptr<base::SequencedTaskRunner>& sync_task_runner)
    : sync_task_runner_(sync_task_runner) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(sync_task_runner_.get());
}

AndroidInvalidatorBridge::Core::~Core() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
         sync_task_runner_->RunsTasksOnCurrentThread());
  DCHECK(!invalidator_registrar_.get());
}

void AndroidInvalidatorBridge::Core::InitializeOnSyncThread() {
  invalidator_registrar_.reset(new syncer::InvalidatorRegistrar());
}

void AndroidInvalidatorBridge::Core::CleanupOnSyncThread() {
  invalidator_registrar_.reset();
}

void AndroidInvalidatorBridge::Core::RegisterHandler(
    syncer::InvalidationHandler* handler) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  invalidator_registrar_->RegisterHandler(handler);
}

void AndroidInvalidatorBridge::Core::UpdateRegisteredIds(
    syncer::InvalidationHandler* handler,
    const syncer::ObjectIdSet& ids) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  invalidator_registrar_->UpdateRegisteredIds(handler, ids);
}

void AndroidInvalidatorBridge::Core::UnregisterHandler(
    syncer::InvalidationHandler* handler) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  invalidator_registrar_->UnregisterHandler(handler);
}

void AndroidInvalidatorBridge::Core::EmitInvalidation(
    const syncer::ObjectIdInvalidationMap& invalidation_map) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  const syncer::ObjectIdInvalidationMap& effective_invalidation_map =
      invalidation_map.empty() ?
      ObjectIdSetToInvalidationMap(
          invalidator_registrar_->GetAllRegisteredIds(), std::string()) :
      invalidation_map;

  invalidator_registrar_->DispatchInvalidationsToHandlers(
      effective_invalidation_map);
}

bool AndroidInvalidatorBridge::Core::IsHandlerRegisteredForTest(
    syncer::InvalidationHandler* handler) const {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  return invalidator_registrar_->IsHandlerRegisteredForTest(handler);
}

syncer::ObjectIdSet
AndroidInvalidatorBridge::Core::GetRegisteredIdsForTest(
    syncer::InvalidationHandler* handler) const {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  return invalidator_registrar_->GetRegisteredIds(handler);
}

AndroidInvalidatorBridge::AndroidInvalidatorBridge(
    const Profile* profile,
    const scoped_refptr<base::SequencedTaskRunner>& sync_task_runner)
    : sync_task_runner_(sync_task_runner),
      core_(new Core(sync_task_runner_)) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(profile);
  registrar_.Add(this, chrome::NOTIFICATION_SYNC_REFRESH_REMOTE,
                 content::Source<Profile>(profile));

  if (!sync_task_runner_->PostTask(
          FROM_HERE, base::Bind(&Core::InitializeOnSyncThread, core_))) {
    NOTREACHED();
  }
}

AndroidInvalidatorBridge::~AndroidInvalidatorBridge() {}

void AndroidInvalidatorBridge::StopForShutdown() {
  if (!sync_task_runner_->PostTask(
          FROM_HERE, base::Bind(&Core::CleanupOnSyncThread, core_))) {
    NOTREACHED();
  }
}

void AndroidInvalidatorBridge::RegisterHandler(
    syncer::InvalidationHandler* handler) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  core_->RegisterHandler(handler);
}

void AndroidInvalidatorBridge::UpdateRegisteredIds(
    syncer::InvalidationHandler* handler,
    const syncer::ObjectIdSet& ids) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  core_->UpdateRegisteredIds(handler, ids);
}

void AndroidInvalidatorBridge::UnregisterHandler(
    syncer::InvalidationHandler* handler) {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  core_->UnregisterHandler(handler);
}

void AndroidInvalidatorBridge::Acknowledge(
    const invalidation::ObjectId& id, const syncer::AckHandle& ack_handle) {
  // Do nothing.
}

syncer::InvalidatorState AndroidInvalidatorBridge::GetInvalidatorState() const {
  return syncer::INVALIDATIONS_ENABLED;
}

void AndroidInvalidatorBridge::UpdateCredentials(
    const std::string& email, const std::string& token) { }

void AndroidInvalidatorBridge::SendInvalidation(
    const syncer::ObjectIdInvalidationMap& invalidation_map) { }

bool AndroidInvalidatorBridge::IsHandlerRegisteredForTest(
    syncer::InvalidationHandler* handler) const {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  return core_->IsHandlerRegisteredForTest(handler);
}

syncer::ObjectIdSet AndroidInvalidatorBridge::GetRegisteredIdsForTest(
    syncer::InvalidationHandler* handler) const {
  DCHECK(sync_task_runner_->RunsTasksOnCurrentThread());
  return core_->GetRegisteredIdsForTest(handler);
}

void AndroidInvalidatorBridge::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_EQ(type, chrome::NOTIFICATION_SYNC_REFRESH_REMOTE);

  // TODO(akalin): Use ObjectIdInvalidationMap here instead.  We'll have to
  // make sure all emitters of the relevant notifications also use
  // ObjectIdInvalidationMap.
  content::Details<const syncer::ModelTypeInvalidationMap>
      state_details(details);
  const syncer::ModelTypeInvalidationMap& invalidation_map =
      *(state_details.ptr());
  if (!sync_task_runner_->PostTask(
          FROM_HERE,
          base::Bind(&Core::EmitInvalidation,
                     core_,
                     ModelTypeInvalidationMapToObjectIdInvalidationMap(
                         invalidation_map)))) {
    NOTREACHED();
  }
}

}  // namespace browser_sync


text:
<resourcesDefinition xmlns="http://thotti/ec2/configuration/1.0"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://thotti/ec2/configuration/1.0
                                         ../../../../../main/resources/schemas/ec2-configuration-v1.xsd"
                     version="1">

    <!-- missing onShutdown attribute -->
    <region availibleZone="default" name="region">
        <serverRequest amiID="amazonMachineImageID0001"
                       instanceType="oneInstanceType"
                       keyPair="aArbitraryKeyPairName"
                       maxInstances="1"
                       minInstances="1"
                />
    </region>

</resourcesDefinition>


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

cr.define('print_preview', function() {
  'use strict';

  /**
   * Capabilities of a cloud-based print destination.
   * @param {print_preview.CollateCapability} collateCapability Print
   *     destination collate capability.
   * @param {print_preview.ColorCapability} colorCapability Print destination
   *     color capability.
   * @param {print_preview.CopiesCapability} copiesCapability Print destination
   *     copies capability.
   * @param {print_preview.DuplexCapability} duplexCapability Print destination
   *     duplexing capability.
   * @constructor
   * @extends {print_preview.ChromiumCapabilities}
   */
  function CloudCapabilities(
      collateCapability, colorCapability, copiesCapability, duplexCapability) {
    print_preview.ChromiumCapabilities.call(
        this,
        !!copiesCapability,
        '1' /*defaultCopiesStr*/,
        !!collateCapability,
        !!collateCapability && collateCapability.isCollateDefault,
        !!duplexCapability,
        !!duplexCapability && duplexCapability.isDuplexDefault,
        true /*hasOrientationCapability*/,
        false /*defaultIsLandscapeEnabled*/,
        !!colorCapability,
        !!colorCapability && colorCapability.isColorDefault);

    /**
     * Print destination collate capability.
     * @type {print_preview.CollateCapability}
     * @private
     */
    this.collateCapability_ = collateCapability;

    /**
     * Print destination color capability.
     * @type {print_preview.ColorCapability}
     * @private
     */
    this.colorCapability_ = colorCapability;

    /**
     * Print destination copies capability.
     * @type {print_preview.CopiesCapability}
     * @private
     */
    this.copiesCapability_ = copiesCapability;

    /**
     * Print destination duplexing capability.
     * @type {print_preview.DuplexCapability}
     * @private
     */
    this.duplexCapability_ = duplexCapability;
  };

  /**
   * Enumeration of the capability formats of cloud-based print destinations.
   * @enum {string}
   */
  CloudCapabilities.Format = {
    HP: 'hp',
    PPD: 'ppd',
    XPS: 'xps'
  };

  CloudCapabilities.prototype = {
    __proto__: print_preview.ChromiumCapabilities.prototype,

    /**
     * @return {print_preview.CollateCapability} The print destination's collate
     *     capability.
     */
    get collateCapability() {
      return this.collateCapability_;
    },

    /**
     * @return {print_preview.CollateCapability} The print destination's color
     *     capability.
     */
    get colorCapability() {
      return this.colorCapability_;
    },

    /**
     * @return {print_preview.CollateCapability} The print destination's copies
     *     capability.
     */
    get copiesCapability() {
      return this.copiesCapability_;
    },

    /**
     * @return {print_preview.CollateCapability} The print destination's
     *     duplexing capability.
     */
    get duplexCapability() {
      return this.duplexCapability_;
    }
  };

  /**
   * A single print capability of a cloud-based print destination.
   * @param {string} id Identifier of the capability.
   * @param {!print_preview.CloudCapability.Type} type Type of the capability.
   * @constructor
   */
  function CloudCapability(id, type) {
    /**
     * Identifier of the capability.
     * @type {string}
     * @private
     */
    this.id_ = id;

    /**
     * Type of the capability.
     * @type {!print_preview.CloudCapability.Type}
     * @private
     */
    this.type_ = type;
  };

  /**
   * Enumeration of the types of cloud-based print capabilities.
   * @enum {string}
   */
  CloudCapability.Type = {
    FEATURE: 'Feature',
    PARAMETER_DEF: 'ParameterDef'
  };

  CloudCapability.prototype = {
    /** @return {string} Identifier of the capability. */
    get id() {
      return this.id_;
    },

    /** @return {!print_preview.CloudCapability.Type} Type of the capability. */
    get type() {
      return this.type_;
    }
  };

  /**
   * Cloud-based collate capability.
   * @param {string} id Identifier of the collate capability.
   * @param {string} collateOption Identifier of the option that enables
   *     collation.
   * @param {string} noCollateOption Identifier of the option that disables
   *     collation.
   * @param {boolean} isCollateDefault Whether collation is enabled by default.
   * @constructor
   * @extends {print_preview.CloudCapability}
   */
  function CollateCapability(
      id, collateOption, noCollateOption, isCollateDefault) {
    CloudCapability.call(this, id, CloudCapability.Type.FEATURE);

    /**
     * Identifier of the option that enables collation.
     * @type {string}
     * @private
     */
    this.collateOption_ = collateOption;

    /**
     * Identifier of the option that disables collation.
     * @type {string}
     * @private
     */
    this.noCollateOption_ = noCollateOption;

    /**
     * Whether collation is enabled by default.
     * @type {boolean}
     * @private
     */
    this.isCollateDefault_ = isCollateDefault;
  };

  /**
   * Mapping of capability formats to an identifier of the collate capability.
   * @type {!Object.<!CloudCapabilities.Format, string>}
   */
  CollateCapability.Id = {};
  CollateCapability.Id[CloudCapabilities.Format.PPD] = 'Collate';
  CollateCapability.Id[CloudCapabilities.Format.XPS] = 'psk:DocumentCollate';

  /**
   * Regular expression that matches a collate option.
   * @type {!RegExp}
   * @const
   */
  CollateCapability.COLLATE_REGEX = /(.*:collated.*|true)/i;

  /**
   * Regular expression that matches a no-collate option.
   * @type {!RegExp}
   * @const
   */
  CollateCapability.NO_COLLATE_REGEX = /(.*:uncollated.*|false)/i;

  CollateCapability.prototype = {
    __proto__: CloudCapability.prototype,

    /** @return {string} Identifier of the option that enables collation. */
    get collateOption() {
      return this.collateOption_;
    },

    /** @return {string} Identifier of the option that disables collation. */
    get noCollateOption() {
      return this.noCollateOption_;
    },

    /** @return {boolean} Whether collation is enabled by default. */
    get isCollateDefault() {
      return this.isCollateDefault_;
    }
  };

  /**
   * Cloud-based color print capability.
   * @param {string} id Identifier of the color capability.
   * @param {string} colorOption Identifier of the color option.
   * @param {string} bwOption Identifier of the black-white option.
   * @param {boolean} Whether color printing is enabled by default.
   * @constructor
   */
  function ColorCapability(id, colorOption, bwOption, isColorDefault) {
    CloudCapability.call(this, id, CloudCapability.Type.FEATURE);

    /**
     * Identifier of the color option.
     * @type {string}
     * @private
     */
    this.colorOption_ = colorOption;

    /**
     * Identifier of the black-white option.
     * @type {string}
     * @private
     */
    this.bwOption_ = bwOption;

    /**
     * Whether to print in color by default.
     * @type {boolean}
     * @private
     */
    this.isColorDefault_ = isColorDefault;
  };

  /**
   * Mapping of capability formats to an identifier of the color capability.
   * @type {!Object.<!CloudCapabilities.Format, string>}
   */
  ColorCapability.Id = {};
  ColorCapability.Id[CloudCapabilities.Format.HP] = 'ns1:Colors';
  ColorCapability.Id[CloudCapabilities.Format.PPD] = 'ColorModel';
  ColorCapability.Id[CloudCapabilities.Format.XPS] = 'psk:PageOutputColor';

  /**
   * Regular expression that matches a color option.
   * @type {!RegExp}
   * @const
   */
  ColorCapability.COLOR_REGEX = /(.*color.*|.*rgb.*|.*cmy.*|true)/i;

  /**
   * Regular expression that matches a black-white option.
   * @type {!RegExp}
   * @const
   */
  ColorCapability.BW_REGEX = /(.*gray.*|.*mono.*|.*black.*|false)/i;

  ColorCapability.prototype = {
    __proto__: CloudCapability.prototype,

    /** @return {string} Identifier of the color option. */
    get colorOption() {
      return this.colorOption_;
    },

    /** @return {string} Identifier of the black-white option. */
    get bwOption() {
      return this.bwOption_;
    },

    /** @return {boolean} Whether to print in color by default. */
    get isColorDefault() {
      return this.isColorDefault_;
    }
  };

  /**
   * Cloud-based copies print capability.
   * @param {string} id Identifier of the copies capability.
   * @constructor
   */
  function CopiesCapability(id) {
    CloudCapability.call(this, id, CloudCapability.Type.PARAMETER_DEF);
  };

  CopiesCapability.prototype = {
    __proto__: CloudCapability.prototype
  };

  /**
   * Mapping of capability formats to an identifier of the copies capability.
   * @type {!Object.<!CloudCapabilities.Format, string>}
   */
  CopiesCapability.Id = {};
  CopiesCapability.Id[CloudCapabilities.Format.XPS] =
      'psk:JobCopiesAllDocuments';

  /**
   * Cloud-based duplex print capability.
   * @param {string} id Identifier of the duplex capability.
   * @param {string} simplexOption Identifier of the no-duplexing option.
   * @param {string} longEdgeOption Identifier of the duplex on long edge
   *     option.
   * @param {boolean} Whether duplexing is enabled by default.
   * @constructor
   */
  function DuplexCapability(
      id, simplexOption, longEdgeOption, isDuplexDefault) {
    CloudCapability.call(this, id, CloudCapability.Type.FEATURE);

    /**
     * Identifier of the no-duplexing option.
     * @type {string}
     * @private
     */
    this.simplexOption_ = simplexOption;

    /**
     * Identifier of the duplex on long edge option.
     * @type {string}
     * @private
     */
    this.longEdgeOption_ = longEdgeOption;

    /**
     * Whether duplexing is enabled by default.
     * @type {boolean}
     * @private
     */
    this.isDuplexDefault_ = isDuplexDefault;
  };

  /**
   * Mapping of capability formats to an identifier of the duplex capability.
   * @type {!Object.<!CloudCapabilities.Format, string>}
   */
  DuplexCapability.Id = {};
  DuplexCapability.Id[CloudCapabilities.Format.PPD] = 'Duplex';
  DuplexCapability.Id[CloudCapabilities.Format.XPS] =
      'psk:JobDuplexAllDocumentsContiguously';

  /**
   * Regular expression that matches a no-duplexing option.
   * @type {!RegExp}
   * @const
   */
  DuplexCapability.SIMPLEX_REGEX = /(.*onesided.*|.*none.*)/i;

  /**
   * Regular expression that matches a duplex on long edge option.
   * @type {!RegExp}
   * @const
   */
  DuplexCapability.LONG_EDGE_REGEX = /(.*longedge.*|duplexNoTumble)/i;

  DuplexCapability.prototype = {
    __proto__: CloudCapability.prototype,

    /** @return {string} Identifier of the no-duplexing option. */
    get simplexOption() {
      return this.simplexOption_;
    },

    /** @return {string} Identifier of the duplex on long edge option. */
    get longEdgeOption() {
      return this.longEdgeOption_;
    },

    /** @return {boolean} Whether duplexing is enabled by default. */
    get isDuplexDefault() {
      return this.isDuplexDefault_;
    }
  };

  // Export
  return {
    CloudCapabilities: CloudCapabilities,
    CollateCapability: CollateCapability,
    ColorCapability: ColorCapability,
    CopiesCapability: CopiesCapability,
    DuplexCapability: DuplexCapability
  };
});


text:
  <form id="<[inputFieldFormId]>">
    <input type="file"
           ng-class="inputFieldClassName"
           class="protractor-test-upload-audio-input">
  </form>

    Please only upload audio files that you created yourself and that you are willing to license under the site's
    license terms.
    Audio translation files should be less than five minutes long.

    
    <[errorMessage]>


text:
**Polymer** behavior. Use `<x-bem-behavior>` to quickly compute BEM classnames.

```html
<div class$="{{bemClass('block-name')}}">
Default block text is black.

  <div class$="{{bemClass('block-name', 'element-name')}}">
    Block children text is blue.
  </div>
</div>

<div class$="{{bemClass('block-name', '', 'modifier')}}">
Special block text is green.
</div>
```

##Install

`bower install --save x-bem-behavior`


text:
namespace clempaul.Dreamhost.ResponseData
{
    public class Domain
    {
        #region Private Variables

        private string _account_id = string.Empty;
        private string _domain = string.Empty;
        private string _home = string.Empty;
        private string _type = string.Empty;
        private string _unique_ip = string.Empty;
        private string _hosting_type = string.Empty;
        private string _user = string.Empty;
        private string _path = string.Empty;
        private string _outside_url = string.Empty;
        private string _www_or_not = string.Empty;
        private string _php = string.Empty;
        private bool _security = false;
        private bool _fastcgi = false;
        private bool _xcache = false;
        private bool _php_fcgid = false;
        private bool _passenger = false;

        #endregion

        #region Accessors

        public string account_id
        {
            get { return this._account_id; }
            set { this._account_id = value; }
        }

        public string domain
        {
            get { return this._domain; }
            set { this._domain = value; }
        }

        public string home
        {
            get { return this._home; }
            set { this._home = value; }
        }

        public string type
        {
            get { return this._type; }
            set { this._type = value; }
        }

        public string unique_ip
        {
            get { return this._unique_ip; }
            set { this._unique_ip = value; }
        }

        public string user
        {
            get { return this._user; }
            set { this._user = value; }
        }

        public string path
        {
            get { return this._path; }
            set { this._path = value; }
        }

        public string outside_url
        {
            get { return this._outside_url; }
            set { this._outside_url = value; }
        }

        public string hosting_type
        {
            get { return this._hosting_type; }
            set { this._hosting_type = value; }
        }

        public string www_or_not
        {
            get { return this._www_or_not; }
            set { this._www_or_not = value; }
        }

        public string php
        {
            get { return this._php; }
            set { this._php = value; }
        }

        public bool security
        {
            get { return this._security; }
            set { this._security = value; }
        }

        public bool fastcgi
        {
            get { return this._fastcgi; }
            set { this._fastcgi = value; }
        }

        public bool xcache
        {
            get { return this._xcache; }
            set { this._xcache = value; }
        }

        public bool php_fcgid
        {
            get { return this._php_fcgid; }
            set { this._php_fcgid = value; }
        }

        public bool passenger
        {
            get { return this._passenger; }
            set { this._passenger = value; }
        }

        #endregion

    }
}


text:
package iri;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class JLCGetFields extends FormattingHelper {

	public String run() throws Exception {
		Method m = Class.class.getMethod("getFields");
		Field[] fs = (Field[]) m.invoke(JLCGetFields.class);
		return format(fs);
	}

	String aString;

}


text:
package at.ac.tuwien.photohawk.evaluation.preprocessing;

import at.ac.tuwien.photohawk.evaluation.BufferedImageHelper;
import org.junit.Assert;
import org.junit.Test;

import java.awt.Color;
import java.awt.image.BufferedImage;

/**
 * Unit tests for ResizePreprocessor.
 */
public class ResizePreprocessorTest {

    @Test
    public void executeTest_equalSize() {
        BufferedImage img1 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        BufferedImage img2 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        ResizePreprocessor pp = new ResizePreprocessor(img1, img2, BufferedImageHelper.DEFAULT_WIDTH,
                                                       BufferedImageHelper.DEFAULT_HEIGHT);
        pp.process();

        Assert.assertEquals(img1, pp.getResult1());
        Assert.assertEquals(img2, pp.getResult2());
    }

    @Test
    public void executeTest_ltWidth_ltHeight() {
        BufferedImage img1 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        BufferedImage img2 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        ResizePreprocessor pp = new ResizePreprocessor(img1, img2, 100, 300);
        pp.process();

        Assert.assertEquals(100, pp.getResult1().getWidth());
        Assert.assertEquals(300, pp.getResult1().getHeight());
        Assert.assertEquals(100, pp.getResult2().getWidth());
        Assert.assertEquals(300, pp.getResult2().getHeight());
    }

    @Test
    public void executeTest_gtWidth_gtHeight() {
        BufferedImage img1 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        BufferedImage img2 = BufferedImageHelper.createSolidImage(new Color(0, 0, 0));
        ResizePreprocessor pp = new ResizePreprocessor(img1, img2, 600, 700);
        pp.process();

        Assert.assertEquals(600, pp.getResult1().getWidth());
        Assert.assertEquals(700, pp.getResult1().getHeight());
        Assert.assertEquals(600, pp.getResult2().getWidth());
        Assert.assertEquals(700, pp.getResult2().getHeight());
    }
}


text:
package projektkurs.simulation.pacman.entity;

import projektkurs.render.Screen;
import projektkurs.simulation.pacman.PacmanBoard;
import projektkurs.util.IHasPositionAndSize;
import projektkurs.util.IUpdatable;
import projektkurs.util.MathUtil;

public abstract class PacmanEntity implements IUpdatable, IHasPositionAndSize<Double, Double> {

    private boolean isDead = false;
    protected PacmanBoard board;
    protected double sizeX;
    protected double sizeY;
    protected double x, y;

    public PacmanEntity(PacmanBoard board, double x, double y, double sizeX, double sizeY) {
        this.board = board;
        this.x = x;
        this.y = y;
        this.sizeX = sizeX;
        this.sizeY = sizeY;
    }

    @Override
    public boolean canUpdate() {
        return false;
    }

    @Override
    public Double getPosX() {
        return x;
    }

    @Override
    public Double getPosY() {
        return y;
    }

    @Override
    public Double getSizeX() {
        return sizeX;
    }

    @Override
    public Double getSizeY() {
        return sizeY;
    }

    public boolean isDead() {
        return isDead;
    }

    public boolean isInside(double x, double y, double sizeX, double sizeY) {
        return MathUtil.isInside(this.x, this.y, this.sizeX, this.sizeY, x, y, sizeX, sizeY);
    }

    public void move(double dx, double dy) {
        x += dx;
        y += dy;
    }

    public void onCollide(PacmanEntity e) {
        // NO-OP
    }

    public void onDeath() {
        // NO-OP
    }

    public abstract void render(Screen screen, int offsetX, int offsetY);

    public void setDead() {
        isDead = true;
        onDeath();
    }

    @Override
    public void setPosition(Double x, Double y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void setSize(Double sizeX, Double sizeY) {
        this.sizeX = sizeX;
        this.sizeY = sizeY;
    }

    @Override
    public void update() {
        // NO-OP
    }

}


text:
'''
Created on Dec 11, 2014

@author: Max
'''
import amo.core.physicalconstants
import amo.core.polylog
import numpy as np
import scipy.optimize
c = amo.core.physicalconstants.PhysicalConstantsSI

class fermigasharmonic(object):
    def __init__(self, temperature, frequencies, mass, atom_number):
        self.temperature = temperature
        self.beta = 1.0 / (c.kb * temperature)
        self.frequencies = frequencies
        self.fbar = np.product(frequencies) ** (1.0 / 3.0)
        self.mass = mass
        self.atom_number

    def trap(self, r):
        return 0.5 * self.mass * np.dot(np.square(2.0 * np.pi * self.frequencies), np.square(r))

    @property
    def mu(self):
        def root_fun(mu):
            self.atom_number / (c.h * self.fbar / (c.kb * self.temperature))**3 +\

        scipy.optimize.root


text:
void BindReflectionFoundation()
{
	BIND_REFLECTION(IObject);
}

//------------------------------------------------------------------------------


text:
class AfpShareService < ShareService
  service_name :netatalk

  def update!
    if AfpServiceConfiguration.update
      restart # supplied by base class
    end
  end
end


text:
namespace FakeItEasy.Specs
{
    using System;
    using FluentAssertions;
    using Xbehave;

    public static class DummyFactorySpecs
    {
        [Scenario]
        public static void DummyFactoryUsage(
            RobotActivatedEvent dummy)
        {
            "when a dummy factory is defined for a set of types"
                .x(() => dummy = A.Dummy<RobotActivatedEvent>());

            "it should create a dummy from the factory"
                .x(() => dummy.ID.Should().BeGreaterThan(0));
        }

        [Scenario]
        public static void DummyFactoryPriority(
            RobotRunsAmokEvent dummy)
        {
            "when two dummy factories apply to the same type"
                .x(() => dummy = A.Dummy<RobotRunsAmokEvent>());

            "it should use the one with higher priority"
                .x(() => dummy.ID.Should().Be(-17));
        }
    }

    public class DomainEventDummyFactory : IDummyFactory
    {
        private int nextID = 1;

        public int Priority
        {
            get { return -3; }
        }

        public bool CanCreate(Type type)
        {
            return typeof(DomainEvent).IsAssignableFrom(type);
        }

        public object Create(Type type)
        {
            var dummy = (DomainEvent)Activator.CreateInstance(type);
            dummy.ID = this.nextID++;
            return dummy;
        }
    }

    public class RobotRunsAmokEventDummyFactory : DummyFactory<RobotRunsAmokEvent>
    {
        protected override RobotRunsAmokEvent Create()
        {
            return new RobotRunsAmokEvent { ID = -17 };
        }
    }
}


text:
function updatePageAgain() {
	var currUrl = window.location.href;
	var pdfUrl = '';
	if (currUrl.indexOf('sciencedirect') !== -1) {
		//pdfUrl = document.getElementById('pdfLink').href;
	}
	else if (currUrl.indexOf('wiley') !== -1) {
		//pdfUrl = document.getElementById('journalToolsPdfLink').href;
		pdfUrl = document.getElementById('pdfDocument').src;
	}
	else if (currUrl.indexOf('rsc.org') !== -1) {
		//pdfUrl = currUrl.replace('articlelanding','articlepdf');
	}
	else if (currUrl.indexOf('acs.org') !== -1) {
		//pdfUrl = document.getElementsByClassName('icon-item pdf-high-res')[0].firstChild.href;
	}
	if (pdfUrl !== '') {
		window.location.href = pdfUrl;
	}
	else {
		// Stay on current page
	}
}
updatePageAgain();


text:
package com.microsoft.spring.data.gremlin.conversion.source;

import com.microsoft.spring.data.gremlin.common.Constants;
import com.microsoft.spring.data.gremlin.mapping.GremlinPersistentProperty;
import com.microsoft.spring.data.gremlin.conversion.MappingGremlinConverter;
import com.microsoft.spring.data.gremlin.exception.GremlinEntityInformationException;
import com.microsoft.spring.data.gremlin.exception.GremlinUnexpectedSourceTypeException;
import com.microsoft.spring.data.gremlin.mapping.GremlinPersistentEntity;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.model.ConvertingPropertyAccessor;
import org.springframework.lang.NonNull;

import java.lang.reflect.Field;

public class GremlinSourceVertexWriter<T> implements GremlinSourceWriter<T> {

    @Override
    @SuppressWarnings("unchecked")
    public void write(@NonNull Object domain, @NonNull MappingGremlinConverter converter,
                      @NonNull GremlinSource<T> source) {
        if (!(source instanceof GremlinSourceVertex)) {
            throw new GremlinUnexpectedSourceTypeException("should be the instance of GremlinSourceVertex");
        }

        source.setId(converter.getIdFieldValue(domain));

        final GremlinPersistentEntity<?> persistentEntity = converter.getPersistentEntity(domain.getClass());
        final ConvertingPropertyAccessor<T> accessor = (ConvertingPropertyAccessor<T>) converter.getPropertyAccessor(domain);

        for (final Field field : FieldUtils.getAllFields(domain.getClass())) {
            final PersistentProperty<GremlinPersistentProperty> property = persistentEntity.getPersistentProperty(field.getName());
            if (property == null) {
                continue;
            }

            if (field.getName().equals(Constants.PROPERTY_ID) || field.getAnnotation(Id.class) != null) {
                continue;
            } else if (field.getName().equals(Constants.GREMLIN_PROPERTY_CLASSNAME)) {
                throw new GremlinEntityInformationException("Domain Cannot use pre-defined field name: "
                        + Constants.GREMLIN_PROPERTY_CLASSNAME);
            }

            source.setProperty(field.getName(), accessor.getProperty(property));
        }
    }
}


text:
for class in $(find . -name '*Repository.class' -print); do
    # Replace /'s with .'s
    class=${class//\//.};
    echo "${class//.class/}";
    # javap
    javap -classpath "$jar" "${class//.class/}";
done


text: """Interesting (non-cryptographic) hashes implemented in pure Python."""


text:
package de.trewys.data.access;

import java.sql.ResultSet;

import de.trewys.data.GenericDataObject;

public class GenericDataReader extends DataReader<GenericDataObject> {

	private String[] columns;

	public GenericDataReader(String[] columns) {
		this.columns = columns;
	}

	@Override
	public GenericDataObject read(ResultSet rs) throws Exception {
		GenericDataObject dataObject = new GenericDataObject();

		dataObject.setId(readLong(rs, "id"));

		for (String column : columns) {
			dataObject.setValue(column, rs.getObject(column));
		}

		return dataObject;
	}

}


text:
package net.spals.appbuilder.app.examples.grpc.sample;

/**
 * A multi service definition for {@link SampleGrpcWebApp}
 *
 * @author tkral
 */
public interface SampleGrpcCustomSet {  }