text:
<?php

namespace Map;

use \User;
use \UserQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;

/**
 * This class defines the structure of the 'user' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 */
class UserTableMap extends TableMap
{
    use InstancePoolTrait;
    use TableMapTrait;

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = '.Map.UserTableMap';

    /**
     * The default database name for this class
     */
    const DATABASE_NAME = 'pst-stack';

    /**
     * The table name for this class
     */
    const TABLE_NAME = 'user';

    /**
     * The related Propel class for this table
     */
    const OM_CLASS = '\\User';

    /**
     * A class that can be returned by this tableMap
     */
    const CLASS_DEFAULT = 'User';

    /**
     * The total number of columns
     */
    const NUM_COLUMNS = 8;

    /**
     * The number of lazy-loaded columns
     */
    const NUM_LAZY_LOAD_COLUMNS = 0;

    /**
     * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
     */
    const NUM_HYDRATE_COLUMNS = 8;

    /**
     * the column name for the id field
     */
    const COL_ID = 'user.id';

    /**
     * the column name for the first_name field
     */
    const COL_FIRST_NAME = 'user.first_name';

    /**
     * the column name for the last_name field
     */
    const COL_LAST_NAME = 'user.last_name';

    /**
     * the column name for the email field
     */
    const COL_EMAIL = 'user.email';

    /**
     * the column name for the password field
     */
    const COL_PASSWORD = 'user.password';

    /**
     * the column name for the uuid field
     */
    const COL_UUID = 'user.uuid';

    /**
     * the column name for the created_at field
     */
    const COL_CREATED_AT = 'user.created_at';

    /**
     * the column name for the updated_at field
     */
    const COL_UPDATED_AT = 'user.updated_at';

    /**
     * The default string format for model objects of the related table
     */
    const DEFAULT_STRING_FORMAT = 'YAML';

    /**
     * holds an array of fieldnames
     *
     * first dimension keys are the type constants
     * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
     */
    protected static $fieldNames = array (
        self::TYPE_PHPNAME       => array('Id', 'FirstName', 'LastName', 'Email', 'Password', 'UUID', 'CreatedAt', 'UpdatedAt', ),
        self::TYPE_CAMELNAME     => array('id', 'firstName', 'lastName', 'email', 'password', 'uUID', 'createdAt', 'updatedAt', ),
        self::TYPE_COLNAME       => array(UserTableMap::COL_ID, UserTableMap::COL_FIRST_NAME, UserTableMap::COL_LAST_NAME, UserTableMap::COL_EMAIL, UserTableMap::COL_PASSWORD, UserTableMap::COL_UUID, UserTableMap::COL_CREATED_AT, UserTableMap::COL_UPDATED_AT, ),
        self::TYPE_FIELDNAME     => array('id', 'first_name', 'last_name', 'email', 'password', 'uuid', 'created_at', 'updated_at', ),
        self::TYPE_NUM           => array(0, 1, 2, 3, 4, 5, 6, 7, )
    );

    /**
     * holds an array of keys for quick access to the fieldnames array
     *
     * first dimension keys are the type constants
     * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0
     */
    protected static $fieldKeys = array (
        self::TYPE_PHPNAME       => array('Id' => 0, 'FirstName' => 1, 'LastName' => 2, 'Email' => 3, 'Password' => 4, 'UUID' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, ),
        self::TYPE_CAMELNAME     => array('id' => 0, 'firstName' => 1, 'lastName' => 2, 'email' => 3, 'password' => 4, 'uUID' => 5, 'createdAt' => 6, 'updatedAt' => 7, ),
        self::TYPE_COLNAME       => array(UserTableMap::COL_ID => 0, UserTableMap::COL_FIRST_NAME => 1, UserTableMap::COL_LAST_NAME => 2, UserTableMap::COL_EMAIL => 3, UserTableMap::COL_PASSWORD => 4, UserTableMap::COL_UUID => 5, UserTableMap::COL_CREATED_AT => 6, UserTableMap::COL_UPDATED_AT => 7, ),
        self::TYPE_FIELDNAME     => array('id' => 0, 'first_name' => 1, 'last_name' => 2, 'email' => 3, 'password' => 4, 'uuid' => 5, 'created_at' => 6, 'updated_at' => 7, ),
        self::TYPE_NUM           => array(0, 1, 2, 3, 4, 5, 6, 7, )
    );

    /**
     * Initialize the table attributes and columns
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('user');
        $this->setPhpName('User');
        $this->setIdentifierQuoting(false);
        $this->setClassName('\\User');
        $this->setPackage('');
        $this->setUseIdGenerator(true);
        // columns
        $this->addPrimaryKey('id', 'Id', 'INTEGER', true, null, null);
        $this->addColumn('first_name', 'FirstName', 'VARCHAR', true, 255, null);
        $this->addColumn('last_name', 'LastName', 'VARCHAR', true, 255, null);
        $this->addColumn('email', 'Email', 'VARCHAR', true, 255, null);
        $this->addColumn('password', 'Password', 'VARCHAR', true, 255, null);
        $this->addColumn('uuid', 'UUID', 'VARCHAR', true, 255, null);
        $this->addColumn('created_at', 'CreatedAt', 'TIMESTAMP', false, null, null);
        $this->addColumn('updated_at', 'UpdatedAt', 'TIMESTAMP', false, null, null);
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
    } // buildRelations()

    /**
     *
     * Gets the list of behaviors registered for this table
     *
     * @return array Associative array (name => parameters) of behaviors
     */
    public function getBehaviors()
    {
        return array(
            'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', 'disable_created_at' => 'false', 'disable_updated_at' => 'false', ),
        );
    } // getBehaviors()

    /**
     * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
     *
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, a serialize()d version of the primary key will be returned.
     *
     * @param array  $row       resultset row.
     * @param int    $offset    The 0-based offset for reading from the resultset row.
     * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME
     *                           TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
     *
     * @return string The primary key hash of the row
     */
    public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
    {
        // If the PK cannot be derived from the row, return NULL.
        if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) {
            return null;
        }

        return null === $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] || is_scalar($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]) || is_callable([$row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], '__toString']) ? (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] : $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)];
    }

    /**
     * Retrieves the primary key from the DB resultset row
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, an array of the primary key columns will be returned.
     *
     * @param array  $row       resultset row.
     * @param int    $offset    The 0-based offset for reading from the resultset row.
     * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME
     *                           TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
     *
     * @return mixed The primary key of the row
     */
    public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
    {
        return (int) $row[
            $indexType == TableMap::TYPE_NUM
                ? 0 + $offset
                : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)
        ];
    }

    /**
     * The class that the tableMap will make instances of.
     *
     * If $withPrefix is true, the returned path
     * uses a dot-path notation which is translated into a path
     * relative to a location on the PHP include_path.
     * (e.g. path.to.MyClass -> 'path/to/MyClass.php')
     *
     * @param boolean $withPrefix Whether or not to return the path with the class name
     * @return string path.to.ClassName
     */
    public static function getOMClass($withPrefix = true)
    {
        return $withPrefix ? UserTableMap::CLASS_DEFAULT : UserTableMap::OM_CLASS;
    }

    /**
     * Populates an object of the default type or an object that inherit from the default.
     *
     * @param array  $row       row returned by DataFetcher->fetch().
     * @param int    $offset    The 0-based offset for reading from the resultset row.
     * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType().
                                 One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME
     *                           TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
     *
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     * @return array           (User object, last column rank)
     */
    public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
    {
        $key = UserTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType);
        if (null !== ($obj = UserTableMap::getInstanceFromPool($key))) {
            // We no longer rehydrate the object, since this can cause data loss.
            // See http://www.propelorm.org/ticket/509
            // $obj->hydrate($row, $offset, true); // rehydrate
            $col = $offset + UserTableMap::NUM_HYDRATE_COLUMNS;
        } else {
            $cls = UserTableMap::OM_CLASS;
            /** @var User $obj */
            $obj = new $cls();
            $col = $obj->hydrate($row, $offset, false, $indexType);
            UserTableMap::addInstanceToPool($obj, $key);
        }

        return array($obj, $col);
    }

    /**
     * The returned array will contain objects of the default type or
     * objects that inherit from the default.
     *
     * @param DataFetcherInterface $dataFetcher
     * @return array
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public static function populateObjects(DataFetcherInterface $dataFetcher)
    {
        $results = array();

        // set the class once to avoid overhead in the loop
        $cls = static::getOMClass(false);
        // populate the object(s)
        while ($row = $dataFetcher->fetch()) {
            $key = UserTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType());
            if (null !== ($obj = UserTableMap::getInstanceFromPool($key))) {
                // We no longer rehydrate the object, since this can cause data loss.
                // See http://www.propelorm.org/ticket/509
                // $obj->hydrate($row, 0, true); // rehydrate
                $results[] = $obj;
            } else {
                /** @var User $obj */
                $obj = new $cls();
                $obj->hydrate($row);
                $results[] = $obj;
                UserTableMap::addInstanceToPool($obj, $key);
            } // if key exists
        }

        return $results;
    }
    /**
     * Add all the columns needed to create a new object.
     *
     * Note: any columns that were marked with lazyLoad="true" in the
     * XML schema will not be added to the select list and only loaded
     * on demand.
     *
     * @param Criteria $criteria object containing the columns to add.
     * @param string   $alias    optional table alias
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public static function addSelectColumns(Criteria $criteria, $alias = null)
    {
        if (null === $alias) {
            $criteria->addSelectColumn(UserTableMap::COL_ID);
            $criteria->addSelectColumn(UserTableMap::COL_FIRST_NAME);
            $criteria->addSelectColumn(UserTableMap::COL_LAST_NAME);
            $criteria->addSelectColumn(UserTableMap::COL_EMAIL);
            $criteria->addSelectColumn(UserTableMap::COL_PASSWORD);
            $criteria->addSelectColumn(UserTableMap::COL_UUID);
            $criteria->addSelectColumn(UserTableMap::COL_CREATED_AT);
            $criteria->addSelectColumn(UserTableMap::COL_UPDATED_AT);
        } else {
            $criteria->addSelectColumn($alias . '.id');
            $criteria->addSelectColumn($alias . '.first_name');
            $criteria->addSelectColumn($alias . '.last_name');
            $criteria->addSelectColumn($alias . '.email');
            $criteria->addSelectColumn($alias . '.password');
            $criteria->addSelectColumn($alias . '.uuid');
            $criteria->addSelectColumn($alias . '.created_at');
            $criteria->addSelectColumn($alias . '.updated_at');
        }
    }

    /**
     * Returns the TableMap related to this object.
     * This method is not needed for general use but a specific application could have a need.
     * @return TableMap
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public static function getTableMap()
    {
        return Propel::getServiceContainer()->getDatabaseMap(UserTableMap::DATABASE_NAME)->getTable(UserTableMap::TABLE_NAME);
    }

    /**
     * Add a TableMap instance to the database for this tableMap class.
     */
    public static function buildTableMap()
    {
        $dbMap = Propel::getServiceContainer()->getDatabaseMap(UserTableMap::DATABASE_NAME);
        if (!$dbMap->hasTable(UserTableMap::TABLE_NAME)) {
            $dbMap->addTableObject(new UserTableMap());
        }
    }

    /**
     * Performs a DELETE on the database, given a User or Criteria object OR a primary key value.
     *
     * @param mixed               $values Criteria or User object or primary key or array of primary keys
     *              which is used to create the DELETE statement
     * @param  ConnectionInterface $con the connection to use
     * @return int             The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
     *                         if supported by native driver or if emulated using Propel.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
     public static function doDelete($values, ConnectionInterface $con = null)
     {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(UserTableMap::DATABASE_NAME);
        }

        if ($values instanceof Criteria) {
            // rename for clarity
            $criteria = $values;
        } elseif ($values instanceof \User) { // it's a model object
            // create criteria based on pk values
            $criteria = $values->buildPkeyCriteria();
        } else { // it's a primary key, or an array of pks
            $criteria = new Criteria(UserTableMap::DATABASE_NAME);
            $criteria->add(UserTableMap::COL_ID, (array) $values, Criteria::IN);
        }

        $query = UserQuery::create()->mergeWith($criteria);

        if ($values instanceof Criteria) {
            UserTableMap::clearInstancePool();
        } elseif (!is_object($values)) { // it's a primary key, or an array of pks
            foreach ((array) $values as $singleval) {
                UserTableMap::removeInstanceFromPool($singleval);
            }
        }

        return $query->delete($con);
    }

    /**
     * Deletes all rows from the user table.
     *
     * @param ConnectionInterface $con the connection to use
     * @return int The number of affected rows (if supported by underlying database driver).
     */
    public static function doDeleteAll(ConnectionInterface $con = null)
    {
        return UserQuery::create()->doDeleteAll($con);
    }

    /**
     * Performs an INSERT on the database, given a User or Criteria object.
     *
     * @param mixed               $criteria Criteria or User object containing data that is used to create the INSERT statement.
     * @param ConnectionInterface $con the ConnectionInterface connection to use
     * @return mixed           The new primary key.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public static function doInsert($criteria, ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(UserTableMap::DATABASE_NAME);
        }

        if ($criteria instanceof Criteria) {
            $criteria = clone $criteria; // rename for clarity
        } else {
            $criteria = $criteria->buildCriteria(); // build Criteria from User object
        }

        if ($criteria->containsKey(UserTableMap::COL_ID) && $criteria->keyContainsValue(UserTableMap::COL_ID) ) {
            throw new PropelException('Cannot insert a value for auto-increment primary key ('.UserTableMap::COL_ID.')');
        }

        // Set the correct dbName
        $query = UserQuery::create()->mergeWith($criteria);

        // use transaction because $criteria could contain info
        // for more than one table (I guess, conceivably)
        return $con->transaction(function () use ($con, $query) {
            return $query->doInsert($con);
        });
    }

} // UserTableMap
// This is the static code needed to register the TableMap for this table with the main Propel class.
//
UserTableMap::buildTableMap();


text:
package com.tung7.docsys.rest;

import com.tung7.docsys.entity.DocConfig;
import com.tung7.docsys.service.inf.IConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO Fill The Description!
 *
 * @author Tung
 * @version 1.0
 * @date 2017/4/29.
 * @update
 */
@RestController
@RequestMapping("/api/config")
public class ConfigRest {
    private static final Logger logger = LoggerFactory.getLogger(ConfigRest.class);

    @Autowired
    IConfigService configService;

    @RequestMapping("/{key}")
    public DocConfig findByKey(@PathVariable("key") String key) {
        return configService.findByKey(key);
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public DocConfig save(DocConfig docConfig) {
        return configService.save(docConfig);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { createOrGetStore } from '../store/storeFactory';
import { Product } from './model';

export function getProductStore() {
    return createOrGetStore<Product>('product');
}


text:
//
//  DBPostgresConnection.m
//  DatabaseKit
//
//  Created by Fjölnir Ásgeirsson on 8.8.2007.
//  Copyright 2007 Fjölnir Ásgeirsson. All rights reserved.
//

#define LOG_QUERIES NO

#import "DBPostgresConnection.h"
#import "../Queries/DBQuery.h"
#import "../Debug.h"
#import <unistd.h>
#import <dispatch/dispatch.h>
// For some reason, on linux (Debian at least) there's a postgresql/ prefix
#ifdef __APPLE__
#import <libpq-fe.h>
#else
#import <postgresql/libpq-fe.h>
#endif

#ifndef INT8OID
    #define INVALID_OID     (-1)
    #define INT8OID         20
    #define INT2OID         21
    #define INT4OID         23
    #define	BOOLOID         16
    #define FLOAT4OID       700
    #define FLOAT8OID       701
    #define VARCHAROID      1043
    #define	TEXTOID         25
    #define DATEOID         1082
    #define TIMEOID         1083
    #define TIMESTAMPOID    1114
    #define TIMESTAMPTZOID  1184
    #define BYTEAOID        17
#endif

/*! @cond IGNORE */
static NSRange rangeOfParameterToken(NSString *param, NSString *query);
static NSString *NSDateToPostgresTimestamp(NSDate *date);
static NSDate *NSDateFromPostgresTimestamp(NSString *timestamp);

@interface DBPostgresConnection () {
    PGconn *_connection;
}
- (id)valueForRow:(unsigned int)rowIndex column:(unsigned int)colIndex result:(PGresult *)result;
@end
/*! @endcond */

#pragma mark -

@implementation DBPostgresConnection
+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [DBConnection registerConnectionClass:self];
    });
}
+ (BOOL)canHandleURL:(NSURL *)URL
{
    return [[URL scheme] isEqualToString:@"postgres"];
}

+ (NSString *)postgresConnectionStringFromURL:(NSURL *)url
{
    NSMutableString *connectionString = [NSMutableString stringWithString:@""];
    if([url host])
        [connectionString appendFormat:@"host='%@' ", [url host]];
    else
        return nil;
    if([url port])
        [connectionString appendFormat:@"port='%@' ", [url port]];
    if([url user])
        [connectionString appendFormat:@"user='%@' ", [url user]];
    if([url password])
        [connectionString appendFormat:@"password='%@' ", [url password]];
    NSString *dbName = [[url lastPathComponent] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if([dbName length] > 0 && ![dbName isEqual:@"/"])
        [connectionString appendFormat:@"dbname='%@' ", dbName];
    else
        return nil; // No database, no dice

    return connectionString;
}

#pragma mark -
#pragma mark Initialization

- (id)initWithURL:(NSURL *)URL error:(NSError **)err;
{
    if(!(self = [super initWithURL:URL error:err]))
        return nil;
    NSString *connInfo = [[self class] postgresConnectionStringFromURL:URL];
    NSAssert1(connInfo, @"Invalid PostgreSQL URL: %@", URL);
    _connection = PQconnectdb([connInfo UTF8String]);
    if(PQstatus(_connection) != CONNECTION_OK) {
        DBLog(@"Unable to connect to %@: %@", URL, @(PQerrorMessage(_connection)));
        if(err) {
            *err = [NSError errorWithDomain:DBConnectionErrorDomain
                                       code:DBPostgresConnectionFailed
                                   userInfo:@{ NSLocalizedDescriptionKey: @(PQerrorMessage(_connection)),
                                                           NSURLErrorKey: URL }];
        }
        return nil;
    }
    return self;
}
- (void)dealloc
{
    [self closeConnection];
}
- (BOOL)closeConnection
{
    if(!_connection)
        return NO;
    PQfinish(_connection), _connection = NULL;
    return YES;
}

#pragma mark -
#pragma mark SQL Execution

- (NSArray *)executeSQL:(NSString *)sql substitutions:(id)substitutions error:(NSError **)outErr
{
    DBLog(@"%@ -- %@", sql, substitutions);
    BOOL isDict = [substitutions isKindOfClass:[NSDictionary class]] ||
                  [substitutions isKindOfClass:[NSMapTable class]];
    NSParameterAssert(!substitutions                                       ||
                      [substitutions isKindOfClass:[NSArray class]]        ||
                      [substitutions isKindOfClass:[NSPointerArray class]] ||
                      isDict);
    //DBDebugLog(@"Executing SQL: %@ subs: %@", sql, substitutions);
    // Prepare the query

    NSUInteger paramCount = [substitutions count];
    const char *paramValues[paramCount];
    int paramLengths[paramCount];
    int paramFormats[paramCount]; // 0 = text, 1 = binary

    NSString *key;
    int i = 0;
    for(__strong id sub in substitutions) {
        if(isDict) {
            key = sub;
            sub = substitutions[key];
            // Unfortunately Postgres doesn't support `:<param>` style named parameters => we need to manually anonymize
            NSString *paramToken = [@":" stringByAppendingString:key];
            NSRange tokenRange = rangeOfParameterToken(paramToken, sql);
            if(tokenRange.location == NSNotFound)
                continue;
            sql = [sql stringByReplacingOccurrencesOfString:paramToken
                                                 withString:[@"$" stringByAppendingFormat:@"%d", i]];
        }

        if([sub isKindOfClass:[NSString class]] || [[sub className] isEqualToString:@"NSCFString"]) {
            paramValues[i]  = [sub UTF8String];
            paramLengths[i] = [sub length];
            paramFormats[i] = 0;
        } else if([sub isKindOfClass:[NSNumber class]] || [sub isKindOfClass:NSClassFromString(@"TQNumber")]) {
            NSString *str;
            switch (*[sub objCType]) {
                case 'd':
                case 'f':
                    str = [NSString stringWithFormat:@"%f", [sub doubleValue]];
                    break;
                case 'l':
                case 'L':
                    str = [NSString stringWithFormat:@"%ld", [sub longValue]];
                    break;
                case 'q':
                case 'Q':
                    str = [NSString stringWithFormat:@"%lld", [sub longLongValue]];
                    break;
                case 'B': // C++/C99 bool
                case 'c': // ObjC BOOL
                    str = [NSString stringWithFormat:@"%d", [sub intValue]];
                    break;
                default:
                    str = [NSString stringWithFormat:@"%ld", [sub longValue]];
                    break;
            }
            paramValues[i]  = [str UTF8String];
            paramLengths[i] = [str length];
            paramFormats[i] = 0;
        } else if([sub isKindOfClass:[NSData class]]) {
            paramValues[i]  = [sub bytes];
            paramLengths[i] = [sub length];
            paramFormats[i] = 1;
        } else if([sub isKindOfClass:[NSDate class]]) {
            NSString *timestamp = NSDateToPostgresTimestamp(sub);
            paramValues[i]  = [timestamp UTF8String];
            paramLengths[i] = [timestamp length];
            paramFormats[i] = 0;
        } else if(!sub || [sub isMemberOfClass:[NSNull class]]) {
            paramValues[i]  = NULL;
            paramLengths[i] = 0;
            paramFormats[i] = 0;
        } else
            [NSException raise:@"Unrecognized object type"
                        format:@"DatabaseKit doesn't know how to handle this type of object: %@ class: %@", sub, [sub className]];
        ++i;
    }

    PGresult *result = PQexecParams(_connection, [sql UTF8String], paramCount, NULL, paramValues, paramLengths, paramFormats, 0);
    switch (PQresultStatus(result)) {
        case PGRES_BAD_RESPONSE:
        case PGRES_FATAL_ERROR:
            DBDebugLog(@"Query error: %@", [NSString stringWithUTF8String:PQresultErrorMessage(result)]);
            if(outErr)
                *outErr = [[NSError alloc] initWithDomain:DBConnectionErrorDomain
                                                     code:DBPostgresQueryFailed
                                                 userInfo:@{ NSLocalizedDescriptionKey: @(PQresultErrorMessage(result)) }];
            return nil;
        default:
            break;
    }
    int rowCount = PQntuples(result);
    NSArray *columnNames = [self columnsForResult:result];
    NSMutableArray *rowArray = [NSMutableArray array];
    NSMutableDictionary *columns;
    for(int i = 0; i < rowCount; ++i) {
        // construct the dictionary for the row
        columns = [NSMutableDictionary dictionary];
        int j = 0;
        for(NSString *columnName in columnNames) {
            columns[columnName] = [self valueForRow:i column:j result:result];
            ++j;
        }
        [rowArray addObject:columns];
    }
    PQclear(result);
    return rowArray;
}

// TODO: implement columnsForTable

#pragma mark Private
- (NSArray *)columnsForResult:(PGresult *)result
{
    int colCount = PQnfields(result);
    if(colCount <= 0)
        return nil;

    NSMutableArray *columnNames = [NSMutableArray array];
    for(int i = 0; i < colCount; ++i) {
        [columnNames addObject:@(PQfname(result, i))];
    }
    return columnNames;
}

// You have to step through the *query yourself,
- (id)valueForRow:(unsigned int)rowIndex column:(unsigned int)colIndex result:(PGresult *)result
{
    const char *bytes = PQgetvalue(result, rowIndex, colIndex);
    if(!bytes)
        return [NSNull null];

    NSUInteger length = PQgetlength(result, rowIndex, colIndex);
    switch(PQftype(result, colIndex))
    {
        case INT2OID:
             return @(atoi(bytes));
        case INT4OID:
            return @(strtoul(bytes, (char **)NULL, 10));
        case INT8OID:
            return @(strtoull(bytes, (char **)NULL, 10));
        case FLOAT4OID:
        case FLOAT8OID:
            return @(atof(bytes));
            break;
        case DATEOID:
        case TIMEOID:
        case TIMESTAMPOID:
        case TIMESTAMPTZOID:
            return NSDateFromPostgresTimestamp(@(bytes));
        case BYTEAOID: {
            const unsigned char *rawBytes = PQunescapeBytea((const unsigned char *)bytes, &length);
            NSData *data = [NSData dataWithBytes:rawBytes length:length];
            PQfreemem((void *)rawBytes);
            return data;
        }
        case VARCHAROID:
        case TEXTOID:
        default:
            return @(bytes);
            break;
    }
    return nil;
}

#pragma mark -
#pragma mark Transactions
- (BOOL)beginTransaction
{
    PGresult *result = PQexec(_connection, "BEGIN");
    if(PQresultStatus(result) != PGRES_COMMAND_OK)
    {
        [NSException raise:@"PostgreSQL error"
                    format:@"Couldn't start transaction, Details: %@", @(PQresultErrorMessage(result))];
        PQclear(result);
        return NO;
    }
    PQclear(result);
    return YES;
}
- (BOOL)rollBack
{
    PGresult *result = PQexec(_connection, "ROLLBACK");
    if(PQresultStatus(result) != PGRES_COMMAND_OK)
    {
        [NSException raise:@"PostgreSQL error"
                    format:@"Couldn't roll back transaction, Details: %@", @(PQresultErrorMessage(result))];
        PQclear(result);
        return NO;
    }
    PQclear(result);
   return YES;
}
- (BOOL)endTransaction
{
    PGresult *result = PQexec(_connection, "COMMIT");
    if(PQresultStatus(result) != PGRES_COMMAND_OK)
    {
        [NSException raise:@"PostgreSQL error"
                    format:@"Couldn't end transaction, Details: %@", @(PQresultErrorMessage(result))];
        PQclear(result);
        return NO;
    }
    PQclear(result);
    return YES;
}
@end

#pragma mark -

static NSRange rangeOfParameterToken(NSString *param, NSString *query)
{
    BOOL inDblQuotes     = NO, inSingleQuotes = NO, escapeNext = NO;
    const char *needle   = [param UTF8String], *haystack = [query UTF8String];
    NSUInteger needleLen = [param length];

    for(int i = 0; i < [query length]; ++i) {
        if(escapeNext)
            escapeNext = NO;
        else if(haystack[i] == '"' && !inSingleQuotes)
            inDblQuotes = !inDblQuotes;
        else if(haystack[i] == '\'' && !inDblQuotes)
            inSingleQuotes = !inSingleQuotes;
        else if(haystack[i] == '\\')
            escapeNext = YES;
        else if(inSingleQuotes || inDblQuotes)
            continue;
        else if(strncmp(haystack+i, needle, needleLen) == 0)
            return (NSRange){ i, needleLen };
    }
    return (NSRange){ NSNotFound, 0 };
}

static NSDateFormatter *pgDateFormatter = nil;
static dispatch_once_t dateFormatterCreated;
static dispatch_block_t createDateFormatter = ^{
    pgDateFormatter = [[NSDateFormatter alloc] init];
    [pgDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [pgDateFormatter setDateFormat:@"yyyy'-'MM'-'dd HH':'mm':'ssZZ"];
};

static NSString *NSDateToPostgresTimestamp(NSDate *date)
{
    dispatch_once(&dateFormatterCreated, createDateFormatter);
    return [pgDateFormatter stringFromDate:date];
}

static NSDate *NSDateFromPostgresTimestamp(NSString *timestamp)
{
    dispatch_once(&dateFormatterCreated, createDateFormatter);

    if([timestamp rangeOfString:@"."].location != NSNotFound)
        timestamp = [NSString stringWithFormat:@"%@ +0000", [timestamp substringToIndex:[timestamp rangeOfString:@"."].location]];
    else
        timestamp = [NSString stringWithFormat:@"%@ +0000", timestamp];

    return [pgDateFormatter dateFromString:timestamp];
}


text:
/**
 * @file
 * @brief ARCv2 Interrupt Unit device driver
 *
 * The ARCv2 interrupt unit has 16 allocated exceptions associated with
 * vectors 0 to 15 and 240 interrupts associated with vectors 16 to 255.
 * The interrupt unit is optional in the ARCv2-based processors. When
 * building a processor, you can configure the processor to include an
 * interrupt unit. The ARCv2 interrupt unit is highly programmable.
 */

#include <kernel.h>
#include <arch/cpu.h>
#include <device.h>
#include <init.h>

extern void *_VectorTable;

#ifdef CONFIG_DEVICE_POWER_MANAGEMENT
#include <power.h>
#include <kernel_structs.h>
#include <v2/irq.h>

#ifdef CONFIG_ARC_HAS_SECURE
#undef _ARC_V2_IRQ_VECT_BASE
#define _ARC_V2_IRQ_VECT_BASE _ARC_V2_IRQ_VECT_BASE_S
#endif

static u32_t _arc_v2_irq_unit_device_power_state = DEVICE_PM_ACTIVE_STATE;
struct arc_v2_irq_unit_ctx {
	u32_t irq_ctrl; /* Interrupt Context Saving Control Register. */
	u32_t irq_vect_base; /* Interrupt Vector Base. */

	/*
	 * IRQ configuration:
	 * - IRQ Priority:BIT(6):BIT(2)
	 * - IRQ Trigger:BIT(1)
	 * - IRQ Enable:BIT(0)
	 */
	u8_t irq_config[CONFIG_NUM_IRQS - 16];
};
static struct arc_v2_irq_unit_ctx ctx;
#endif

/*
 * @brief Initialize the interrupt unit device driver
 *
 * Initializes the interrupt unit device driver and the device
 * itself.
 *
 * Interrupts are still locked at this point, so there is no need to protect
 * the window between a write to IRQ_SELECT and subsequent writes to the
 * selected IRQ's registers.
 *
 * @return N/A
 */

static int _arc_v2_irq_unit_init(struct device *unused)
{
	ARG_UNUSED(unused);
	int irq; /* the interrupt index */

	/* Interrupts from 0 to 15 are exceptions and they are ignored
	 * by IRQ auxiliary registers. For that reason we skip those
	 * values in this loop.
	 */
	for (irq = 16; irq < CONFIG_NUM_IRQS; irq++) {
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
#ifdef CONFIG_ARC_HAS_SECURE
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_PRIORITY,
			 (CONFIG_NUM_IRQ_PRIO_LEVELS-1) |
			 _ARC_V2_IRQ_PRIORITY_SECURE); /* lowest priority */
#else
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_PRIORITY,
			 (CONFIG_NUM_IRQ_PRIO_LEVELS-1)); /* lowest priority */
#endif
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_ENABLE, _ARC_V2_INT_DISABLE);
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_TRIGGER, _ARC_V2_INT_LEVEL);
	}

	return 0;
}

void _arc_v2_irq_unit_int_eoi(int irq)
{
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_PULSE_CANCEL, 1);
}

void _arc_v2_irq_unit_trigger_set(int irq, unsigned int trigger)
{
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_TRIGGER, trigger);
}

unsigned int _arc_v2_irq_unit_trigger_get(int irq)
{
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
	return _arc_v2_aux_reg_read(_ARC_V2_IRQ_TRIGGER);
}

#ifdef CONFIG_DEVICE_POWER_MANAGEMENT

static int _arc_v2_irq_unit_suspend(struct device *dev)
{
	u8_t irq;

	ARG_UNUSED(dev);

	/* Interrupts from 0 to 15 are exceptions and they are ignored
	 * by IRQ auxiliary registers. For that reason we skip those
	 * values in this loop.
	 */
	for (irq = 16U; irq < CONFIG_NUM_IRQS; irq++) {
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
		ctx.irq_config[irq - 16] =
			_arc_v2_aux_reg_read(_ARC_V2_IRQ_PRIORITY) << 2;
		ctx.irq_config[irq - 16] |=
			_arc_v2_aux_reg_read(_ARC_V2_IRQ_TRIGGER) << 1;
		ctx.irq_config[irq - 16] |=
			_arc_v2_aux_reg_read(_ARC_V2_IRQ_ENABLE);
	}

	ctx.irq_ctrl = _arc_v2_aux_reg_read(_ARC_V2_AUX_IRQ_CTRL);
	ctx.irq_vect_base = _arc_v2_aux_reg_read(_ARC_V2_IRQ_VECT_BASE);

	_arc_v2_irq_unit_device_power_state = DEVICE_PM_SUSPEND_STATE;

	return 0;
}

static int _arc_v2_irq_unit_resume(struct device *dev)
{
	u8_t irq;
	u32_t status32;

	ARG_UNUSED(dev);

	/* Interrupts from 0 to 15 are exceptions and they are ignored
	 * by IRQ auxiliary registers. For that reason we skip those
	 * values in this loop.
	 */
	for (irq = 16U; irq < CONFIG_NUM_IRQS; irq++) {
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_SELECT, irq);
#ifdef CONFIG_ARC_HAS_SECURE
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_PRIORITY,
				ctx.irq_config[irq - 16] >> 2 |
				_ARC_V2_IRQ_PRIORITY_SECURE);
#else
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_PRIORITY,
				ctx.irq_config[irq - 16] >> 2);
#endif
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_TRIGGER,
				(ctx.irq_config[irq - 16] >> 1) & BIT(0));
		_arc_v2_aux_reg_write(_ARC_V2_IRQ_ENABLE,
				ctx.irq_config[irq - 16] & BIT(0));
	}

	_arc_v2_aux_reg_write(_ARC_V2_AUX_IRQ_CTRL, ctx.irq_ctrl);
	_arc_v2_aux_reg_write(_ARC_V2_IRQ_VECT_BASE, ctx.irq_vect_base);

	status32 = _arc_v2_aux_reg_read(_ARC_V2_STATUS32);
	status32 |= _ARC_V2_STATUS32_E(_ARC_V2_DEF_IRQ_LEVEL);

	__builtin_arc_kflag(status32);

	_arc_v2_irq_unit_device_power_state = DEVICE_PM_ACTIVE_STATE;

	return 0;
}

static int _arc_v2_irq_unit_get_state(struct device *dev)
{
	ARG_UNUSED(dev);

	return _arc_v2_irq_unit_device_power_state;
}

/*
 * Implements the driver control management functionality
 * the *context may include IN data or/and OUT data
 */
static int _arc_v2_irq_unit_device_ctrl(struct device *device,
		u32_t ctrl_command, void *context)
{
	if (ctrl_command == DEVICE_PM_SET_POWER_STATE) {
		if (*((u32_t *)context) == DEVICE_PM_SUSPEND_STATE) {
			return _arc_v2_irq_unit_suspend(device);
		} else if (*((u32_t *)context) == DEVICE_PM_ACTIVE_STATE) {
			return _arc_v2_irq_unit_resume(device);
		}
	} else if (ctrl_command == DEVICE_PM_GET_POWER_STATE) {
		*((u32_t *)context) = _arc_v2_irq_unit_get_state(device);
		return 0;
	}
	return 0;
}

SYS_DEVICE_DEFINE("arc_v2_irq_unit", _arc_v2_irq_unit_init,
		_arc_v2_irq_unit_device_ctrl, PRE_KERNEL_1,
		CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
#else
SYS_INIT(_arc_v2_irq_unit_init, PRE_KERNEL_1,
		CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
#endif   /* CONFIG_DEVICE_POWER_MANAGEMENT */


text:
'use strict';

var gulp = require('gulp');
var runSequence = require('run-sequence');

gulp.task('devSync', ['lib'], function(cb) {
    cb = cb || function() {};

    global.isProd = false;

    runSequence(['stylesSync', 'images', 'fonts', 'views', 'index', 'browserifySync'], 'clean', 'watchSync', cb);
});


text:
import SocketServer
import logging
from multiprocessing import Process, Manager, Event, log_to_stderr

from python_client import SocketRelay, ThreadedTCPServer, USBMux, MuxError

_LOGGER = log_to_stderr()
_JOIN_TIMEOUT = 5

class DeviceTCPRelay(SocketServer.BaseRequestHandler):

	def handle(self):
		if self.server.stopped():
			return

		if not self.server.muxdev:
			_LOGGER.error("Device invalid")
			self.request.close()
			return

		_LOGGER.debug("Connecting to device %s" % str(self.server.muxdev))
		dsock = None
		try:
			dsock = self.server.mux.connect(self.server.muxdev, self.server.rport)
		except MuxError:
			_LOGGER.warning("Connection to device %s died!" % str(self.server.muxdev))
			if self.request:
				self.request.close()
			return
		lsock = self.request
		_LOGGER.debug("Connection established, relaying data")
		try:
			fwd = SocketRelay(dsock, lsock)
				#, self.server.bufsize * 1024)
			fwd.handle()
		finally:
			dsock.close()
			lsock.close()
		_LOGGER.debug("Connection closed")

class DeviceServer(ThreadedTCPServer, Process):

	#causes handle_request to return
	timeout = 1

	def __init__(self, mux, muxdevice, server_address, RequestHandlerClass):
		Process.__init__(self)
		ThreadedTCPServer.__init__(self, server_address, RequestHandlerClass)
		self.mux = mux
		self.muxdev = muxdevice
		self._stop = Event()

	def stop(self):
		self._stop.set()

	def stopped(self):
		return self._stop.is_set()

	def run(self):
		if self.stopped():
			_LOGGER.warning("Thread already stopped")

		while not self.stopped():
			self.handle_request()
		self.socket.close()
		_LOGGER.debug("%s will exit now" % (str(self)))

class DeviceConnectionHandler(Process):

	def __init__(self):
		super(DeviceConnectionHandler, self).__init__()
		self._stop = Event()
		self.manager = Manager()

		# devices: dont read that field after start() (will be empty)
		self.devices = {}
		# a managed dict to sync changes between threads
		self.device_id_map = self.manager.dict()

		self.mux = USBMux()

	def handle(self):
		""" Start device handling. Will not return until calling stop() """

		if not self.mux.devices:
			self.mux.process(1.0)

		while not self.stopped():
			muxdevs = self.mux.devices
	#		print muxdevs

			#create new device handlers
			for dev in muxdevs:
				if dev not in self.devices:
					_LOGGER.info("New Device: %s" % str(dev))

					# create device connection tunnel via usbmux
					server = DeviceServer(self.mux, dev, ('localhost', 0), DeviceTCPRelay)
					server.rport = 8080

					server.start()
					self.devices[dev] = server
					self.device_id_map[dev.serial] = server.server_address

					_LOGGER.debug("Serving device %s via %s" % (str(dev), server.server_address))

			#remove invalid devices
			for dev in self.devices.keys():
				if dev not in muxdevs:
					_LOGGER.info("Device gone: %s" % str(dev))
					_LOGGER.debug("Server: %s" % server)
					server.stop()
					server.join(_JOIN_TIMEOUT)
					_LOGGER.debug("Server stopped: %s" % server)
					self.devices.pop(dev)
					self.device_id_map.pop(dev.serial)

			#check for new devices, ...
			self.mux.process(0.1)

	def stop(self):
		self._stop.set()

	def stopped(self):
		return self._stop.is_set()

	def run(self):
		self.handle()

		_LOGGER.debug("stopping device servers...")
		for server in self.devices.itervalues():
			server.stop()
			server.join(_JOIN_TIMEOUT)
		_LOGGER.debug("%s will exit now" % (str(self)))

	def device_connection_info(self, deviceUUID):
		'''Returns a tuple of ip and port'''
		if deviceUUID in self.device_id_map:
				return self.device_id_map[deviceUUID]
		else:
			return None

_SHARED_DEVICE_HANDLER = None

def shared_device_handler():
	global _SHARED_DEVICE_HANDLER
	if not _SHARED_DEVICE_HANDLER:
		_SHARED_DEVICE_HANDLER = DeviceConnectionHandler()
		_SHARED_DEVICE_HANDLER.start()
		import time
		time.sleep(1)
	return _SHARED_DEVICE_HANDLER


text:
class TestFileFlag < Minitest::Test
  def setup
    FileUtils.mkdir_p('tmp')
    @flag = RFlags::FileFlag.new('tmp/file_flag')
    FileUtils.rm_f('tmp/file_flag')
  end

  def teardown
    FileUtils.rm_f('tmp/file_flag')
  end

  include FlagAssetions
end


text:
jQuery(document).ready(function() {

    /*
        Fullscreen background
    */
    $.backstretch("ref/dist/img/backgrounds/3.jpg");

    /*
        Login form validation
    */
    $('.login-form input[type="text"], .login-form input[type="password"], .login-form textarea').on('focus', function() {
    	$(this).removeClass('input-error');
    });

    $('.login-form').on('submit', function(e) {

    	$(this).find('input[type="text"], input[type="password"], textarea').each(function(){
    		if( $(this).val() == "" ) {
    			e.preventDefault();
    			$(this).addClass('input-error');
    		}
    		else {
    			$(this).removeClass('input-error');
    		}
    	});

    });

    /*
        Registration form validation
    */
    $('.registration-form input[type="text"], .registration-form textarea').on('focus', function() {
    	$(this).removeClass('input-error');
    });

    $('.registration-form').on('submit', function(e) {

    	$(this).find('input[type="text"], textarea').each(function(){
    		if( $(this).val() == "" ) {
    			e.preventDefault();
    			$(this).addClass('input-error');
    		}
    		else {
    			$(this).removeClass('input-error');
    		}
    	});

    });

});


text:
<?php
//config/autoload/doctrine.global.php
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'dbname' => 'soccer',
    'user' => 'root',
    'password' => ''
),
),
)
));


text:
package org.wso2.carbon.apimgt.impl.utils;

import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.Stub;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.util.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dto.Environment;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.localentry.stub.APILocalEntryAdminStub;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils;

import java.rmi.RemoteException;

/**
 * A Service Implementation for the LocalEntryAdmin service. This class is implemented as a wrapper for
 * the LocalEntryAdminServiceStub. This implementation loads the necessary service
 * endpoint information and admin user credentials required to invoke the admin service
 * from the APIManagerConfiguration.
 */
public class LocalEntryAdminClient {

    private static final Log log = LogFactory.getLog(LocalEntryAdminClient.class);
    private APILocalEntryAdminStub localEntryAdminServiceStub;
    private String tenantDomain;

    public LocalEntryAdminClient(Environment environment, String tenantDomain) throws AxisFault {

        this.tenantDomain = tenantDomain;
        setupLocalEntryClient(environment);
    }

    private void setupLocalEntryClient(Environment environment) throws AxisFault {

        ConfigurationContext configurationContext = ServiceReferenceHolder.getContextService().getClientConfigContext();
        localEntryAdminServiceStub = new APILocalEntryAdminStub(configurationContext,
                environment.getServerURL() + "APILocalEntryAdmin");
        setup(localEntryAdminServiceStub, environment, configurationContext);
        CarbonUtils.setBasicAccessSecurityHeaders(environment.getUserName(), environment.getPassword(),
                localEntryAdminServiceStub._getServiceClient());
    }

    public LocalEntryAdminClient(String tenantDomain) throws AxisFault {

        this.tenantDomain = tenantDomain;
        Environment environment = new Environment();
        try {
            UserRealm bootstrapRealm = ServiceReferenceHolder.getInstance().getRealmService().getBootstrapRealm();
            if (bootstrapRealm != null) {
                environment.setServerURL("https://localhost:"
                        + APIUtil.getCarbonTransportPort(APIConstants.HTTPS_PROTOCOL) + "/services/");
                environment.setUserName(bootstrapRealm.getRealmConfiguration().getAdminUserName());
                environment.setPassword(bootstrapRealm.getRealmConfiguration().getAdminPassword());
                setupLocalEntryClient(environment);
            }
        } catch (UserStoreException e) {
            String msg = "Failed to get the super admin credentials for the gateway " + e.getMessage();
            log.error(msg);
            throw new AxisFault(msg, e);
        }
    }

    protected final void setup(Stub stub, Environment environment, ConfigurationContext configurationContext)
            throws AxisFault {

        String cookie = gatewayLogin(environment, configurationContext);
        ServiceClient serviceClient = stub._getServiceClient();
        Options options = serviceClient.getOptions();
        options.setTimeOutInMilliSeconds(15 * 60 * 1000);
        options.setProperty(HTTPConstants.SO_TIMEOUT, 15 * 60 * 1000);
        options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, 15 * 60 * 1000);
        options.setManageSession(true);
        options.setProperty(HTTPConstants.COOKIE_STRING, cookie);

    }

    private String gatewayLogin(Environment environment, ConfigurationContext configurationContext) throws AxisFault {

        String userName = environment.getUserName();
        String password = environment.getPassword();
        String serverURL = environment.getServerURL();

        if (serverURL == null || userName == null || password == null) {
            throw new AxisFault("Required API gateway admin configuration unspecified");
        }
        String host;
        host = new URL(serverURL).getHost();
        AuthenticationAdminStub authAdminStub = new AuthenticationAdminStub(configurationContext,
                serverURL + "AuthenticationAdmin");
        ServiceClient client = authAdminStub._getServiceClient();
        Options options = client.getOptions();
        options.setManageSession(true);
        try {
            authAdminStub.login(userName, password, host);
            ServiceContext serviceContext = authAdminStub.
                    _getServiceClient().getLastOperationContext().getServiceContext();
            return (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
        } catch (RemoteException e) {
            throw new AxisFault("Error while contacting the authentication admin services", e);
        } catch (LoginAuthenticationExceptionException e) {
            throw new AxisFault("Error while authenticating against the API gateway admin", e);
        }
    }

    /**
     * This method is used to add the Local Entry.
     *
     * @param content Content of the Local Entry.
     * @throws AxisFault If error occurs when adding Local Entry.
     */
    public void addLocalEntry(String content) throws AxisFault {

        try {
            localEntryAdminServiceStub.addLocalEntry(content, tenantDomain);
        } catch (RemoteException e) {
            throw new AxisFault("Error occurred while adding the Local Entry: ", e.getMessage(), e);
        }
    }

    /**
     * This method is used to get the LocalEntry.
     *
     * @param key Local entry key to be retrieved.
     * @return LocalEntry
     * @throws AxisFault If error occurs when retrieving Local Entry.
     */
    public Boolean localEntryExists(String key) throws AxisFault {

        try {
            return localEntryAdminServiceStub.isLocalEntryExists(key, tenantDomain);
        } catch (RemoteException e) {
            throw new AxisFault("Error occurred while getting the Local Entry: ", e.getMessage(), e);
        }
    }

    /**
     * This method is used to delete given Local Entry.
     *
     * @param key Local Entry key to be deleted.
     * @return Status of the operation.
     * @throws AxisFault If error occurs when deleting the Local Entry.
     */
    public boolean deleteEntry(String key) throws AxisFault {

        try {
            return localEntryAdminServiceStub.deleteLocalEntry(key, tenantDomain);
        } catch (RemoteException e) {
            throw new AxisFault("Error occurred while deleting the Local Entry: ", e.getMessage(), e);
        }
    }

}


text:
'''
Created by auto_sdk on 2012.11.23
'''
from top.api.base import RestApi
class SellercenterRoleInfoGetRequest(RestApi):
	def __init__(self,domain='gw.api.taobao.com',port=80):
		RestApi.__init__(self,domain, port)
		self.role_id = None

	def getapiname(self):
		return 'taobao.sellercenter.role.info.get'


text:
require 'spec_helper'

module Comptroller
  describe Practice do
    context 'crud api' do
      it 'retrieves all pratices' do
        expect(Practice.all.first).to eql(Practice.new(:export_url => 'https://optimis.duxware.com', :token => '12345', :external_id => 3))
      end

      it 'creates new practices' do
        practice = Practice.create(:external_id => 5, :export_url => 'http://hello.world', :token => '12345')
        expect(practice).to eql(Practice.new(:external_id => 5, :export_url => 'http://hello.world', :token => '12345'))
      end

      it 'retrieves practice by id' do
        practice = Practice.find(1)
        expect(practice).to eql(Practice.new(:external_id => 3, :export_url => 'https://optimis.duxware.com', :token => '12345'))
      end

      it 'updates practices' do
        expect(Practice.save_existing(1, :export_url => 'https://optimis.webpt.com')).to be_true
        expect(Practice.find(1).export_url).to eql('https://optimis.webpt.com')
      end

      it 'deletes practices' do
        Practice.destroy_existing(1)
        practice_ids = Practice.all.map(&:id)
        expect(practice_ids.include?(1)).to be_false
      end
    end
  end
end


text:
package java.net;

import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * Abstract datagram and multicast socket implementation base class.
 *
 * @implNote Sockets created with the {@code DatagramSocket} and {@code
 * MulticastSocket} public constructors historically delegated all socket
 * operations to a {@code DatagramSocketImpl} implementation named
 * "PlainDatagramSocketImpl". {@code DatagramSocket} and {@code MulticastSocket}
 * have since been changed to a new implementation based on {@code DatagramChannel}.
 * The JDK continues to ship with the older implementation to allow code to run
 * that depends on unspecified behavior that differs between the old and new
 * implementations. The old implementation will be used if the Java virtual
 * machine is started with the system property {@systemProperty
 * jdk.net.usePlainDatagramSocketImpl} set to use the old implementation. It may
 * also be set in the JDK's network configuration file, located in {@code
 * ${java.home}/conf/net.properties}. The value of the property is the string
 * representation of a boolean. If set without a value then it defaults to {@code
 * true}, hence running with {@code -Djdk.net.usePlainDatagramSocketImpl} or
 * {@code -Djdk.net.usePlainDatagramSocketImpl=true} will configure the Java
 * virtual machine to use the old implementation. The property and old
 * implementation will be removed in a future version.
 *
 * @author Pavani Diwanji
 * @since  1.1
 */

public abstract class DatagramSocketImpl implements SocketOptions {

    /**
     * Constructor for subclasses to call.
     */
    public DatagramSocketImpl() {}

    /**
     * The local port number.
     */
    protected int localPort;

    /**
     * The file descriptor object.
     */
    protected FileDescriptor fd;

    int dataAvailable() {
        // default impl returns zero, which disables the calling
        // functionality
        return 0;
    }

    /**
     * Creates a datagram socket.
     * @throws    SocketException if there is an error in the
     * underlying protocol, such as a TCP error.
     */
    protected abstract void create() throws SocketException;

    /**
     * Binds a datagram socket to a local port and address.
     * @param     lport the local port
     * @param     laddr the local address
     * @throws    SocketException if there is an error in the
     *            underlying protocol, such as a TCP error.
     */
    protected abstract void bind(int lport, InetAddress laddr) throws SocketException;

    /**
     * Sends a datagram packet. The packet contains the data and the
     * destination address to send the packet to.
     * @param    p the packet to be sent.
     * @throws   IOException if an I/O exception occurs while sending the
     *           datagram packet.
     * @throws   PortUnreachableException may be thrown if the socket is connected
     *           to a currently unreachable destination. Note, there is no guarantee that
     *           the exception will be thrown.
     */
    protected abstract void send(DatagramPacket p) throws IOException;

    /**
     * Connects a datagram socket to a remote destination. This associates the remote
     * address with the local socket so that datagrams may only be sent to this destination
     * and received from this destination. This may be overridden to call a native
     * system connect.
     *
     * <p>If the remote destination to which the socket is connected does not
     * exist, or is otherwise unreachable, and if an ICMP destination unreachable
     * packet has been received for that address, then a subsequent call to
     * send or receive may throw a PortUnreachableException.
     * Note, there is no guarantee that the exception will be thrown.
     * @param   address the remote InetAddress to connect to
     * @param   port the remote port number
     * @throws  SocketException may be thrown if the socket cannot be
     *          connected to the remote destination
     * @since   1.4
     */
    protected void connect(InetAddress address, int port) throws SocketException {}

    /**
     * Disconnects a datagram socket from its remote destination.
     * @since 1.4
     */
    protected void disconnect() {}

    /**
     * Peek at the packet to see who it is from. Updates the specified {@code InetAddress}
     * to the address which the packet came from.
     * @param     i an InetAddress object
     * @return    the port number which the packet came from.
     * @throws    IOException if an I/O exception occurs
     * @throws    PortUnreachableException may be thrown if the socket is connected
     *            to a currently unreachable destination. Note, there is no guarantee that the
     *            exception will be thrown.
     */
    protected abstract int peek(InetAddress i) throws IOException;

    /**
     * Peek at the packet to see who it is from. The data is copied into the specified
     * {@code DatagramPacket}. The data is returned,
     * but not consumed, so that a subsequent peekData/receive operation
     * will see the same data.
     * @param     p the Packet Received.
     * @return    the port number which the packet came from.
     * @throws    IOException if an I/O exception occurs
     * @throws    PortUnreachableException may be thrown if the socket is connected
     *            to a currently unreachable destination. Note, there is no guarantee that the
     *            exception will be thrown.
     * @since 1.4
     */
    protected abstract int peekData(DatagramPacket p) throws IOException;
    /**
     * Receive the datagram packet.
     * @param     p the Packet Received.
     * @throws    IOException if an I/O exception occurs
     *            while receiving the datagram packet.
     * @throws    PortUnreachableException may be thrown if the socket is connected
     *            to a currently unreachable destination. Note, there is no guarantee that the
     *            exception will be thrown.
     */
    protected abstract void receive(DatagramPacket p) throws IOException;

    /**
     * Set the TTL (time-to-live) option.
     * @param ttl a byte specifying the TTL value
     *
     * @deprecated use setTimeToLive instead.
     * @throws    IOException if an I/O exception occurs while setting
     * the time-to-live option.
     * @see #getTTL()
     */
    @Deprecated
    protected abstract void setTTL(byte ttl) throws IOException;

    /**
     * Retrieve the TTL (time-to-live) option.
     *
     * @throws    IOException if an I/O exception occurs
     * while retrieving the time-to-live option
     * @deprecated use getTimeToLive instead.
     * @return a byte representing the TTL value
     * @see #setTTL(byte)
     */
    @Deprecated
    protected abstract byte getTTL() throws IOException;

    /**
     * Set the TTL (time-to-live) option.
     * @param ttl an {@code int} specifying the time-to-live value
     * @throws    IOException if an I/O exception occurs
     * while setting the time-to-live option.
     * @see #getTimeToLive()
     */
    protected abstract void setTimeToLive(int ttl) throws IOException;

    /**
     * Retrieve the TTL (time-to-live) option.
     * @throws    IOException if an I/O exception occurs
     * while retrieving the time-to-live option
     * @return an {@code int} representing the time-to-live value
     * @see #setTimeToLive(int)
     */
    protected abstract int getTimeToLive() throws IOException;

    /**
     * Join the multicast group.
     * @param inetaddr multicast address to join.
     * @throws    IOException if an I/O exception occurs
     * while joining the multicast group.
     */
    protected abstract void join(InetAddress inetaddr) throws IOException;

    /**
     * Leave the multicast group.
     * @param inetaddr multicast address to leave.
     * @throws    IOException if an I/O exception occurs
     * while leaving the multicast group.
     */
    protected abstract void leave(InetAddress inetaddr) throws IOException;

    /**
     * Join the multicast group.
     * @param mcastaddr address to join.
     * @param netIf specifies the local interface to receive multicast
     *        datagram packets
     * @throws IOException if an I/O exception occurs while joining
     * the multicast group
     * @since 1.4
     */
    protected abstract void joinGroup(SocketAddress mcastaddr,
                                      NetworkInterface netIf)
        throws IOException;

    /**
     * Leave the multicast group.
     * @param mcastaddr address to leave.
     * @param netIf specified the local interface to leave the group at
     * @throws IOException if an I/O exception occurs while leaving
     * the multicast group
     * @since 1.4
     */
    protected abstract void leaveGroup(SocketAddress mcastaddr,
                                       NetworkInterface netIf)
        throws IOException;

    /**
     * Close the socket.
     */
    protected abstract void close();

    /**
     * Gets the local port.
     * @return an {@code int} representing the local port value
     */
    protected int getLocalPort() {
        return localPort;
    }

    /**
     * Gets the datagram socket file descriptor.
     * @return a {@code FileDescriptor} object representing the datagram socket
     * file descriptor
     */
    protected FileDescriptor getFileDescriptor() {
        return fd;
    }

    /**
     * Called to set a socket option.
     *
     * @implSpec
     * The default implementation of this method first checks that the given
     * socket option {@code name} is not null, then throws {@code
     * UnsupportedOperationException}. Subclasses should override this method
     * with an appropriate implementation.
     *
     * @param  <T> The type of the socket option value
     * @param  name The socket option
     * @param  value The value of the socket option. A value of {@code null}
     *              may be valid for some options.
     *
     * @throws UnsupportedOperationException if the DatagramSocketImpl does not
     *         support the option
     * @throws IllegalArgumentException if the value is not valid for
     *         the option
     * @throws IOException if an I/O error occurs, or if the socket is closed
     * @throws NullPointerException if name is {@code null}
     *
     * @since 9
     */
    protected <T> void setOption(SocketOption<T> name, T value) throws IOException {
        Objects.requireNonNull(name);
        throw new UnsupportedOperationException("'" + name + "' not supported");
    }

    /**
     * Called to get a socket option.
     *
     * @implSpec
     * The default implementation of this method first checks that the given
     * socket option {@code name} is not null, then throws {@code
     * UnsupportedOperationException}. Subclasses should override this method
     * with an appropriate implementation.
     *
     * @param  <T> The type of the socket option value
     * @param  name The socket option
     * @return the socket option
     *
     * @throws UnsupportedOperationException if the DatagramSocketImpl does not
     *         support the option
     * @throws IOException if an I/O error occurs, or if the socket is closed
     * @throws NullPointerException if name is {@code null}
     *
     * @since 9
     */
    protected <T> T getOption(SocketOption<T> name) throws IOException {
        Objects.requireNonNull(name);
        throw new UnsupportedOperationException("'" + name + "' not supported");
    }

    /**
     * Returns a set of SocketOptions supported by this impl
     * and by this impl's socket (DatagramSocket or MulticastSocket)
     *
     * @implSpec
     * The default implementation of this method returns an empty set.
     * Subclasses should override this method with an appropriate implementation.
     *
     * @return a Set of SocketOptions
     *
     * @since 9
     */
    protected Set<SocketOption<?>> supportedOptions() {
        return Set.of();
    }
}


text:
/* classes: h_files */

#ifndef SCM_DEPRECATION_H
#define SCM_DEPRECATION_H

/* Copyright (C) 2001, 2006, 2008, 2009 Free Software Foundation, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "libguile/__scm.h"

/* These functions are a possibly useful part of the API and not only used
   internally, thus they are exported always, not depending on
   SCM_ENABLE_DEPRECATED.  */

SCM_API void scm_c_issue_deprecation_warning (const char *msg);
SCM_API void scm_c_issue_deprecation_warning_fmt (const char *msg, ...);
SCM_API SCM scm_issue_deprecation_warning (SCM msgs);

SCM_API SCM scm_include_deprecated_features (void);
SCM_INTERNAL void scm_init_deprecation (void);

#endif  /* SCM_DEPRECATION_H */

/*
  Local Variables:
  c-file-style: "gnu"
  End:
*/


text:
package com.loadburn.heron.captcha.config.background;

import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;

import java.io.Serializable;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-19
 */
public class GuiceWordGen implements Serializable {

    private static final long serialVersionUID = 8846127718542580313L;
    private RandomWordGenerator wordGen;
    private String text;

    public RandomWordGenerator getWordGen() {
        wordGen = new RandomWordGenerator(text);
        return wordGen;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}


text:
/**
 * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v25.0.1
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var rowNode_1 = require("../entities/rowNode");
var context_1 = require("../context/context");
var events_1 = require("../events");
var constants_1 = require("../constants/constants");
var beanStub_1 = require("../context/beanStub");
var generic_1 = require("../utils/generic");
var array_1 = require("../utils/array");
var PinnedRowModel = /** @class */ (function (_super) {
    __extends(PinnedRowModel, _super);
    function PinnedRowModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PinnedRowModel.prototype.init = function () {
        this.setPinnedTopRowData(this.gridOptionsWrapper.getPinnedTopRowData());
        this.setPinnedBottomRowData(this.gridOptionsWrapper.getPinnedBottomRowData());
    };
    PinnedRowModel.prototype.isEmpty = function (floating) {
        var rows = floating === constants_1.Constants.PINNED_TOP ? this.pinnedTopRows : this.pinnedBottomRows;
        return generic_1.missingOrEmpty(rows);
    };
    PinnedRowModel.prototype.isRowsToRender = function (floating) {
        return !this.isEmpty(floating);
    };
    PinnedRowModel.prototype.getRowAtPixel = function (pixel, floating) {
        var rows = floating === constants_1.Constants.PINNED_TOP ? this.pinnedTopRows : this.pinnedBottomRows;
        if (generic_1.missingOrEmpty(rows)) {
            return 0; // this should never happen, just in case, 0 is graceful failure
        }
        for (var i = 0; i < rows.length; i++) {
            var rowNode = rows[i];
            var rowTopPixel = rowNode.rowTop + rowNode.rowHeight - 1;
            // only need to range check against the top pixel, as we are going through the list
            // in order, first row to hit the pixel wins
            if (rowTopPixel >= pixel) {
                return i;
            }
        }
        return rows.length - 1;
    };
    PinnedRowModel.prototype.setPinnedTopRowData = function (rowData) {
        this.pinnedTopRows = this.createNodesFromData(rowData, true);
        var event = {
            type: events_1.Events.EVENT_PINNED_ROW_DATA_CHANGED,
            api: this.gridApi,
            columnApi: this.columnApi
        };
        this.eventService.dispatchEvent(event);
    };
    PinnedRowModel.prototype.setPinnedBottomRowData = function (rowData) {
        this.pinnedBottomRows = this.createNodesFromData(rowData, false);
        var event = {
            type: events_1.Events.EVENT_PINNED_ROW_DATA_CHANGED,
            api: this.gridApi,
            columnApi: this.columnApi
        };
        this.eventService.dispatchEvent(event);
    };
    PinnedRowModel.prototype.createNodesFromData = function (allData, isTop) {
        var _this = this;
        var rowNodes = [];
        if (allData) {
            var nextRowTop_1 = 0;
            allData.forEach(function (dataItem, index) {
                var rowNode = new rowNode_1.RowNode();
                _this.context.createBean(rowNode);
                rowNode.data = dataItem;
                var idPrefix = isTop ? rowNode_1.RowNode.ID_PREFIX_TOP_PINNED : rowNode_1.RowNode.ID_PREFIX_BOTTOM_PINNED;
                rowNode.id = idPrefix + index;
                rowNode.rowPinned = isTop ? constants_1.Constants.PINNED_TOP : constants_1.Constants.PINNED_BOTTOM;
                rowNode.setRowTop(nextRowTop_1);
                rowNode.setRowHeight(_this.gridOptionsWrapper.getRowHeightForNode(rowNode).height);
                rowNode.setRowIndex(index);
                nextRowTop_1 += rowNode.rowHeight;
                rowNodes.push(rowNode);
            });
        }
        return rowNodes;
    };
    PinnedRowModel.prototype.getPinnedTopRowData = function () {
        return this.pinnedTopRows;
    };
    PinnedRowModel.prototype.getPinnedBottomRowData = function () {
        return this.pinnedBottomRows;
    };
    PinnedRowModel.prototype.getPinnedTopTotalHeight = function () {
        return this.getTotalHeight(this.pinnedTopRows);
    };
    PinnedRowModel.prototype.getPinnedTopRowCount = function () {
        return this.pinnedTopRows ? this.pinnedTopRows.length : 0;
    };
    PinnedRowModel.prototype.getPinnedBottomRowCount = function () {
        return this.pinnedBottomRows ? this.pinnedBottomRows.length : 0;
    };
    PinnedRowModel.prototype.getPinnedTopRow = function (index) {
        return this.pinnedTopRows[index];
    };
    PinnedRowModel.prototype.getPinnedBottomRow = function (index) {
        return this.pinnedBottomRows[index];
    };
    PinnedRowModel.prototype.forEachPinnedTopRow = function (callback) {
        if (generic_1.missingOrEmpty(this.pinnedTopRows)) {
            return;
        }
        this.pinnedTopRows.forEach(callback);
    };
    PinnedRowModel.prototype.forEachPinnedBottomRow = function (callback) {
        if (generic_1.missingOrEmpty(this.pinnedBottomRows)) {
            return;
        }
        this.pinnedBottomRows.forEach(callback);
    };
    PinnedRowModel.prototype.getPinnedBottomTotalHeight = function () {
        return this.getTotalHeight(this.pinnedBottomRows);
    };
    PinnedRowModel.prototype.getTotalHeight = function (rowNodes) {
        if (!rowNodes || rowNodes.length === 0) {
            return 0;
        }
        var lastNode = array_1.last(rowNodes);
        return lastNode.rowTop + lastNode.rowHeight;
    };
    __decorate([
        context_1.Autowired('columnApi')
    ], PinnedRowModel.prototype, "columnApi", void 0);
    __decorate([
        context_1.Autowired('gridApi')
    ], PinnedRowModel.prototype, "gridApi", void 0);
    __decorate([
        context_1.PostConstruct
    ], PinnedRowModel.prototype, "init", null);
    PinnedRowModel = __decorate([
        context_1.Bean('pinnedRowModel')
    ], PinnedRowModel);
    return PinnedRowModel;
}(beanStub_1.BeanStub));
exports.PinnedRowModel = PinnedRowModel;

//# sourceMappingURL=pinnedRowModel.js.map


text:
package com.fissionworks.ddtutils.data.generator;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.testng.Assert;
import org.testng.annotations.Test;

public class RandomIntegerUtilsTest {

    @Test
    public void generate_shouldReturnAnyRandomInteger() {
        final int actual = RandomIntegerUtils.generate();
        // hmmmm, not much to check here!
        Assert.assertTrue(actual >= Integer.MIN_VALUE && actual <= Integer.MAX_VALUE,
                "generate should create a integer from full range of integers");
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void generate_withEvenAndOddModifier_shouldThrowException() {
        RandomIntegerUtils.generate("[randint{even}{odd}]");
    }

    @Test
    public void generate_withEvenAndRangeModifiers_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -27;
        final int max = 28;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(String.format("[randint{range=%s:%s}{even}]", min, max));
            Assert.assertTrue(actual >= min && actual <= max, "|" + actual + "| is not in the specified range");
            Assert.assertTrue(actual % 2 == 0, "|" + actual + "| is not an even number");
        }
    }

    @Test
    public void generate_withEvenModifier_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{even}]");
            Assert.assertTrue(actual % 2 == 0, "|" + actual + "| is not an even number");
        }
    }

    @Test
    public void generate_withEvenModifierAndInternalWhitespace_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{ even }]");
            Assert.assertTrue(actual % 2 == 0, "|" + actual + "| is not an even number");
        }
    }

    @Test
    public void generate_withEvenModifierMixedCase_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{EvEn}]");
            Assert.assertTrue(actual % 2 == 0, "|" + actual + "| is not an even number");
        }
    }

    @Test
    public void generate_withKeywordNoModifiers_shouldReturnAnyRandomInteger() {
        final int actual = RandomIntegerUtils.generate("[randint]");
        // hmmmm, not much to check here!
        Assert.assertTrue(actual >= Integer.MIN_VALUE && actual <= Integer.MAX_VALUE,
                "generate should create a integer from full range of integers");
    }

    @Test
    public void generate_withKeywordNoModifiersAndInternalWhitespace_shouldReturnAnyRandomInteger() {
        final int actual = RandomIntegerUtils.generate("[    randint     ]");
        // hmmmm, not much to check here!
        Assert.assertTrue(actual >= Integer.MIN_VALUE && actual <= Integer.MAX_VALUE,
                "generate should create a integer from full range of integers");
    }

    @Test
    public void generate_withKeywordNoModifiersAndLeadingTrailingWhitespace_shouldReturnAnyRandomInteger() {
        final int actual = RandomIntegerUtils.generate("     [randint]     ");
        // hmmmm, not much to check here!
        Assert.assertTrue(actual >= Integer.MIN_VALUE && actual <= Integer.MAX_VALUE,
                "generate should create a integer from full range of integers");
    }

    @Test
    public void generate_withKeywordNoModifiersAndMixedCase_shouldReturnAnyRandomInteger() {
        final int actual = RandomIntegerUtils.generate("[RaNdInT]");
        // hmmmm, not much to check here!
        Assert.assertTrue(actual >= Integer.MIN_VALUE && actual <= Integer.MAX_VALUE,
                "generate should create a integer from full range of integers");
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void generate_withMinValueGreaterThanMaxValue_shouldThrowException() {
        RandomIntegerUtils.generate(10, 9);
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void generate_withMissingColon_shouldThrowException() {
        RandomIntegerUtils.generate(String.format("[randint{range=5}]"));
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void generate_withNonNumericRangeValues_shouldThrowException() {
        RandomIntegerUtils.generate(String.format("[randint{range=chicken:turtle}]"));
    }

    @Test
    public void generate_withOddAndRangeModifiers_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -27;
        final int max = 28;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(String.format("[randint{range=%s:%s}{odd}]", min, max));
            Assert.assertTrue(actual >= min && actual <= max, "|" + actual + "| is not in the specified range");
            Assert.assertTrue(actual % 2 != 0, "|" + actual + "| is not an odd number");
        }
    }

    @Test
    public void generate_withOddModifier_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{odd}]");
            Assert.assertTrue(actual % 2 != 0, "|" + actual + "| is not an odd number");
        }
    }

    @Test
    public void generate_withOddModifierAndInternalWhitespace_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{ odd }]");
            Assert.assertTrue(actual % 2 != 0, "|" + actual + "| is not an odd number");
        }
    }

    @Test
    public void generate_withOddModifierMixedCase_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate("[randint{OdD}]");
            Assert.assertTrue(actual % 2 != 0, "|" + actual + "| is not an odd number");
        }
    }

    @Test
    public void generate_withValidRange_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -5;
        final int max = 6;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(min, max);
            Assert.assertTrue(actual >= min && actual <= max, actual + ".");
        }
    }

    @Test
    public void generate_withValidRangeModifier_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -5;
        final int max = 6;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(String.format("[randint{range=%s:%s}]", min, max));
            Assert.assertTrue(actual >= min && actual <= max, "|" + actual + "| is not in the specified range");
        }
    }

    @Test
    public void generate_withValidRangeModifierAndInternalWhitespace_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -5;
        final int max = 6;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(String.format("[randint{ range  =  %s  :  %s }]", min, max));
            Assert.assertTrue(actual >= min && actual <= max, "|" + actual + "| is not in the specified range");
        }
    }

    @Test
    public void generate_withValidRangeModifierMixedCase_shouldReturnRandomIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        final int min = -5;
        final int max = 6;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 20; i++) {
            actual = RandomIntegerUtils.generate(String.format("[randint{RaNgE=%s:%s}]", min, max));
            Assert.assertTrue(actual >= min && actual <= max, "|" + actual + "| is not in the specified range");
        }
    }

    @Test
    public void generateEven_shouldReturnAnyRandomEvenInteger() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateEven();
            Assert.assertTrue(actual % 2 == 0);
        }
    }

    @Test
    public void generateEven_withEvenRangeNumbers_shouldReturnRandomEvenIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateEven(-6, 4);
            Assert.assertTrue(actual % 2 == 0);
        }
    }

    @Test
    public void generateEven_withOddRangeNumbers_shouldReturnRandomEvenIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateEven(-3, 9);
            Assert.assertTrue(actual % 2 == 0);
        }
    }

    @Test
    public void generateOdd_shouldReturnAnyRandomOddInteger() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateOdd();
            Assert.assertTrue(actual % 2 != 0);
        }
    }

    @Test
    public void generateOdd_withEvenRangeNumbers_shouldReturnRandomOddIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateOdd(-4, 6);
            Assert.assertTrue(actual % 2 != 0);
        }
    }

    @Test
    public void generateOdd_withOddRangeNumbers_shouldReturnRandomOddIntegerInDesiredRange() {
        int actual = Integer.MIN_VALUE;
        // perform multiple checks to generate range of random numbers to test due dynamic nature of the
        // random numbers
        for (int i = 0; i < 100; i++) {
            actual = RandomIntegerUtils.generateOdd(-3, 9);
            Assert.assertTrue(actual % 2 != 0);
        }
    }

    @Test
    public void isRandomIntegerKeyword_withKeywordStringWithInternalWhitespace_shouldReturnTrue() {
        Assert.assertTrue(RandomIntegerUtils.isRandomIntegerKeyword("    [    randint   {xxxxx}]   "));
    }

    @Test
    public void isRandomIntegerKeyword_withKeywordStringWithLeadingTrailingWhitespace_shouldReturnTrue() {
        Assert.assertTrue(RandomIntegerUtils.isRandomIntegerKeyword("    [randint{xxxxx}]   "));
    }

    @Test
    public void isRandomIntegerKeyword_withKeywordStringWithMixedCase_shouldReturnTrue() {
        Assert.assertTrue(RandomIntegerUtils.isRandomIntegerKeyword("[RaNdInT{xxxxx}]"));
    }

    @Test
    public void isRandomIntegerKeyword_withNonKeywordString_shouldReturnFalse() {
        Assert.assertFalse(RandomIntegerUtils.isRandomIntegerKeyword("[notarandint{xxxxx}]"));
    }

    @Test
    public void isRandomIntegerKeyword_withSimpleKeywordString_shouldReturnTrue() {
        Assert.assertTrue(RandomIntegerUtils.isRandomIntegerKeyword("[randint{xxxxx}]"));
    }

    @Test
    public void RandomIntegerUtils_shouldHaveInaccessibleConstructor() {
        final Constructor<?>[] constructors = RandomIntegerUtils.class.getDeclaredConstructors();
        final Constructor<?> constructor = constructors[0];
        Assert.assertFalse(constructor.isAccessible(), "Constructor should be inaccessible");
    }

    @Test
    public void RandomIntegerUtils_shouldHaveOneConstructor() {
        final Constructor<?>[] constructors = RandomIntegerUtils.class.getDeclaredConstructors();
        Assert.assertEquals(constructors.length, 1);
    }

    @Test(expectedExceptions = InvocationTargetException.class)
    public void RandomIntegerUtilsInstantiationThroughReflection_shouldThrowException() throws Exception {
        final Constructor<?>[] constructors = RandomIntegerUtils.class.getDeclaredConstructors();
        final Constructor<?> constructor = constructors[0];
        constructor.setAccessible(true);
        constructor.newInstance();
    }
}