text:
#ifndef PyMPI_COMPAT_OPENMPI_H
#define PyMPI_COMPAT_OPENMPI_H

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

/*
 * The hackery below redefines the actuall calls to 'MPI_Init()' and
 * 'MPI_Init_thread()' in order to preload the main MPI dynamic
 * library with appropriate flags to 'dlopen()' ensuring global
 * availability of library symbols.
 */

#if !defined(OPENMPI_DLOPEN_LIBMPI) && defined(OMPI_MAJOR_VERSION)
#if OMPI_MAJOR_VERSION >= 3 && OMPI_MAJOR_VERSION < 10
#define OPENMPI_DLOPEN_LIBMPI 0
#endif
#endif

#ifndef OPENMPI_DLOPEN_LIBMPI
#define OPENMPI_DLOPEN_LIBMPI 1
#endif

#if OPENMPI_DLOPEN_LIBMPI
#if HAVE_DLOPEN

#include "../dynload.h"

/*
static void * my_dlopen(const char *name, int mode) {
  void *handle;
  static int called = 0;
  if (!called) {
    called = 1;
    #if HAVE_DLFCN_H
    printf("HAVE_DLFCN_H: yes\n");
    #else
    printf("HAVE_DLFCN_H: no\n");
    #endif
    printf("\n");
    printf("RTLD_LAZY:    0x%X\n", RTLD_LAZY   );
    printf("RTLD_NOW:     0x%X\n", RTLD_NOW    );
    printf("RTLD_LOCAL:   0x%X\n", RTLD_LOCAL  );
    printf("RTLD_GLOBAL:  0x%X\n", RTLD_GLOBAL );
    #ifdef RTLD_NOLOAD
    printf("RTLD_NOLOAD:  0x%X\n", RTLD_NOLOAD );
    #endif
    printf("\n");
  }
  handle = dlopen(name, mode);
  printf("dlopen(\"%s\",0x%X) -> %p\n", name, mode, handle);
  printf("dlerror() -> %s\n\n", dlerror());
  return handle;
}
#define dlopen my_dlopen
*/

static void PyMPI_OPENMPI_dlopen_libmpi(void)
{
  void *handle = 0;
  int mode = RTLD_NOW | RTLD_GLOBAL;
#if defined(__APPLE__)
  /* macOS */
  #ifdef RTLD_NOLOAD
  mode |= RTLD_NOLOAD;
  #endif
  #if defined(OMPI_MAJOR_VERSION)
  #if   OMPI_MAJOR_VERSION >= 4
  if (!handle) handle = dlopen("libmpi.40.dylib", mode);
  #elif OMPI_MAJOR_VERSION == 3
  if (!handle) handle = dlopen("libmpi.40.dylib", mode);
  #elif OMPI_MAJOR_VERSION == 2
  if (!handle) handle = dlopen("libmpi.20.dylib", mode);
  #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 10
  if (!handle) handle = dlopen("libmpi.12.dylib", mode);
  #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 6
  if (!handle) handle = dlopen("libmpi.1.dylib", mode);
  #elif OMPI_MAJOR_VERSION == 1
  if (!handle) handle = dlopen("libmpi.0.dylib", mode);
  #endif
  #endif
  if (!handle) handle = dlopen("libmpi.dylib", mode);
#else
  /* GNU/Linux and others */
  #ifdef RTLD_NOLOAD
  mode |= RTLD_NOLOAD;
  #endif
  #if defined(OMPI_MAJOR_VERSION)
  #if OMPI_MAJOR_VERSION >= 10 /* IBM Spectrum MPI */
  if (!handle) handle = dlopen("libmpi_ibm.so.2", mode);
  if (!handle) handle = dlopen("libmpi_ibm.so.1", mode);
  if (!handle) handle = dlopen("libmpi_ibm.so", mode);
  #elif OMPI_MAJOR_VERSION >= 4
  if (!handle) handle = dlopen("libmpi.so.40", mode);
  #elif OMPI_MAJOR_VERSION == 3
  if (!handle) handle = dlopen("libmpi.so.40", mode);
  #elif OMPI_MAJOR_VERSION == 2
  if (!handle) handle = dlopen("libmpi.so.20", mode);
  #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 10
  if (!handle) handle = dlopen("libmpi.so.12", mode);
  #elif OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION >= 6
  if (!handle) handle = dlopen("libmpi.so.1", mode);
  #elif OMPI_MAJOR_VERSION == 1
  if (!handle) handle = dlopen("libmpi.so.0", mode);
  #endif
  #endif
  if (!handle) handle = dlopen("libmpi.so", mode);
#endif
}

static int PyMPI_OPENMPI_MPI_Init(int *argc, char ***argv)
{
  PyMPI_OPENMPI_dlopen_libmpi();
  return MPI_Init(argc, argv);
}
#undef  MPI_Init
#define MPI_Init PyMPI_OPENMPI_MPI_Init

static int PyMPI_OPENMPI_MPI_Init_thread(int *argc, char ***argv,
                                         int required, int *provided)
{
  PyMPI_OPENMPI_dlopen_libmpi();
  return MPI_Init_thread(argc, argv, required, provided);
}
#undef  MPI_Init_thread
#define MPI_Init_thread PyMPI_OPENMPI_MPI_Init_thread

#endif /* !HAVE_DLOPEN */
#endif /* !OPENMPI_DLOPEN_LIBMPI */

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

/* ------------------------------------------------------------------------- */

#if (defined(OMPI_MAJOR_VERSION) && \
     defined(OMPI_MINOR_VERSION) && \
     defined(OMPI_RELEASE_VERSION))
#define PyMPI_OPENMPI_VERSION ((OMPI_MAJOR_VERSION   * 10000) + \
                               (OMPI_MINOR_VERSION   * 100)   + \
                               (OMPI_RELEASE_VERSION * 1))
#else
#define PyMPI_OPENMPI_VERSION 10000
#endif

/* ------------------------------------------------------------------------- */

/*
 * Open MPI < 1.1.3 generates an error when MPI_File_get_errhandler()
 * is called with the predefined error handlers MPI_ERRORS_RETURN and
 * MPI_ERRORS_ARE_FATAL.
 */

#if PyMPI_OPENMPI_VERSION < 10103

static int PyMPI_OPENMPI_Errhandler_free(MPI_Errhandler *errhandler)
{
  if (errhandler && ((*errhandler == MPI_ERRORS_RETURN) ||
                     (*errhandler == MPI_ERRORS_ARE_FATAL))) {
    *errhandler = MPI_ERRHANDLER_NULL;
    return MPI_SUCCESS;
  }
  return MPI_Errhandler_free(errhandler);
}
#undef  MPI_Errhandler_free
#define MPI_Errhandler_free PyMPI_OPENMPI_Errhandler_free

#endif /* !(PyMPI_OPENMPI_VERSION < 10103) */

/* ------------------------------------------------------------------------- */

/*
 * Open MPI 1.1 generates an error when MPI_File_get_errhandler() is
 * called with the MPI_FILE_NULL handle.  The code below try to fix
 * this bug by intercepting the calls to the functions setting and
 * getting the error handlers for MPI_File's.
 */

#if PyMPI_OPENMPI_VERSION < 10200

static MPI_Errhandler PyMPI_OPENMPI_FILE_NULL_ERRHANDLER = (MPI_Errhandler)0;

static int PyMPI_OPENMPI_File_get_errhandler(MPI_File file,
                                             MPI_Errhandler *errhandler)
{
  if (file == MPI_FILE_NULL) {
    if (PyMPI_OPENMPI_FILE_NULL_ERRHANDLER == (MPI_Errhandler)0) {
      PyMPI_OPENMPI_FILE_NULL_ERRHANDLER = MPI_ERRORS_RETURN;
    }
    *errhandler = PyMPI_OPENMPI_FILE_NULL_ERRHANDLER;
    return MPI_SUCCESS;
  }
  return MPI_File_get_errhandler(file, errhandler);
}
#undef  MPI_File_get_errhandler
#define MPI_File_get_errhandler PyMPI_OPENMPI_File_get_errhandler

static int PyMPI_OPENMPI_File_set_errhandler(MPI_File file,
                                             MPI_Errhandler errhandler)
{
  int ierr = MPI_File_set_errhandler(file, errhandler);
  if (ierr != MPI_SUCCESS) return ierr;
  if (file == MPI_FILE_NULL) {
    PyMPI_OPENMPI_FILE_NULL_ERRHANDLER = errhandler;
  }
  return ierr;
}
#undef  MPI_File_set_errhandler
#define MPI_File_set_errhandler PyMPI_OPENMPI_File_set_errhandler

#endif /* !(PyMPI_OPENMPI_VERSION < 10200) */

/* ---------------------------------------------------------------- */

#if PyMPI_OPENMPI_VERSION < 10301

static MPI_Fint PyMPI_OPENMPI_File_c2f(MPI_File file)
{
  if (file == MPI_FILE_NULL) return (MPI_Fint)0;
  return MPI_File_c2f(file);
}
#define MPI_File_c2f PyMPI_OPENMPI_File_c2f

#endif /* !(PyMPI_OPENMPI_VERSION < 10301) */

/* ------------------------------------------------------------------------- */

#if PyMPI_OPENMPI_VERSION < 10402

static int PyMPI_OPENMPI_MPI_Cancel(MPI_Request *request)
{
  if (request && *request == MPI_REQUEST_NULL) {
    MPI_Comm_call_errhandler(MPI_COMM_WORLD, MPI_ERR_REQUEST);
    return MPI_ERR_REQUEST;
  }
  return MPI_Cancel(request);
}
#undef  MPI_Cancel
#define MPI_Cancel PyMPI_OPENMPI_MPI_Cancel

static int PyMPI_OPENMPI_MPI_Request_free(MPI_Request *request)
{
  if (request && *request == MPI_REQUEST_NULL) {
    MPI_Comm_call_errhandler(MPI_COMM_WORLD, MPI_ERR_REQUEST);
    return MPI_ERR_REQUEST;
  }
  return MPI_Request_free(request);
}
#undef  MPI_Request_free
#define MPI_Request_free PyMPI_OPENMPI_MPI_Request_free

static int PyMPI_OPENMPI_MPI_Win_get_errhandler(MPI_Win win,
                                                MPI_Errhandler *errhandler)
{
  if (win == MPI_WIN_NULL) {
    MPI_Comm_call_errhandler(MPI_COMM_WORLD, MPI_ERR_WIN);
    return MPI_ERR_WIN;
  }
  return MPI_Win_get_errhandler(win, errhandler);
}
#undef  MPI_Win_get_errhandler
#define MPI_Win_get_errhandler PyMPI_OPENMPI_MPI_Win_get_errhandler

static int PyMPI_OPENMPI_MPI_Win_set_errhandler(MPI_Win win,
                                                MPI_Errhandler errhandler)
{
  if (win == MPI_WIN_NULL) {
    MPI_Comm_call_errhandler(MPI_COMM_WORLD, MPI_ERR_WIN);
    return MPI_ERR_WIN;
  }
  return MPI_Win_set_errhandler(win, errhandler);
}
#undef  MPI_Win_set_errhandler
#define MPI_Win_set_errhandler PyMPI_OPENMPI_MPI_Win_set_errhandler

#endif /* !(PyMPI_OPENMPI_VERSION < 10402) */

/* ------------------------------------------------------------------------- */

/*
 * Open MPI 1.7 tries to set status even in the case of MPI_STATUS_IGNORE.
 */

#if PyMPI_OPENMPI_VERSION >= 10700 && PyMPI_OPENMPI_VERSION < 10800
static int PyMPI_OPENMPI_MPI_Mrecv(void *buf, int count, MPI_Datatype type,
                                   MPI_Message *message, MPI_Status *status)
{
  MPI_Status sts; if (status == MPI_STATUS_IGNORE) status = &sts;
  return MPI_Mrecv(buf, count, type, message, status);
}
#undef  MPI_Mrecv
#define MPI_Mrecv PyMPI_OPENMPI_MPI_Mrecv
#endif  /* !(PyMPI_OPENMPI_VERSION > 10700) */

/* ------------------------------------------------------------------------- */

/*
 * Open MPI < 1.10.3 errors with MPI_Get_address(MPI_BOTTOM, &address).
 */

#if PyMPI_OPENMPI_VERSION < 11003

static int PyMPI_OPENMPI_Get_address(const void *location, MPI_Aint *address)
{
  if (location == MPI_BOTTOM && address) {
    *address = 0;
    return MPI_SUCCESS;
  }
  return MPI_Get_address(location, address);
}
#undef  MPI_Get_address
#define MPI_Get_address PyMPI_OPENMPI_Get_address

#endif

/* ------------------------------------------------------------------------- */

/*
 * Open MPI < 2.0.0 matched probes do not return MPI_MESSAGE_NO_PROC
 * for source=MPI_PROC_NULL if status=MPI_STATUS_IGNORE.
 */

#if PyMPI_OPENMPI_VERSION < 20000

static int PyMPI_OPENMPI_Mprobe(int source, int tag, MPI_Comm comm,
                                MPI_Message *message, MPI_Status *status)
{
  MPI_Status _pympi_status;
  if (source == MPI_PROC_NULL &&
      status == MPI_STATUS_IGNORE)
    status = &_pympi_status;
  return MPI_Mprobe(source, tag, comm, message, status);
}
#undef  MPI_Mprobe
#define MPI_Mprobe PyMPI_OPENMPI_Mprobe

static int PyMPI_OPENMPI_Improbe(int source, int tag, MPI_Comm comm, int *flag,
                                 MPI_Message *message, MPI_Status *status)
{
  MPI_Status _pympi_status;
  if (source == MPI_PROC_NULL &&
      status == MPI_STATUS_IGNORE)
    status = &_pympi_status;
  return MPI_Improbe(source, tag, comm, flag, message, status);
}
#undef  MPI_Improbe
#define MPI_Improbe PyMPI_OPENMPI_Improbe

#endif

/* ------------------------------------------------------------------------- */

#endif /* !PyMPI_COMPAT_OPENMPI_H */

/*
  Local Variables:
  c-basic-offset: 2
  indent-tabs-mode: nil
  End:
*/


text:
<?php
namespace Procure\Application\Service\Shared\Snapshot;

use Application\Domain\Shared\Number\NumberParser;
use Doctrine\ORM\EntityManager;
use Inventory\Domain\Item\GenericItemSnapshot;
use Inventory\Domain\Item\Contracts\ItemType;
use Inventory\Infrastructure\Doctrine\ItemQueryRepositoryImpl;
use Procure\Domain\RowSnapshot;
use Procure\Domain\AccountPayable\APRowSnapshot;
use Procure\Domain\GoodsReceipt\GRRowSnapshot;
use Procure\Domain\PurchaseRequest\PRSnapshot;
use Procure\Infrastructure\Doctrine\GRQueryRepositoryImpl;
use Procure\Infrastructure\Doctrine\POQueryRepositoryImpl;
use Procure\Infrastructure\Persistence\Domain\Doctrine\PRQueryRepositoryImplV1;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class GenericRowSnapshotModifier
{

    /**
     *
     * @param RowSnapshot $snapshot
     * @param EntityManager $doctrineEM
     * @param string $locale
     * @return NULL|\Procure\Domain\RowSnapshot
     */
    public static function updateItemDetails(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof RowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }

        if ($snapshot->getItem() > 0) {
            $rep = new ItemQueryRepositoryImpl($doctrineEM);
            $itemSnapshot = $rep->getItemSnapshotById($snapshot->getItem());

            if ($itemSnapshot instanceof GenericItemSnapshot) {

                switch ($itemSnapshot->getItemTypeId()) {
                    case ItemType::FIXED_ASSET_ITEM_TYPE:
                        $snapshot->isFixedAsset = 1;
                        break;

                    case ItemType::INVENTORY_ITEM_TYPE:
                        $snapshot->isInventoryItem = 1;
                        break;
                    case ItemType::SERVICE_ITEM_TYPE:
                        // throw new \InvalidArgumentException("SERVICE_ITEM_TYPE!");
                        // $snapshot->warehouse = null;
                        break;
                }

                $snapshot->itemStandardUnitName = $itemSnapshot->getStandardUnitName();
            }
        }
        return $snapshot;
    }

    /**
     *
     * @param RowSnapshot $snapshot
     * @param EntityManager $doctrineEM
     * @param string $locale
     * @throws \InvalidArgumentException
     * @return NULL|\Procure\Domain\RowSnapshot
     */
    public static function updatePRDetails(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof RowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }

        if ($snapshot->getPrRow() > 0) {
            $rep = new PRQueryRepositoryImplV1($doctrineEM);

            $prSnapshot = $rep->getHeaderSnapshotByRowId($snapshot->getPrRow());

            if ($prSnapshot instanceof PRSnapshot) {
                $snapshot->pr = $prSnapshot->getId();

                if ($snapshot->getWarehouse() != $prSnapshot->getWarehouse()) {
                    // throw new \InvalidArgumentException("Warehouse must match with Warehouse of PR!" . $prSnapshot->getWarehouse());
                    // Always use PR warehouse.
                    $snapshot->warehouse = $prSnapshot->getWarehouse();
                }
            }
        }

        return $snapshot;
    }

    public static function updatePODetails(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof APRowSnapshot || $snapshot instanceof GRRowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }

        // updating PO Referrence.
        if ($snapshot->getPoRow() > 0) {
            $rep = new POQueryRepositoryImpl($doctrineEM);
            $snapshot->po = $rep->getHeaderIdByRowId($snapshot->getPoRow());
        }
        return $snapshot;
    }

    public static function updateGRDetails(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof APRowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }
        if ($snapshot->getGrRow() > 0) {
            $rep = new GRQueryRepositoryImpl($doctrineEM);
            $snapshot->grId = $rep->getHeaderIdByRowId($snapshot->getGrRow());
        }

        return $snapshot;
    }

    /**
     *
     * @param RowSnapshot $snapshot
     * @param EntityManager $doctrineEM
     * @param string $locale
     * @throws \InvalidArgumentException
     * @return NULL|\Procure\Domain\RowSnapshot
     */
    public static function parseAndUpdateQuantity(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof RowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }

        // parse Number
        $parsedDocQuantity = NumberParser::parseAndConvertToEN($snapshot->getDocQuantity(), $locale);
        if ($parsedDocQuantity == false) {
            $snapshot->addError(\sprintf('Can not parse doc quantity [%s]-Locale: %s.', $snapshot->getDocQuantity(), $locale));
        }

        $parsedStandardConvertFactor = NumberParser::parseAndConvertToEN($snapshot->getStandardConvertFactor(), $locale);
        if ($parsedStandardConvertFactor == false) {
            $snapshot->addError(\sprintf('Can not parse standard conversion factor [%s]-Locale: %s.', $snapshot->getStandardConvertFactor(), $locale));
        }

        if ($snapshot->hasErrors()) {
            throw new \InvalidArgumentException($snapshot->getErrorMessage(true));
        }

        $snapshot->docQuantity = $parsedDocQuantity;
        $snapshot->conversionFactor = $parsedStandardConvertFactor;
        $snapshot->standardConvertFactor = $parsedStandardConvertFactor;

        return $snapshot;
    }

    /**
     *
     * @param RowSnapshot $snapshot
     * @param EntityManager $doctrineEM
     * @param string $locale
     * @throws \InvalidArgumentException
     * @return NULL|\Procure\Domain\RowSnapshot
     */
    public static function parseAndUpdatePrice(RowSnapshot $snapshot, EntityManager $doctrineEM, $locale = 'en_EN')
    {
        if (! $snapshot instanceof RowSnapshot || ! $doctrineEM instanceof EntityManager) {
            return null;
        }

        // parse Number

        $parsedDocUnitPrice = NumberParser::parseAndConvertToEN($snapshot->getDocUnitPrice(), $locale);
        if ($parsedDocUnitPrice == false) {
            $snapshot->addError(\sprintf('Can not parse unit price [%s].  Locale: %s', $snapshot->getDocUnitPrice(), $locale));
        }

        /*
         * $parsedExwUnitPrice = NumberParser::parseAndConvertToEN($snapshot->getExwUnitPrice(), $locale);
         * if ($parsedExwUnitPrice == false) {
         * $snapshot->addError(\sprintf('Can not parse Exw unit price [%s]. Locale: %s', $snapshot->getExwUnitPrice(), $locale));
         * }
         */

        if ($snapshot->hasErrors()) {
            throw new \InvalidArgumentException($snapshot->getErrorMessage(false));
        }

        $snapshot->docUnitPrice = $parsedDocUnitPrice;
        $snapshot->unitPrice = $parsedDocUnitPrice;
        $snapshot->exwUnitPrice = $parsedDocUnitPrice;

        return $snapshot;
    }
}

redpajama_set_name: RedPajamaGithub


text:
NSString* const kCBLReplicationChangeNotification = @"CBLReplicationChange";

// Declared in CBL_Replicator.h
NSString* CBL_ReplicatorProgressChangedNotification = @"CBL_ReplicatorProgressChanged";
NSString* CBL_ReplicatorStoppedNotification = @"CBL_ReplicatorStopped";

#define kByChannelFilterName @"sync_gateway/bychannel"
#define kChannelsQueryParam  @"channels"

@interface CBLReplication ()
@property (nonatomic, readwrite) BOOL running;
@property (nonatomic, readwrite) CBLReplicationStatus status;
@property (nonatomic, readwrite) unsigned completedChangesCount, changesCount;
@property (nonatomic, readwrite, strong, nullable) NSError* lastError;
@end

@implementation CBLReplication
{
    NSSet* _pendingDocIDs;
    bool _started;
    id<CBL_Replicator> _bg_replicator;       // ONLY used on the server thread
    NSMutableArray* _bg_pendingCookies;
    NSConditionLock* _bg_stopLock;
}

@synthesize localDatabase=_database, createTarget=_createTarget;
@synthesize continuous=_continuous, filter=_filter, filterParams=_filterParams;
@synthesize documentIDs=_documentIDs, network=_network, remoteURL=_remoteURL, pull=_pull;
@synthesize headers=_headers, OAuth=_OAuth, customProperties=_customProperties;
@synthesize running = _running, completedChangesCount=_completedChangesCount;
@synthesize changesCount=_changesCount, lastError=_lastError, status=_status;
@synthesize authenticator=_authenticator, serverCertificate=_serverCertificate;

- (instancetype) initWithDatabase: (CBLDatabase*)database
                           remote: (NSURL*)remote
                             pull: (BOOL)pull
{
    NSParameterAssert(database);
    NSParameterAssert(remote);
    self = [super init];
    if (self) {
        _database = database;
        _remoteURL = remote;
        _pull = pull;
    }
    return self;
}

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    cfrelease(_serverCertificate);
}

- (NSString*) description {
    return [NSString stringWithFormat: @"%@[%@ %@]",
                self.class, (self.pull ? @"from" : @"to"), self.remoteURL.my_sanitizedString];
}

- (void) setContinuous:(bool)continuous {
    if (continuous != _continuous) {
        _continuous = continuous;
        [self restart];
    }
}

- (void) setFilter:(NSString *)filter {
    if (!$equal(filter, _filter)) {
        _filter = filter;
        [self restart];
    }
}

- (void) setHeaders: (NSDictionary*)headers {
    if (!$equal(headers, _headers)) {
        _headers = headers;
        [self restart];
    }
}

- (NSArray*) channels {
    NSString* params = self.filterParams[kChannelsQueryParam];
    if (!self.pull || !$equal(self.filter, kByChannelFilterName) || params.length == 0)
        return nil;
    return [params componentsSeparatedByString: @","];
}

- (void) setChannels:(NSArray *)channels {
    if (channels) {
        Assert(self.pull, @"filterChannels can only be set in pull replications");
        self.filter = kByChannelFilterName;
        self.filterParams = @{kChannelsQueryParam: [channels componentsJoinedByString: @","]};
    } else if ($equal(self.filter, kByChannelFilterName)) {
        self.filter = nil;
        self.filterParams = nil;
    }
}

#pragma mark - AUTHENTICATION:

- (NSURLCredential*) credential {
    return [self.remoteURL my_credentialForRealm: nil
                            authenticationMethod: NSURLAuthenticationMethodDefault];
}

- (void) setCredential:(NSURLCredential *)cred {
    // Hardcoded username doesn't mix with stored credentials.
    NSURL* url = self.remoteURL;
    _remoteURL = url.my_URLByRemovingUser;

    NSURLProtectionSpace* space = [url my_protectionSpaceWithRealm: nil
                                            authenticationMethod: NSURLAuthenticationMethodDefault];
    NSURLCredentialStorage* storage = [NSURLCredentialStorage sharedCredentialStorage];
    if (cred) {
        self.authenticator = nil;
        [storage setDefaultCredential: cred forProtectionSpace: space];
    } else {
        cred = [storage defaultCredentialForProtectionSpace: space];
        if (cred)
            [storage removeCredential: cred forProtectionSpace: space];
    }
    [self restart];
}

- (NSURL*) personaOrigin {
    return self.remoteURL.my_baseURL;
}

- (void) setCookieNamed: (NSString*)name
              withValue: (NSString*)value
                   path: (NSString*)path
         expirationDate: (NSDate*)expirationDate
                 secure: (BOOL)secure
{
    if (secure && !_remoteURL.my_isHTTPS)
        Warn(@"%@: Attempting to set secure cookie for non-secure URL %@", self, _remoteURL);
    NSDictionary* props = $dict({NSHTTPCookieOriginURL, _remoteURL.my_baseURL},
                                {NSHTTPCookiePath, (path ?: _remoteURL.path)},
                                {NSHTTPCookieName, name},
                                {NSHTTPCookieValue, value},
                                {NSHTTPCookieExpires, expirationDate},
                                {NSHTTPCookieSecure, (secure ? @YES : nil)});
    NSHTTPCookie* cookie = [NSHTTPCookie cookieWithProperties: props];
    if (!cookie) {
        Warn(@"%@: Could not create cookie from parameters", self);
        return;
    }

    [self tellReplicator: ^(id<CBL_Replicator> bgReplicator) {
        if (bgReplicator)
            [bgReplicator.cookieStorage setCookie: cookie];
        else {
            if (!_bg_pendingCookies)
                _bg_pendingCookies = [NSMutableArray array];
            [_bg_pendingCookies addObject: cookie];
        }
    }];
}

- (void) deleteCookieNamed: (NSString*)name {
    [self tellReplicator: ^(id<CBL_Replicator> bgReplicator) {
        if (_bg_replicator)
            [_bg_replicator.cookieStorage deleteCookiesNamed: name];
        else {
            if (!_bg_pendingCookies)
                _bg_pendingCookies = [NSMutableArray array];
            [_bg_pendingCookies addObject: name];
        }
    }];
}

+ (void) setAnchorCerts: (NSArray*)certs onlyThese: (BOOL)onlyThese {
    CBLSetAnchorCerts(certs, onlyThese);
}

#pragma mark - START/STOP:

- (NSDictionary*) properties {
    // This is basically the inverse of -[CBLManager parseReplicatorProperties:...]
    NSMutableDictionary* props = $mdict({@"continuous", @(_continuous)},
                                        {@"create_target", @(_createTarget)},
                                        {@"filter", _filter},
                                        {@"query_params", _filterParams},
                                        {@"doc_ids", _documentIDs});
    NSURL* remoteURL = _remoteURL;
    NSMutableDictionary* authDict = nil;
    if (_authenticator) {
        remoteURL = remoteURL.my_URLByRemovingUser;
    } else if (_OAuth) {
        remoteURL = remoteURL.my_URLByRemovingUser;
        authDict = $mdict({@"oauth", _OAuth});
    }
    NSDictionary* remote = $dict({@"url", remoteURL.absoluteString},
                                 {@"headers", _headers},
                                 {@"auth", authDict});
    if (_pull) {
        props[@"source"] = remote;
        props[@"target"] = _database.name;
    } else {
        props[@"source"] = _database.name;
        props[@"target"] = remote;
    }

    if (_customProperties)
        [props addEntriesFromDictionary: _customProperties];
    return props;
}

- (void) start {
    if (!_database.isOpen)  // Race condition: db closed before replication starts
        return;

    if (!_started) {
        _started = YES;

        NSDictionary* properties= self.properties;
        id<CBLAuthorizer> auth = (id<CBLAuthorizer>)_authenticator;
        [_database.manager.backgroundServer tellDatabaseManager: ^(CBLManager* bgManager) {
            // This runs on the server thread:
            [self bg_startReplicator: bgManager properties: properties auth: auth];
        }];

        // Initialize the status to something other than kCBLReplicationStopped:
        [self updateStatus: kCBLReplicationOffline error: nil processed: 0 ofTotal: 0
                serverCert: NULL];

        [_database addReplication: self];
    }
}

- (void) stop {
    if (!_started)
        return;

    BOOL stopping = [[self tellReplicatorAndWait: ^id(id<CBL_Replicator> bgReplicator) {
        if (bgReplicator.status != kCBLReplicatorStopped) {
            _bg_stopLock = [[NSConditionLock alloc] initWithCondition: 0];
            [bgReplicator stop];
            return @(YES);
        }
        return @(NO);
    }] boolValue];

    if (!stopping)
        return;

    // Waiting for the background stop notification:
    NSDate* timeout = [NSDate dateWithTimeIntervalSinceNow: 2.0]; // 2 seconds:
    if ([_bg_stopLock lockWhenCondition: 1 beforeDate: timeout])
        [_bg_stopLock unlock];
    else
        Warn(@"%@: Timeout waiting for background stop notification", self);

    [self tellReplicatorAndWait: ^id(id<CBL_Replicator> bgReplicator) {
        _bg_stopLock = nil;
        return @(YES);
    }];
}

- (void) restart {
    if (_started) {
        [self stop];

        // Schedule to call the -start method in the next runloop queue or dispatch queue.
        // This allows the -start method to be called after the _started var is set to 'NO'
        // in the -updateStatus: method.
        [_database doAsync:^{
            [self start];
        }];
    }
}

- (BOOL) suspended {
    NSNumber* result = [self tellReplicatorAndWait: ^(id<CBL_Replicator> bgReplicator) {
        return @(bgReplicator.suspended);
    }];
    return result.boolValue;
}

- (void) setSuspended: (BOOL)suspended {
    [self tellReplicator: ^(id<CBL_Replicator> bgReplicator) {
        bgReplicator.suspended = suspended;
    }];
}

- (void) updateStatus: (CBLReplicationStatus)status
                error: (NSError*)error
            processed: (NSUInteger)changesProcessed
              ofTotal: (NSUInteger)changesTotal
           serverCert: (SecCertificateRef)serverCert
{
    if (!_started)
        return;
    if (status == kCBLReplicationStopped) {
        _started = NO;
        [_database forgetReplication: self];
    }

    _pendingDocIDs = nil; // forget cached IDs

    BOOL changed = NO;
    if (!$equal(error, _lastError)) {
        self.lastError = error;
        changed = YES;
    }
    if (changesProcessed != _completedChangesCount || changesTotal != _changesCount) {
        // Change the two at the same time to avoid confusing KVO observers:
        [self willChangeValueForKey: @"completedChangesCount"];
        [self willChangeValueForKey: @"changesCount"];
        _changesCount = (unsigned)changesTotal;
        _completedChangesCount = (unsigned)changesProcessed;
        [self didChangeValueForKey: @"changesCount"];
        [self didChangeValueForKey: @"completedChangesCount"];
        changed = YES;
    }
    if (status != _status) {
        self.status = status;
        changed = YES;
    }
    BOOL running = (status > kCBLReplicationStopped);
    if (running != _running) {
        self.running = running;
        changed = YES;
    }

    cfSetObj(&_serverCertificate, serverCert);

    if (changed) {
#ifndef MY_DISABLE_LOGGING
        static const char* kStatusNames[] = {"stopped", "offline", "idle", "active"};
        LogTo(Sync, @"%@: %s, progress = %u / %u, err: %@",
              self, kStatusNames[status], (unsigned)changesProcessed, (unsigned)changesTotal,
              error.localizedDescription);
#endif
        [[NSNotificationCenter defaultCenter]
                        postNotificationName: kCBLReplicationChangeNotification object: self];
    }
}

#pragma mark - PUSH REPLICATION ONLY:

- (NSSet*) pendingDocumentIDs {
    if (_pull || (_started && _pendingDocIDs))
        return _pendingDocIDs;

    _pendingDocIDs = [_database.manager.backgroundServer
                      waitForDatabaseNamed: _database.name to: ^id(CBLDatabase* bgDb)
    {
        CBLStatus status;
        CBL_ReplicatorSettings* settings =
            [bgDb.manager replicatorSettingsWithProperties: self.properties
                                                toDatabase: nil
                                                    status: &status];
        if (!settings) {
            Warn(@"Error parsing replicator settings : %@", CBLStatusToNSError(status));
            return nil;
        }

        NSString* lastSequence = _bg_replicator.lastSequence;
        if (!lastSequence)
            lastSequence = [bgDb lastSequenceForReplicator: settings];

        NSError* error;
        CBL_RevisionList* revs = [bgDb unpushedRevisionsSince: lastSequence
                                                       filter: settings.filterBlock
                                                       params: settings.filterParameters
                                                        error: &error];
        if (revs)
            return [NSSet setWithArray: revs.allDocIDs];
        else
            Warn(@"Error getting unpushed revisions : %@", error);
        return nil;
    }];
    return _pendingDocIDs;
}

- (BOOL) isDocumentPending: (CBLDocument*)doc {
    return doc && [self.pendingDocumentIDs containsObject: doc.documentID];
    //OPT: It may be cheaper to do this by fetching the replicator's checkpoint sequence and
    // comparing the doc's sequence to it.
}

#pragma mark - BACKGROUND OPERATIONS:

- (void) tellReplicator: (void (^)(id<CBL_Replicator>))block {
    [_database.manager.backgroundServer tellDatabaseManager: ^(CBLManager* _) {
        block(_bg_replicator);
    }];
}

- (id) tellReplicatorAndWait: (id (^)(id<CBL_Replicator>))block {
    return [_database.manager.backgroundServer waitForDatabaseManager: ^(CBLManager* _) {
        return block(_bg_replicator);
    }];
}

// CAREFUL: This is called on the server's background thread!
- (void) bg_setReplicator: (id<CBL_Replicator>)repl {
    if (_bg_replicator) {
        [[NSNotificationCenter defaultCenter] removeObserver: self name: nil
                                                      object: _bg_replicator];
    }
    _bg_replicator = repl;
    if (_bg_replicator) {
        [[NSNotificationCenter defaultCenter] addObserver: self
                                                 selector: @selector(bg_replicationProgressChanged:)
                                                     name: CBL_ReplicatorProgressChangedNotification
                                                   object: _bg_replicator];
    }
}

// CAREFUL: This is called on the server's background thread!
- (void) bg_startReplicator: (CBLManager*)server_dbmgr
                 properties: (NSDictionary*)properties
                       auth: (id<CBLAuthorizer>)auth
{
    // The setup must use properties, not ivars, because the ivars may change on the main thread.
    CBLStatus status;
    id<CBL_Replicator> repl = [server_dbmgr replicatorWithProperties: properties status: &status];
    if (!repl) {
        __weak CBLReplication *weakSelf = self;
        [_database doAsync: ^{
            CBLReplication *strongSelf = weakSelf;
            [strongSelf updateStatus: kCBLReplicationStopped
                               error: CBLStatusToNSError(status)
                           processed: 0 ofTotal: 0 serverCert: NULL];
        }];
        return;
    }
    if (auth)
        repl.settings.authorizer = auth;

    if ([_bg_pendingCookies count] > 0) {
        for (id cookie in _bg_pendingCookies) {
            if ([cookie isKindOfClass: [NSHTTPCookie class]])
                [repl.cookieStorage setCookie: cookie];
            else if ([cookie isKindOfClass: [NSString class]])
                [repl.cookieStorage deleteCookiesNamed: cookie];
        }
        _bg_pendingCookies = nil;
    }

    CBLPropertiesTransformationBlock xformer = self.propertiesTransformationBlock;
    if (xformer) {
        repl.settings.revisionBodyTransformationBlock = ^(CBL_Revision* rev) {
            NSDictionary* properties = rev.properties;
            NSDictionary* xformedProperties = xformer(properties);
            if (xformedProperties == nil) {
                rev = nil;
            } else if (xformedProperties != properties) {
                Assert(xformedProperties != nil);
                AssertEqual(xformedProperties.cbl_id, properties.cbl_id);
                AssertEqual(xformedProperties.cbl_rev, properties.cbl_rev);
                CBL_MutableRevision* nuRev = rev.mutableCopy;
                nuRev.properties = xformedProperties;
                rev = nuRev;
            }
            return rev;
        };
    }

    [self bg_setReplicator: repl];
    [repl start];
    [self bg_updateProgress];
}

// CAREFUL: This is called on the server's background thread!
- (void) bg_replicationProgressChanged: (NSNotification*)n {
    if (n.object == _bg_replicator)
        [self bg_updateProgress];
    else
        Warn(@"%@: Received replication change notification from "
             "an unexpected replicator %@ (expected %@)", self, n.object, _bg_replicator);
}

// CAREFUL: This is called on the server's background thread!
- (void) bg_updateProgress {
    CBLReplicationStatus status = (CBLReplicationStatus)_bg_replicator.status;
    NSError* error = _bg_replicator.error;
    NSUInteger changes = _bg_replicator.changesProcessed;
    NSUInteger total = _bg_replicator.changesTotal;
    SecCertificateRef serverCert = _bg_replicator.serverCert;
    cfretain(serverCert);

    if (status == kCBLReplicationStopped) {
        [self bg_setReplicator: nil];
    }

    // Communicate its state back to the main thread:
    __weak CBLReplication *weakSelf = self;
    [_database doAsync: ^{
        CBLReplication *strongSelf = weakSelf;
        [strongSelf updateStatus: status error: error processed: changes ofTotal: total
                          serverCert: serverCert];
        cfrelease(serverCert);
    }];

    if (status == kCBLReplicationStopped) {
        [_bg_stopLock lockWhenCondition: 0];
        [_bg_stopLock unlockWithCondition: 1];
    }
}

@end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

/**
 *
 * @author vi
 */
/**
 * Copyright (c) blackbear, Inc All Rights Reserved.
 */

import java.io.InputStream;
import java.net.URLEncoder;
import java.text.MessageFormat;

import org.apache.commons.io.IOUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * TranslateUtil
 *
 *
翻譯工具
 * PS: 透過google translate
 *

 *
 * @author catty
 * @version 1.0, Created on 2011/9/2
 */
public class TranslateUtil {

	protected static final String URL_TEMPLATE = "http://translate.google.com/?langpair={0}&text={1}";
	protected static final String ID_RESULTBOX = "result_box";
	protected static final String ENCODING = "UTF-8";

	protected static final String AUTO = "auto"; // google自動判斷來源語系
	protected static final String TAIWAN = "zh-TW"; // 繁中
	protected static final String CHINA = "zh-CN"; // 簡中
	protected static final String ENGLISH = "en"; // 英
	protected static final String JAPAN = "ja"; // 日

	/**
	 *
Google翻譯
	 * PS: 交由google自動判斷來源語系
	 *

	 *
	 * @param text
	 * @param target_lang 目標語系
	 * @return
	 * @throws Exception
	 */
	public static String translate(final String text, final String target_lang) throws Exception {
		return translate(text, AUTO, target_lang);
	}

	/**
	 *
Google翻譯

	 *
	 * @param text
	 * @param src_lang 來源語系
	 * @param target_lang 目標語系
	 * @return
	 * @throws Exception
	 */
	public static String translate(final String text, final String src_lang, final String target_lang)
			throws Exception {
		InputStream is = null;
		Document doc = null;
		Element ele = null;
		try {
			// create URL string
			String url = MessageFormat.format(URL_TEMPLATE,
					URLEncoder.encode(src_lang + "|" + target_lang, ENCODING),
					URLEncoder.encode(text, ENCODING));

			// connect & download html
			is = HttpClientUtil.downloadAsStream(url);

			// parse html by Jsoup
			doc = Jsoup.parse(is, ENCODING, "");
			ele = doc.getElementById(ID_RESULTBOX);
			String result = ele.text();
			return result;

		} finally {
			IOUtils.closeQuietly(is);
			is = null;
			doc = null;
			ele = null;
		}
	}

	/**
	 *
Google翻譯: 簡中-->繁中

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String cn2tw(final String text) throws Exception {
		return translate(text, CHINA, TAIWAN);
	}

	/**
	 *
Google翻譯: 繁中-->簡中

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String tw2cn(final String text) throws Exception {
		return translate(text, TAIWAN, CHINA);
	}

	/**
	 *
Google翻譯: 英文-->繁中

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String en2tw(final String text) throws Exception {
		return translate(text, ENGLISH, TAIWAN);
	}/**
	 *
Google翻譯: 英文-->繁中

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String en2cn(final String text) throws Exception {
		return translate(text, ENGLISH, CHINA);
	}

	/**
	 *
Google翻譯: 繁中-->英文

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String tw2en(final String text) throws Exception {
		return translate(text, TAIWAN, ENGLISH);
	}

	/**
	 *
Google翻譯: 日文-->繁中

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String jp2tw(final String text) throws Exception {
		return translate(text, JAPAN, TAIWAN);
	}

	/**
	 *
Google翻譯: 繁中-->日

	 *
	 * @param text
	 * @return
	 * @throws Exception
	 */
	public static String tw2jp(final String text) throws Exception {
		return translate(text, TAIWAN, JAPAN);
	}

}


text:
package bosphorus;

import javax.xml.bind.annotation.XmlElement;

public abstract class TestParent {
	protected String someVal;

	@XmlElement(name="someval")
	public String getSomeVal(){
		return someVal;
	}

	public void setSomeVal(String pSomeVal){
		someVal = pSomeVal;
	}

}


text:
package com.google.common.io;

public enum FileWriteMode {
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows;

namespace MouseDragDemo
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
    }
}


text:
package Numero2;

import java.util.Scanner;

public class Ex2 {

	public static void main(String[] args) {

		@SuppressWarnings("resource")
		Scanner s = new Scanner(System.in);

		double n;
		double n2;
		double n3;
		double r;

		System.out.println("Váriavel x:");
		n = s.nextDouble();

		System.out.println("Váriavel y");
		n2 = s.nextDouble();

		System.out.println("Váriavel z");
		n3 = s.nextDouble();

		r = n * n2 * n3;

		System.out.println("Resultado:" + r);

	}

}


text:
package main

import (
	"fmt"
	"net/http"

	sarama "github.com/Shopify/sarama"
)

// Handler posts a message to Kafka Topic
func Handler(w http.ResponseWriter, r *http.Request) {
	brokers := []string{"broker.kafka.svc.cluster.local:9092"}
	producerConfig := sarama.NewConfig()
	producerConfig.Producer.RequiredAcks = sarama.WaitForAll
	producerConfig.Producer.Retry.Max = 10
	producerConfig.Producer.Return.Successes = true
	producerConfig.Version = sarama.V0_11_0_0
	producer, err := sarama.NewSyncProducer(brokers, producerConfig)
	fmt.Println("Created a new producer ", producer)
	if err != nil {
		panic(err)
	}

	headers := []sarama.RecordHeader{{Key: []byte("Z-Custom-Name"), Value: []byte("Kafka-Header-test")}}
	_, _, err = producer.SendMessage(&sarama.ProducerMessage{
		Topic:   "testtopic",
		Value:   sarama.StringEncoder("{\"name\": \"testvalue\"}"),
		Headers: headers,
	})

	if err != nil {
		w.Write([]byte(fmt.Sprintf("Failed to publish message to topic %s: %v", "testtopic", err)))
		return
	}
	w.Write([]byte("Successfully sent to testtopic"))
}


text:
<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Application Debug Mode
	|--------------------------------------------------------------------------
	|
	| When your application is in debug mode, detailed error messages with
	| stack traces will be shown on every error that occurs within your
	| application. If disabled, a simple generic error page is shown.
	|
	*/

	'debug' => true,

	'aws_ses_sourceemail' => 'evans022@gmail.com'
);


text:
/*
 * $Id: DOMXPathException.hpp 671894 2008-06-26 13:29:21Z borisk $
 */

#if !defined(XERCESC_INCLUDE_GUARD_DOMXPATHEXCEPTION_HPP)
#define XERCESC_INCLUDE_GUARD_DOMXPATHEXCEPTION_HPP

#include <xercesc/dom/DOMException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

/**
 * @since DOM Level 3
 */
class CDOM_EXPORT DOMXPathException : public DOMException
{
public:
    //@{
    /**
     * ExceptionCode
     *
INVALID_EXPRESSION_ERR The expression has a syntax error or otherwise
     * is not a legal expression according to the rules of the specific
     * DOMXPathEvaluator or contains specialized extension functions
     * or variables not supported by this implementation.
     *
TYPE_ERR The expression cannot be converted to return the specified type.
     *
NO_RESULT_ERROR There is no current result in the result object.
     */
	enum ExceptionCode {
		INVALID_EXPRESSION_ERR = 51,
		TYPE_ERR = 52,
                NO_RESULT_ERROR = 53
	};
    //@}

public:
    // -----------------------------------------------------------------------
    //  Constructors
    // -----------------------------------------------------------------------
    /** @name Constructors */
    //@{
    /**
      * Default constructor for DOMXPathException.
      *
      */
    DOMXPathException();

    /**
      * Constructor which takes an error code and a message.
      *
      * @param code The error code which indicates the exception
      * @param messageCode    The string containing the error message
      * @param memoryManager  The memory manager used to (de)allocate memory
      */
    DOMXPathException(short code,
                      short messageCode = 0,
                      MemoryManager* const  memoryManager = XMLPlatformUtils::fgMemoryManager);

    /**
      * Copy constructor.
      *
      * @param other The object to be copied.
      */
    DOMXPathException(const DOMXPathException  &other);

    //@}

    // -----------------------------------------------------------------------
    //  Destructors
    // -----------------------------------------------------------------------
    /** @name Destructor. */
    //@{
	 /**
	  * Destructor for DOMXPathException.
	  *
	  */
    virtual ~DOMXPathException();
    //@}

private:
    // -----------------------------------------------------------------------
    // Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    DOMXPathException& operator = (const DOMXPathException&);
};

XERCES_CPP_NAMESPACE_END

#endif


text:
const hasContraction = /'/

const isHas = (terms, i) => {
  //look for a past-tense verb
  let after = terms.slice(i + 1, i + 3)
  return after.some(t => t.tags.has('PastTense'))
}

// 's -> [possessive, 'has', or 'is']
const apostropheS = function (terms, i) {
  // possessive, is/has
  let before = terms[i].normal.split(hasContraction)[0]
  // spencer's got -> 'has'
  if (isHas(terms, i)) {
    return [before, 'has']
  }
  // let's
  if (before === 'let') {
    return [before, 'us']
  }
  // allow slang "there's" -> there are
  if (before === 'there') {
    let nextTerm = terms[i + 1]
    if (nextTerm && nextTerm.tags.has('Plural')) {
      return [before, 'are']
    }
  }
  return [before, 'is']
}
export default apostropheS


text:
package de.hpi.interactionnet;

import de.hpi.PTnet.PTNet;
import de.hpi.PTnet.PTNetFactory;

public class InteractionNetFactory extends PTNetFactory {

	public static InteractionNetFactory eINSTANCE = new InteractionNetFactory();

	public InteractionNet createInteractionNet() {
		return new InteractionNet();
	}

	public Role createRole() {
		return new Role();
	}

	public InteractionTransition createLabeledTransition() {
		return new InteractionTransition();
	}

	public static InteractionNetFactory init() {
		return new InteractionNetFactory();
	}

	public ActionTransition createActionTransition() {
		return new ActionTransition();
	}

	public InteractionTransition createInteractionTransition() {
		return new InteractionTransition();
	}

	@Override
	public PTNet createPetriNet() {
		return createInteractionNet();
	}

}


text:
.class final Lcom/google/inject/internal/util/$Iterators$8;
.super Lcom/google/inject/internal/util/$UnmodifiableIterator;
.source "Iterators.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/google/inject/internal/util/$Iterators;->singletonIterator(Ljava/lang/Object;)Lcom/google/inject/internal/util/$UnmodifiableIterator;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/google/inject/internal/util/$UnmodifiableIterator",
        "<TT;>;"
    }
.end annotation

# instance fields
.field done:Z

.field final synthetic val$value:Ljava/lang/Object;

# direct methods
.method constructor <init>(Ljava/lang/Object;)V
    .locals 0

    .prologue
    .line 290
    iput-object p1, p0, Lcom/google/inject/internal/util/$Iterators$8;->val$value:Ljava/lang/Object;

    invoke-direct {p0}, Lcom/google/inject/internal/util/$UnmodifiableIterator;-><init>()V

    return-void
.end method

# virtual methods
.method public hasNext()Z
    .locals 1

    .prologue
    .line 293
    iget-boolean v0, p0, Lcom/google/inject/internal/util/$Iterators$8;->done:Z

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public next()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    .prologue
    .line 296
    iget-boolean v0, p0, Lcom/google/inject/internal/util/$Iterators$8;->done:Z

    if-eqz v0, :cond_0

    .line 297
    new-instance v0, Ljava/util/NoSuchElementException;

    invoke-direct {v0}, Ljava/util/NoSuchElementException;-><init>()V

    throw v0

    .line 299
    :cond_0
    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/google/inject/internal/util/$Iterators$8;->done:Z

    .line 300
    iget-object v0, p0, Lcom/google/inject/internal/util/$Iterators$8;->val$value:Ljava/lang/Object;

    return-object v0
.end method


text:
package tests

import (
	"bytes"
	"testing"

	"github.com/telehash/gogotelehash/Godeps/_workspace/src/github.com/stretchr/testify/suite"

	"github.com/telehash/gogotelehash/e3x/cipherset"
	"github.com/telehash/gogotelehash/internal/lob"
)

type cipherTestSuite struct {
	suite.Suite
	cipher cipherset.Cipher
}

func Run(t *testing.T, c cipherset.Cipher) {
	suite.Run(t, &cipherTestSuite{cipher: c})
}

func (s *cipherTestSuite) TestMessage() {
	var (
		assert = s.Assertions
		c      = s.cipher
	)

	var (
		ka  cipherset.Key
		kb  cipherset.Key
		sa  cipherset.State
		box []byte
		msg []byte
		err error
	)

	ka, err = c.GenerateKey()
	assert.NoError(err)
	assert.NotNil(ka)

	sa, err = c.NewState(ka)
	assert.NoError(err)
	assert.NotNil(sa)
	assert.False(sa.CanEncryptMessage())
	assert.False(sa.CanEncryptHandshake())
	assert.False(sa.CanDecryptMessage())
	assert.True(sa.CanDecryptHandshake())
	assert.True(sa.NeedsRemoteKey())

	kb, err = c.GenerateKey()
	assert.NoError(err)
	assert.NotNil(kb)

	err = sa.SetRemoteKey(kb)
	assert.NoError(err)
	assert.True(sa.CanEncryptMessage())
	assert.True(sa.CanEncryptHandshake())
	assert.True(sa.CanDecryptMessage())
	assert.True(sa.CanDecryptHandshake())
	assert.False(sa.NeedsRemoteKey())

	box, err = sa.EncryptMessage([]byte("Hello World!"))
	assert.NoError(err)
	assert.NotNil(box)

	msg, err = c.DecryptMessage(kb, ka, box)
	assert.NoError(err)
	assert.NotNil(msg)
	assert.Equal([]byte("Hello World!"), msg)
}

func (s *cipherTestSuite) TestHandshake() {
	var (
		assert = s.Assertions
		c      = s.cipher
	)

	var (
		ka  cipherset.Key
		kb  cipherset.Key
		sa  cipherset.State
		sb  cipherset.State
		ha  cipherset.Handshake
		hb  cipherset.Handshake
		box []byte
		err error
		ok  bool
	)

	ka, err = c.GenerateKey()
	assert.NoError(err)
	assert.NotNil(ka)

	sa, err = c.NewState(ka)
	assert.NoError(err)
	assert.NotNil(sa)
	assert.False(sa.CanEncryptMessage())
	assert.False(sa.CanEncryptHandshake())
	assert.False(sa.CanDecryptMessage())
	assert.True(sa.CanDecryptHandshake())
	assert.True(sa.NeedsRemoteKey())

	kb, err = c.GenerateKey()
	assert.NoError(err)
	assert.NotNil(kb)

	err = sa.SetRemoteKey(kb)
	assert.NoError(err)
	assert.True(sa.CanEncryptMessage())
	assert.True(sa.CanEncryptHandshake())
	assert.True(sa.CanDecryptMessage())
	assert.True(sa.CanDecryptHandshake())
	assert.False(sa.NeedsRemoteKey())

	box, err = sa.EncryptHandshake(1, cipherset.Parts{0x01: "foobarzzzzfoobarzzzzfoobarzzzzfoobarzzzzfoobarzzzz34"})
	assert.NoError(err)
	assert.NotNil(box)

	hb, err = c.DecryptHandshake(kb, box)
	assert.NoError(err)
	if assert.NotNil(hb) {
		assert.Equal(ka.Public(), hb.PublicKey().Public())
		assert.Equal(cipherset.Parts{0x01: "foobarzzzzfoobarzzzzfoobarzzzzfoobarzzzzfoobarzzzz34"}, hb.Parts())
		assert.Equal(uint32(1), hb.At())
	}

	sb, err = c.NewState(kb)
	assert.NoError(err)
	if assert.NotNil(sb) {
		assert.False(sb.CanEncryptMessage())
		assert.False(sb.CanEncryptHandshake())
		assert.False(sb.CanDecryptMessage())
		assert.True(sb.CanDecryptHandshake())
		assert.True(sb.NeedsRemoteKey())
	}

	if sb != nil && hb != nil {
		ok = sb.ApplyHandshake(hb)
		assert.True(ok)
		assert.True(sb.CanEncryptMessage())
		assert.True(sb.CanEncryptHandshake())
		assert.True(sb.CanDecryptMessage())
		assert.True(sb.CanDecryptHandshake())
		assert.False(sb.NeedsRemoteKey())
	}

	box, err = sb.EncryptHandshake(1, cipherset.Parts{0x01: "foobarzzzzfoobarzzzzfoobarzzzzfoobarzzzzfoobarzzzz34"})
	assert.NoError(err)
	assert.NotNil(box)

	ha, err = c.DecryptHandshake(ka, box)
	assert.NoError(err)
	assert.NotNil(ha)
	assert.Equal(kb.Public(), ha.PublicKey().Public())
	assert.Equal(cipherset.Parts{0x01: "foobarzzzzfoobarzzzzfoobarzzzzfoobarzzzzfoobarzzzz34"}, ha.Parts())
	assert.Equal(uint32(1), ha.At())

	ok = sa.ApplyHandshake(ha)
	assert.True(ok)
	assert.True(sa.CanEncryptMessage())
	assert.True(sa.CanEncryptHandshake())
	assert.True(sa.CanDecryptMessage())
	assert.True(sa.CanDecryptHandshake())
	assert.False(sa.NeedsRemoteKey())
}

func (s *cipherTestSuite) TestPacketEncryption() {
	var (
		assert = s.Assertions
		c      = s.cipher
	)

	var (
		ka  cipherset.Key
		kb  cipherset.Key
		sa  cipherset.State
		sb  cipherset.State
		ha  cipherset.Handshake
		hb  cipherset.Handshake
		pkt *lob.Packet
		box []byte
		err error
		ok  bool
	)

	ka, err = c.GenerateKey()
	assert.NoError(err)
	kb, err = c.GenerateKey()
	assert.NoError(err)

	sa, err = c.NewState(ka)
	assert.NoError(err)
	sb, err = c.NewState(kb)
	assert.NoError(err)

	err = sa.SetRemoteKey(kb)
	assert.NoError(err)
	box, err = sa.EncryptHandshake(1, nil)
	assert.NoError(err)
	hb, err = c.DecryptHandshake(kb, box)
	assert.NoError(err)
	ok = sb.ApplyHandshake(hb)
	assert.True(ok)
	box, err = sb.EncryptHandshake(1, nil)
	assert.NoError(err)
	ha, err = c.DecryptHandshake(ka, box)
	assert.NoError(err)
	ok = sa.ApplyHandshake(ha)
	assert.True(ok)

	pkt = lob.New([]byte("Hello world!"))
	pkt.Header().SetInt("foo", 0xbeaf)
	pkt, err = sa.EncryptPacket(pkt)
	assert.NoError(err)
	assert.NotNil(pkt)
	assert.Nil(pkt.Header().Bytes)
	assert.True(pkt.Header().IsZero())
	assert.NotEmpty(pkt.Body)

	pkt, err = sb.DecryptPacket(pkt)
	assert.NoError(err)
	assert.NotNil(pkt)
	assert.Nil(pkt.Header().Bytes)
	assert.Equal(&lob.Header{Extra: map[string]interface{}{"foo": 0xbeaf}}, pkt.Header())
	assert.Equal([]byte("Hello world!"), pkt.Body(nil))

	pkt = lob.New([]byte("Bye world!"))
	pkt.Header().SetInt("bar", 0xdead)
	pkt, err = sb.EncryptPacket(pkt)
	assert.NoError(err)
	assert.NotNil(pkt)
	assert.Nil(pkt.Header().Bytes)
	assert.True(pkt.Header().IsZero())
	assert.NotEmpty(pkt.Body)

	pkt, err = sa.DecryptPacket(pkt)
	assert.NoError(err)
	assert.NotNil(pkt)
	assert.Nil(pkt.Header().Bytes)
	assert.Equal(&lob.Header{Extra: map[string]interface{}{"bar": 0xdead}}, pkt.Header())
	assert.Equal([]byte("Bye world!"), pkt.Body(nil))
}

func BenchmarkPacketEncryption(b *testing.B, c cipherset.Cipher) {
	pkt := lob.New(bytes.Repeat([]byte{'x'}, 1024))

	lkey, err := c.GenerateKey()
	if err != nil {
		b.Fatal(err)
	}

	rkey, err := c.GenerateKey()
	if err != nil {
		b.Fatal(err)
	}

	lstate, err := c.NewState(lkey)
	if err != nil {
		b.Fatal(err)
	}

	rstate, err := c.NewState(rkey)
	if err != nil {
		b.Fatal(err)
	}

	err = lstate.SetRemoteKey(rkey)
	if err != nil {
		b.Fatal(err)
	}

	hs, err := lstate.EncryptHandshake(1, nil)
	if err != nil {
		b.Fatal(err)
	}

	hsMsg, err := c.DecryptHandshake(rkey, hs)
	if err != nil {
		b.Fatal(err)
	}

	ok := rstate.ApplyHandshake(hsMsg)
	if !ok {
		b.Fatal("handshake failed")
	}

	hs, err = rstate.EncryptHandshake(1, nil)
	if err != nil {
		b.Fatal(err)
	}

	hsMsg, err = c.DecryptHandshake(lkey, hs)
	if err != nil {
		b.Fatal(err)
	}

	ok = lstate.ApplyHandshake(hsMsg)
	if !ok {
		b.Fatal("handshake failed")
	}

	b.SetBytes(1024)
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		epkt, err := lstate.EncryptPacket(pkt)
		epkt.Free()
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkPacketDecryption(b *testing.B, c cipherset.Cipher) {
	pkt := lob.New(bytes.Repeat([]byte{'x'}, 1024))

	lkey, err := c.GenerateKey()
	if err != nil {
		b.Fatal(err)
	}

	rkey, err := c.GenerateKey()
	if err != nil {
		b.Fatal(err)
	}

	lstate, err := c.NewState(lkey)
	if err != nil {
		b.Fatal(err)
	}

	rstate, err := c.NewState(rkey)
	if err != nil {
		b.Fatal(err)
	}

	err = lstate.SetRemoteKey(rkey)
	if err != nil {
		b.Fatal(err)
	}

	hs, err := lstate.EncryptHandshake(1, nil)
	if err != nil {
		b.Fatal(err)
	}

	hsMsg, err := c.DecryptHandshake(rkey, hs)
	if err != nil {
		b.Fatal(err)
	}

	ok := rstate.ApplyHandshake(hsMsg)
	if !ok {
		b.Fatal("handshake failed")
	}

	hs, err = rstate.EncryptHandshake(1, nil)
	if err != nil {
		b.Fatal(err)
	}

	hsMsg, err = c.DecryptHandshake(lkey, hs)
	if err != nil {
		b.Fatal(err)
	}

	ok = lstate.ApplyHandshake(hsMsg)
	if !ok {
		b.Fatal("handshake failed")
	}

	pkt, err = rstate.EncryptPacket(pkt)
	if err != nil {
		b.Fatal(err)
	}

	b.SetBytes(1024)
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		epkt, err := lstate.DecryptPacket(pkt)
		epkt.Free()
		if err != nil {
			b.Fatal(err)
		}
	}
}


text:
import {Component} from '@angular/core';

@Component({
  selector: 'bnj-loader',
  template: `

  `
})
export class LoaderComponent {}


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

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#17d42d" />

    <corners android:radius="30dp" />
</shape>


text:
//
//  AFHTTPClient+AYRequestMethodPUT.h
//  AYNetworking
//
//  Created by Jan Boehler on 09.02.13.
//  Copyright (c) 2013 Jan Böhler. All rights reserved.
//

#import <AYNetworking.h>

@interface AFHTTPClient (AYRequestMethodPUT)

// Delagete API

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource timeout:(NSTimeInterval)timeout delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters timeout:(NSTimeInterval)timeout delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers delegate:(id<AYHTTPRequestOperationDelegate>)delegate;
/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout delegate:(id<AYHTTPRequestOperationDelegate>)delegate;

// Block API

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource timeout:(NSTimeInterval)timeout
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters timeout:(NSTimeInterval)timeout
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout
                        success:(void (^)(AFHTTPRequestOperation *operation, id response))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

// Synchronous API

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource timeout:(NSTimeInterval)timeout;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters timeout:(NSTimeInterval)timeout;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers;

/**
 */
- (AFHTTPRequestOperation *)put:(NSString *)resource parameters:(NSDictionary *)parameters headers:(NSDictionary *)headers timeout:(NSTimeInterval)timeout;

@end


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using eStationCore.IManagers;
using eStationCore.Model;
using eStationCore.Model.Fuel.Entity;
using eStationCore.Model.Fuel.Views;
using Humanizer;

namespace eStationCore.Store.SqlServer
{
    public class PompesManager : IPompesManager
    {
        private readonly StationContext _db;

        public PompesManager(StationContext stationContext)
        {
            _db = stationContext;
        }

        #region CRUD

        public bool Post(Pompe myPompe)
        {
            using (var db = new StationContext())
            {
                if (!db.Citernes.Any(f => f.CiterneGuid == myPompe.CiterneGuid))
                    throw new InvalidOperationException("CITERNE_REFERENCE_NOT_FOUND");

                if (myPompe.PompeGuid == Guid.Empty) myPompe.PompeGuid = Guid.NewGuid();

                myPompe.DateAdded = DateTime.Now;
                myPompe.LastEditDate = DateTime.Now;

                db.Pompes.Add(myPompe);
                return db.SaveChanges() > 0;
            }
        }

        public async Task<bool> Post(FuelPrelevement myPrelevement)
        {
            using (var db = new StationContext())
            {
                if (myPrelevement.PrelevementGuid == Guid.Empty) myPrelevement.PrelevementGuid = Guid.NewGuid();

                var citerneGuid = db.Pompes.Find(myPrelevement.PompeGuid).CiterneGuid;
                if (citerneGuid != null)
                    myPrelevement.CiterneGuid = (Guid)citerneGuid;
                else
                    throw new ArgumentException("CAN_NOT_FIND_CITERNE");

                myPrelevement.CurrentPrice = (await FuelManager.GetFuelCurrentPrice(db.Pompes.Find(myPrelevement.PompeGuid).Citerne.FuelGuid));

                myPrelevement.DateAdded = DateTime.Now;
                myPrelevement.LastEditDate = DateTime.Now;

                db.Set<FuelPrelevement>().Add(myPrelevement);
                return await db.SaveChangesAsync() > 0;
            }
        }

        public bool Put(Pompe myPompe)
        {
            using (var db = new StationContext())
            {
                myPompe.LastEditDate = DateTime.Now;

                db.Pompes.Attach(myPompe);
                db.Entry(myPompe).State = EntityState.Modified;
                return db.SaveChanges() > 0;
            }
        }

        public bool Put(FuelPrelevement myPrelevement)
        {
            using (var db = new StationContext())
            {
                myPrelevement.LastEditDate = DateTime.Now;

                db.Set<FuelPrelevement>().Attach(myPrelevement);
                db.Entry(myPrelevement).State = EntityState.Modified;
                return db.SaveChanges() > 0;
            }
        }

        public async Task<bool> Delete(Guid pompeGuid)
        {
            using (var db = new StationContext())
            {
                var myObject = await db.Pompes.FindAsync(pompeGuid);

                if (myObject == null) throw new InvalidOperationException("POMPE_NOT_FOUND");

                myObject.LastEditDate = DateTime.Now;
                myObject.DeleteDate = DateTime.Now;
                myObject.IsDeleted = true;

                db.Pompes.Attach(myObject);
                db.Entry(myObject).State = EntityState.Modified;
                return await db.SaveChangesAsync() > 0;
            }
        }

        public Pompe Get(Guid pompeGuid)
        {
            using (var db = new StationContext())
                return db.Pompes.Find(pompeGuid);
        }

        public async Task<bool> Post(Price newPrice)
        {
            using (var db = new StationContext())
            {
                if (!db.Fuels.Any(f => f.FuelGuid == newPrice.ProductGuid))
                    throw new InvalidOperationException("FUEL_REFERENCE_NOT_FOUND");

                if (newPrice.PriceGuid == Guid.Empty) newPrice.PriceGuid = Guid.NewGuid();

                newPrice.DateAdded = DateTime.Now;
                newPrice.LastEditDate = DateTime.Now;

                db.Set<Price>().Add(newPrice);
                return await db.SaveChangesAsync() > 0;
            }
        }

        #endregion

        #region Views

        public List<string> GetColonnes()
        {
            using (var db = new StationContext())
                return db.Pompes.Where(p=> !string.IsNullOrEmpty(p.Colonne)).Select(p=> p.Colonne.ToLower()).Distinct().ToList().Select(s=> s.Titleize()).ToList();
        }

        public IEnumerable<PrelevCard> GetPrelevCards(List<Guid> fuelsGuids, DateTime fromDate, DateTime toDate)
        {
            using (var db = new StationContext()){
                var prelevements = new List<FuelPrelevement>();
                foreach (var citernes in db.Fuels.Where(f => fuelsGuids.Contains(f.FuelGuid)).Select(d => d.Citernes.Where(c=> !c.IsDeleted)))
                    foreach (var citerne in citernes)
                        prelevements.AddRange(citerne.Prelevements.Where(p=> p.DatePrelevement.GetValueOrDefault().Date >= fromDate && p.DatePrelevement.GetValueOrDefault().Date<= toDate && !p.IsDeleted));
                return prelevements.OrderByDescending(p => p.DatePrelevement).Select(p => new PrelevCard(p)).ToList();
            }
        }

        public FuelPrelevement GetPrelevement(Guid prelevGuid)
        {
            using (var db = new StationContext())
                return db.Set<FuelPrelevement>().Find(prelevGuid);
        }

        public async Task<FuelPrelevement> GetLastPrelevement(Guid pompeGuid)
            => await StaticGetLastPrelevement(pompeGuid);

        public async Task<List<ColonneCard>> GetColonnesCard()
        {
            return await Task.Run(() =>
            {
                using (var db = new StationContext())
                {
                    var cardList = new ConcurrentBag<ColonneCard>();

                    var nd = new ColonneCard("");
                    if (nd.Pompes.Any())
                        cardList.Add(nd);

                    var cols = (db.Pompes.Where(s => !s.IsDeleted).ToList()
                        .Where(s => !string.IsNullOrEmpty(s.Colonne))
                        .Select(s => s.Colonne.ToLower())).Distinct().ToList();

                    Parallel.ForEach(cols, dep => cardList.Add(new ColonneCard(dep)));

                    return cardList.Any() ? cardList.OrderBy(d => d.Libel).ToList() : null;
                }
            });
        }

        #endregion

        #region Internal Static

        internal async static Task<FuelPrelevement> StaticGetLastPrelevement(Guid pompeGuid)
        {
            return await Task.Run(() => {
                using (var db = new StationContext())
                return db.Pompes.Find(pompeGuid).Prelevements.Where(p=> !p.IsDeleted).OrderByDescending(p => p.DatePrelevement).FirstOrDefault() ??
                    new FuelPrelevement {Meter = db.Pompes.Find(pompeGuid).InitialMeter};
            });
        }

        #endregion

    }
}


text:
package rescuecore2.worldmodel;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

/**
   Interface for the properties that make up an entity.
 */
public interface Property {
    /**
       Get the urn of this property.
       @return The urn of this property.
     */
    String getURN();

    /**
       Does this property have a defined value?
       @return True if a value has been set for this property, false otherwise.
     */
    boolean isDefined();

    /**
       Undefine the value of this property. Future calls to {@link #isDefined()} will return false.
     */
    void undefine();

    /**
       Take on the value of another property.
       @param other The other property to inspect.
       @throws IllegalArgumentException If the other property is the wrong type.
     */
    void takeValue(Property other);

    /**
       Write this property to a stream.
       @param out The stream to write to.
       @throws IOException If the write fails.
     */
    void write(OutputStream out) throws IOException;

    /**
       Read this property from a stream.
       @param in The stream to read from.
       @throws IOException If the read fails.
     */
    void read(InputStream in) throws IOException;

    /**
       Get the value of this property. If the property is undefined then the return value should be null.
       @return The value of this property.
    */
    Object getValue();

    /**
       Create a copy of this property.
       @return A copy of this property.
    */
    Property copy();
}


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "meeo/CoverageEnvelopeWin";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.CoverageEnvelopeWin = Ti.UI.createWindow({
        backgroundImage: "/images/bgImage.png",
        title: "Envelope",
        id: "CoverageEnvelopeWin"
    });
    $.__views.CoverageEnvelopeWin && $.addTopLevelView($.__views.CoverageEnvelopeWin);
    var __alloyId118 = [];
    $.__views.__alloyId119 = Ti.UI.createTableViewSection({
        headerTitle: L("WcsCoverageEnvelope_section1_title"),
        id: "__alloyId119"
    });
    __alloyId118.push($.__views.__alloyId119);
    $.__views.__alloyId120 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId120"
    });
    $.__views.__alloyId119.add($.__views.__alloyId120);
    $.__views.__alloyId121 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row1_title"),
        id: "__alloyId121"
    });
    $.__views.__alloyId120.add($.__views.__alloyId121);
    $.__views.srsName = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "srsName"
    });
    $.__views.__alloyId120.add($.__views.srsName);
    $.__views.__alloyId122 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId122"
    });
    $.__views.__alloyId119.add($.__views.__alloyId122);
    $.__views.__alloyId123 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row2_title"),
        id: "__alloyId123"
    });
    $.__views.__alloyId122.add($.__views.__alloyId123);
    $.__views.srsDomain = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "srsDomain"
    });
    $.__views.__alloyId122.add($.__views.srsDomain);
    $.__views.__alloyId124 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId124"
    });
    $.__views.__alloyId119.add($.__views.__alloyId124);
    $.__views.__alloyId125 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row3_title"),
        id: "__alloyId125"
    });
    $.__views.__alloyId124.add($.__views.__alloyId125);
    $.__views.axisLabel = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "axisLabel"
    });
    $.__views.__alloyId124.add($.__views.axisLabel);
    $.__views.__alloyId126 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId126"
    });
    $.__views.__alloyId119.add($.__views.__alloyId126);
    $.__views.__alloyId127 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row4_title"),
        id: "__alloyId127"
    });
    $.__views.__alloyId126.add($.__views.__alloyId127);
    $.__views.axisUoms = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "axisUoms"
    });
    $.__views.__alloyId126.add($.__views.axisUoms);
    $.__views.__alloyId128 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId128"
    });
    $.__views.__alloyId119.add($.__views.__alloyId128);
    $.__views.__alloyId129 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row5_title"),
        id: "__alloyId129"
    });
    $.__views.__alloyId128.add($.__views.__alloyId129);
    $.__views.lowerCorner = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "lowerCorner"
    });
    $.__views.__alloyId128.add($.__views.lowerCorner);
    $.__views.__alloyId130 = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        backgroundColor: "#fff",
        hasChild: "false",
        id: "__alloyId130"
    });
    $.__views.__alloyId119.add($.__views.__alloyId130);
    $.__views.__alloyId131 = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.titleFontSize,
            fontWeight: "bold"
        },
        color: Ti.API.WxsCss.titleColor,
        left: "10dp",
        top: "5dp",
        height: Ti.UI.SIZE,
        right: "10dp",
        text: L("WcsCoverageEnvelope_row6_title"),
        id: "__alloyId131"
    });
    $.__views.__alloyId130.add($.__views.__alloyId131);
    $.__views.upperCorner = Ti.UI.createLabel({
        font: {
            fontSize: Ti.API.WxsCss.descriptionFontSize,
            fontWeight: "normal"
        },
        color: Ti.API.WxsCss.descriptionColor,
        left: "10dp",
        top: "25dp",
        bottom: "5dp",
        right: "10dp",
        height: Ti.UI.SIZE,
        id: "upperCorner"
    });
    $.__views.__alloyId130.add($.__views.upperCorner);
    $.__views.__alloyId117 = Ti.UI.createTableView({
        minRowHeight: "50dp",
        backgroundColor: "transparent",
        separatorColor: "gray",
        data: __alloyId118,
        id: "__alloyId117"
    });
    $.__views.CoverageEnvelopeWin.add($.__views.__alloyId117);
    exports.destroy = function() {};
    _.extend($, $.__views);
    Ti.API.WxsCss;
    var xmlData = arguments[0].xmlData;
    $.CoverageEnvelopeWin.addEventListener("open", function() {
        var actionBar;
        if ($.CoverageEnvelopeWin.activity) {
            actionBar = $.CoverageEnvelopeWin.activity.actionBar;
            if (actionBar) {
                actionBar.displayHomeAsUp = true;
                actionBar.onHomeIconItemSelected = function() {
                    $.CoverageEnvelopeWin.close();
                };
            }
        } else Ti.API.error("Can't access action bar on a lightweight window.");
    });
    $.srsName.text = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getAttribute("srsName");
    $.srsDomain.text = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getAttribute("srsDimension");
    $.axisLabel.text = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getAttribute("axisLabels").replace(/ /g, "\n");
    $.axisUoms.text = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getAttribute("uomLabels").replace(/ /g, "\n");
    var str = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getElementsByTagName("lowerCorner").item(0).textContent;
    var numbersArray = [];
    numbersArray = str.split(" ");
    str = "";
    for (var i = 0; numbersArray.length > i; i++) str += parseFloat(numbersArray[i]).toFixed(6) + "\n";
    str = str.substr(0, str.length - 1);
    $.lowerCorner.text = str;
    var str = xmlData.documentElement.getElementsByTagName("Envelope").item(0).getElementsByTagName("upperCorner").item(0).textContent;
    var numbersArray = [];
    numbersArray = str.split(" ");
    str = "";
    for (var i = 0; numbersArray.length > i; i++) str += parseFloat(numbersArray[i]).toFixed(6) + "\n";
    str = str.substr(0, str.length - 1);
    $.upperCorner.text = str;
    if (Alloy.Globals.debug_mode) {
        Ti.API.info($.srsName.text);
        Ti.API.info($.srsName.text);
        Ti.API.info($.srsDomain.text);
        Ti.API.info($.axisLabel.text);
        Ti.API.info($.axisUoms.text);
        Ti.API.info($.lowerCorner.text);
        Ti.API.info($.upperCorner.text);
    }
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
async function fetchAPI(query, { variables, preview } = {}) {
  const res = await fetch(process.env.GRAPHCMS_PROJECT_API, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${
        preview
          ? process.env.GRAPHCMS_DEV_AUTH_TOKEN
          : process.env.GRAPHCMS_PROD_AUTH_TOKEN
      }`,
    },
    body: JSON.stringify({
      query,
      variables,
    }),
  })
  const json = await res.json()

  if (json.errors) {
    console.log(process.env.NEXT_EXAMPLE_CMS_GCMS_PROJECT_ID)
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }

  return json.data
}

export async function getPreviewPostBySlug(slug) {
  const data = await fetchAPI(
    `
    query PostBySlug($slug: String!, $stage: Stage!) {
      post(where: {slug: $slug}, stage: $stage) {
        slug
      }
    }`,
    {
      preview: true,
      variables: {
        stage: 'DRAFT',
        slug,
      },
    }
  )
  return data.post
}

export async function getAllPostsWithSlug() {
  const data = await fetchAPI(`
    {
      posts {
        slug
      }
    }
  `)
  return data.posts
}

export async function getAllPostsForHome(preview) {
  const data = await fetchAPI(
    `
    {
      posts(orderBy: date_DESC, first: 20) {
        title
        slug
        excerpt
        date
        coverImage {
          url(transformation: {
            image: {
              resize: {
                fit:crop,
                width:2000,
                height:1000
              }
            }
          })
        }
        author {
          name
          picture {
            url(transformation: {
              image: {
                resize: {
                  width:100,
                  height:100,
                  fit:crop
                }
              }
            })
          }
        }
      }
    }
  `,
    { preview }
  )
  return data.posts
}

export async function getPostAndMorePosts(slug, preview) {
  const data = await fetchAPI(
    `
    query PostBySlug($slug: String!, $stage: Stage!) {
      post(stage: $stage, where: {slug: $slug}) {
        title
        slug
        content {
          html
        }
        date
        ogImage: coverImage {
          url(transformation: {image: {resize: {fit: crop, width: 2000, height: 1000}}})
        }
        coverImage {
          url(transformation: {image: {resize: {fit: crop, width: 2000, height: 1000}}})
        }
        author {
          name
          picture {
            url(transformation: {image: {resize: {fit: crop, width: 100, height: 100}}})
          }
        }
      }
      morePosts: posts(orderBy: date_DESC, first: 2, where: {slug_not_in: [$slug]}) {
        title
        slug
        excerpt
        date
        coverImage {
          url(transformation: {image: {resize: {fit: crop, width: 2000, height: 1000}}})
        }
        author {
          name
          picture {
            url(transformation: {image: {resize: {fit: crop, width: 100, height: 100}}})
          }
        }
      }
    }
  `,
    {
      preview,
      variables: {
        stage: preview ? 'DRAFT' : 'PUBLISHED',
        slug,
      },
    }
  )
  return data
}


text:
WebInspector.AuditsPanel = function()
{
    WebInspector.Panel.call(this, "audits");

    this._constructCategories();

    this.createSidebar();
    this.auditsTreeElement = new WebInspector.SidebarSectionTreeElement("", {}, true);
    this.sidebarTree.appendChild(this.auditsTreeElement);
    this.auditsTreeElement.listItemElement.addStyleClass("hidden");
    this.auditsTreeElement.expand();

    this.auditsItemTreeElement = new WebInspector.AuditsSidebarTreeElement();
    this.auditsTreeElement.appendChild(this.auditsItemTreeElement);

    this.auditResultsTreeElement = new WebInspector.SidebarSectionTreeElement(WebInspector.UIString("RESULTS"), {}, true);
    this.sidebarTree.appendChild(this.auditResultsTreeElement);
    this.auditResultsTreeElement.expand();

    this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear audit results."), "clear-status-bar-item");
    this.clearResultsButton.addEventListener("click", this._clearButtonClicked.bind(this), false);

    this.viewsContainerElement = document.createElement("div");
    this.viewsContainerElement.id = "audit-views";
    this.element.appendChild(this.viewsContainerElement);

    this._launcherView = new WebInspector.AuditLauncherView(this.categoriesById, this.initiateAudit.bind(this));
}

WebInspector.AuditsPanel.prototype = {
    get toolbarItemLabel()
    {
        return WebInspector.UIString("Audits");
    },

    get statusBarItems()
    {
        return [this.clearResultsButton.element];
    },

    get mainResourceLoadTime()
    {
        return this._mainResourceLoadTime;
    },

    set mainResourceLoadTime(x)
    {
        this._mainResourceLoadTime = x;
        this._didMainResourceLoad();
    },

    get mainResourceDOMContentTime()
    {
        return this._mainResourceDOMContentTime;
    },

    set mainResourceDOMContentTime(x)
    {
        this._mainResourceDOMContentTime = x;
    },

    get categoriesById()
    {
        return this._auditCategoriesById;
    },

    resourceStarted: function(resource)
    {
        this._launcherView.resourceStarted(resource);
    },

    resourceFinished: function(resource)
    {
        this._launcherView.resourceFinished(resource);
    },

    _constructCategories: function()
    {
        this._auditCategoriesById = {};
        for (var categoryCtorID in WebInspector.AuditCategories) {
            var auditCategory = new WebInspector.AuditCategories[categoryCtorID]();
            auditCategory._id = categoryCtorID;
            this.categoriesById[categoryCtorID] = auditCategory;
        }
    },

    _executeAudit: function(categories, resultCallback)
    {
        var resources = [];
        for (var id in WebInspector.resources)
            resources.push(WebInspector.resources[id]);

        var rulesRemaining = 0;
        for (var i = 0; i < categories.length; ++i)
            rulesRemaining += categories[i].ruleCount;

        var results = [];
        var mainResourceURL = WebInspector.mainResource.url;

        function ruleResultReadyCallback(categoryResult, ruleResult)
        {
            if (ruleResult && ruleResult.children)
                categoryResult.addRuleResult(ruleResult);

            --rulesRemaining;

            if (!rulesRemaining && resultCallback)
                resultCallback(mainResourceURL, results);
        }

        if (!rulesRemaining) {
            resultCallback(mainResourceURL, results);
            return;
        }

        for (var i = 0; i < categories.length; ++i) {
            var category = categories[i];
            var result = new WebInspector.AuditCategoryResult(category);
            results.push(result);
            category.runRules(resources, ruleResultReadyCallback.bind(null, result));
        }
    },

    _auditFinishedCallback: function(launcherCallback, mainResourceURL, results)
    {
        var children = this.auditResultsTreeElement.children;
        var ordinal = 1;
        for (var i = 0; i < children.length; ++i) {
            if (children[i].mainResourceURL === mainResourceURL)
                ordinal++;
        }

        var resultTreeElement = new WebInspector.AuditResultSidebarTreeElement(results, mainResourceURL, ordinal);
        this.auditResultsTreeElement.appendChild(resultTreeElement);
        resultTreeElement.reveal();
        resultTreeElement.select();
        if (launcherCallback)
            launcherCallback();
    },

    initiateAudit: function(categoryIds, runImmediately, launcherCallback)
    {
        if (!categoryIds || !categoryIds.length)
            return;

        var categories = [];
        for (var i = 0; i < categoryIds.length; ++i)
            categories.push(this.categoriesById[categoryIds[i]]);

        function initiateAuditCallback(categories, launcherCallback)
        {
            this._executeAudit(categories, this._auditFinishedCallback.bind(this, launcherCallback));
        }

        if (runImmediately)
            initiateAuditCallback.call(this, categories, launcherCallback);
        else
            this._reloadResources(initiateAuditCallback.bind(this, categories, launcherCallback));
    },

    _reloadResources: function(callback)
    {
        this._resourceTrackingCallback = callback;

        if (!WebInspector.panels.resources.resourceTrackingEnabled) {
            InspectorBackend.enableResourceTracking(false);
            this._updateLauncherViewControls(true);
        } else
            InspectorBackend.reloadPage();
    },

    _didMainResourceLoad: function()
    {
        if (this._resourceTrackingCallback) {
            var callback = this._resourceTrackingCallback;
            delete this._resourceTrackingCallback;
            callback();
        }
    },

    showResults: function(categoryResults)
    {
        if (!categoryResults._resultView)
            categoryResults._resultView = new WebInspector.AuditResultView(categoryResults);

        this.visibleView = categoryResults._resultView;
    },

    showLauncherView: function()
    {
        this.visibleView = this._launcherView;
    },

    get visibleView()
    {
        return this._visibleView;
    },

    set visibleView(x)
    {
        if (this._visibleView === x)
            return;

        if (this._visibleView)
            this._visibleView.hide();

        this._visibleView = x;

        if (x)
            x.show(this.viewsContainerElement);
    },

    show: function()
    {
        WebInspector.Panel.prototype.show.call(this);
        this._updateLauncherViewControls(WebInspector.panels.resources.resourceTrackingEnabled);
    },

    reset: function()
    {
        this._launcherView.reset();
    },

    attach: function()
    {
        WebInspector.Panel.prototype.attach.call(this);

        this.auditsItemTreeElement.select();
    },

    updateMainViewWidth: function(width)
    {
        this.viewsContainerElement.style.left = width + "px";
    },

    _updateLauncherViewControls: function(isTracking)
    {
        if (this._launcherView)
            this._launcherView.updateResourceTrackingState(isTracking);
    },

    _clearButtonClicked: function()
    {
        this.auditsItemTreeElement.reveal();
        this.auditsItemTreeElement.select();
        this.auditResultsTreeElement.removeChildren();
    }
}

WebInspector.AuditsPanel.prototype.__proto__ = WebInspector.Panel.prototype;

WebInspector.AuditCategory = function(displayName)
{
    this._displayName = displayName;
    this._rules = [];
}

WebInspector.AuditCategory.prototype = {
    get id()
    {
        // this._id value is injected at construction time.
        return this._id;
    },

    get displayName()
    {
        return this._displayName;
    },

    get ruleCount()
    {
        this._ensureInitialized();
        return this._rules.length;
    },

    addRule: function(rule, severity)
    {
        rule.severity = severity;
        this._rules.push(rule);
    },

    runRules: function(resources, callback)
    {
        this._ensureInitialized();
        for (var i = 0; i < this._rules.length; ++i)
            this._rules[i].run(resources, callback);
    },

    _ensureInitialized: function()
    {
        if (!this._initialized) {
            if ("initialize" in this)
                this.initialize();
            this._initialized = true;
        }
    }
}

WebInspector.AuditRule = function(id, displayName)
{
    this._id = id;
    this._displayName = displayName;
}

WebInspector.AuditRule.Severity = {
    Info: "info",
    Warning: "warning",
    Severe: "severe"
}

WebInspector.AuditRule.SeverityOrder = {
    "info": 3,
    "warning": 2,
    "severe": 1
}

WebInspector.AuditRule.prototype = {
    get id()
    {
        return this._id;
    },

    get displayName()
    {
        return this._displayName;
    },

    set severity(severity)
    {
        this._severity = severity;
    },

    run: function(resources, callback)
    {
        var result = new WebInspector.AuditRuleResult(this.displayName);
        result.severity = this._severity;
        this.doRun(resources, result, callback);
    },

    doRun: function(resources, result, callback)
    {
        throw new Error("doRun() not implemented");
    }
}

WebInspector.AuditCategoryResult = function(category)
{
    this.title = category.displayName;
    this.ruleResults = [];
}

WebInspector.AuditCategoryResult.prototype = {
    addRuleResult: function(ruleResult)
    {
        this.ruleResults.push(ruleResult);
    }
}

WebInspector.AuditRuleResult = function(value, expanded, className)
{
    this.value = value;
    this.className = className;
    this.expanded = expanded;
    this.violationCount = 0;
}

WebInspector.AuditRuleResult.linkifyDisplayName = function(url)
{
    return WebInspector.linkifyURL(url, WebInspector.displayNameForURL(url));
}

WebInspector.AuditRuleResult.resourceDomain = function(domain)
{
    return domain || WebInspector.UIString("[empty domain]");
}

WebInspector.AuditRuleResult.prototype = {
    addChild: function(value, expanded, className)
    {
        if (!this.children)
            this.children = [];
        var entry = new WebInspector.AuditRuleResult(value, expanded, className);
        this.children.push(entry);
        return entry;
    },

    addURL: function(url)
    {
        return this.addChild(WebInspector.AuditRuleResult.linkifyDisplayName(url));
    },

    addURLs: function(urls)
    {
        for (var i = 0; i < urls.length; ++i)
            this.addURL(urls[i]);
    },

    addSnippet: function(snippet)
    {
        return this.addChild(snippet, false, "source-code");
    }
}

WebInspector.AuditsSidebarTreeElement = function()
{
    this.small = false;

    WebInspector.SidebarTreeElement.call(this, "audits-sidebar-tree-item", WebInspector.UIString("Audits"), "", null, false);
}

WebInspector.AuditsSidebarTreeElement.prototype = {
    onattach: function()
    {
        WebInspector.SidebarTreeElement.prototype.onattach.call(this);
    },

    onselect: function()
    {
        WebInspector.panels.audits.showLauncherView();
    },

    get selectable()
    {
        return true;
    },

    refresh: function()
    {
        this.refreshTitles();
    }
}

WebInspector.AuditsSidebarTreeElement.prototype.__proto__ = WebInspector.SidebarTreeElement.prototype;

WebInspector.AuditResultSidebarTreeElement = function(results, mainResourceURL, ordinal)
{
    this.results = results;
    this.mainResourceURL = mainResourceURL;

    WebInspector.SidebarTreeElement.call(this, "audit-result-sidebar-tree-item", String.sprintf("%s (%d)", mainResourceURL, ordinal), "", {}, false);
}

WebInspector.AuditResultSidebarTreeElement.prototype = {
    onselect: function()
    {
        WebInspector.panels.audits.showResults(this.results);
    },

    get selectable()
    {
        return true;
    }
}

WebInspector.AuditResultSidebarTreeElement.prototype.__proto__ = WebInspector.SidebarTreeElement.prototype;

// Contributed audit rules should go into this namespace.
WebInspector.AuditRules = {};

// Contributed audit categories should go into this namespace.
WebInspector.AuditCategories = {};