text:
#ifndef _TCQDB_H                         /* duplication check */
#define _TCQDB_H

#if defined(__cplusplus)
#define __TCQDB_CLINKAGEBEGIN extern "C" {
#define __TCQDB_CLINKAGEEND }
#else
#define __TCQDB_CLINKAGEBEGIN
#define __TCQDB_CLINKAGEEND
#endif
__TCQDB_CLINKAGEBEGIN

#include <tcutil.h>
#include <tchdb.h>
#include <tcbdb.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>

/*************************************************************************************************
 * API
 *************************************************************************************************/

typedef struct {                         /* type of structure for a q-gram database */
  void *mmtx;                            /* mutex for method */
  TCBDB *idx;                            /* internal database object */
  bool open;                             /* whether the internal database is opened */
  TCMAP *cc;                             /* cache of q-gram tokens */
  uint64_t icsiz;                        /* capacity of the cache */
  uint32_t lcnum;                        /* max number of cached leaves */
  TCMAP *dtokens;                        /* deleted tokens */
  struct _TCIDSET *dids;                 /* deleted ID numbers */
  uint32_t etnum;                        /* expected number of tokens */
  uint8_t opts;                          /* options */
  uint32_t fwmmax;                       /* maximum number of forward matching expansion */
  bool (*synccb)(int, int, const char *, void *);  /* callback function for sync progression */
  void *syncopq;                         /* opaque for the sync callback function */
} TCQDB;

enum {                                   /* enumeration for tuning options */
  QDBTLARGE = 1 << 0,                    /* use 64-bit bucket array */
  QDBTDEFLATE = 1 << 1,                  /* compress each page with Deflate */
  QDBTBZIP = 1 << 2,                     /* compress each record with BZIP2 */
  QDBTTCBS = 1 << 3                      /* compress each page with TCBS */
};

enum {                                   /* enumeration for open modes */
  QDBOREADER = 1 << 0,                   /* open as a reader */
  QDBOWRITER = 1 << 1,                   /* open as a writer */
  QDBOCREAT = 1 << 2,                    /* writer creating */
  QDBOTRUNC = 1 << 3,                    /* writer truncating */
  QDBONOLCK = 1 << 4,                    /* open without locking */
  QDBOLCKNB = 1 << 5                     /* lock without blocking */
};

enum {                                   /* enumeration for get modes */
  QDBSSUBSTR,                            /* substring matching */
  QDBSPREFIX,                            /* prefix matching */
  QDBSSUFFIX,                            /* suffix matching */
  QDBSFULL                               /* full matching */
};

/* String containing the version information. */
extern const char *tdversion;

/* Get the message string corresponding to an error code.
   `ecode' specifies the error code.
   The return value is the message string of the error code. */
const char *tcqdberrmsg(int ecode);

/* Create a q-gram database object.
   The return value is the new q-gram database object. */
TCQDB *tcqdbnew(void);

/* Delete a q-gram database object.
   `qdb' specifies the q-gram database object.
   If the database is not closed, it is closed implicitly.  Note that the deleted object and its
   derivatives can not be used anymore. */
void tcqdbdel(TCQDB *qdb);

/* Get the last happened error code of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the last happened error code.
   The following error code is defined: `TCESUCCESS' for success, `TCETHREAD' for threading
   error, `TCEINVALID' for invalid operation, `TCENOFILE' for file not found, `TCENOPERM' for no
   permission, `TCEMETA' for invalid meta data, `TCERHEAD' for invalid record header, `TCEOPEN'
   for open error, `TCECLOSE' for close error, `TCETRUNC' for trunc error, `TCESYNC' for sync
   error, `TCESTAT' for stat error, `TCESEEK' for seek error, `TCEREAD' for read error,
   `TCEWRITE' for write error, `TCEMMAP' for mmap error, `TCELOCK' for lock error, `TCEUNLINK'
   for unlink error, `TCERENAME' for rename error, `TCEMKDIR' for mkdir error, `TCERMDIR' for
   rmdir error, `TCEKEEP' for existing record, `TCENOREC' for no record found, and `TCEMISC' for
   miscellaneous error. */
int tcqdbecode(TCQDB *qdb);

/* Set the tuning parameters of a q-gram database object.
   `qdb' specifies the q-gram database object which is not opened.
   `etnum' specifies the expected number of tokens to be stored.  If it is not more than 0, the
   default value is specified.  The default value is 1000000.
   `opts' specifies options by bitwise-or: `QDBTLARGE' specifies that the size of the database
   can be larger than 2GB by using 64-bit bucket array, `QDBTDEFLATE' specifies that each page
   is compressed with Deflate encoding, `QDBTBZIP' specifies that each page is compressed with
   BZIP2 encoding, `QDBTTCBS' specifies that each page is compressed with TCBS encoding.
   If successful, the return value is true, else, it is false.
   Note that the tuning parameters should be set before the database is opened. */
bool tcqdbtune(TCQDB *qdb, int64_t etnum, uint8_t opts);

/* Set the caching parameters of a q-gram database object.
   `qdb' specifies the q-gram database object which is not opened.
   `icsiz' specifies the capacity size of the token cache.  If it is not more than 0, the default
   value is specified.  The default value is 134217728.
   `lcnum' specifies the maximum number of cached leaf nodes of B+ tree.  If it is not more than
   0, the default value is specified.  The default value is 64 for writer or 1024 for reader.
   If successful, the return value is true, else, it is false.
   Note that the caching parameters should be set before the database is opened. */
bool tcqdbsetcache(TCQDB *qdb, int64_t icsiz, int32_t lcnum);

/* Set the maximum number of forward matching expansion of a q-gram database object.
   `qdb' specifies the q-gram database object.
   `fwmmax' specifies the maximum number of forward matching expansion.
   If successful, the return value is true, else, it is false.
   Note that the matching parameters should be set before the database is opened. */
bool tcqdbsetfwmmax(TCQDB *qdb, uint32_t fwmmax);

/* Open a q-gram database object.
   `qdb' specifies the q-gram database object.
   `path' specifies the path of the database file.
   `omode' specifies the connection mode: `QDBOWRITER' as a writer, `QDBOREADER' as a reader.
   If the mode is `QDBOWRITER', the following may be added by bitwise-or: `QDBOCREAT', which
   means it creates a new database if not exist, `QDBOTRUNC', which means it creates a new
   database regardless if one exists.  Both of `QDBOREADER' and `QDBOWRITER' can be added to by
   bitwise-or: `QDBONOLCK', which means it opens the database file without file locking, or
   `QDBOLCKNB', which means locking is performed without blocking.
   If successful, the return value is true, else, it is false. */
bool tcqdbopen(TCQDB *qdb, const char *path, int omode);

/* Close a q-gram database object.
   `qdb' specifies the q-gram database object.
   If successful, the return value is true, else, it is false.
   Update of a database is assured to be written when the database is closed.  If a writer opens
   a database but does not close it appropriately, the database will be broken. */
bool tcqdbclose(TCQDB *qdb);

/* Store a record into a q-gram database object.
   `qdb' specifies the q-gram database object connected as a writer.
   `id' specifies the ID number of the record.  It should be positive.
   `text' specifies the string of the record, whose encoding should be UTF-8.
   If successful, the return value is true, else, it is false. */
bool tcqdbput(TCQDB *qdb, int64_t id, const char *text);

/* Remove a record of a q-gram database object.
   `qdb' specifies the q-gram database object connected as a writer.
   `id' specifies the ID number of the record.  It should be positive.
   `text' specifies the string of the record, which should be same as the stored one.
   If successful, the return value is true, else, it is false. */
bool tcqdbout(TCQDB *qdb, int64_t id, const char *text);

/* Search a q-gram database.
   `qdb' specifies the q-gram database object.
   `word' specifies the string of the word to be matched to.
   `smode' specifies the matching mode: `QDBSSUBSTR' as substring matching, `QDBSPREFIX' as prefix
   matching, `QDBSSUFFIX' as suffix matching, or `QDBSFULL' as full matching.
   `np' specifies the pointer to the variable into which the number of elements of the return
   value is assigned.
   If successful, the return value is the pointer to an array of ID numbers of the corresponding
   records.  `NULL' is returned on failure.
   Because the region of the return value is allocated with the `malloc' call, it should be
   released with the `free' call when it is no longer in use. */
uint64_t *tcqdbsearch(TCQDB *qdb, const char *word, int smode, int *np);

/* Synchronize updated contents of a q-gram database object with the file and the device.
   `qdb' specifies the q-gram database object connected as a writer.
   If successful, the return value is true, else, it is false.
   This function is useful when another process connects the same database file. */
bool tcqdbsync(TCQDB *qdb);

/* Optimize the file of a q-gram database object.
   `qdb' specifies the q-gram database object connected as a writer.
   If successful, the return value is true, else, it is false.
   This function is useful to reduce the size of the database file with data fragmentation by
   successive updating. */
bool tcqdboptimize(TCQDB *qdb);

/* Remove all records of a q-gram database object.
   `qdb' specifies the q-gram database object connected as a writer.
   If successful, the return value is true, else, it is false. */
bool tcqdbvanish(TCQDB *qdb);

/* Copy the database file of a q-gram database object.
   `qdb' specifies the q-gram database object.
   `path' specifies the path of the destination file.  If it begins with `@', the trailing
   substring is executed as a command line.
   If successful, the return value is true, else, it is false.  False is returned if the executed
   command returns non-zero code.
   The database file is assured to be kept synchronized and not modified while the copying or
   executing operation is in progress.  So, this function is useful to create a backup file of
   the database file. */
bool tcqdbcopy(TCQDB *qdb, const char *path);

/* Get the file path of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the path of the database file or `NULL' if the object does not connect to
   any database file. */
const char *tcqdbpath(TCQDB *qdb);

/* Get the number of tokens of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the number of tokens or 0 if the object does not connect to any database
   file. */
uint64_t tcqdbtnum(TCQDB *qdb);

/* Get the size of the database file of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the size of the database file or 0 if the object does not connect to any
   database file. */
uint64_t tcqdbfsiz(TCQDB *qdb);

/*************************************************************************************************
 * features for experts
 *************************************************************************************************/

#define _TD_VERSION    "0.9.13"
#define _TD_LIBVER     114
#define _TD_FORMATVER  "0.9"

#define QDBSYNCMSGF    "started"         /* first message of sync progression */
#define QDBSYNCMSGL    "finished"        /* last message of sync progression */

typedef struct {                         /* type of structure for a result set */
  uint64_t *ids;                         /* array of ID numbers */
  int num;                               /* number of the array */
} QDBRSET;

typedef struct _TCIDSET {                /* type of structure for an ID set */
  uint64_t *buckets;                     /* bucket array */
  uint32_t bnum;                         /* number of buckets */
  TCMAP *trails;                         /* map of trailing records */
} TCIDSET;

enum {                                   /* enumeration for text normalization options */
  TCTNLOWER = 1 << 0,                    /* into lower cases */
  TCTNNOACC = 1 << 1,                    /* into ASCII alphabets */
  TCTNSPACE = 1 << 2                     /* into ASCII space */
};

/* Set the file descriptor for debugging output.
   `qdb' specifies the q-gram database object.
   `fd' specifies the file descriptor for debugging output. */
void tcqdbsetdbgfd(TCQDB *qdb, int fd);

/* Get the file descriptor for debugging output.
   `qdb' specifies the q-gram database object.
   The return value is the file descriptor for debugging output. */
int tcqdbdbgfd(TCQDB *qdb);

/* Synchronize updating contents on memory of a q-gram database object.
   `qdb' specifies the q-gram database object.
   `level' specifies the synchronization lavel; 0 means cache synchronization, 1 means database
   synchronization, and 2 means file synchronization.
   If successful, the return value is true, else, it is false. */
bool tcqdbmemsync(TCQDB *qdb, int level);

/* Clear the cache of a q-gram database object.
   `qdb' specifies the q-gram database object.
   If successful, the return value is true, else, it is false. */
bool tcqdbcacheclear(TCQDB *qdb);

/* Get the inode number of the database file of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the inode number of the database file or 0 the object does not connect to
   any database file. */
uint64_t tcqdbinode(TCQDB *qdb);

/* Get the modification time of the database file of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the inode number of the database file or 0 the object does not connect to
   any database file. */
time_t tcqdbmtime(TCQDB *qdb);

/* Get the options of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the options. */
uint8_t tcqdbopts(TCQDB *qdb);

/* Get the maximum number of forward matching expansion of a q-gram database object.
   `qdb' specifies the q-gram database object.
   The return value is the maximum number of forward matching expansion. */
uint32_t tcqdbfwmmax(TCQDB *qdb);

/* Get the number of records in the cache of a q-gram database object.
   `wdb' specifies the word database object.
   The return value is the number of records in the cache. */
uint32_t tcqdbcnum(TCQDB *qdb);

/* Set the callback function for sync progression of a q-gram database object.
   `qdb' specifies the q-gram database object.
   `cb' specifies the pointer to the callback function for sync progression.  Its first argument
   specifies the number of tokens to be synchronized.  Its second argument specifies the number
   of processed tokens.  Its third argument specifies the message string.  The fourth argument
   specifies an arbitrary pointer.  Its return value should be true usually, or false if the sync
   operation should be terminated.
   `opq' specifies the arbitrary pointer to be given to the callback function. */
void tcqdbsetsynccb(TCQDB *qdb, bool (*cb)(int, int, const char *, void *), void *opq);

/* Merge multiple result sets by union.
   `rsets' specifies the pointer to the array of result sets.
   `rsnum' specifies the number of the array.
   `np' specifies the pointer to the variable into which the number of elements of the return
   value is assigned.
   If successful, the return value is the pointer to an array of ID numbers of the result.
   Because the region of the return value is allocated with the `malloc' call, it should be
   released with the `free' call when it is no longer in use. */
uint64_t *tcqdbresunion(QDBRSET *rsets, int rsnum, int *np);

/* Merge multiple result sets by intersection.
   `rsets' specifies the pointer to the array of result sets.
   `rsnum' specifies the number of the array.
   `np' specifies the pointer to the variable into which the number of elements of the return
   value is assigned.
   If successful, the return value is the pointer to an array of ID numbers of the result.
   Because the region of the return value is allocated with the `malloc' call, it should be
   released with the `free' call when it is no longer in use. */
uint64_t *tcqdbresisect(QDBRSET *rsets, int rsnum, int *np);

/* Merge multiple result sets by difference.
   `rsets' specifies the pointer to the array of result sets.
   `rsnum' specifies the number of the array.
   `np' specifies the pointer to the variable into which the number of elements of the return
   value is assigned.
   If successful, the return value is the pointer to an array of ID numbers of the result.
   Because the region of the return value is allocated with the `malloc' call, it should be
   released with the `free' call when it is no longer in use. */
uint64_t *tcqdbresdiff(QDBRSET *rsets, int rsnum, int *np);

/* Normalize a text.
   `text' specifies the string of the record, whose encoding should be UTF-8.
   `opts' specifies options by bitwise-or: `TCTNLOWER' specifies that alphabetical characters are
   normalized into lower cases, `TCTNNOACC' specifies that alphabetical characters with accent
   marks are normalized without accent marks, `TCTNSPACE' specifies that white space characters
   are normalized into the ASCII space and they are squeezed into one. */
void tctextnormalize(char *text, int opts);

/* Create an ID set object.
   `bnum' specifies the number of the buckets.
   The return value is the new ID set object. */
TCIDSET *tcidsetnew(uint32_t bnum);

/* Delete an ID set object.
   `idset' specifies the ID set object. */
void tcidsetdel(TCIDSET *idset);

/* Mark an ID number of an ID set object.
   `idset' specifies the ID set object.
   `id' specifies the ID number. */
void tcidsetmark(TCIDSET *idset, int64_t id);

/* Check an ID of an ID set object.
   `idset' specifies the ID set object.
   `id' specifies the ID number.
   The return value is true if the ID number is marked, else, it is false. */
bool tcidsetcheck(TCIDSET *idset, int64_t id);

/* Clear an ID set object.
   `idset' specifies the ID set object. */
void tcidsetclear(TCIDSET *idset);

__TCQDB_CLINKAGEEND
#endif                                   /* duplication check */

/* END OF FILE */


text:
from ctypes import c_uint, c_ulong, Structure
from bcc import BPF
from time import sleep
import sys
from unittest import main, TestCase
from utils import mayFail

arg1 = sys.argv.pop(1).encode()
arg2 = b""
if len(sys.argv) > 1:
  arg2 = sys.argv.pop(1)

class TestBlkRequest(TestCase):
    def setUp(self):
        b = BPF(arg1, arg2, debug=0)
        self.latency = b.get_table(b"latency", c_uint, c_ulong)
        if BPF.get_kprobe_functions(b"blk_start_request"):
            b.attach_kprobe(event=b"blk_start_request",
                    fn_name=b"probe_blk_start_request")
        b.attach_kprobe(event=b"blk_mq_start_request",
                fn_name=b"probe_blk_start_request")
        b.attach_kprobe(event=b"blk_update_request",
                fn_name=b"probe_blk_update_request")

    def test_blk1(self):
        import subprocess
        import os
        # use /opt instead of /tmp so that it hits a real disk
        for i in range(0, 2):
            subprocess.call(["dd", "if=/dev/zero", "of=/opt/trace3.txt",
                             "count=1024", "bs=4096"])
            subprocess.call(["sync"])
        os.unlink("/opt/trace3.txt")
        for key, leaf in self.latency.items():
            print("latency %u:" % key.value, "count %u" % leaf.value)
        sys.stdout.flush()
        self.assertEqual(len(list(self.latency.keys())), len(self.latency))

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
name             'linux_base'
maintainer       'gnslngr.us'
maintainer_email 'james@gnslngr.us'
license          'Apache 2.0'
description      'Installs/Configures linux_base'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.2'

depends "users"
depends "openssh"
depends "sudo"


text:
#ifdef _WIN32
#   include <windows.h>
#endif

#include <sql.h>
#include <sqlext.h>

#include <string>

#include <boost/test/unit_test.hpp>

#include "ignite/ignition.h"

#include "test_utils.h"
#include "odbc_test_suite.h"

using namespace ignite;
using namespace ignite_test;

using namespace boost::unit_test;

/**
 * Test setup fixture.
 */
struct TransactionTestSuiteFixture : public odbc::OdbcTestSuite
{
    static Ignite StartAdditionalNode(const char* name)
    {
        return StartTestNode("queries-transaction.xml", name);
    }

    /**
     * Constructor.
     */
    TransactionTestSuiteFixture() :
        grid(StartAdditionalNode("NodeMain"))
    {
        // No-op.
    }

    /**
     * Destructor.
     */
    ~TransactionTestSuiteFixture()
    {
        // No-op.
    }

    /**
     * Insert test string value in cache and make all the neccessary checks.
     *
     * @param key Key.
     * @param value Value.
     */
    void InsertTestValue(int64_t key, const std::string& value)
    {
        InsertTestValue(stmt, key, value);
    }

    /**
     * Insert test string value in cache and make all the neccessary checks.
     *
     * @param stmt Statement.
     * @param key Key.
     * @param value Value.
     */
    static void InsertTestValue(SQLHSTMT stmt, int64_t key, const std::string& value)
    {
        SQLCHAR insertReq[] = "INSERT INTO TestType(_key, strField) VALUES(?, ?)";

        SQLRETURN ret = SQLPrepare(stmt, insertReq, SQL_NTS);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        char strField[1024] = { 0 };
        SQLLEN strFieldLen = 0;

        ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_BIGINT, 0, 0, &key, 0, 0);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, sizeof(strField),
            sizeof(strField), &strField, sizeof(strField), &strFieldLen);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        strncpy(strField, value.c_str(), sizeof(strField));
        strFieldLen = SQL_NTS;

        ret = SQLExecute(stmt);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        SQLLEN affected = 0;
        ret = SQLRowCount(stmt, &affected);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        BOOST_CHECK_EQUAL(affected, 1);

        ret = SQLMoreResults(stmt);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ResetStatement(stmt);
    }

    /**
     * Update test string value in cache and make all the neccessary checks.
     *
     * @param key Key.
     * @param value Value.
     */
    void UpdateTestValue(int64_t key, const std::string& value)
    {
        UpdateTestValue(stmt, key, value);
    }

    /**
     * Update test string value in cache and make all the neccessary checks.
     *
     * @param stmt Statement.
     * @param key Key.
     * @param value Value.
     */
    static void UpdateTestValue(SQLHSTMT stmt, int64_t key, const std::string& value)
    {
        SQLCHAR insertReq[] = "UPDATE TestType SET strField=? WHERE _key=?";

        SQLRETURN ret = SQLPrepare(stmt, insertReq, SQL_NTS);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        char strField[1024] = { 0 };
        SQLLEN strFieldLen = 0;

        ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, sizeof(strField),
            sizeof(strField), &strField, sizeof(strField), &strFieldLen);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_BIGINT, 0, 0, &key, 0, 0);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        strncpy(strField, value.c_str(), sizeof(strField));
        strFieldLen = SQL_NTS;

        ret = SQLExecute(stmt);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        SQLLEN affected = 0;
        ret = SQLRowCount(stmt, &affected);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        BOOST_CHECK_EQUAL(affected, 1);

        ret = SQLMoreResults(stmt);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ResetStatement(stmt);
    }

    /**
     * Delete test string value.
     *
     * @param key Key.
     */
    void DeleteTestValue(int64_t key)
    {
        DeleteTestValue(stmt, key);
    }

    /**
     * Delete test string value.
     *
     * @param stmt Statement.
     * @param key Key.
     */
    static void DeleteTestValue(SQLHSTMT stmt, int64_t key)
    {
        SQLCHAR insertReq[] = "DELETE FROM TestType WHERE _key=?";

        SQLRETURN ret = SQLPrepare(stmt, insertReq, SQL_NTS);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_BIGINT, 0, 0, &key, 0, 0);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLExecute(stmt);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        SQLLEN affected = 0;
        ret = SQLRowCount(stmt, &affected);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        BOOST_CHECK_EQUAL(affected, 1);

        ret = SQLMoreResults(stmt);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ResetStatement(stmt);
    }
    /**
     * Selects and checks the value.
     *
     * @param key Key.
     * @param expect Expected value.
     */
    void CheckTestValue(int64_t key, const std::string& expect)
    {
        CheckTestValue(stmt, key, expect);
    }

    /**
     * Selects and checks the value.
     *
     * @param stmt Statement.
     * @param key Key.
     * @param expect Expected value.
     */
    static void CheckTestValue(SQLHSTMT stmt, int64_t key, const std::string& expect)
    {
        // Just selecting everything to make sure everything is OK
        SQLCHAR selectReq[] = "SELECT strField FROM TestType WHERE _key = ?";

        char strField[1024] = { 0 };
        SQLLEN strFieldLen = 0;

        SQLRETURN ret = SQLBindCol(stmt, 1, SQL_C_CHAR, &strField, sizeof(strField), &strFieldLen);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_BIGINT, 0, 0, &key, 0, 0);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLExecDirect(stmt, selectReq, sizeof(selectReq));

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLFetch(stmt);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        BOOST_CHECK_EQUAL(std::string(strField, strFieldLen), expect);

        ret = SQLFetch(stmt);

        BOOST_CHECK_EQUAL(ret, SQL_NO_DATA);

        ret = SQLMoreResults(stmt);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ResetStatement(stmt);
    }

    /**
     * Selects and checks that value is absent.
     *
     * @param key Key.
     */
    void CheckNoTestValue(int64_t key)
    {
        CheckNoTestValue(stmt, key);
    }

    /**
     * Selects and checks that value is absent.
     *
     * @param stmt Statement.
     * @param key Key.
     */
    static void CheckNoTestValue(SQLHSTMT stmt, int64_t key)
    {
        // Just selecting everything to make sure everything is OK
        SQLCHAR selectReq[] = "SELECT strField FROM TestType WHERE _key = ?";

        char strField[1024] = { 0 };
        SQLLEN strFieldLen = 0;

        SQLRETURN ret = SQLBindCol(stmt, 1, SQL_C_CHAR, &strField, sizeof(strField), &strFieldLen);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_BIGINT, 0, 0, &key, 0, 0);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLExecDirect(stmt, selectReq, sizeof(selectReq));

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLFetch(stmt);

        BOOST_CHECK_EQUAL(ret, SQL_NO_DATA);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLMoreResults(stmt);

        BOOST_CHECK_EQUAL(ret, SQL_NO_DATA);

        if (ret != SQL_NO_DATA)
            ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ResetStatement(stmt);
    }

    /**
     * Reset statement state.
     */
    void ResetStatement()
    {
        ResetStatement(stmt);
    }

    /**
     * Reset statement state.
     *
     * @param stmt Statement.
     */
    static void ResetStatement(SQLHSTMT stmt)
    {
        SQLRETURN ret = SQLFreeStmt(stmt, SQL_RESET_PARAMS);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);

        ret = SQLFreeStmt(stmt, SQL_UNBIND);

        ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_STMT, stmt);
    }

    /** Node started during the test. */
    Ignite grid;
};

BOOST_FIXTURE_TEST_SUITE(TransactionTestSuite, TransactionTestSuiteFixture)

BOOST_AUTO_TEST_CASE(TransactionConnectionCommit)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionConnectionRollbackInsert)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckNoTestValue(42);
}

BOOST_AUTO_TEST_CASE(TransactionConnectionRollbackUpdate1)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionConnectionRollbackUpdate2)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionConnectionRollbackDelete1)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    DeleteTestValue(42);

    CheckNoTestValue(42);

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionConnectionRollbackDelete2)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");

    DeleteTestValue(42);

    CheckNoTestValue(42);

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionConnectionTxModeError)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=error");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    BOOST_CHECK_EQUAL(ret, SQL_ERROR);
}

BOOST_AUTO_TEST_CASE(TransactionConnectionTxModeIgnore)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=ignore");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckNoTestValue(42);
}

BOOST_AUTO_TEST_CASE(TransactionConnectionTxModeCommit)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=commit");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentCommit)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentRollbackInsert)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckNoTestValue(42);
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentRollbackUpdate1)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentRollbackUpdate2)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentRollbackDelete1)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    DeleteTestValue(42);

    CheckNoTestValue(42);

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentRollbackDelete2)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    CheckTestValue(42, "Some");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");

    DeleteTestValue(42);

    CheckNoTestValue(42);

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentTxModeError)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=error");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    BOOST_CHECK_EQUAL(ret, SQL_ERROR);
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentTxModeIgnore)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=ignore");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckNoTestValue(42);
}

BOOST_AUTO_TEST_CASE(TransactionEnvironmentTxModeCommit)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache;nested_tx_mode=commit");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    InsertTestValue(42, "Some");

    ret = ExecQuery("BEGIN");

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    UpdateTestValue(42, "Other");

    CheckTestValue(42, "Other");

    ret = SQLEndTran(SQL_HANDLE_ENV, env, SQL_ROLLBACK);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_ENV, env);

    CheckTestValue(42, "Some");
}

BOOST_AUTO_TEST_CASE(TransactionVersionMismatchError)
{
    Connect("DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    InsertTestValue(1, "test_1");

    SQLRETURN ret = SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    CheckTestValue(1, "test_1");

    SQLHDBC dbc2;
    SQLHSTMT stmt2;

    Connect(dbc2, stmt2, "DRIVER={Apache Ignite};address=127.0.0.1:11110;schema=cache");

    ret = SQLSetConnectAttr(dbc2, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc2);

    InsertTestValue(stmt2, 2, "test_2");

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc2, SQL_COMMIT);

    ODBC_FAIL_ON_ERROR(ret, SQL_HANDLE_DBC, dbc2);

    CheckTestValue(stmt2, 1, "test_1");
    CheckTestValue(stmt2, 2, "test_2");

    try
    {
        InsertTestValue(2, "test_2");

        BOOST_FAIL("Exception is expected");
    }
    catch (OdbcClientError& err)
    {
        BOOST_CHECK(err.message.find("Cannot serialize transaction due to write conflict") != err.message.npos);
        BOOST_CHECK_EQUAL(err.sqlstate, "40001");

        ResetStatement(stmt);
    }

    try
    {
        CheckTestValue(1, "test_1");

        BOOST_FAIL("Exception is expected");
    }
    catch (OdbcClientError& err)
    {
        BOOST_CHECK(err.message.find("Transaction is already completed") != err.message.npos);
        BOOST_CHECK_EQUAL(err.sqlstate, "25000");

        ResetStatement(stmt);
    }

    ret = SQLEndTran(SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);
    ODBC_THROW_ON_ERROR(ret, SQL_HANDLE_DBC, dbc);

    SQLFreeHandle(SQL_HANDLE_STMT, stmt2);

    SQLDisconnect(dbc2);

    SQLFreeHandle(SQL_HANDLE_DBC, dbc2);
}

BOOST_AUTO_TEST_SUITE_END()


text:
    @if(empty($loader_text_off))

{!!$loader_text or 'Loading...'!!}

    @endif


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dataproc/v1beta2/jobs.proto

package com.google.cloud.dataproc.v1beta2;

public interface PySparkJobOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.dataproc.v1beta2.PySparkJob)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The HCFS URI of the main Python file to use as the driver. Must
   * be a .py file.
   *

   *
   * string main_python_file_uri = 1;
   */
  java.lang.String getMainPythonFileUri();
  /**
   *
   *
   *

   * Required. The HCFS URI of the main Python file to use as the driver. Must
   * be a .py file.
   *

   *
   * string main_python_file_uri = 1;
   */
  com.google.protobuf.ByteString getMainPythonFileUriBytes();

  /**
   *
   *
   *

   * Optional. The arguments to pass to the driver.  Do not include arguments,
   * such as `--conf`, that can be set as job properties, since a collision may
   * occur that causes an incorrect job submission.
   *

   *
   * repeated string args = 2;
   */
  java.util.List<java.lang.String> getArgsList();
  /**
   *
   *
   *

   * Optional. The arguments to pass to the driver.  Do not include arguments,
   * such as `--conf`, that can be set as job properties, since a collision may
   * occur that causes an incorrect job submission.
   *

   *
   * repeated string args = 2;
   */
  int getArgsCount();
  /**
   *
   *
   *

   * Optional. The arguments to pass to the driver.  Do not include arguments,
   * such as `--conf`, that can be set as job properties, since a collision may
   * occur that causes an incorrect job submission.
   *

   *
   * repeated string args = 2;
   */
  java.lang.String getArgs(int index);
  /**
   *
   *
   *

   * Optional. The arguments to pass to the driver.  Do not include arguments,
   * such as `--conf`, that can be set as job properties, since a collision may
   * occur that causes an incorrect job submission.
   *

   *
   * repeated string args = 2;
   */
  com.google.protobuf.ByteString getArgsBytes(int index);

  /**
   *
   *
   *

   * Optional. HCFS file URIs of Python files to pass to the PySpark
   * framework. Supported file types: .py, .egg, and .zip.
   *

   *
   * repeated string python_file_uris = 3;
   */
  java.util.List<java.lang.String> getPythonFileUrisList();
  /**
   *
   *
   *

   * Optional. HCFS file URIs of Python files to pass to the PySpark
   * framework. Supported file types: .py, .egg, and .zip.
   *

   *
   * repeated string python_file_uris = 3;
   */
  int getPythonFileUrisCount();
  /**
   *
   *
   *

   * Optional. HCFS file URIs of Python files to pass to the PySpark
   * framework. Supported file types: .py, .egg, and .zip.
   *

   *
   * repeated string python_file_uris = 3;
   */
  java.lang.String getPythonFileUris(int index);
  /**
   *
   *
   *

   * Optional. HCFS file URIs of Python files to pass to the PySpark
   * framework. Supported file types: .py, .egg, and .zip.
   *

   *
   * repeated string python_file_uris = 3;
   */
  com.google.protobuf.ByteString getPythonFileUrisBytes(int index);

  /**
   *
   *
   *

   * Optional. HCFS URIs of jar files to add to the CLASSPATHs of the
   * Python driver and tasks.
   *

   *
   * repeated string jar_file_uris = 4;
   */
  java.util.List<java.lang.String> getJarFileUrisList();
  /**
   *
   *
   *

   * Optional. HCFS URIs of jar files to add to the CLASSPATHs of the
   * Python driver and tasks.
   *

   *
   * repeated string jar_file_uris = 4;
   */
  int getJarFileUrisCount();
  /**
   *
   *
   *

   * Optional. HCFS URIs of jar files to add to the CLASSPATHs of the
   * Python driver and tasks.
   *

   *
   * repeated string jar_file_uris = 4;
   */
  java.lang.String getJarFileUris(int index);
  /**
   *
   *
   *

   * Optional. HCFS URIs of jar files to add to the CLASSPATHs of the
   * Python driver and tasks.
   *

   *
   * repeated string jar_file_uris = 4;
   */
  com.google.protobuf.ByteString getJarFileUrisBytes(int index);

  /**
   *
   *
   *

   * Optional. HCFS URIs of files to be copied to the working directory of
   * Python drivers and distributed tasks. Useful for naively parallel tasks.
   *

   *
   * repeated string file_uris = 5;
   */
  java.util.List<java.lang.String> getFileUrisList();
  /**
   *
   *
   *

   * Optional. HCFS URIs of files to be copied to the working directory of
   * Python drivers and distributed tasks. Useful for naively parallel tasks.
   *

   *
   * repeated string file_uris = 5;
   */
  int getFileUrisCount();
  /**
   *
   *
   *

   * Optional. HCFS URIs of files to be copied to the working directory of
   * Python drivers and distributed tasks. Useful for naively parallel tasks.
   *

   *
   * repeated string file_uris = 5;
   */
  java.lang.String getFileUris(int index);
  /**
   *
   *
   *

   * Optional. HCFS URIs of files to be copied to the working directory of
   * Python drivers and distributed tasks. Useful for naively parallel tasks.
   *

   *
   * repeated string file_uris = 5;
   */
  com.google.protobuf.ByteString getFileUrisBytes(int index);

  /**
   *
   *
   *

   * Optional. HCFS URIs of archives to be extracted in the working directory of
   * .jar, .tar, .tar.gz, .tgz, and .zip.
   *

   *
   * repeated string archive_uris = 6;
   */
  java.util.List<java.lang.String> getArchiveUrisList();
  /**
   *
   *
   *

   * Optional. HCFS URIs of archives to be extracted in the working directory of
   * .jar, .tar, .tar.gz, .tgz, and .zip.
   *

   *
   * repeated string archive_uris = 6;
   */
  int getArchiveUrisCount();
  /**
   *
   *
   *

   * Optional. HCFS URIs of archives to be extracted in the working directory of
   * .jar, .tar, .tar.gz, .tgz, and .zip.
   *

   *
   * repeated string archive_uris = 6;
   */
  java.lang.String getArchiveUris(int index);
  /**
   *
   *
   *

   * Optional. HCFS URIs of archives to be extracted in the working directory of
   * .jar, .tar, .tar.gz, .tgz, and .zip.
   *

   *
   * repeated string archive_uris = 6;
   */
  com.google.protobuf.ByteString getArchiveUrisBytes(int index);

  /**
   *
   *
   *

   * Optional. A mapping of property names to values, used to configure PySpark.
   * Properties that conflict with values set by the Cloud Dataproc API may be
   * overwritten. Can include properties set in
   * /etc/spark/conf/spark-defaults.conf and classes in user code.
   *

   *
   * map<string, string> properties = 7;
   */
  int getPropertiesCount();
  /**
   *
   *
   *

   * Optional. A mapping of property names to values, used to configure PySpark.
   * Properties that conflict with values set by the Cloud Dataproc API may be
   * overwritten. Can include properties set in
   * /etc/spark/conf/spark-defaults.conf and classes in user code.
   *

   *
   * map<string, string> properties = 7;
   */
  boolean containsProperties(java.lang.String key);
  /** Use {@link #getPropertiesMap()} instead. */
  @java.lang.Deprecated
  java.util.Map<java.lang.String, java.lang.String> getProperties();
  /**
   *
   *
   *

   * Optional. A mapping of property names to values, used to configure PySpark.
   * Properties that conflict with values set by the Cloud Dataproc API may be
   * overwritten. Can include properties set in
   * /etc/spark/conf/spark-defaults.conf and classes in user code.
   *

   *
   * map<string, string> properties = 7;
   */
  java.util.Map<java.lang.String, java.lang.String> getPropertiesMap();
  /**
   *
   *
   *

   * Optional. A mapping of property names to values, used to configure PySpark.
   * Properties that conflict with values set by the Cloud Dataproc API may be
   * overwritten. Can include properties set in
   * /etc/spark/conf/spark-defaults.conf and classes in user code.
   *

   *
   * map<string, string> properties = 7;
   */
  java.lang.String getPropertiesOrDefault(java.lang.String key, java.lang.String defaultValue);
  /**
   *
   *
   *

   * Optional. A mapping of property names to values, used to configure PySpark.
   * Properties that conflict with values set by the Cloud Dataproc API may be
   * overwritten. Can include properties set in
   * /etc/spark/conf/spark-defaults.conf and classes in user code.
   *

   *
   * map<string, string> properties = 7;
   */
  java.lang.String getPropertiesOrThrow(java.lang.String key);

  /**
   *
   *
   *

   * Optional. The runtime log config for job execution.
   *

   *
   * .google.cloud.dataproc.v1beta2.LoggingConfig logging_config = 8;
   */
  boolean hasLoggingConfig();
  /**
   *
   *
   *

   * Optional. The runtime log config for job execution.
   *

   *
   * .google.cloud.dataproc.v1beta2.LoggingConfig logging_config = 8;
   */
  com.google.cloud.dataproc.v1beta2.LoggingConfig getLoggingConfig();
  /**
   *
   *
   *

   * Optional. The runtime log config for job execution.
   *

   *
   * .google.cloud.dataproc.v1beta2.LoggingConfig logging_config = 8;
   */
  com.google.cloud.dataproc.v1beta2.LoggingConfigOrBuilder getLoggingConfigOrBuilder();
}


text:
The event handling systems sends a few events to the EventDispatcher

* **config**

With this event we send an ConfigEvent which contains the Config object for extending the config before running
* **pre.run**

This event is send after the configuration is loaded and before we started doing anything.
* **post.run**

This event is send after we are finished doing al the upload work to the remote servers
* **pre.upload**

With this event we send an ServerEvent and is executed before we start uploading and after we connect to the remote server. This event should be fired if custom servers are implemented.
* **post.upload**

With this event we send an ServerEvent and is executed after we finished uploading and before we disconnect from the remote server. This event should be fired if custom servers are implemented.

## Listners

We have the following build in events inside the default deployment

* [LocalExecute](#LocalExecute)
* [RemoteExecute](#RemoteExecute)
* [MailZend](#MailZend)

### LocalExecute

### RemoteExecute

### MailZend

## Events

The following event objects are integrated

* [ConfigEvent](#ConfigEvent)
* [ServerEvent](#ServerEvent)

### ConfigEvent

### ServerEvent


text:
<?php

namespace comyii\user\widgets;

use Yii;
use comyii\user\models\User;
use comyii\user\models\UserProfile;
use comyii\user\models\SocialProfile;

class ProfileView extends Widget
{
    /**
     * @var User the user model
     */
    public $model;

    /**
     * @var UserProfile the userprofile model
     */
    public $profile;

    /**
     * @var SocialProfile the social profile model
     */
    public $social;

    /**
     * @var bool whether to display the social connections
     */
    public $hasSocial;

    /**
     * @var bool whether to display the profile details
     */
    public $hasProfile;

    /**
     * @var array the settings for the profile
     */
    public $profileSettings = [];

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $m = $this->_module;
        if (!isset($this->hasSocial)) {
            $this->hasSocial = $m->socialSettings['enabled'];
        }
        if (!isset($this->hasProfile)) {
            $this->hasProfile = $m->profileSettings['enabled'];
        }
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        $socialDetails = $authClients = $avatar = $profile = $details = '';
        $accountDetails = AccountDetails::widget(['model' => $this->model]);
        if ($this->hasSocial) {
            $avatar = AvatarImage::widget(['profile' => $this->profile]);
            $socialDetails = SocialDetails::widget(['social' => $this->social, 'profile' => $this->profile]);
            if (Yii::$app->user->id == $this->model->id) {
                $authClients = SocialConnect::widget([
                    'model' => $this->model,
                    'profile' => $this->profile
                ]);
            }
            if ($this->_module->socialSettings['widgetEnabled']) {
                $details = <<hasProfile) {
            $profile = ProfileDetails::widget(['profile' => $this->profile]);
            $out = <<hasSocial) {
                $details = '
' . $socialDetails . '
';
                $col = 6;
            }
            $out = <<< HTML

                        {$accountDetails}

                    {$details}

HTML;
        }
        echo $out;
    }
}


text:
# Задача 4. Вариант 27.
# Напишите программу, которая выводит имя, под которым скрывается Доменико
#Теотокопули. Дополнительно необходимо вывести область интересов указанной
#личности, место рождения, годы рождения и смерти (если человек умер),
#вычислить возраст на данный момент (или момент смерти). Для хранения всех
#необходимых данных требуется использовать переменные. После вывода
#информации программа должна дожидаться пока пользователь нажмет Enter для
#выхода

# Denisenko A. N.
# 02.06.2016

psevdonim = "Эль Греко"
interesi = "художник"
mestorogdeniya = "остров Крит деревня Фоделе"
godrogdeniya = 1541
godsmerti = 1614
vozrast = godsmerti - godrogdeniya

print("Доменико Теотокопули\nПсевдоним  - ", psevdonim, "\nРод деятельности - ", interesi, "\nМесто рождения - ", mestorogdeniya,
      "Год рождения - " , godrogdeniya, "\nГод смерти - ", godsmerti, "\nВозраст - ", vozrast)

input("\n\nВведите Enter для выхода")


text:
class DisableInvalidServiceTemplates2 < ActiveRecord::Migration
  DOWNTIME = false

  unless defined?(Service)
    class Service < ActiveRecord::Base
      self.inheritance_column = nil
    end
  end

  def up
    Service.where(template: true, active: true).each do |template|
      template.update(active: false) unless template.valid?
    end
  end
end


text:
/sbin/chkconfig --level 0123456 rpcgssd off

#
# Stop rpcgssd if currently running
#
/sbin/service rpcgssd stop


text:
#include "GLFW/glfw3.h"
#include "baseinput.h"
#include "inputmanager.h"

namespace crap
{

InputManager::InputManager( uint32_t memory, window_t* window ) :
		_allocator( memory ),
		_window(window)
{

}

InputManager::~InputManager( void )
{

}

void InputManager::setWindow( window_t* window )
{
	_window = window;
}

window_t* InputManager::getWindow( void )
{
	return _window;
}

bool InputManager::update( uint32_t deltatime )
{
	if(_window != 0 )
		glfwPollEvents();

	for( intrusive_node<BaseInput>* node = _list.begin(); node != _list.end(); node = _list.next(node) )
	{
		node->parent()->receiveInput();
	}
	return true;
}

BaseInput* InputManager::getInputHandle( string_hash name )
{
	for( intrusive_node<BaseInput>* node = _list.begin(); node != _list.end(); node = _list.next(node) )
	{
		if( *node->parent() == name)
			return node->parent();
	}
	return 0;
}

} /* namespace crap */


text:
typedef NS_OPTIONS(unsigned long, JRTViewPinEdges){
    JRTViewPinTopEdge = 1 << 0,
    JRTViewPinRightEdge = 1 << 1,
    JRTViewPinBottomEdge = 1 << 2,
    JRTViewPinLeftEdge = 1 << 3,
    JRTViewPinAllEdges = ~0UL
};

@interface UIView (AutoLayout)
/// Return a frameless view that does not automatically use autoresizing (for use in autolayouts)
+(id)autoLayoutView;

/// Centers the receiver in the superview
-(void)centerInView:(UIView*)superview;
-(void)centerInContainerOnAxis:(NSLayoutAttribute)axis;

/// Pins a view to a specific edge(s) of its superview, with a specified inset
-(NSArray*)pinToSuperviewEdges:(JRTViewPinEdges)edges inset:(CGFloat)inset;

/// Pins a view to all edges of its superview, with specified edge insets
-(NSArray*)pinToSuperviewEdgesWithInset:(UIEdgeInsets)insets;

/// Pins a view's edge to a peer view's edge
-(void)pinEdge:(NSLayoutAttribute)edge toEdge:(NSLayoutAttribute)toEdge ofView:(UIView*)peerView;
-(void)pinEdge:(NSLayoutAttribute)edge toEdge:(NSLayoutAttribute)toEdge ofView:(UIView*)peerView inset:(CGFloat)inset;

/// Set to a specific size. 0 in any axis results in no constraint being applied.
-(void)constrainToSize:(CGSize)size;

/// Pins a point to a specific point in the superview's frame. Use NSLayoutAttributeNotAnAttribute to only pin in one dimension
-(void)pinPointAtX:(NSLayoutAttribute)x Y:(NSLayoutAttribute)y toPoint:(CGPoint)point;

@end


text:
	NPC Spawn Platforms V2 - lua/autorun/client/panel-npcselect.lua
    Copyright 2009-2017 Lex Robinson

    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.
--]]

local PANEL = {};

DEFINE_BASECLASS "DPropertySheet";

AccessorFunc( PANEL, "m_ConVar", "ConVar" );

function PANEL:Init()
	local npcs = list.Get('NPC');

	function onNPCSelected(_, _, line)
		RunConsoleCommand( self:GetConVar(), line.nicename )
	end

	-- All tab
	local ctrl = vgui.Create( "DListView" );
	ctrl:SetMultiSelect( false );
	ctrl:AddColumn( "#npcs" );
	ctrl:AddColumn( "#category" );

	for nicename, data in pairs( npcs ) do
		local line = ctrl:AddLine( data.Name, data.Category or "Other" )
		line.nicename = nicename;
	end

	ctrl.OnRowSelected = onNPCSelected;
	ctrl:SortByColumn(2, false);
	self:AddSheet("#All", ctrl);

	local categories = {};

	for nicename, data in pairs(npcs) do
		local cat = data.Category or "Other";
		categories[cat] = categories[cat] or {};
		categories[cat][nicename] = data;
	end

	for category, npcs in SortedPairs(categories) do
		-- Temp standin
		local ctrl = vgui.Create( "DListView" );
		ctrl:SetMultiSelect( false );
		ctrl:AddColumn( "#npcs" );

		for nicename, data in pairs( npcs ) do
			local line = ctrl:AddLine( data.Name )
			line.nicename = nicename;
		end
		ctrl.OnRowSelected = onNPCSelected;

		ctrl:SortByColumn( 1, false )

		self:AddSheet(category, ctrl);
	end

	self:SetTall(200);
	self.list = ctrl;

end

function PANEL:ControlValues( data )
	if ( data.command ) then
		self:SetConVar( data.command );
	end
end

-- TODO: Think hook!

derma.DefineControl("NPCSpawnSelecter", "Selects a NPC fo' spawnin'", PANEL, "DPropertySheet")


text:
/*
 * ----------------------------------------
 *      Nutrient Usage Tracking System
 * ----------------------------------------
 *          Produced by Dan Grew
 *                 2017
 * ----------------------------------------
 */
package uk.dangrew.nuts.graphics.day;

import javafx.scene.layout.GridPane;
import uk.dangrew.kode.javafx.style.JavaFxStyle;
import uk.dangrew.kode.javafx.table.base.ConceptTable;
import uk.dangrew.kode.javafx.table.base.ConceptTableRowImpl;
import uk.dangrew.kode.javafx.table.controller.UnresponsiveConceptTableController;
import uk.dangrew.nuts.graphics.table.TableComponents;
import uk.dangrew.nuts.graphics.table.tree.DayPlanTreePane;
import uk.dangrew.nuts.graphics.template.TemplateTableColumns;
import uk.dangrew.nuts.store.Database;
import uk.dangrew.nuts.template.Template;

public class UiCalendarPaneWithTree extends GridPane {

   static final double DATES_HEIGHT_PROPORTION = 30.0;
   static final double TEMPLATES_HEIGHT_PROPORTION = 10.0;
   static final double PLAN_VIEW_HEIGHT_PROPORTION = 60.0;

   private final UiCalendar uiCalendar;
   private final DayPlanTreePane dayPlanTree;
   private final ConceptTable< Template > templatesTable;

   public UiCalendarPaneWithTree( Database database ) {
      this( new JavaFxStyle(), database );
   }// End Constructor

   UiCalendarPaneWithTree( JavaFxStyle styling, Database database ) {
      this.uiCalendar = new UiCalendar( database );
//      this.consumptionProperties = new ConsumptionProperties();

      styling.configureConstraintsForRowPercentages(
               this,
               DATES_HEIGHT_PROPORTION,
               TEMPLATES_HEIGHT_PROPORTION,
               PLAN_VIEW_HEIGHT_PROPORTION
      );
      styling.configureConstraintsForEvenColumns( this, 1 );

      add( uiCalendar, 0, 0 );
      add( templatesTable = new TableComponents< Template >()
               .withDatabase( database )
               .applyColumns( TemplateTableColumns::new )
               .withController( new UnresponsiveConceptTableController<>() )
               .buildTable(),
      0, 1 );
      add( dayPlanTree = new DayPlanTreePane( database ), 0, 2 );

      uiCalendar.controller().selector().selection().addListener( ( s, o, n ) -> {
         dayPlanTree.controller().show( n );
         templatesTable.getRows().clear();
         templatesTable.getRows().add( new ConceptTableRowImpl<>( n ) );
//         consumptionProperties.setDayPlan( n );
      } );
   }// End Constructor

}//End Class


text:
package com.spotify.helios.common.descriptors;

import static com.google.common.base.Preconditions.checkNotNull;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.google.common.net.InetAddresses;
import org.jetbrains.annotations.Nullable;

/**
 * Represents a mapping from a port inside the container to be exposed on the agent.
 *
 *
A typical JSON representation might be:
 *

 * {
 *   "ip": "0.0.0.0",
 *   "externalPort" : 8061,
 *   "internalPort" : 8081,
 *   "protocol" : "tcp"
 * }
 *

 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class PortMapping extends Descriptor {

  public static final String TCP = "tcp";
  public static final String UDP = "udp";

  private final String ip;
  private final int internalPort;
  private final Integer externalPort;
  private final String protocol;

  public PortMapping(@JsonProperty("ip") @Nullable final String ip,
                     @JsonProperty("internalPort") final int internalPort,
                     @JsonProperty("externalPort") @Nullable final Integer externalPort,
                     @JsonProperty("protocol") @Nullable final String protocol) {
    this.ip = ip;
    // Validate IP here instead of in PortMappingParser to guaruntee every instance has a valid IP
    if (ip != null && !InetAddresses.isInetAddress(this.ip)) {
      throw new IllegalArgumentException(ip + " is not a valid IP address.");
    }

    this.internalPort = internalPort;
    this.externalPort = externalPort;
    this.protocol = Optional.fromNullable(protocol).or(TCP);
  }

  public PortMapping(final int internalPort, final Integer externalPort) {
    this(null, internalPort, externalPort, TCP);
  }

  public PortMapping(final int internalPort) {
    this(null, internalPort, null, TCP);
  }

  private PortMapping(final Builder builder) {
    this(builder.ip, builder.internalPort, builder.externalPort,
        checkNotNull(builder.protocol));
  }

  @Nullable
  public String getIp() {
    return ip;
  }

  public int getInternalPort() {
    return internalPort;
  }

  public boolean hasExternalPort() {
    return externalPort != null;
  }

  @Nullable
  public Integer getExternalPort() {
    return externalPort;
  }

  public String getProtocol() {
    return protocol;
  }

  public PortMapping withExternalPort(final Integer externalPort) {
    return PortMapping.of(internalPort, externalPort, protocol);
  }

  public static PortMapping of(final int internalPort) {
    return new PortMapping(internalPort);
  }

  public static PortMapping of(final int internalPort, final Integer externalPort) {
    return new PortMapping(internalPort, externalPort);
  }

  public static PortMapping of(final int internalPort, final Integer externalPort,
                               final String protocol) {
    return new PortMapping(null, internalPort, externalPort, protocol);
  }

  public static PortMapping of(final int internalPort, final String protocol) {
    return new PortMapping(null, internalPort, null, protocol);
  }

  public static Builder builder() {
    return new Builder().protocol(TCP);
  }

  public static class Builder {
    private String ip;
    private int internalPort;
    private Integer externalPort;
    private String protocol;

    public Builder ip(final String ip) {
      this.ip = ip;
      return this;
    }

    public Builder internalPort(final int internalPort) {
      this.internalPort = internalPort;
      return this;
    }

    public Builder externalPort(final Integer externalPort) {
      this.externalPort = externalPort;
      return this;
    }

    public Builder protocol(final String protocol) {
      this.protocol = protocol;
      return this;
    }

    public PortMapping build() {
      return new PortMapping(this);
    }
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }

    final PortMapping that = (PortMapping) obj;

    if (ip != null ? !ip.equals(that.ip) : that.ip != null) {
      return false;
    }
    if (internalPort != that.internalPort) {
      return false;
    }
    if (externalPort != null ? !externalPort.equals(that.externalPort)
                             : that.externalPort != null) {
      return false;
    }
    if (protocol != null ? !protocol.equals(that.protocol) : that.protocol != null) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int result = internalPort;
    result = 31 * result + (ip != null ? ip.hashCode() : 0);
    result = 31 * result + (externalPort != null ? externalPort.hashCode() : 0);
    result = 31 * result + (protocol != null ? protocol.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "PortMapping{"
           + "ip=" + ip
           + ", internalPort=" + internalPort
           + ", externalPort=" + externalPort
           + ", protocol='" + protocol + '\''
           + '}';
  }
}


text:
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace Carbon.Css.Parser.Tests
{
    public class TokenizerTests
    {
        [Fact]
        public void TokenizeAnd()
        {
            var tokens = GetTokens(@"
&:nth-child(odd) {
  background-color: red;
};".Trim());

            Assert.Equal((TokenKind.Ampersand,        "&"),           tokens[0].AsTuple());
            Assert.Equal((TokenKind.Name,             ":nth-child"),  tokens[1].AsTuple());
            Assert.Equal((TokenKind.LeftParenthesis,  "("),           tokens[2].AsTuple());
            Assert.Equal((TokenKind.Name,             "odd"),         tokens[3].AsTuple());
            Assert.Equal((TokenKind.RightParenthesis, ")"),           tokens[4].AsTuple());
        }

        [Fact]
        public void BackenizeBackToBackPseudoClasses()
        {
            var tokens = GetTokens(@"
&:last-child:after {
  background-color: rgba($bg-color, $shade);
};".Trim());

            Assert.Equal((TokenKind.Ampersand, "&"),           tokens[0].AsTuple());
            Assert.Equal((TokenKind.Name,      ":last-child"), tokens[1].AsTuple());
            Assert.Equal((TokenKind.Name,      ":after"),      tokens[2].AsTuple());

        }

        [Fact]
        public void TokenizeSimpleMixin()
        {
            var tokens = GetTokens(@"
@mixin hi {
	color: red;
}".Trim());

            Assert.Equal((TokenKind.AtSymbol, "@"),   tokens[0].AsTuple());
            Assert.Equal((TokenKind.Name, "mixin"),   tokens[1].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[2].AsTuple());
            Assert.Equal((TokenKind.Name, "hi"),      tokens[3].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[4].AsTuple());
            Assert.Equal((TokenKind.BlockStart, "{"), tokens[5].AsTuple());
            Assert.Equal((TokenKind.Whitespace),      tokens[6].Kind);
            Assert.Equal((TokenKind.Name, "color"),   tokens[7].AsTuple());
            Assert.Equal((TokenKind.Colon, ":"),      tokens[8].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[9].AsTuple());
            Assert.Equal((TokenKind.String, "red"),   tokens[10].AsTuple());
            Assert.Equal((TokenKind.Semicolon, ";"),  tokens[11].AsTuple());
            Assert.Equal((TokenKind.Whitespace),      tokens[12].Kind);
            Assert.Equal((TokenKind.BlockEnd, "}"),   tokens[13].AsTuple());
        }

        [Fact]
        public void TokenizeComplexMixin()
        {
            var tokens = GetTokens(@"
@mixin blerg {
	a {
		color: pink;

		&:hover { color: #000; }
	}
}".Trim());

            Assert.Equal((TokenKind.AtSymbol, "@"), tokens[0].AsTuple());
            Assert.Equal((TokenKind.Name, "mixin"), tokens[1].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[2].AsTuple());
            Assert.Equal((TokenKind.Name, "blerg"), tokens[3].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[4].AsTuple());
            Assert.Equal((TokenKind.BlockStart, "{"), tokens[5].AsTuple());
            Assert.Equal((TokenKind.Whitespace), tokens[6].Kind);
            Assert.Equal((TokenKind.Name, "a"), tokens[7].AsTuple());
            Assert.Equal(TokenKind.Whitespace, tokens[8].Kind);
            Assert.Equal((TokenKind.BlockStart, "{"), tokens[9].AsTuple());
            Assert.Equal(TokenKind.Whitespace, tokens[10].Kind);
            Assert.Equal((TokenKind.Name, "color"), tokens[11].AsTuple());
            Assert.Equal((TokenKind.Colon, ":"), tokens[12].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[13].AsTuple());
            Assert.Equal((TokenKind.String, "pink"), tokens[14].AsTuple());
            Assert.Equal((TokenKind.Semicolon, ";"), tokens[15].AsTuple());
            Assert.Equal(TokenKind.Whitespace, tokens[16].Kind);
            Assert.Equal((TokenKind.Ampersand, "&"), tokens[17].AsTuple());
            Assert.Equal((TokenKind.Name, ":hover"), tokens[18].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[19].AsTuple());
            Assert.Equal((TokenKind.BlockStart, "{"), tokens[20].AsTuple());
            Assert.Equal(TokenKind.Whitespace, tokens[21].Kind);

            Assert.Equal((TokenKind.Name, "color"), tokens[22].AsTuple());
            Assert.Equal((TokenKind.Colon, ":"), tokens[23].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[24].AsTuple());
            Assert.Equal((TokenKind.String, "#000"), tokens[25].AsTuple());
            Assert.Equal((TokenKind.Semicolon, ";"), tokens[26].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "), tokens[27].AsTuple());
            Assert.Equal((TokenKind.BlockEnd, "}"), tokens[28].AsTuple());
            Assert.Equal(TokenKind.Whitespace, tokens[29].Kind);
            Assert.Equal((TokenKind.BlockEnd, "}"), tokens[30].AsTuple());
        }

        [Fact]
        public void TokenizeMediaRule()
        {
            var tokens = GetTokens(@"
@media (min-width: 700px) {
	@include blerg;

	div {
		background-color: $bgColor;
		@include hi;
	}
}".Trim());

            Assert.Equal((TokenKind.AtSymbol, "@"),         tokens[0].AsTuple());
            Assert.Equal((TokenKind.Name, "media"),         tokens[1].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "),       tokens[2].AsTuple());
            Assert.Equal((TokenKind.LeftParenthesis, "("),  tokens[3].AsTuple());
            Assert.Equal((TokenKind.Name, "min-width"),     tokens[4].AsTuple());
            Assert.Equal((TokenKind.Colon, ":"),            tokens[5].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "),       tokens[6].AsTuple());
            Assert.Equal((TokenKind.Number, "700"),         tokens[7].AsTuple());
            Assert.Equal((TokenKind.Unit, "px"),            tokens[8].AsTuple());
            Assert.Equal((TokenKind.RightParenthesis, ")"), tokens[9].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "),       tokens[10].AsTuple());
            Assert.Equal((TokenKind.BlockStart, "{"),       tokens[11].AsTuple());
            Assert.Equal((TokenKind.Whitespace),            tokens[12].Kind);

            Assert.Equal((TokenKind.AtSymbol, "@"),         tokens[13].AsTuple());
            Assert.Equal((TokenKind.Name, "include"),       tokens[14].AsTuple());
            Assert.Equal((TokenKind.Whitespace, " "),       tokens[15].AsTuple());
            Assert.Equal((TokenKind.Name, "blerg"),         tokens[16].AsTuple());

            Assert.Equal((TokenKind.Semicolon, ";"),        tokens[17].AsTuple());
        }

        private static List<CssToken> GetTokens(string text)
        {
            using var tokenizer = new CssTokenizer(text);

            var tokens = new List<CssToken>();

            do
            {
                tokens.Add(tokenizer.Consume());
            }
            while (!tokenizer.IsEnd);

            return tokens;
        }

        [Fact]
        public void CalcTest4()
        {
            var tokens = GetTokens("calc(100% / 3 - 2 * 1em - 2 * 1px)");

            Assert.Equal(27, tokens.Count);

            Assert.Equal((TokenKind.LeftParenthesis, "("),   tokens[1].AsTuple());
            Assert.Equal((TokenKind.Number,          "100"), tokens[2].AsTuple());
            Assert.Equal((TokenKind.Unit,            "%"),   tokens[3].AsTuple());
            Assert.Equal((TokenKind.Whitespace,      " "),   tokens[4].AsTuple());
            Assert.Equal((TokenKind.Divide,          "/"),   tokens[5].AsTuple());
            Assert.Equal((TokenKind.Whitespace,      " "),   tokens[6].AsTuple());

            /*
			Assert.Equal(tokens[6].Kind, TokenKind.Number);
			Assert.Equal(tokens[7].Kind, TokenKind.Whitespace);
			Assert.Equal(tokens[8].Kind, TokenKind.Subtract);
			Assert.Equal(tokens[9].Kind, TokenKind.Add);
			*/

            var styles = "main { margin: 0.5in; width: calc(100% / 3 - 2 * 1em - 2 * 1px); }";

            Assert.Equal(@"main {
  margin: 0.5in;
  width: calc(100% / 3 - 2 * 1em - 2 * 1px);
}", StyleSheet.Parse(styles).ToString());
        }
    }
}


text:
@implementation UIView (LGNoDataView)

- (UIView *)lg_noDataView
{
    UIView *view = objc_getAssociatedObject(self, _cmd);
    if (!view) {
        UIView *view = [[UIView alloc] initWithFrame:self.bounds];
//        UIView *emptyView = [PHDIYEmptyView diyNoDataWithImage:self.lg_noDataImageName title:self.lg_noDataTitle detail:self.lg_noDataContent offsety:kEmptyDefualtOffsetY];
//        [view addSubview:emptyView];
        self.lg_noDataView = view;
    }
    return view;
}
- (void)setLg_noDataView:(UIView *)lg_noDataView {
    objc_setAssociatedObject(self, @selector(lg_noDataView), lg_noDataView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)lg_noDataImageName
{
    return objc_getAssociatedObject(self, @selector(setLg_noDataImageName:));
}
- (void)setLg_noDataImageName:(NSString *)lg_noDataImageName {
    objc_setAssociatedObject(self, _cmd, lg_noDataImageName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)lg_noDataTitle
{
    NSString *n = objc_getAssociatedObject(self, @selector(setLg_noDataTitle:));
    if (n) {
        return n;
    }
    return NSLocalizedString(@"no.data.title", nil);
}
- (void)setLg_noDataTitle:(NSString *)lg_noDataTitle {
    objc_setAssociatedObject(self, _cmd, lg_noDataTitle, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)lg_noDataContent
{
    return objc_getAssociatedObject(self, @selector(setLg_noDataContent:));
}
- (void)setLg_noDataContent:(NSString *)lg_noDataContent {
    objc_setAssociatedObject(self, _cmd, lg_noDataContent, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

#pragma mark - public
- (void)lg_showNoDataView {
    [self addSubview:self.lg_noDataView];
}
- (void)lg_resetNoDataView {
    [self.lg_noDataView removeFromSuperview];
}
@end


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class WelcomeController extends Controller
{
    /**
     * Set the layout that will be used with these routes
     */
    protected $layout = 'layouts.home';

    public function index(){
        return view($this->layout, ['content' => view('welcome')]);
    }
}


text:
package ca.ualberta.cs.swapmyride.View;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

import ca.ualberta.cs.swapmyride.Misc.UserSingleton;
import ca.ualberta.cs.swapmyride.Model.Trade;
import ca.ualberta.cs.swapmyride.R;

/**
 * This is the list view of active trades that can be viewed by clicking pending trades in the user tab
 */
public class ViewPendingTradesActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView pendingTrades;
    ArrayList<String> pendingTradeArray;
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pendingtrades);

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

        pendingTrades = (ListView) findViewById(R.id.pendingTrades);

        pendingTrades.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), ViewAPendingTradeActivity.class);

                intent.putExtra("PendingTradePosition", position);

                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        pendingTradeArray = new ArrayList<>();

        ArrayList<Trade> tradeList = UserSingleton.getCurrentUser().getPendingTrades().getTrades();

        for (Trade trade: tradeList) {
            String s = String.format("%s wants to trade %d item(s) for %d item(s)", trade.getOwner(), trade.getOwnerItems().size(), trade.getBorrowerItems().size());
            pendingTradeArray.add(s);
        }

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, pendingTradeArray);

        pendingTrades.setAdapter(adapter);
    }
}


text:
// VPA collects CPU and memory usage measurements from all containers running in
// the cluster and aggregates them in memory in structures called
// AggregateContainerState.
// During aggregation the usage samples are grouped together by the key called
// AggregateStateKey and stored in structures such as histograms of CPU and
// memory usage, that are parts of the AggregateContainerState.
//
// The AggregateStateKey consists of the container name, the namespace and the
// set of labels on the pod the container belongs to. In other words, whenever
// two samples come from containers with the same name, in the same namespace
// and with the same pod labels, they end up in the same histogram.
//
// Recall that VPA produces one recommendation for all containers with a given
// name and namespace, having pod labels that match a given selector. Therefore
// for each VPA object and container name the recommender has to take all
// matching AggregateContainerStates and further aggregate them together, in
// order to obtain the final aggregation that is the input to the recommender
// function.

package model

import (
	"fmt"
	"math"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	vpa_types "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"
	"k8s.io/autoscaler/vertical-pod-autoscaler/pkg/recommender/util"
)

// ContainerNameToAggregateStateMap maps a container name to AggregateContainerState
// that aggregates state of containers with that name.
type ContainerNameToAggregateStateMap map[string]*AggregateContainerState

const (
	// SupportedCheckpointVersion is the tag of the supported version of serialized checkpoints.
	// Version id should be incremented on every non incompatible change, i.e. if the new
	// version of the recommender binary can't initialize from the old checkpoint format or the
	// previous version of the recommender binary can't initialize from the new checkpoint format.
	SupportedCheckpointVersion = "v3"
)

var (
	// DefaultControlledResources is a default value of Spec.ResourcePolicy.ContainerPolicies[].ControlledResources.
	DefaultControlledResources = []ResourceName{ResourceCPU, ResourceMemory}
)

// ContainerStateAggregator is an interface for objects that consume and
// aggregate container usage samples.
type ContainerStateAggregator interface {
	// AddSample aggregates a single usage sample.
	AddSample(sample *ContainerUsageSample)
	// SubtractSample removes a single usage sample. The subtracted sample
	// should be equal to some sample that was aggregated with AddSample()
	// in the past.
	SubtractSample(sample *ContainerUsageSample)
	// GetLastRecommendation returns last recommendation calculated for this
	// aggregator.
	GetLastRecommendation() corev1.ResourceList
	// NeedsRecommendation returns true if this aggregator should have
	// a recommendation calculated.
	NeedsRecommendation() bool
	// GetUpdateMode returns the update mode of VPA controlling this aggregator,
	// nil if aggregator is not autoscaled.
	GetUpdateMode() *vpa_types.UpdateMode
}

// AggregateContainerState holds input signals aggregated from a set of containers.
// It can be used as an input to compute the recommendation.
// The CPU and memory distributions use decaying histograms by default
// (see NewAggregateContainerState()).
// Implements ContainerStateAggregator interface.
type AggregateContainerState struct {
	// AggregateCPUUsage is a distribution of all CPU samples.
	AggregateCPUUsage util.Histogram
	// AggregateMemoryPeaks is a distribution of memory peaks from all containers:
	// each container should add one peak per memory aggregation interval (e.g. once every 24h).
	AggregateMemoryPeaks util.Histogram
	// Note: first/last sample timestamps as well as the sample count are based only on CPU samples.
	FirstSampleStart  time.Time
	LastSampleStart   time.Time
	TotalSamplesCount int
	CreationTime      time.Time

	// Following fields are needed to correctly report quality metrics
	// for VPA. When we record a new sample in an AggregateContainerState
	// we want to know if it needs recommendation, if the recommendation
	// is present and if the automatic updates are on (are we able to
	// apply the recommendation to the pods).
	LastRecommendation  corev1.ResourceList
	IsUnderVPA          bool
	UpdateMode          *vpa_types.UpdateMode
	ScalingMode         *vpa_types.ContainerScalingMode
	ControlledResources *[]ResourceName
}

// GetLastRecommendation returns last recorded recommendation.
func (a *AggregateContainerState) GetLastRecommendation() corev1.ResourceList {
	return a.LastRecommendation
}

// NeedsRecommendation returns true if the state should have recommendation calculated.
func (a *AggregateContainerState) NeedsRecommendation() bool {
	return a.IsUnderVPA && a.ScalingMode != nil && *a.ScalingMode != vpa_types.ContainerScalingModeOff
}

// GetUpdateMode returns the update mode of VPA controlling this aggregator,
// nil if aggregator is not autoscaled.
func (a *AggregateContainerState) GetUpdateMode() *vpa_types.UpdateMode {
	return a.UpdateMode
}

// GetScalingMode returns the container scaling mode of the container
// represented byt his aggregator, nil if aggregator is not autoscaled.
func (a *AggregateContainerState) GetScalingMode() *vpa_types.ContainerScalingMode {
	return a.ScalingMode
}

// GetControlledResources returns the list of resources controlled by VPA controlling this aggregator.
// Returns default if not set.
func (a *AggregateContainerState) GetControlledResources() []ResourceName {
	if a.ControlledResources != nil {
		return *a.ControlledResources
	}
	return DefaultControlledResources
}

// MarkNotAutoscaled registers that this container state is not controlled by
// a VPA object.
func (a *AggregateContainerState) MarkNotAutoscaled() {
	a.IsUnderVPA = false
	a.LastRecommendation = nil
	a.UpdateMode = nil
	a.ScalingMode = nil
	a.ControlledResources = nil
}

// MergeContainerState merges two AggregateContainerStates.
func (a *AggregateContainerState) MergeContainerState(other *AggregateContainerState) {
	a.AggregateCPUUsage.Merge(other.AggregateCPUUsage)
	a.AggregateMemoryPeaks.Merge(other.AggregateMemoryPeaks)

	if a.FirstSampleStart.IsZero() ||
		(!other.FirstSampleStart.IsZero() && other.FirstSampleStart.Before(a.FirstSampleStart)) {
		a.FirstSampleStart = other.FirstSampleStart
	}
	if other.LastSampleStart.After(a.LastSampleStart) {
		a.LastSampleStart = other.LastSampleStart
	}
	a.TotalSamplesCount += other.TotalSamplesCount
}

// NewAggregateContainerState returns a new, empty AggregateContainerState.
func NewAggregateContainerState() *AggregateContainerState {
	config := GetAggregationsConfig()
	return &AggregateContainerState{
		AggregateCPUUsage:    util.NewDecayingHistogram(config.CPUHistogramOptions, config.CPUHistogramDecayHalfLife),
		AggregateMemoryPeaks: util.NewDecayingHistogram(config.MemoryHistogramOptions, config.MemoryHistogramDecayHalfLife),
		CreationTime:         time.Now(),
	}
}

// AddSample aggregates a single usage sample.
func (a *AggregateContainerState) AddSample(sample *ContainerUsageSample) {
	switch sample.Resource {
	case ResourceCPU:
		a.addCPUSample(sample)
	case ResourceMemory:
		a.AggregateMemoryPeaks.AddSample(BytesFromMemoryAmount(sample.Usage), 1.0, sample.MeasureStart)
	default:
		panic(fmt.Sprintf("AddSample doesn't support resource '%s'", sample.Resource))
	}
}

// SubtractSample removes a single usage sample from an aggregation.
// The subtracted sample should be equal to some sample that was aggregated with
// AddSample() in the past.
// Only memory samples can be subtracted at the moment. Support for CPU could be
// added if necessary.
func (a *AggregateContainerState) SubtractSample(sample *ContainerUsageSample) {
	switch sample.Resource {
	case ResourceMemory:
		a.AggregateMemoryPeaks.SubtractSample(BytesFromMemoryAmount(sample.Usage), 1.0, sample.MeasureStart)
	default:
		panic(fmt.Sprintf("SubtractSample doesn't support resource '%s'", sample.Resource))
	}
}

func (a *AggregateContainerState) addCPUSample(sample *ContainerUsageSample) {
	cpuUsageCores := CoresFromCPUAmount(sample.Usage)
	cpuRequestCores := CoresFromCPUAmount(sample.Request)
	// Samples are added with the weight equal to the current request. This means that
	// whenever the request is increased, the history accumulated so far effectively decays,
	// which helps react quickly to CPU starvation.
	a.AggregateCPUUsage.AddSample(
		cpuUsageCores, math.Max(cpuRequestCores, minSampleWeight), sample.MeasureStart)
	if sample.MeasureStart.After(a.LastSampleStart) {
		a.LastSampleStart = sample.MeasureStart
	}
	if a.FirstSampleStart.IsZero() || sample.MeasureStart.Before(a.FirstSampleStart) {
		a.FirstSampleStart = sample.MeasureStart
	}
	a.TotalSamplesCount++
}

// SaveToCheckpoint serializes AggregateContainerState as VerticalPodAutoscalerCheckpointStatus.
// The serialization may result in loss of precission of the histograms.
func (a *AggregateContainerState) SaveToCheckpoint() (*vpa_types.VerticalPodAutoscalerCheckpointStatus, error) {
	memory, err := a.AggregateMemoryPeaks.SaveToChekpoint()
	if err != nil {
		return nil, err
	}
	cpu, err := a.AggregateCPUUsage.SaveToChekpoint()
	if err != nil {
		return nil, err
	}
	return &vpa_types.VerticalPodAutoscalerCheckpointStatus{
		LastUpdateTime:    metav1.NewTime(time.Now()),
		FirstSampleStart:  metav1.NewTime(a.FirstSampleStart),
		LastSampleStart:   metav1.NewTime(a.LastSampleStart),
		TotalSamplesCount: a.TotalSamplesCount,
		MemoryHistogram:   *memory,
		CPUHistogram:      *cpu,
		Version:           SupportedCheckpointVersion,
	}, nil
}

// LoadFromCheckpoint deserializes data from VerticalPodAutoscalerCheckpointStatus
// into the AggregateContainerState.
func (a *AggregateContainerState) LoadFromCheckpoint(checkpoint *vpa_types.VerticalPodAutoscalerCheckpointStatus) error {
	if checkpoint.Version != SupportedCheckpointVersion {
		return fmt.Errorf("unsuported checkpoint version %s", checkpoint.Version)
	}
	a.TotalSamplesCount = checkpoint.TotalSamplesCount
	a.FirstSampleStart = checkpoint.FirstSampleStart.Time
	a.LastSampleStart = checkpoint.LastSampleStart.Time
	err := a.AggregateMemoryPeaks.LoadFromCheckpoint(&checkpoint.MemoryHistogram)
	if err != nil {
		return err
	}
	err = a.AggregateCPUUsage.LoadFromCheckpoint(&checkpoint.CPUHistogram)
	if err != nil {
		return err
	}
	return nil
}

func (a *AggregateContainerState) isExpired(now time.Time) bool {
	if a.isEmpty() {
		return now.Sub(a.CreationTime) >= GetAggregationsConfig().GetMemoryAggregationWindowLength()
	}
	return now.Sub(a.LastSampleStart) >= GetAggregationsConfig().GetMemoryAggregationWindowLength()
}

func (a *AggregateContainerState) isEmpty() bool {
	return a.TotalSamplesCount == 0
}

// UpdateFromPolicy updates container state scaling mode and controlled resources based on resource
// policy of the VPA object.
func (a *AggregateContainerState) UpdateFromPolicy(resourcePolicy *vpa_types.ContainerResourcePolicy) {
	// ContainerScalingModeAuto is the default scaling mode
	scalingModeAuto := vpa_types.ContainerScalingModeAuto
	a.ScalingMode = &scalingModeAuto
	if resourcePolicy != nil && resourcePolicy.Mode != nil {
		a.ScalingMode = resourcePolicy.Mode
	}
	a.ControlledResources = &DefaultControlledResources
	if resourcePolicy != nil && resourcePolicy.ControlledResources != nil {
		a.ControlledResources = ResourceNamesApiToModel(*resourcePolicy.ControlledResources)
	}
}

// AggregateStateByContainerName takes a set of AggregateContainerStates and merge them
// grouping by the container name. The result is a map from the container name to the aggregation
// from all input containers with the given name.
func AggregateStateByContainerName(aggregateContainerStateMap aggregateContainerStatesMap) ContainerNameToAggregateStateMap {
	containerNameToAggregateStateMap := make(ContainerNameToAggregateStateMap)
	for aggregationKey, aggregation := range aggregateContainerStateMap {
		containerName := aggregationKey.ContainerName()
		aggregateContainerState, isInitialized := containerNameToAggregateStateMap[containerName]
		if !isInitialized {
			aggregateContainerState = NewAggregateContainerState()
			containerNameToAggregateStateMap[containerName] = aggregateContainerState
		}
		aggregateContainerState.MergeContainerState(aggregation)
	}
	return containerNameToAggregateStateMap
}

// ContainerStateAggregatorProxy is a wrapper for ContainerStateAggregator
// that creates ContainerStateAgregator for container if it is no longer
// present in the cluster state.
type ContainerStateAggregatorProxy struct {
	containerID ContainerID
	cluster     *ClusterState
}

// NewContainerStateAggregatorProxy creates a ContainerStateAggregatorProxy
// pointing to the cluster state.
func NewContainerStateAggregatorProxy(cluster *ClusterState, containerID ContainerID) ContainerStateAggregator {
	return &ContainerStateAggregatorProxy{containerID, cluster}
}

// AddSample adds a container sample to the aggregator.
func (p *ContainerStateAggregatorProxy) AddSample(sample *ContainerUsageSample) {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	aggregator.AddSample(sample)
}

// SubtractSample subtracts a container sample from the aggregator.
func (p *ContainerStateAggregatorProxy) SubtractSample(sample *ContainerUsageSample) {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	aggregator.SubtractSample(sample)
}

// GetLastRecommendation returns last recorded recommendation.
func (p *ContainerStateAggregatorProxy) GetLastRecommendation() corev1.ResourceList {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	return aggregator.GetLastRecommendation()
}

// NeedsRecommendation returns true if the aggregator should have recommendation calculated.
func (p *ContainerStateAggregatorProxy) NeedsRecommendation() bool {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	return aggregator.NeedsRecommendation()
}

// GetUpdateMode returns update mode of VPA controlling the aggregator.
func (p *ContainerStateAggregatorProxy) GetUpdateMode() *vpa_types.UpdateMode {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	return aggregator.GetUpdateMode()
}

// GetScalingMode returns scaling mode of container represented by the aggregator.
func (p *ContainerStateAggregatorProxy) GetScalingMode() *vpa_types.ContainerScalingMode {
	aggregator := p.cluster.findOrCreateAggregateContainerState(p.containerID)
	return aggregator.GetScalingMode()
}


text:
'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['exports'], factory);
  } else if (typeof exports !== 'undefined') {
    factory(exports);
  } else {
    factory((root.deduplicatingTreeBuilder = {}));
  }
}(this, function (exports) {
  function MakeBuilder (baseClass, getObjectId, deduplicationUsageThreshold) {
    var ctor = function (/* ... */) {
      this.internTable = Object.create(null);
      this.hitCounts   = new WeakMap();
      this.nodesFinalized = 0;
      this.nodesPruned    = 0;

      return baseClass.apply(this, arguments);
    };

    ctor.prototype = Object.create(baseClass.prototype);

    ctor.prototype.$getTable = function (type) {
      var result = this.internTable[type];
      if (!result)
        result = this.internTable[type] = Object.create(null);

      return result;
    };

    var appendValueHash = function (head, v) {
      var vt = typeof (v);
      if (v === null)
        head += "\x01"
      else if (Array.isArray(v)) {
        // It's important to examine the structure of the array,
        //  since we want to deduplicate by contents instead of
        //  by referential identity
        head += "\x04";

        for (var i = 0, l = v.length; i < l; i++) {
          var element = v[i];
          head = appendValueHash(head, element);
        }

        head += "\x05";
      } else if (vt === "object")
        head += getObjectId(v);
      else if (vt === "string")
        head += v;
      else if (vt === "number")
        head += v.toString();
      else if (vt === "boolean")
        head += v ? "\x03" : "\x02";
      else
        throw new Error("Unexpected '" + vt + "' while interning");

      head += "\x00";

      return head;
    };

    ctor.prototype.getHitCount = function (obj) {
      var result = this.hitCounts.get(obj) || 0;
      return result | 0;
    };

    ctor.prototype.finalize = function (obj) {
      var table = this.$getTable(obj.type);
      this.nodesFinalized += 1;

      // TODO: Generate some sort of cheap integer hash instead
      // TODO: Use shape table instead of walking properties
      var bruteForceHash = "";
      for (var k in obj) {
        var v = obj[k];

        try {
          bruteForceHash = appendValueHash(bruteForceHash, v);
        } catch (e) {
          console.log("Was interning o[" + k + "] for o=", obj);
          throw e;
        }
      }

      var interned = table[bruteForceHash];
      if (interned) {
        var useCount = this.hitCounts.get(interned);
        this.hitCounts.set(interned, useCount + 1);

        var shouldDeduplicate = useCount >= deduplicationUsageThreshold
        if (shouldDeduplicate) {
          this.nodesPruned += 1;
          return interned;
        }
      }

      table[bruteForceHash] = obj;
      this.hitCounts.set(obj, 1);

      return baseClass.prototype.finalize.call(this, obj);
    };

    return ctor;
  };

  exports.MakeBuilder = MakeBuilder;
}));


text:
package com.alibaba.jstorm.task.comm;

import java.util.List;

import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.TupleImplExt;

import com.alibaba.jstorm.task.TaskTransfer;

/**
 * Send init/ack/fail tuple to acker
 *
 * @author yannian
 *
 */

public class UnanchoredSend {
	public static void send(TopologyContext topologyContext,
			TaskSendTargets taskTargets, TaskTransfer transfer_fn,
			String stream, List<Object> values) {

		java.util.List<Integer> tasks = taskTargets.get(stream, values);
		if (tasks.size() == 0) {
			return;
		}

		Integer taskId = topologyContext.getThisTaskId();

		for (Integer task : tasks) {
			TupleImplExt tup = new TupleImplExt(topologyContext, values,
					taskId, stream);
			tup.setTargetTaskId(task);

			transfer_fn.transfer(tup);
		}
	}
}


text:
BOT_NAME = "ukpollingreport"
SPIDER_MODULES = ["ukpollingreport.spiders"]
NEWSPIDER_MODULE = "ukpollingreport.spiders"
ITEM_PIPELINES = {
    "ukpollingreport.pipelines.PollPipeline": 300,
}

FEED_FORMAT = "csv"
FEED_EXPORT_FIELDS = ["date", "pollster", "client", "party", "share"]

FEED_STORAGES = {"cartodb": "ukpollingreport.exporters.cartodb.CartoDBFeedStorage"}
FEED_URI = "cartodb://username:api_key@table_name"
CARTODB_TRUNCATE = True
CARTODB_RESET_IDS = True

# Fix for https://github.com/scrapy/scrapy/issues/1344.
DOWNLOAD_HANDLERS = {"s3": None}