text:
#ifndef _LSM_H
#define _LSM_H
#include <stddef.h>
#include "sqlite4.h" /* for sqlite4_size_t */
#ifdef __cplusplus
extern "C" {
#endif

/*
** Opaque handle types.
*/
typedef struct lsm_compress lsm_compress;   /* Compression library functions */
typedef struct lsm_compress_factory lsm_compress_factory;
typedef struct lsm_cursor lsm_cursor;       /* Database cursor handle */
typedef struct lsm_db lsm_db;               /* Database connection handle */
typedef struct lsm_env lsm_env;             /* Runtime environment */
typedef struct lsm_file lsm_file;           /* OS file handle */
typedef struct lsm_mutex lsm_mutex;         /* Mutex handle */

/* 64-bit integer type used for file offsets. */
typedef long long int lsm_i64;              /* 64-bit signed integer type */

/* Candidate values for the 3rd argument to lsm_env.xLock() */
#define LSM_LOCK_UNLOCK 0
#define LSM_LOCK_SHARED 1
#define LSM_LOCK_EXCL   2

/* Flags for lsm_env.xOpen() */
#define LSM_OPEN_READONLY 0x0001

/*
** CAPI: Database Runtime Environment
**
** Run-time environment used by LSM
*/
struct lsm_env {
  int nByte;                 /* Size of this structure in bytes */
  int iVersion;              /* Version number of this structure (1) */
  /****** file i/o ***********************************************/
  void *pVfsCtx;
  int (*xFullpath)(lsm_env*, const char *, char *, int *);
  int (*xOpen)(lsm_env*, const char *, int flags, lsm_file **);
  int (*xRead)(lsm_file *, lsm_i64, void *, int);
  int (*xWrite)(lsm_file *, lsm_i64, void *, int);
  int (*xTruncate)(lsm_file *, lsm_i64);
  int (*xSync)(lsm_file *);
  int (*xSectorSize)(lsm_file *);
  int (*xRemap)(lsm_file *, lsm_i64, void **, lsm_i64*);
  int (*xFileid)(lsm_file *, void *pBuf, int *pnBuf);
  int (*xClose)(lsm_file *);
  int (*xUnlink)(lsm_env*, const char *);
  int (*xLock)(lsm_file*, int, int);
  int (*xTestLock)(lsm_file*, int, int, int);
  int (*xShmMap)(lsm_file*, int, int, void **);
  void (*xShmBarrier)(void);
  int (*xShmUnmap)(lsm_file*, int);
  /****** memory allocation ****************************************/
  void *pMemCtx;
  void *(*xMalloc)(lsm_env*, int);            /* malloc(3) function */
  void *(*xRealloc)(lsm_env*, void *, int);   /* realloc(3) function */
  void (*xFree)(lsm_env*, void *);            /* free(3) function */
  sqlite4_size_t (*xSize)(lsm_env*, void *);  /* xSize function */
  /****** mutexes ****************************************************/
  void *pMutexCtx;
  int (*xMutexStatic)(lsm_env*,int,lsm_mutex**); /* Obtain a static mutex */
  int (*xMutexNew)(lsm_env*, lsm_mutex**);       /* Get a new dynamic mutex */
  void (*xMutexDel)(lsm_mutex *);           /* Delete an allocated mutex */
  void (*xMutexEnter)(lsm_mutex *);         /* Grab a mutex */
  int (*xMutexTry)(lsm_mutex *);            /* Attempt to obtain a mutex */
  void (*xMutexLeave)(lsm_mutex *);         /* Leave a mutex */
  int (*xMutexHeld)(lsm_mutex *);           /* Return true if mutex is held */
  int (*xMutexNotHeld)(lsm_mutex *);        /* Return true if mutex not held */
  /****** other ****************************************************/
  int (*xSleep)(lsm_env*, int microseconds);

  /* New fields may be added in future releases, in which case the
  ** iVersion value will increase. */
};

/*
** Values that may be passed as the second argument to xMutexStatic.
*/
#define LSM_MUTEX_GLOBAL 1
#define LSM_MUTEX_HEAP   2

/*
** CAPI: LSM Error Codes
*/
#define LSM_OK         0
#define LSM_ERROR      1
#define LSM_BUSY       5
#define LSM_NOMEM      7
#define LSM_READONLY   8
#define LSM_IOERR     10
#define LSM_CORRUPT   11
#define LSM_FULL      13
#define LSM_CANTOPEN  14
#define LSM_PROTOCOL  15
#define LSM_MISUSE    21

#define LSM_MISMATCH  50

#define LSM_IOERR_NOENT (LSM_IOERR | (1<<8))

/*
** CAPI: Creating and Destroying Database Connection Handles
**
** Open and close a database connection handle.
*/
int lsm_new(lsm_env*, lsm_db **ppDb);
int lsm_close(lsm_db *pDb);

/*
** CAPI: Connecting to a Database
*/
int lsm_open(lsm_db *pDb, const char *zFilename);

/*
** CAPI: Obtaining pointers to database environments
**
** Return a pointer to the environment used by the database connection
** passed as the first argument. Assuming the argument is valid, this
** function always returns a valid environment pointer - it cannot fail.
*/
lsm_env *lsm_get_env(lsm_db *pDb);

/*
** The lsm_default_env() function returns a pointer to the default LSM
** environment for the current platform.
*/
lsm_env *lsm_default_env(void);

/*
** CAPI: Configuring a database connection.
**
** The lsm_config() function is used to configure a database connection.
*/
int lsm_config(lsm_db *, int, ...);

/*
** The following values may be passed as the second argument to lsm_config().
**
** LSM_CONFIG_AUTOFLUSH:
**   A read/write integer parameter.
**
**   This value determines the amount of data allowed to accumulate in a
**   live in-memory tree before it is marked as old. After committing a
**   transaction, a connection checks if the size of the live in-memory tree,
**   including data structure overhead, is greater than the value of this
**   option in KB. If it is, and there is not already an old in-memory tree,
**   the live in-memory tree is marked as old.
**
**   The maximum allowable value is 1048576 (1GB). There is no minimum
**   value. If this parameter is set to zero, then an attempt is made to
**   mark the live in-memory tree as old after each transaction is committed.
**
**   The default value is 1024 (1MB).
**
** LSM_CONFIG_PAGE_SIZE:
**   A read/write integer parameter. This parameter may only be set before
**   lsm_open() has been called.
**
** LSM_CONFIG_BLOCK_SIZE:
**   A read/write integer parameter.
**
**   This parameter may only be set before lsm_open() has been called. It
**   must be set to a power of two between 64 and 65536, inclusive (block
**   sizes between 64KB and 64MB).
**
**   If the connection creates a new database, the block size of the new
**   database is set to the value of this option in KB. After lsm_open()
**   has been called, querying this parameter returns the actual block
**   size of the opened database.
**
**   The default value is 1024 (1MB blocks).
**
** LSM_CONFIG_SAFETY:
**   A read/write integer parameter. Valid values are 0, 1 (the default)
**   and 2. This parameter determines how robust the database is in the
**   face of a system crash (e.g. a power failure or operating system
**   crash). As follows:
**
**     0 (off):    No robustness. A system crash may corrupt the database.
**
**     1 (normal): Some robustness. A system crash may not corrupt the
**                 database file, but recently committed transactions may
**                 be lost following recovery.
**
**     2 (full):   Full robustness. A system crash may not corrupt the
**                 database file. Following recovery the database file
**                 contains all successfully committed transactions.
**
** LSM_CONFIG_AUTOWORK:
**   A read/write integer parameter.
**
** LSM_CONFIG_AUTOCHECKPOINT:
**   A read/write integer parameter.
**
**   If this option is set to non-zero value N, then a checkpoint is
**   automatically attempted after each N KB of data have been written to
**   the database file.
**
**   The amount of uncheckpointed data already written to the database file
**   is a global parameter. After performing database work (writing to the
**   database file), the process checks if the total amount of uncheckpointed
**   data exceeds the value of this paramter. If so, a checkpoint is performed.
**   This means that this option may cause the connection to perform a
**   checkpoint even if the current connection has itself written very little
**   data into the database file.
**
**   The default value is 2048 (checkpoint every 2MB).
**
** LSM_CONFIG_MMAP:
**   A read/write integer parameter. If this value is set to 0, then the
**   database file is accessed using ordinary read/write IO functions. Or,
**   if it is set to 1, then the database file is memory mapped and accessed
**   that way. If this parameter is set to any value N greater than 1, then
**   up to the first N KB of the file are memory mapped, and any remainder
**   accessed using read/write IO.
**
**   The default value is 1 on 64-bit platforms and 32768 on 32-bit platforms.
**
**
** LSM_CONFIG_USE_LOG:
**   A read/write boolean parameter. True (the default) to use the log
**   file normally. False otherwise.
**
** LSM_CONFIG_AUTOMERGE:
**   A read/write integer parameter. The minimum number of segments to
**   merge together at a time. Default value 4.
**
** LSM_CONFIG_MAX_FREELIST:
**   A read/write integer parameter. The maximum number of free-list
**   entries that are stored in a database checkpoint (the others are
**   stored elsewhere in the database).
**
**   There is no reason for an application to configure or query this
**   parameter. It is only present because configuring a small value
**   makes certain parts of the lsm code easier to test.
**
** LSM_CONFIG_MULTIPLE_PROCESSES:
**   A read/write boolean parameter. This parameter may only be set before
**   lsm_open() has been called. If true, the library uses shared-memory
**   and posix advisory locks to co-ordinate access by clients from within
**   multiple processes. Otherwise, if false, all database clients must be
**   located in the same process. The default value is true.
**
** LSM_CONFIG_SET_COMPRESSION:
**   Set the compression methods used to compress and decompress database
**   content. The argument to this option should be a pointer to a structure
**   of type lsm_compress. The lsm_config() method takes a copy of the
**   structures contents.
**
**   This option may only be used before lsm_open() is called. Invoking it
**   after lsm_open() has been called results in an LSM_MISUSE error.
**
** LSM_CONFIG_GET_COMPRESSION:
**   Query the compression methods used to compress and decompress database
**   content.
**
** LSM_CONFIG_SET_COMPRESSION_FACTORY:
**   Configure a factory method to be invoked in case of an LSM_MISMATCH
**   error.
**
** LSM_CONFIG_READONLY:
**   A read/write boolean parameter. This parameter may only be set before
**   lsm_open() is called.
*/
#define LSM_CONFIG_AUTOFLUSH                1
#define LSM_CONFIG_PAGE_SIZE                2
#define LSM_CONFIG_SAFETY                   3
#define LSM_CONFIG_BLOCK_SIZE               4
#define LSM_CONFIG_AUTOWORK                 5
#define LSM_CONFIG_MMAP                     7
#define LSM_CONFIG_USE_LOG                  8
#define LSM_CONFIG_AUTOMERGE                9
#define LSM_CONFIG_MAX_FREELIST            10
#define LSM_CONFIG_MULTIPLE_PROCESSES      11
#define LSM_CONFIG_AUTOCHECKPOINT          12
#define LSM_CONFIG_SET_COMPRESSION         13
#define LSM_CONFIG_GET_COMPRESSION         14
#define LSM_CONFIG_SET_COMPRESSION_FACTORY 15
#define LSM_CONFIG_READONLY                16

#define LSM_SAFETY_OFF    0
#define LSM_SAFETY_NORMAL 1
#define LSM_SAFETY_FULL   2

/*
** CAPI: Compression and/or Encryption Hooks
*/
struct lsm_compress {
  void *pCtx;
  unsigned int iId;
  int (*xBound)(void *, int nSrc);
  int (*xCompress)(void *, char *, int *, const char *, int);
  int (*xUncompress)(void *, char *, int *, const char *, int);
  void (*xFree)(void *pCtx);
};

struct lsm_compress_factory {
  void *pCtx;
  int (*xFactory)(void *, lsm_db *, unsigned int);
  void (*xFree)(void *pCtx);
};

#define LSM_COMPRESSION_EMPTY 0
#define LSM_COMPRESSION_NONE  1

/*
** CAPI: Allocating and Freeing Memory
**
** Invoke the memory allocation functions that belong to environment
** pEnv. Or the system defaults if no memory allocation functions have
** been registered.
*/
void *lsm_malloc(lsm_env*, size_t);
void *lsm_realloc(lsm_env*, void *, size_t);
void lsm_free(lsm_env*, void *);

/*
** CAPI: Querying a Connection For Operational Data
**
** Query a database connection for operational statistics or data.
*/
int lsm_info(lsm_db *, int, ...);

int lsm_get_user_version(lsm_db *, unsigned int *);
int lsm_set_user_version(lsm_db *, unsigned int);

/*
** The following values may be passed as the second argument to lsm_info().
**
** LSM_INFO_NWRITE:
**   The third parameter should be of type (int *). The location pointed
**   to by the third parameter is set to the number of 4KB pages written to
**   the database file during the lifetime of this connection.
**
** LSM_INFO_NREAD:
**   The third parameter should be of type (int *). The location pointed
**   to by the third parameter is set to the number of 4KB pages read from
**   the database file during the lifetime of this connection.
**
** LSM_INFO_DB_STRUCTURE:
**   The third argument should be of type (char **). The location pointed
**   to is populated with a pointer to a nul-terminated string containing
**   the string representation of a Tcl data-structure reflecting the
**   current structure of the database file. Specifically, the current state
**   of the worker snapshot. The returned string should be eventually freed
**   by the caller using lsm_free().
**
**   The returned list contains one element for each level in the database,
**   in order from most to least recent. Each element contains a
**   single element for each segment comprising the corresponding level,
**   starting with the lhs segment, then each of the rhs segments (if any)
**   in order from most to least recent.
**
**   Each segment element is itself a list of 4 integer values, as follows:
**
**   <ol><li> First page of segment
**       <li> Last page of segment
**       <li> Root page of segment (if applicable)
**       <li> Total number of pages in segment
**   </ol>
**
** LSM_INFO_ARRAY_STRUCTURE:
**   There should be two arguments passed following this option (i.e. a
**   total of four arguments passed to lsm_info()). The first argument
**   should be the page number of the first page in a database array
**   (perhaps obtained from an earlier INFO_DB_STRUCTURE call). The second
**   trailing argument should be of type (char **). The location pointed
**   to is populated with a pointer to a nul-terminated string that must
**   be eventually freed using lsm_free() by the caller.
**
**   The output string contains the text representation of a Tcl list of
**   integers. Each pair of integers represent a range of pages used by
**   the identified array. For example, if the array occupies database
**   pages 993 to 1024, then pages 2048 to 2777, then the returned string
**   will be "993 1024 2048 2777".
**
**   If the specified integer argument does not correspond to the first
**   page of any database array, LSM_ERROR is returned and the output
**   pointer is set to a NULL value.
**
** LSM_INFO_LOG_STRUCTURE:
**   The third argument should be of type (char **). The location pointed
**   to is populated with a pointer to a nul-terminated string containing
**   the string representation of a Tcl data-structure. The returned
**   string should be eventually freed by the caller using lsm_free().
**
**   The Tcl structure returned is a list of six integers that describe
**   the current structure of the log file.
**
** LSM_INFO_ARRAY_PAGES:
**
** LSM_INFO_PAGE_ASCII_DUMP:
**   As with LSM_INFO_ARRAY_STRUCTURE, there should be two arguments passed
**   with calls that specify this option - an integer page number and a
**   (char **) used to return a nul-terminated string that must be later
**   freed using lsm_free(). In this case the output string is populated
**   with a human-readable description of the page content.
**
**   If the page cannot be decoded, it is not an error. In this case the
**   human-readable output message will report the systems failure to
**   interpret the page data.
**
** LSM_INFO_PAGE_HEX_DUMP:
**   This argument is similar to PAGE_ASCII_DUMP, except that keys and
**   values are represented using hexadecimal notation instead of ascii.
**
** LSM_INFO_FREELIST:
**   The third argument should be of type (char **). The location pointed
**   to is populated with a pointer to a nul-terminated string containing
**   the string representation of a Tcl data-structure. The returned
**   string should be eventually freed by the caller using lsm_free().
**
**   The Tcl structure returned is a list containing one element for each
**   free block in the database. The element itself consists of two
**   integers - the block number and the id of the snapshot that freed it.
**
** LSM_INFO_CHECKPOINT_SIZE:
**   The third argument should be of type (int *). The location pointed to
**   by this argument is populated with the number of KB written to the
**   database file since the most recent checkpoint.
**
** LSM_INFO_TREE_SIZE:
**   If this value is passed as the second argument to an lsm_info() call, it
**   should be followed by two arguments of type (int *) (for a total of four
**   arguments).
**
**   At any time, there are either one or two tree structures held in shared
**   memory that new database clients will access (there may also be additional
**   tree structures being used by older clients - this API does not provide
**   information on them). One tree structure - the current tree - is used to
**   accumulate new data written to the database. The other tree structure -
**   the old tree - is a read-only tree holding older data and may be flushed
**   to disk at any time.
**
**   Assuming no error occurs, the location pointed to by the first of the two
**   (int *) arguments is set to the size of the old in-memory tree in KB.
**   The second is set to the size of the current, or live in-memory tree.
**
** LSM_INFO_COMPRESSION_ID:
**   This value should be followed by a single argument of type
**   (unsigned int *). If successful, the location pointed to is populated
**   with the database compression id before returning.
*/
#define LSM_INFO_NWRITE           1
#define LSM_INFO_NREAD            2
#define LSM_INFO_DB_STRUCTURE     3
#define LSM_INFO_LOG_STRUCTURE    4
#define LSM_INFO_ARRAY_STRUCTURE  5
#define LSM_INFO_PAGE_ASCII_DUMP  6
#define LSM_INFO_PAGE_HEX_DUMP    7
#define LSM_INFO_FREELIST         8
#define LSM_INFO_ARRAY_PAGES      9
#define LSM_INFO_CHECKPOINT_SIZE 10
#define LSM_INFO_TREE_SIZE       11
#define LSM_INFO_FREELIST_SIZE   12
#define LSM_INFO_COMPRESSION_ID  13

/*
** CAPI: Opening and Closing Write Transactions
**
** These functions are used to open and close transactions and nested
** sub-transactions.
**
** The lsm_begin() function is used to open transactions and sub-transactions.
** A successful call to lsm_begin() ensures that there are at least iLevel
** nested transactions open. To open a top-level transaction, pass iLevel=1.
** To open a sub-transaction within the top-level transaction, iLevel=2.
** Passing iLevel=0 is a no-op.
**
** lsm_commit() is used to commit transactions and sub-transactions. A
** successful call to lsm_commit() ensures that there are at most iLevel
** nested transactions open. To commit a top-level transaction, pass iLevel=0.
** To commit all sub-transactions inside the main transaction, pass iLevel=1.
**
** Function lsm_rollback() is used to roll back transactions and
** sub-transactions. A successful call to lsm_rollback() restores the database
** to the state it was in when the iLevel'th nested sub-transaction (if any)
** was first opened. And then closes transactions to ensure that there are
** at most iLevel nested transactions open. Passing iLevel=0 rolls back and
** closes the top-level transaction. iLevel=1 also rolls back the top-level
** transaction, but leaves it open. iLevel=2 rolls back the sub-transaction
** nested directly inside the top-level transaction (and leaves it open).
*/
int lsm_begin(lsm_db *pDb, int iLevel);
int lsm_commit(lsm_db *pDb, int iLevel);
int lsm_rollback(lsm_db *pDb, int iLevel);

/*
** CAPI: Writing to a Database
**
** Write a new value into the database. If a value with a duplicate key
** already exists it is replaced.
*/
int lsm_insert(lsm_db*, const void *pKey, int nKey, const void *pVal, int nVal);

/*
** Delete a value from the database. No error is returned if the specified
** key value does not exist in the database.
*/
int lsm_delete(lsm_db *, const void *pKey, int nKey);

/*
** Delete all database entries with keys that are greater than (pKey1/nKey1)
** and smaller than (pKey2/nKey2). Note that keys (pKey1/nKey1) and
** (pKey2/nKey2) themselves, if they exist in the database, are not deleted.
**
** Return LSM_OK if successful, or an LSM error code otherwise.
*/
int lsm_delete_range(lsm_db *,
    const void *pKey1, int nKey1, const void *pKey2, int nKey2
);

/*
** CAPI: Explicit Database Work and Checkpointing
**
** This function is called by a thread to work on the database structure.
*/
int lsm_work(lsm_db *pDb, int nMerge, int nKB, int *pnWrite);

int lsm_flush(lsm_db *pDb);

/*
** Attempt to checkpoint the current database snapshot. Return an LSM
** error code if an error occurs or LSM_OK otherwise.
**
** If the current snapshot has already been checkpointed, calling this
** function is a no-op. In this case if pnKB is not NULL, *pnKB is
** set to 0. Or, if the current snapshot is successfully checkpointed
** by this function and pbKB is not NULL, *pnKB is set to the number
** of bytes written to the database file since the previous checkpoint
** (the same measure as returned by the LSM_INFO_CHECKPOINT_SIZE query).
*/
int lsm_checkpoint(lsm_db *pDb, int *pnKB);

/*
** CAPI: Opening and Closing Database Cursors
**
** Open and close a database cursor.
*/
int lsm_csr_open(lsm_db *pDb, lsm_cursor **ppCsr);
int lsm_csr_close(lsm_cursor *pCsr);

/*
** CAPI: Positioning Database Cursors
**
** If the fourth parameter is LSM_SEEK_EQ, LSM_SEEK_GE or LSM_SEEK_LE,
** this function searches the database for an entry with key (pKey/nKey).
** If an error occurs, an LSM error code is returned. Otherwise, LSM_OK.
**
** If no error occurs and the requested key is present in the database, the
** cursor is left pointing to the entry with the specified key. Or, if the
** specified key is not present in the database the state of the cursor
** depends on the value passed as the final parameter, as follows:
**
** LSM_SEEK_EQ:
**   The cursor is left at EOF (invalidated). A call to lsm_csr_valid()
**   returns non-zero.
**
** LSM_SEEK_LE:
**   The cursor is left pointing to the largest key in the database that
**   is smaller than (pKey/nKey). If the database contains no keys smaller
**   than (pKey/nKey), the cursor is left at EOF.
**
** LSM_SEEK_GE:
**   The cursor is left pointing to the smallest key in the database that
**   is larger than (pKey/nKey). If the database contains no keys larger
**   than (pKey/nKey), the cursor is left at EOF.
**
** If the fourth parameter is LSM_SEEK_LEFAST, this function searches the
** database in a similar manner to LSM_SEEK_LE, with two differences:
**
** <ol><li>Even if a key can be found (the cursor is not left at EOF), the
** lsm_csr_value() function may not be used (attempts to do so return
** LSM_MISUSE).
**
** <li>The key that the cursor is left pointing to may be one that has
** been recently deleted from the database. In this case it is
** guaranteed that the returned key is larger than any key currently
** in the database that is less than or equal to (pKey/nKey).
** </ol>
**
** LSM_SEEK_LEFAST requests are intended to be used to allocate database
** keys.
*/
int lsm_csr_seek(lsm_cursor *pCsr, const void *pKey, int nKey, int eSeek);

int lsm_csr_first(lsm_cursor *pCsr);
int lsm_csr_last(lsm_cursor *pCsr);

/*
** Advance the specified cursor to the next or previous key in the database.
** Return LSM_OK if successful, or an LSM error code otherwise.
**
** Functions lsm_csr_seek(), lsm_csr_first() and lsm_csr_last() are "seek"
** functions. Whether or not lsm_csr_next and lsm_csr_prev may be called
** successfully also depends on the most recent seek function called on
** the cursor. Specifically:
**
** <ul>
** <li> At least one seek function must have been called on the cursor.
** <li> To call lsm_csr_next(), the most recent call to a seek function must
** have been either lsm_csr_first() or a call to lsm_csr_seek() specifying
** LSM_SEEK_GE.
** <li> To call lsm_csr_prev(), the most recent call to a seek function must
** have been either lsm_csr_first() or a call to lsm_csr_seek() specifying
** LSM_SEEK_GE.
** </ul>
**
** Otherwise, if the above conditions are not met when lsm_csr_next or
** lsm_csr_prev is called, LSM_MISUSE is returned and the cursor position
** remains unchanged.
*/
int lsm_csr_next(lsm_cursor *pCsr);
int lsm_csr_prev(lsm_cursor *pCsr);

/*
** Values that may be passed as the fourth argument to lsm_csr_seek().
*/
#define LSM_SEEK_LEFAST   -2
#define LSM_SEEK_LE       -1
#define LSM_SEEK_EQ        0
#define LSM_SEEK_GE        1

/*
** CAPI: Extracting Data From Database Cursors
**
** Retrieve data from a database cursor.
*/
int lsm_csr_valid(lsm_cursor *pCsr);
int lsm_csr_key(lsm_cursor *pCsr, const void **ppKey, int *pnKey);
int lsm_csr_value(lsm_cursor *pCsr, const void **ppVal, int *pnVal);

/*
** If no error occurs, this function compares the database key passed via
** the pKey/nKey arguments with the key that the cursor passed as the first
** argument currently points to. If the cursors key is less than, equal to
** or greater than pKey/nKey, *piRes is set to less than, equal to or greater
** than zero before returning. LSM_OK is returned in this case.
**
** Or, if an error occurs, an LSM error code is returned and the final
** value of *piRes is undefined. If the cursor does not point to a valid
** key when this function is called, LSM_MISUSE is returned.
*/
int lsm_csr_cmp(lsm_cursor *pCsr, const void *pKey, int nKey, int *piRes);

/*
** CAPI: Change these!!
**
** Configure a callback to which debugging and other messages should
** be directed. Only useful for debugging lsm.
*/
void lsm_config_log(lsm_db *, void (*)(void *, int, const char *), void *);

/*
** Configure a callback that is invoked if the database connection ever
** writes to the database file.
*/
void lsm_config_work_hook(lsm_db *, void (*)(lsm_db *, void *), void *);

/* ENDOFAPI */
#ifdef __cplusplus
}  /* End of the 'extern "C"' block */
#endif
#endif /* ifndef _LSM_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AWSDynamoDBCreateTableOutput.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AWSDynamoDBCreateTableOutput</TokenIdentifier>
			<Abstract type="html">
Represents the output of a CreateTable operation.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<NodeRef refid="313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBCreateTableOutput/setTableDescription:</TokenIdentifier>
			<Abstract type="html">
Represents the properties of a table.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBTableDescription *tableDescription</Declaration>

			<Anchor>//api/name/tableDescription</Anchor>
            <NodeRef refid="313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSDynamoDBCreateTableOutput/tableDescription</TokenIdentifier>
			<Abstract type="html">
Represents the properties of a table.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBTableDescription *tableDescription</Declaration>

			<Anchor>//api/name/tableDescription</Anchor>
            <NodeRef refid="313"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSDynamoDBCreateTableOutput/tableDescription</TokenIdentifier>
			<Abstract type="html">
Represents the properties of a table.
</Abstract>
			<DeclaredIn>AWSDynamoDBModel.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSDynamoDBTableDescription *tableDescription</Declaration>

			<Anchor>//api/name/tableDescription</Anchor>
            <NodeRef refid="313"/>
		</Token>

	</File>
</Tokens>

redpajama_set_name: RedPajamaGithub


text:
#include "Coordinate.h"

#include <cmath>
#include <stdlib.h>
namespace wf_ngp {

Coordinate::Coordinate(const NParam* param, uint32& index)
{
   m_lat = param->incGetInt32(index);
   m_lon = param->incGetInt32(index);
}

// forward declaration of coordinate conversion function
// to make templated ctor work.
// template <typename FromCoordinate>
// Coordinate convertCoordinate(const FromCoordinate& other);

// Doesn't work - generates code as if the class is templated
// Coordinate<T>
// template <typename FromCoordinate>
// Coordinate::Coordinate(const FromCoordinate& other)
// {
// //    *this = convertCoordinate<FromCoordinate, Coordinate>(other);
// }

Coordinate::Coordinate(int32 lat, int32 lon)
   : m_lat(lat),
     m_lon(lon)
{
}

Coordinate::Coordinate()
   : m_lat(MAX_INT32),
     m_lon(MAX_INT32)
{
}

bool
Coordinate::isValid() const
{
   static const int32 MAX_ABS_LON = static_cast<int32>(M_PI * 1E8);
   static const int32 MAX_ABS_LAT = MAX_ABS_LAT / 2;
   return (abs(m_lat) < MAX_ABS_LAT && abs(m_lon) < MAX_ABS_LON);
}

void
Coordinate::serialize(NParam& param) const
{
   param.addInt32(m_lat);
   param.addInt32(m_lon);
}

} // namespace


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="featureNameTitle">featureNameTitle</string>
</resources>


text:
title: Blinds.com
logo:
    small: "/images/sponsors/blinds-com-sm.png"
site_url: "http://www.blinds.com"
display_home_page: false
display_home_page_order: 4
display_sponsors_page: true
display_sponsors_page_order: 1
---


text:
#include <aws/iotwireless/model/UpdateWirelessGatewayRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::IoTWireless::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateWirelessGatewayRequest::UpdateWirelessGatewayRequest() :
    m_idHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_joinEuiFiltersHasBeenSet(false),
    m_netIdFiltersHasBeenSet(false)
{
}

Aws::String UpdateWirelessGatewayRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_joinEuiFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> joinEuiFiltersJsonList(m_joinEuiFilters.size());
   for(unsigned joinEuiFiltersIndex = 0; joinEuiFiltersIndex < joinEuiFiltersJsonList.GetLength(); ++joinEuiFiltersIndex)
   {
     Aws::Utils::Array<JsonValue> joinEuiRangeJsonList(m_joinEuiFilters[joinEuiFiltersIndex].size());
     for(unsigned joinEuiRangeIndex = 0; joinEuiRangeIndex < joinEuiRangeJsonList.GetLength(); ++joinEuiRangeIndex)
     {
       joinEuiRangeJsonList[joinEuiRangeIndex].AsString(m_joinEuiFilters[joinEuiFiltersIndex][joinEuiRangeIndex]);
     }
     joinEuiFiltersJsonList[joinEuiFiltersIndex].AsArray(std::move(joinEuiRangeJsonList));
   }
   payload.WithArray("JoinEuiFilters", std::move(joinEuiFiltersJsonList));

  }

  if(m_netIdFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> netIdFiltersJsonList(m_netIdFilters.size());
   for(unsigned netIdFiltersIndex = 0; netIdFiltersIndex < netIdFiltersJsonList.GetLength(); ++netIdFiltersIndex)
   {
     netIdFiltersJsonList[netIdFiltersIndex].AsString(m_netIdFilters[netIdFiltersIndex]);
   }
   payload.WithArray("NetIdFilters", std::move(netIdFiltersJsonList));

  }

  return payload.View().WriteReadable();
}


text:
"""Defines utility functions."""

import tensorflow as tf

def assign_moving_average_vars(model, ema_model, optimizer):
  """Assigns moving average variables to the model using moving average.

  Args:
    model: An original model.
    ema_model: A model using moving average.
    optimizer: An optimizer which stores moving average variables.
  """
  non_avg_weights = model.get_weights()
  optimizer.assign_average_vars(model.variables)
  ema_model.set_weights(model.get_weights())
  model.set_weights(non_avg_weights)

def create_checkpoint(ckpt_dir_path,
                      max_to_keep=10,
                      keep_checkpoint_every_n_hours=0.5,
                      **ckpt_objects):
  """Creates and restores checkpoint (if one exists on the path).

  Args:
    ckpt_dir_path: A string for the directory path where the checkpoints are
      created and restored.
    max_to_keep: An integer for the maximume number of checkpoints to store.
    keep_checkpoint_every_n_hours: A float indicating the time interval to keep
      checkpoints since the last preserved one.
    **ckpt_objects: A dictionary for attributes saved with the checkpoint.
      Values must be trackable objects.

  Returns:
    ckpt_manager: A tf.train.CheckpointManager object.
    status: A load status object.
    checkpoint: The restored tf.train.Checkpoint object.
  """
  checkpoint = tf.train.Checkpoint(**ckpt_objects)
  ckpt_manager = tf.train.CheckpointManager(
      checkpoint,
      directory=ckpt_dir_path,
      max_to_keep=max_to_keep,
      keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours)
  status = checkpoint.restore(ckpt_manager.latest_checkpoint)
  return ckpt_manager, status, checkpoint


text:
#include "folly/experimental/symbolizer/StackTrace.h"
#include "folly/experimental/symbolizer/Symbolizer.h"

#include <glog/logging.h>
#include <gtest/gtest.h>

using namespace folly;
using namespace folly::symbolizer;

void foo1() __attribute__((noinline));
void foo2() __attribute__((noinline));

void verifyStackTraces() {
  constexpr size_t kMaxAddresses = 100;
  FrameArray<kMaxAddresses> fa;
  CHECK(getStackTrace(fa));

  FrameArray<kMaxAddresses> faSafe;
  CHECK(getStackTraceSafe(faSafe));

  CHECK_EQ(fa.frameCount, faSafe.frameCount);

  if (VLOG_IS_ON(1)) {
    Symbolizer symbolizer;
    OStreamSymbolizePrinter printer(std::cerr, SymbolizePrinter::COLOR_IF_TTY);

    symbolizer.symbolize(fa);
    VLOG(1) << "getStackTrace\n";
    printer.println(fa);

    symbolizer.symbolize(faSafe);
    VLOG(1) << "getStackTraceSafe\n";
    printer.println(faSafe);
  }

  // Other than the top 2 frames (this one and getStackTrace /
  // getStackTraceSafe), the stack traces should be identical
  for (size_t i = 2; i < fa.frameCount; ++i) {
    VLOG(1) << "i=" << i << " " << std::hex << fa.addresses[i] << " "
            << faSafe.addresses[i];
    CHECK_EQ(fa.addresses[i], faSafe.addresses[i]);
  }
}

void foo1() {
  foo2();
}

void foo2() {
  verifyStackTraces();
}

volatile bool handled = false;
void handler(int num, siginfo_t* info, void* ctx) {
  // Yes, getStackTrace and VLOG aren't async-signal-safe, but signals
  // raised with raise() aren't "async" signals.
  foo1();
  handled = true;
}

TEST(StackTraceTest, Simple) {
  foo1();
}

TEST(StackTraceTest, Signal) {
  struct sigaction sa;
  memset(&sa, 0, sizeof(sa));
  sa.sa_sigaction = handler;
  sa.sa_flags = SA_RESETHAND | SA_SIGINFO;
  CHECK_ERR(sigaction(SIGUSR1, &sa, nullptr));
  raise(SIGUSR1);
  CHECK(handled);
}

int main(int argc, char *argv[]) {
  testing::InitGoogleTest(&argc, argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  return RUN_ALL_TESTS();
}


text:
package v1alpha2

const (
	DBModeCluster    = "Cluster"
	DBModeSharded    = "Sharded"
	DBStandalone     = "Standalone"
	DBModeReplicaSet = "ReplicaSet"
)


text:
package org.ovirt.engine.core.common.action;

import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.compat.Guid;

public class ManagementNetworkOnClusterOperationParameters extends VdsGroupOperationParameters {

    private static final long serialVersionUID = 1L;

    private Guid managementNetworkId;

    public ManagementNetworkOnClusterOperationParameters(VDSGroup cluster) {
        this(cluster, null);
    }

    public ManagementNetworkOnClusterOperationParameters(VDSGroup cluster, Guid managementNetworkId) {
        super(cluster);

        this.managementNetworkId = managementNetworkId;
    }

    public Guid getManagementNetworkId() {
        return managementNetworkId;
    }

    public ManagementNetworkOnClusterOperationParameters() {
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.pnambic.depan</groupId>
    <artifactId>depan-oxygen-test-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../../depan-oxygen-test-parent</relativePath>
  </parent>

  <artifactId>com.google.devtools.depan.edges-test</artifactId>
  <version>2.1.0-SNAPSHOT</version>
  <packaging>eclipse-test-plugin</packaging>

  <name>DepAn Edges [Tests]</name>
  <description>Manipulate Relations, Edges, Paths and related DepAn data structures [Tests]</description>

  <build>
    <sourceDirectory>src</sourceDirectory>
  </build>

  <dependencies>
    <!-- Third party dependencies -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <!-- DepAn dependencies -->
    <dependency>
      <groupId>com.pnambic.depan</groupId>
      <artifactId>com.google.devtools.depan.edges</artifactId>
      <version>2.1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>com.pnambic.depan</groupId>
      <artifactId>com.google.devtools.depan.test</artifactId>
      <version>2.1.0-SNAPSHOT</version>
    </dependency>
  </dependencies>
</project>


text:
<?php
// Created: 2014
// Modified: 26 jan 2015

class OpenNoodEnvelopController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('deny',  // deny all users
				'users'=>array('?'),
			),
			array(	'deny',  // deny if event_id is not set
				'actions'=>array('update', 'create'),
				'expression'=> '!isset($_GET["group_id"])',
			),
            array(	'allow', // allow admin user to perform 'viewplayers' actions
                'actions'=>array('index', 'update', 'delete'),
                'expression'=> 'OpenNoodEnvelop::model()->isActionAllowed(
                    Yii::app()->controller->id,
                    Yii::app()->controller->action->id,
                    $_GET["event_id"])',
            ),
            array(	'allow', // allow admin user to perform 'viewplayers' actions
                'actions'=>array('create'),
                'expression'=> 'OpenNoodEnvelop::model()->isActionAllowed(
                    Yii::app()->controller->id,
                    Yii::app()->controller->action->id,
                    $_GET["event_id"],
					"",
					$_GET["group_id"])',
            ),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$nood_envelop_id=$_GET['nood_envelop_id'];
		$event_id=$_GET['event_id'];
		$group_id=$_GET['group_id'];
		$model=new OpenNoodEnvelop;

		$noodEnvelop = NoodEnvelop::model()->find('nood_envelop_ID =:nood_envelop_Id',
						array(':nood_envelop_Id' => $nood_envelop_id));

		$model->event_ID = $event_id;
		$model->nood_envelop_ID = $nood_envelop_id;
		$model->group_ID = $group_id;
		$model->opened = 1;

		if($model->save())
			$this->redirect(array('/game/groupOverview',
						  'event_id'=>$_GET['event_id'],
						  'group_id'=>$_GET['group_id']));

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		/*
		if(isset($_POST['OpenNoodEnvelop']))
		{
			$model->attributes=$_POST['OpenNoodEnvelop'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->open_nood_envelop_ID));
		}

		$this->render('create',array(
			'model'=>$model,
		));*/
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['OpenNoodEnvelop']))
		{
			$model->attributes=$_POST['OpenNoodEnvelop'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->open_nood_envelop_ID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model = new OpenNoodEnvelop('searchOpened');

		$this->layout='//layouts/column1';
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['OpenNoodEnvelop']))
			$model->attributes=$_GET['OpenNoodEnvelop'];
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new OpenNoodEnvelop('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['OpenNoodEnvelop']))
			$model->attributes=$_GET['OpenNoodEnvelop'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return OpenNoodEnvelop the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=OpenNoodEnvelop::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param OpenNoodEnvelop $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='open-nood-envelop-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
static int _new_map(const char *id_type, int pid,
                    int child_id, int parent_id, int range)
{
    char cmd[100];

    memset(cmd, '\0', sizeof(cmd));
    int ret = snprintf(cmd, sizeof(cmd), "new%smap %u %u %u %u", id_type,
                       pid, child_id, parent_id, range);

    if (ret >= sizeof(cmd) && ret < 1)
        log_error("Cannot format command for setting ID map: %d.", ret);
    else if (system(cmd) != 0)
        log_error("Failed to setup %s map", id_type);
    else
        return 0;

    return -1;
}

int new_uid_map(int pid, int child_uid, int parent_uid, int range)
{
    return _new_map("uid", pid, child_uid, parent_uid, range);
}

int new_gid_map(int pid, int child_uid, int parent_uid, int range)
{
    return _new_map("gid", pid, child_uid, parent_uid, range);
}

int new_id_map(int pid, int child_id, int parent_id, int range)
{
    if (new_uid_map(pid, child_id, parent_id, range) ||
        new_gid_map(pid, child_id, parent_id, range))
        return -1;

    return 0;
}

int set_id(uid_t uid, gid_t gid, size_t groups_cnt, gid_t *groups)
{
    if (setgid(gid))
        log_error("Failed to set GID to %u", gid);
    else if (setuid(uid))
        log_error("Failed to set UID to %u", uid);
    else if (setgroups(groups_cnt, groups))
        log_error("Failed to set additional groups");
    else
        return 0;

    return -1;
}

int set_propagation(const char *target, unsigned long propagation)
{
    const unsigned long valid_propagation =
            MS_SHARED | MS_SLAVE | MS_PRIVATE | MS_UNBINDABLE;
    if (propagation & valid_propagation != propagation)
        log_error("Invalid propagation was specified %u", propagation);
    else if (mount(NULL, target, NULL, propagation | MS_REC, NULL))
        log_error("Failed to set propagation of %s to %u",
                  target, propagation);
    else
        return 0;

    return -1;

}

int mount_fs(const char *source, const char *target,
             const char *type, unsigned long flags)
{
    // may fail, especially if the mount point does not exist
    // but we don't care about that, because the purpose of this method
    // is to mount/remount
    umount(target);

    if (mount(source, target, type, flags, NULL))
        log_error("Failed to mount %s", source);
    else
        return 0;

    return -1;
}


text:
function I = myMontage(IMG)
% function I = myMontage(IMG)
% Input: IMG is a N x N x 3 x k set of images and this function simply tiles them

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Saurabh Gupta
%
% This file is part of the Utils code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

	k = size(IMG,4);
	kk = ceil(sqrt(k));
	if(kk*kk > k)
		IMG(:,:,:,kk*kk) = 0;
	end
	for i = 1:kk*kk,
		I{ceil((i)/kk), mod(i-1, kk)+1} = IMG(:,:,:,i);
	end
	I = cell2mat(I);
end


text:
<?php
namespace User\Bundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;

class StaffSecurityFactory implements SecurityFactoryInterface
{
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {

        $providerId = 'staff.security.authentication_provider.' . $id;
        $listenerId = 'staff.security.authentication_listener.' . $id;

        $container->setDefinition($providerId, new DefinitionDecorator('staff.security.authentication_provider'));
        $container->setDefinition($listenerId, new DefinitionDecorator('staff.security.authentication_listener'));

        return array($providerId, $listenerId, $defaultEntryPoint);
    }

    public function getPosition()
    {
        return 'pre_auth';
    }

    public function getKey()
    {
        return 'staff_security';
    }

    public function addConfiguration(NodeDefinition $node)
    {
    }
}


text:
require 'test/unit'
require 'rubygems'
require 'active_support/core_ext/string'
require 'mocha'
require 'i18n'
require 'net/http'
require File.dirname(File.expand_path(__FILE__)) + '/../lib/recaptcha'

class RecaptchaVerifyTest < Test::Unit::TestCase
  def setup
    Recaptcha.configuration.private_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    @controller = TestController.new
    @controller.request = stub(:remote_ip => "1.1.1.1")
    @controller.params = {:recaptcha_challenge_field => "challenge", :recaptcha_response_field => "response"}

    @expected_post_data = {}
    @expected_post_data["privatekey"] = Recaptcha.configuration.private_key
    @expected_post_data["remoteip"]   = @controller.request.remote_ip
    @expected_post_data["challenge"]  = "challenge"
    @expected_post_data["response"]   = "response"

    @expected_uri = URI.parse(Recaptcha.configuration.verify_url)
  end

  def test_should_raise_exception_without_private_key
    assert_raise Recaptcha::RecaptchaError do
      Recaptcha.configuration.private_key = nil
      @controller.verify_recaptcha
    end
  end

  def test_should_return_false_when_key_is_invalid
    expect_http_post(response_with_body("false\ninvalid-site-private-key"))

    assert !@controller.verify_recaptcha
    assert_equal "invalid-site-private-key", @controller.flash[:recaptcha_error]
  end

  def test_returns_true_on_success
    @controller.flash[:recaptcha_error] = "previous error that should be cleared"
    expect_http_post(response_with_body("true\n"))

    assert @controller.verify_recaptcha
    assert_nil @controller.flash[:recaptcha_error]
  end

  def test_errors_should_be_added_to_model
    expect_http_post(response_with_body("false\nbad-news"))

    errors = mock
    errors.expects(:add).with(:base, "Word verification response is incorrect, please try again.")
    model = mock(:errors => errors)

    assert !@controller.verify_recaptcha(:model => model)
    assert_equal "bad-news", @controller.flash[:recaptcha_error]
  end

  def test_returns_true_on_success_with_optional_key
    @controller.flash[:recaptcha_error] = "previous error that should be cleared"
    # reset private key
    @expected_post_data["privatekey"] =  'ADIFFERENTPRIVATEKEYXXXXXXXXXXXXXX'
    expect_http_post(response_with_body("true\n"))

    assert @controller.verify_recaptcha(:private_key => 'ADIFFERENTPRIVATEKEYXXXXXXXXXXXXXX')
    assert_nil @controller.flash[:recaptcha_error]
  end

  def test_timeout
    expect_http_post(Timeout::Error, :exception => true)
    assert !@controller.verify_recaptcha()
    assert_equal "recaptcha-not-reachable", @controller.flash[:recaptcha_error]
  end

  def test_message_should_use_i18n
    I18n.locale = :de
    verification_failed_translated   = "Sicherheitscode konnte nicht verifiziert werden."
    verification_failed_default      = "Word verification response is incorrect, please try again."
    recaptcha_unreachable_translated = "Netzwerkfehler, bitte versuchen Sie es später erneut."
    recaptcha_unreachable_default    = "Oops, we failed to validate your word verification response. Please try again."
    I18n.expects(:translate).with(:'recaptcha.errors.verification_failed', :default => verification_failed_default).returns(verification_failed_translated)
    I18n.expects(:translate).with(:'recaptcha.errors.recaptcha_unreachable', :default => recaptcha_unreachable_default).returns(recaptcha_unreachable_translated)

    errors = mock
    errors.expects(:add).with(:base, verification_failed_translated)
    errors.expects(:add).with(:base, recaptcha_unreachable_translated)
    model  = mock; model.stubs(:errors => errors)

    expect_http_post(response_with_body("false\nbad-news"))
    @controller.verify_recaptcha(:model => model)

    expect_http_post(Timeout::Error, :exception => true)
    @controller.verify_recaptcha(:model => model)

  end

  private

  class TestController
    include Recaptcha::Verify
    attr_accessor :request, :params, :flash

    def initialize
      @flash = {}
    end
  end

  def expect_http_post(response, options = {})
    unless options[:exception]
      Net::HTTP.expects(:post_form).with(@expected_uri, @expected_post_data).returns(response)
    else
      Net::HTTP.expects(:post_form).raises response
    end
  end

  def response_with_body(body)
    stub(:body => body)
  end
end


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object2689449295.h"

// System.Collections.Generic.Dictionary`2<UnityEngine.Networking.Types.NetworkID,UnityEngine.Networking.Types.NetworkAccessToken>
struct Dictionary_2_t1898959281;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Networking.Utility
struct  Utility_t2692878198  : public Il2CppObject
{
public:

public:
};

struct Utility_t2692878198_StaticFields
{
public:
	// System.Collections.Generic.Dictionary`2<UnityEngine.Networking.Types.NetworkID,UnityEngine.Networking.Types.NetworkAccessToken> UnityEngine.Networking.Utility::s_dictTokens
	Dictionary_2_t1898959281 * ___s_dictTokens_0;

public:
	inline static int32_t get_offset_of_s_dictTokens_0() { return static_cast<int32_t>(offsetof(Utility_t2692878198_StaticFields, ___s_dictTokens_0)); }
	inline Dictionary_2_t1898959281 * get_s_dictTokens_0() const { return ___s_dictTokens_0; }
	inline Dictionary_2_t1898959281 ** get_address_of_s_dictTokens_0() { return &___s_dictTokens_0; }
	inline void set_s_dictTokens_0(Dictionary_2_t1898959281 * value)
	{
		___s_dictTokens_0 = value;
		Il2CppCodeGenWriteBarrier(&___s_dictTokens_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
package seedu.address.logic.parser;

import static org.junit.Assert.assertEquals;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import java.lang.reflect.Field;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.IncorrectCommand;
import seedu.address.model.tag.Tag;
import seedu.address.model.task.Description;
import seedu.address.model.task.Event;
import seedu.address.model.task.Name;
import seedu.address.model.task.Priority;
import seedu.address.model.task.ReadOnlyRecurringTask.RecurringMode;
import seedu.address.model.task.RecurringEvent;
import seedu.address.model.task.RecurringTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.TaskDate;
import seedu.address.model.task.TaskTime;
import seedu.address.model.task.Venue;

public class AddCommandParserTest {

    public AddCommandParser theOne = AddCommandParser.getInstance();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void addTask_emptyString_incorrectCommand() throws Exception {

        Field field = IncorrectCommand.class.getDeclaredField("feedbackToUser");
        field.setAccessible(true);

        IncorrectCommand incorrectCommand =  (IncorrectCommand) theOne.parse(null);
        assertEquals(field.get(incorrectCommand), String.format(MESSAGE_INVALID_COMMAND_FORMAT,
                AddCommand.MESSAGE_USAGE));
    }

    @Test
    public void addTask_onlyName_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) theOne.parse("CS2103 Lecture \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        Task sampleTask = new Task(sampleTaskName, new TaskDate(""), new TaskTime(""),
                new Description(""), new Tag(""), new Venue(""), new Priority(""), false);
        assertEqualTasks((Task) field.get(addCommand), sampleTask);
    }

    @Test
    public void addTask_someFields_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) AddCommandParser.getInstance().parse("CS2103 Lecture due/30/03 "
                + "dueT/16:00 d/Interesting #CS2103 \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        TaskDate sampleTaskDate = new TaskDate("30/03");
        TaskTime sampleTaskTime = new TaskTime("16:00");
        Description sampleTaskDescription = new Description("Interesting");
        Tag sampleTaskTag = new Tag("CS2103");
        Task sampleTask = new Task(sampleTaskName, sampleTaskDate, sampleTaskTime,
                sampleTaskDescription, sampleTaskTag, new Venue(""), new Priority(""), false);
        assertEqualTasks((Task) field.get(addCommand), sampleTask);
    }

    @Test
    public void addTask_allFields_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) theOne.parse("CS2103 Lecture due/30/3 "
                + "dueT/16:00 d/Interesting #CS2103 @I3 p/3 \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        TaskDate sampleTaskDate = new TaskDate("30/3");
        TaskTime sampleTaskTime = new TaskTime("16:00");
        Description sampleTaskDescription = new Description("Interesting");
        Tag sampleTaskTag = new Tag("CS2103");
        Venue sampleTaskVenue = new Venue("I3");
        Priority sampleTaskPriority = new Priority("3");
        Task sampleTask = new Task(sampleTaskName, sampleTaskDate, sampleTaskTime,
                sampleTaskDescription, sampleTaskTag, sampleTaskVenue, sampleTaskPriority, false);
        assertEqualTasks((Task) field.get(addCommand), sampleTask);
    }

    @Test
    public void addEvent_allFields_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) theOne.parse("CS2103 Lecture due/30/3 "
                + "dueT/16:00 d/Interesting #CS2103 @I3 p/3 start/29/3 startT/15:00 \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        TaskDate sampleTaskDate = new TaskDate("30/3");
        TaskTime sampleTaskTime = new TaskTime("16:00");
        TaskDate sampleTaskStartDate = new TaskDate("29/3");
        TaskTime sampleTaskStartTime = new TaskTime("15:00");
        Description sampleTaskDescription = new Description("Interesting");
        Tag sampleTaskTag = new Tag("CS2103");
        Venue sampleTaskVenue = new Venue("I3");
        Priority sampleTaskPriority = new Priority("3");
        Event sampleEvent = new Event(sampleTaskName, sampleTaskStartDate, sampleTaskStartTime,
                sampleTaskDate, sampleTaskTime, sampleTaskDescription, sampleTaskTag,
                sampleTaskVenue, sampleTaskPriority, false);
        assertEqualEvents((Event) field.get(addCommand), sampleEvent);
    }

    @Test
    public void addRecurringTask_allFields_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) theOne.parse("CS2103 Lecture due/30/3 "
                + "dueT/16:00 d/Interesting #CS2103 @I3 p/3 f/week \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        TaskDate sampleTaskDate = new TaskDate("30/3");
        TaskTime sampleTaskTime = new TaskTime("16:00");
        Description sampleTaskDescription = new Description("Interesting");
        Tag sampleTaskTag = new Tag("CS2103");
        Venue sampleTaskVenue = new Venue("I3");
        Priority sampleTaskPriority = new Priority("3");
        RecurringMode mode = RecurringMode.WEEK;
        RecurringTask sampleRecurringTask = new RecurringTask(
                sampleTaskName, sampleTaskDate, sampleTaskTime, sampleTaskDescription, sampleTaskTag,
                sampleTaskVenue, sampleTaskPriority, false, mode);
        assertEqualRecurringTasks((RecurringTask) field.get(addCommand), sampleRecurringTask);
    }

    @Test
    public void addRecurringEvent_allFields_correctlyAdd() throws Exception {

        Field field = AddCommand.class.getDeclaredField("toAdd");
        field.setAccessible(true);

        AddCommand addCommand =  (AddCommand) theOne.parse("CS2103 Lecture due/30/3 "
                + "dueT/16:00 d/Interesting #CS2103 @I3 p/3 start/29/3 startT/15:00 f/week \n");
        Name sampleTaskName = new Name("CS2103 Lecture");
        TaskDate sampleTaskDate = new TaskDate("30/3");
        TaskTime sampleTaskTime = new TaskTime("16:00");
        TaskDate sampleTaskStartDate = new TaskDate("29/3");
        TaskTime sampleTaskStartTime = new TaskTime("15:00");
        Description sampleTaskDescription = new Description("Interesting");
        Tag sampleTaskTag = new Tag("CS2103");
        Venue sampleTaskVenue = new Venue("I3");
        Priority sampleTaskPriority = new Priority("3");
        RecurringMode mode = RecurringMode.WEEK;
        RecurringEvent sampleRecurringEvent = new RecurringEvent(
                sampleTaskName, sampleTaskStartDate, sampleTaskStartTime,
                sampleTaskDate, sampleTaskTime, sampleTaskDescription, sampleTaskTag,
                sampleTaskVenue, sampleTaskPriority, false, mode);
        assertEqualRecurringEvents((RecurringEvent) field.get(addCommand), sampleRecurringEvent);
    }

    private void assertEqualTasks(Task task1, Task sampleTask) {
        assertEquals(task1.getName(), sampleTask.getName());
        assertEquals(task1.getDate(), sampleTask.getDate());
        assertEquals(task1.getTime(), sampleTask.getTime());
        assertEquals(task1.getDescription(), sampleTask.getDescription());
        assertEquals(task1.getTag(), sampleTask.getTag());
        assertEquals(task1.getVenue(), sampleTask.getVenue());
        assertEquals(task1.getPriority(), sampleTask.getPriority());
        assertEquals(task1.isFavorite(), sampleTask.isFavorite());
        assertEquals(task1.isFinished(), sampleTask.isFinished());
    }

    private void assertEqualRecurringTasks(RecurringTask task1, RecurringTask task2) {
        assertEqualTasks(task1, task2);
        assertEquals(task1.getMode(), task2.getMode());
    }

    private void assertEqualEvents(Event event1, Event event2) {
        assertEqualTasks(event1, event2);
        assertEquals(event1.getStartTime(), event2.getStartTime());
        assertEquals(event1.getStartDate(), event2.getStartDate());
    }

    private void assertEqualRecurringEvents(RecurringEvent event1, RecurringEvent event2) {
        assertEqualEvents(event1, event2);
        assertEquals(event1.getMode(), event2.getMode());
    }
}


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const semi_1 = __importDefault(require("eslint/lib/rules/semi"));
const util = __importStar(require("../util"));
exports.default = util.createRule({
    name: 'semi',
    meta: {
        type: 'layout',
        docs: {
            description: 'Require or disallow semicolons instead of ASI',
            category: 'Stylistic Issues',
            // too opinionated to be recommended
            recommended: false,
            extendsBaseRule: true,
        },
        fixable: 'code',
        schema: semi_1.default.meta.schema,
        messages: (_a = semi_1.default.meta.messages) !== null && _a !== void 0 ? _a : {
            missingSemi: 'Missing semicolon.',
            extraSemi: 'Extra semicolon.',
        },
    },
    defaultOptions: [
        'always',
        {
            omitLastInOneLineBlock: false,
            beforeStatementContinuationChars: 'any',
        },
    ],
    create(context) {
        const rules = semi_1.default.create(context);
        const checkForSemicolon = rules.ExpressionStatement;
        /*
          The following nodes are handled by the member-delimiter-style rule
          AST_NODE_TYPES.TSCallSignatureDeclaration,
          AST_NODE_TYPES.TSConstructSignatureDeclaration,
          AST_NODE_TYPES.TSIndexSignature,
          AST_NODE_TYPES.TSMethodSignature,
          AST_NODE_TYPES.TSPropertySignature,
        */
        const nodesToCheck = [
            experimental_utils_1.AST_NODE_TYPES.ClassProperty,
            experimental_utils_1.AST_NODE_TYPES.TSAbstractClassProperty,
            experimental_utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition,
            experimental_utils_1.AST_NODE_TYPES.TSDeclareFunction,
            experimental_utils_1.AST_NODE_TYPES.TSExportAssignment,
            experimental_utils_1.AST_NODE_TYPES.TSImportEqualsDeclaration,
            experimental_utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration,
        ].reduce((acc, node) => {
            acc[node] = checkForSemicolon;
            return acc;
        }, {});
        return Object.assign(Object.assign(Object.assign({}, rules), nodesToCheck), { ExportDefaultDeclaration(node) {
                if (node.declaration.type !== experimental_utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) {
                    rules.ExportDefaultDeclaration(node);
                }
            } });
    },
});
//# sourceMappingURL=semi.js.map


text:
export {};
//# sourceMappingURL=i18n-de.module.d.ts.map


text:
<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Ch6GarbageCollection</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>ru.tsibrovskii</groupId>
        <artifactId>javaaz</artifactId>
        <version>1.0</version>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
from setuptools import setup, find_packages
import os

version = '0.0.32.dev0'

setup(
    name='touchdown',
    version=version,
    url="http://yaybu.com/",
    description="Orchestration and configuration management in Python",
    long_description = open("README.rst").read(),
    author="Isotoma Limited",
    author_email="support@isotoma.com",
    license="Apache Software License",
    classifiers = [
        "Intended Audience :: System Administrators",
        "Operating System :: POSIX",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
    ],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'six',
        'contextlib2',
        'netaddr',
        'fuselage>=0.0.10',
        'botocore>=1.0.0a2',
        'progressbar2<3.0.0',
        'requests',
    ],
    entry_points='''
        [console_scripts]
        touchdown = touchdown.core.main:main
    ''',
)


text:
/*
 * (C) 2007-2012 Alibaba Group Holding Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Authors:
 *   wuhua <wq163@163.com> , boyan <killme2008@gmail.com>
 */
package com.taobao.metamorphosis.client.consumer.storage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * JDBC¹¤¾ßÀà
 *
 * @author boyan
 * @Date 2011-4-28
 *
 */
public class JDBCUtils {
    static final Log log = LogFactory.getLog(JDBCUtils.class);

    public static class CannotGetConnectionException extends RuntimeException {
        static final long serialVersionUID = -1L;

        public CannotGetConnectionException(String message, Throwable cause) {
            super(message, cause);

        }

        public CannotGetConnectionException(String message) {
            super(message);

        }

    }

    public interface ConnectionCallback {
        public Object doInConnection(Connection conn) throws SQLException;
    }

    public interface PreparedStatementCallback {
        public Object doInPreparedStatement(PreparedStatement pstmt) throws SQLException;
    }

    public interface ResultSetCallback {
        public Object doInResultSet(ResultSet rs) throws SQLException;
    }

    public static Connection getConnection(DataSource ds) {
        try {
            return ds.getConnection();
        }
        catch (SQLException e) {
            throw new CannotGetConnectionException("Can not get connection from datasource", e);
        }
    }

    public static Object execute(Connection conn, ConnectionCallback connectionCallBack) {
        try {
            if (connectionCallBack != null && conn != null) {
                return connectionCallBack.doInConnection(conn);
            }
        }
        catch (SQLException e) {
            log.error("doInConnection failed", e);
        }
        finally {
            close(conn);
        }
        return null;
    }

    public static Object execute(PreparedStatement pstmt, PreparedStatementCallback pstmtCallBack) {
        try {
            if (pstmtCallBack != null && pstmt != null) {
                return pstmtCallBack.doInPreparedStatement(pstmt);
            }
        }
        catch (SQLException e) {
            log.error("doInPreparedStatement failed", e);
        }
        finally {
            close(pstmt);
        }
        return null;
    }

    public static Object execute(ResultSet rs, ResultSetCallback rsCallback) {
        try {
            if (rsCallback != null && rs != null) {
                return rsCallback.doInResultSet(rs);
            }
        }
        catch (SQLException e) {
            log.error("doInResultSet failed", e);
        }
        finally {
            close(rs);
        }
        return null;
    }

    public static void close(PreparedStatement preparedStatement) {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            }
            catch (SQLException e) {
                log.error("Close PreparedStatement failed", e);
            }

        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            }
            catch (SQLException ex) {
                log.error("Close ResultSet failed", ex);
            }
        }
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            }
            catch (SQLException ex) {
                log.error("Close connection failed", ex);
            }
        }
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Assets.Scripts.Kinect {
    [Serializable]
    public class JointOverlays : IEnumerable<GameObject> {
        public GameObject Hips;
        public GameObject Spine;
        public GameObject Neck;
        public GameObject Head;
        public GameObject LeftShoulder;
        public GameObject LeftElbow;
        public GameObject LeftWrist;
        public GameObject LeftHand;
        public GameObject RightShoulder;
        public GameObject RightElbow;
        public GameObject RightWrist;
        public GameObject RightHand;
        public GameObject LeftHip;
        public GameObject LeftKnee;
        public GameObject LeftAnkle;
        public GameObject LeftFoot;
        public GameObject RightHip;
        public GameObject RightKnee;
        public GameObject RightAnkle;
        public GameObject RightFoot;

        private Dictionary<GameObject, float> _overlays;
        private Dictionary<GameObject, Joints> _mappings;
        private Joints[] _overlayedJoints = {};

        public float this[GameObject overlay] {
            get { return _overlays[overlay]; }
            set { _overlays[overlay] = value; }
        }

        public void Init() {
            _overlays = (new[] {
            Hips, Spine, Neck, Head, LeftShoulder, LeftElbow, LeftWrist, LeftHand,
            RightShoulder, RightElbow, RightWrist, RightHand, LeftHip, LeftKnee,
            LeftAnkle, LeftFoot, RightHip, RightKnee, RightAnkle, RightFoot
        }).Where(obj => obj != null).ToDictionary(obj => obj, obj => 0f);

            _mappings = new Dictionary<GameObject, Joints>();
            if (Hips != null) _mappings[Hips] = Joints.Hips;
            if (Spine != null) _mappings[Spine] = Joints.Spine;
            if (Neck != null) _mappings[Neck] = Joints.Neck;
            if (Head != null) _mappings[Head] = Joints.Head;
            if (LeftShoulder != null) _mappings[LeftShoulder] = Joints.LeftShoulder;
            if (LeftElbow != null) _mappings[LeftElbow] = Joints.LeftElbow;
            if (LeftWrist != null) _mappings[LeftWrist] = Joints.LeftWrist;
            if (LeftHand != null) _mappings[LeftHand] = Joints.LeftHand;
            if (RightShoulder != null) _mappings[RightShoulder] = Joints.RightShoulder;
            if (RightElbow != null) _mappings[RightElbow] = Joints.RightElbow;
            if (RightWrist != null) _mappings[RightWrist] = Joints.RightWrist;
            if (RightHand != null) _mappings[RightHand] = Joints.RightHand;
            if (LeftHip != null) _mappings[LeftHip] = Joints.LeftHip;
            if (LeftKnee != null) _mappings[LeftKnee] = Joints.LeftKnee;
            if (LeftAnkle != null) _mappings[LeftAnkle] = Joints.LeftAnkle;
            if (LeftFoot != null) _mappings[LeftFoot] = Joints.LeftFoot;
            if (RightHip != null) _mappings[RightHip] = Joints.RightHip;
            if (RightKnee != null) _mappings[RightKnee] = Joints.RightKnee;
            if (RightAnkle != null) _mappings[RightAnkle] = Joints.RightAnkle;
            if (RightFoot != null) _mappings[RightFoot] = Joints.RightFoot;
            _overlayedJoints = _mappings.Values.ToArray();
        }

        public void Position(KinectManager manager, JointPositions positions, GameObject overlayObject, float smoothFactor) {
            if (!overlayObject || !_mappings.ContainsKey(overlayObject)) return;

            var joint = _mappings[overlayObject];
            var jointPosition = positions[joint];

            var depthPosition = manager.GetDepthMapPosForJointPos(jointPosition);
            var colorPosition = manager.GetColorMapPosForDepthPos(depthPosition);

            var scaleX = colorPosition.x / KinectWrapper.Constants.ColorImageWidth;
            var scaleY = 1.0f - colorPosition.y / KinectWrapper.Constants.ColorImageHeight;

            var distanceToCamera = _overlays[overlayObject];
            var overlayPosition = Camera.main.ViewportToWorldPoint(new Vector3(scaleX, scaleY, distanceToCamera));
            overlayObject.transform.position = Vector3.Lerp(overlayObject.transform.position, overlayPosition, smoothFactor * Time.deltaTime);
        }

        public Joints[] GetOverlayedJoints() {
            return _overlayedJoints ;
        }

        public IEnumerator<GameObject> GetEnumerator() {
            return _overlays.Keys.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }
}


text:
package com.microsoft.azure.management.resources.v2020_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The ApiProfile model.
 */
public class ApiProfile {
    /**
     * The profile version.
     */
    @JsonProperty(value = "profileVersion", access = JsonProperty.Access.WRITE_ONLY)
    private String profileVersion;

    /**
     * The API version.
     */
    @JsonProperty(value = "apiVersion", access = JsonProperty.Access.WRITE_ONLY)
    private String apiVersion;

    /**
     * Get the profile version.
     *
     * @return the profileVersion value
     */
    public String profileVersion() {
        return this.profileVersion;
    }

    /**
     * Get the API version.
     *
     * @return the apiVersion value
     */
    public String apiVersion() {
        return this.apiVersion;
    }

}


text:
#ifndef RGBPLAIN_H
#define RGBPLAIN_H

#include <QObject>

#include "rgbalgorithm.h"

/** @addtogroup engine_functions Functions
 * @{
 */

#define KXMLQLCRGBPlain "Plain"

class RGBPlain : public QObject, public RGBAlgorithm
{
    Q_OBJECT

public:
    RGBPlain(Doc * doc);
    RGBPlain(const RGBPlain& t, QObject *parent = 0);
    ~RGBPlain();

    /** @reimp */
    RGBAlgorithm* clone() const;

    /************************************************************************
     * RGBAlgorithm
     ************************************************************************/
public:
    /** @reimp */
    int rgbMapStepCount(const QSize& size);

    /** @reimp */
    void rgbMap(const QSize& size, uint rgb, int step, RGBMap &map);

    /** @reimp */
    QString name() const;

    /** @reimp */
    QString author() const;

    /** @reimp */
    int apiVersion() const;

    /** @reimp */
    void setColors(QColor start, QColor end);

    /** @reimp */
    RGBAlgorithm::Type type() const;

    /** @reimp */
    int acceptColors() const;

    /************************************************************************
     * Load & Save
     ************************************************************************/
public:
    /** @reimp */
    bool loadXML(QXmlStreamReader &root);

    /** @reimp */
    bool saveXML(QXmlStreamWriter *doc) const;
};

/** @} */

#endif


text:
package edu.uw.zookeeper.net.intravm;

import edu.uw.zookeeper.common.Pair;
import edu.uw.zookeeper.common.ParameterizedFactory;

public class IntraVmConnection<I,O> extends AbstractIntraVmConnection<I,O,I,O,IntraVmEndpoint<I,O>,IntraVmConnection<I,O>> {

    public static <I,O> ParameterizedFactory<Pair<? extends IntraVmEndpoint<I,O>, ? extends AbstractIntraVmEndpoint<?,?,?,? super I>>, IntraVmConnection<I,O>> factory() {
        return new ParameterizedFactory<Pair<? extends IntraVmEndpoint<I,O>, ? extends AbstractIntraVmEndpoint<?,?,?,? super I>>, IntraVmConnection<I,O>>() {
            @Override
            public IntraVmConnection<I,O> get(Pair<? extends IntraVmEndpoint<I,O>, ? extends AbstractIntraVmEndpoint<?, ?, ?, ? super I>> value) {
                return newInstance(value.first(), value.second());
            }
        };
    }

    public static <I,O> IntraVmConnection<I,O> newInstance(
            IntraVmEndpoint<I,O> local,
            AbstractIntraVmEndpoint<?,?,?,? super I> remote) {
        return new IntraVmConnection<I,O>(local, remote);
    }

    protected IntraVmConnection(
            IntraVmEndpoint<I,O> local,
            AbstractIntraVmEndpoint<?,?,?,? super I> remote) {
        super(local, remote);
    }
}


text:
.. highlight:: shell

============
Installation
============

Stable release
--------------

To install wavefront_reader, run this command in your terminal:

.. code-block:: console

    $ pip install wavefront_reader

This is the preferred method to install wavefront_reader, as it will always install the most recent stable release.

If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.

.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/

From sources
------------

The sources for wavefront_reader can be downloaded from the `Github repo`_.

You can either clone the public repository:

.. code-block:: console

    $ git clone git://github.com/neuroneuro15/wavefront_reader

Or download the `tarball`_:

.. code-block:: console

    $ curl  -OL https://github.com/neuroneuro15/wavefront_reader/tarball/master

Once you have a copy of the source, you can install it with:

.. code-block:: console

    $ python setup.py install

.. _Github repo: https://github.com/neuroneuro15/wavefront_reader
.. _tarball: https://github.com/neuroneuro15/wavefront_reader/tarball/master


text:
%Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
%Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
%   notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
%   notice, this list of conditions and the following disclaimer in the
%   documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

function [indices, dists] = flann_search(data, testset, n, search_params)
%NN_SEARCH  Fast approximate nearest neighbors search
%
% Performs a fast approximate nearest neighbor search using an
% index constructed using flann_build_index or directly a
% dataset.

% Marius Muja, January 2008

    algos = struct( 'linear', 0, 'kdtree', 1, 'kmeans', 2, 'composite', 3, 'saved', 254, 'autotuned', 255 );
    center_algos = struct('random', 0, 'gonzales', 1, 'kmeanspp', 2 );
    log_levels = struct('none', 0, 'fatal', 1, 'error', 2, 'warning', 3, 'info', 4);
    function value = id2value(map, id)
        fields = fieldnames(map);
        for i = 1:length(fields),
            val = cell2mat(fields(i));
            if map.(val) == id
                value = val;
                break;
            end
        end
    end
    function id = value2id(map,value)
        id = map.(value);
    end

    default_params = struct('algorithm', 'kdtree' ,'checks', 32,  'trees', 4, 'branching', 32, 'iterations', 5, 'centers_init', 'random', 'cb_index', 0.4, 'target_precision', -1, 'build_weight', 0.01, 'memory_weight', 0, 'sample_fraction', 0.1, 'log_level', 'warning', 'random_seed', 0);

    if ~isstruct(search_params)
        error('The "search_params" argument must be a structure');
    end

    params = default_params;
    fn = fieldnames(search_params);
    for i = [1:length(fn)],
        name = cell2mat(fn(i));
        params.(name) = search_params.(name);
    end
    if ~isnumeric(params.algorithm),
        params.algorithm = value2id(algos,params.algorithm);
    end
    if ~isnumeric(params.centers_init),
        params.centers_init = value2id(center_algos,params.centers_init);
    end
    if ~isnumeric(params.log_level),
        params.log_level = value2id(log_levels,params.log_level);
    end

    if (size(data,1)==1 && size(data,2)==1)
        % we already have an index
        [indices,dists] = nearest_neighbors('index_find_nn', data, testset, n, params);
    else
        % create the index and search
        [indices,dists] = nearest_neighbors('find_nn', data, testset, n, params);
    end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.0.1.css">


text:
<?php

require_once __DIR__ . "/vendor/autoload.php";

$app = new Silex\Application();
$app->register(new Cerberus\Providers\CerberusServiceProvider());

$app->get('/helloworld/', function ($name) use ($app) {
    return 'Hello World';
});

$app->run();