text:
<!DOCTYPE html>

    <title>Table View - PatternFly</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="../../dist/img/favicon.ico">

    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../../dist/img/apple-touch-icon-precomposed-152.png">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../dist/img/apple-touch-icon-precomposed-144.png">

    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="../../dist/img/apple-touch-icon-precomposed-76.png">

    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../dist/img/apple-touch-icon-precomposed-72.png">

    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="../../dist/img/apple-touch-icon-precomposed-180.png">

    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../dist/img/apple-touch-icon-precomposed-114.png">

    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="../../dist/img/apple-touch-icon-precomposed-57.png">
    <link rel="stylesheet" href="../../dist/css/patternfly.min.css" >
    <link rel="stylesheet" href="../../dist/css/patternfly-additions.min.css" >

      <link href="tests.css" rel="stylesheet" media="screen, print">

Table View

        These examples are included for development testing purposes.  For official documentation, see https://www.patternfly.org, http://getbootstrap.com, and http://datatables.net.

    <form class="toolbar-pf-actions">

        Rendering Engine

            <button type="button" class="btn btn-default dropdown-toggle" id="filter" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Rendering Engine </button>

Rendering Engine

Browser

Platform(s)

Engine Version

CSS Grade

          <input type="text" class="form-control" placeholder="Filter By Rendering Engine..." autocomplete="off" id="filterInput">

        <button class="btn btn-default" type="button" id="deleteRows1">Delete Rows</button>
        <button class="btn btn-default" type="button" id="restoreRows1" disabled>Restore Rows</button>

  <button class="btn btn-link dropdown-toggle" type="button" id="dropdownKebab" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

  </button>

Action

Another action

Something else here

Separated link

          <button class="btn btn-link btn-find" type="button">

          </button>

            <input type="text" class="form-control" id="find" placeholder="Find By Keyword...">

              1 of 3
              <button class="btn btn-link" type="button">

              </button>
              <button class="btn btn-link" type="button">

              </button>
              <button class="btn btn-link btn-find-close" type="button">

              </button>

    </form>

0 Results

Active filters:

Clear All Filters

        0 of 0 selected

      Select all rows<input type="checkbox" id="selectAll" name="selectAll">
      Rendering Engine
      Browser
      Platform(s)
      Engine Version
      CSS Grade
      Actions

<form class="content-view-pf-pagination table-view-pf-pagination clearfix" id="pagination1">

    <select class="selectpicker pagination-pf-pagesize">
      <option value="6">6</option>
      <option value="10" >10</option>
      <option value="15" selected="selected">15</option>
      <option value="25">25</option>
      <option value="50">50</option>
    </select>
    per page

    1-15 of 75

    Current Page
    <input class="pagination-pf-page" type="text" value="1" id="pagination1-page"/>
    of 5

</form>

    Empty State Title

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Learn more about this on the documentation.

    <button class="btn btn-primary btn-lg"> Main Action </button>

    <button class="btn btn-default"> Secondary Action </button> <button class="btn btn-default"> Secondary Action </button> <button class="btn btn-default"> Secondary Action </button>


text:
package amu.saeed.kcminer.old;

import java.util.Arrays;

public class OldCliqueState {
    public int[] clique = null;
    public int[] extension = null;
    public int extSize = 0;

    public OldCliqueState() {}

    final public static OldCliqueState fromInts(int[] array) {
        int index = 0;
        OldCliqueState state = new OldCliqueState();

        int count = array[index++];
        state.clique = Arrays.copyOfRange(array, index, index + count);
        index += count;

        count = array[index++];
        state.extension = Arrays.copyOfRange(array, index, index + count);
        state.extSize = count;
        return state;
    }

    final public long countCliquesRecursive(final int k, final OldGraph graph, final OldCliqueStateManager cliqueMan) {
        long cliqueCount = 0;
        if (clique.length == k)
            cliqueCount = 1L;
        else if (clique.length == k - 1)
            cliqueCount = extSize;
        else {
            int w;
            for (int i = 0; i < extSize; i++) {
                w = extension[i];
                OldCliqueState new_state = cliqueMan.expand(this, w, graph.getNeighbors(w));
                if (new_state.clique.length + new_state.extSize >= k)
                    cliqueCount += new_state.countCliquesRecursive(k, graph, cliqueMan);
            }
        }
        return cliqueCount;
    }

    final public String toString() {
        StringBuilder b = new StringBuilder();
        b.append('[');
        if (clique.length == 0)
            b.append(']');
        else
            for (int i = 0; ; i++) {
                b.append(clique[i]);
                if (i == clique.length - 1) {
                    b.append(']').toString();
                    break;
                }
                b.append(", ");
            }
        b.append("->");
        b.append('[');
        if (extSize == 0)
            b.append(']');
        else
            for (int i = 0; ; i++) {
                b.append(extension[i]);
                if (i == extSize - 1) {
                    b.append(']').toString();
                    break;
                }
                b.append(", ");
            }

        return b.toString();
    }

    public final int[] toIntArray() {
        int[] array = new int[clique.length + extSize + 2];
        int index = 0;
        array[index++] = clique.length;
        for (int x : clique)
            array[index++] = x;
        array[index++] = extSize;
        for (int i = 0; i < extSize; i++)
            array[index++] = extension[i];
        return array;
    }

    private final void expandCliqueAndWriteToStringBuilder(int lastVertex, StringBuilder sb) {
        for (int v : clique)
            sb.append(v).append('\t');
        sb.append(lastVertex).append('\n');
    }

    public final void writeCliqueToStringBuilder(StringBuilder sb) {
        if (clique.length == 0)
            sb.append('\n');
        else
            for (int i = 0; ; i++) {
                sb.append(clique[i]);
                if (i == clique.length - 1) {
                    sb.append('\n');
                    break;
                }
                sb.append('\t');
            }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.

Copyright (C) 2007-2015  Dirk Beyer
All rights reserved.

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

# prepare for Python 3
from __future__ import absolute_import, division, print_function, unicode_literals

import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from subprocess import CalledProcessError
sys.dont_write_bytecode = True # prevent creation of .pyc files

here = os.path.dirname(__file__)
base_dir = os.path.join(here, '..')
bin_dir = os.path.join(base_dir, 'bin')
benchexec = os.path.join(bin_dir, 'benchexec')
result_dtd = os.path.join(base_dir, 'doc', 'result.dtd')
result_dtd_public_id = '+//IDN sosy-lab.org//DTD BenchExec result 1.2//EN'

benchmark_test_file = os.path.join(base_dir, 'doc', 'benchmark-example-rand.xml')
benchmark_test_tasks = ['DTD files', 'Markdown files', 'XML files', 'Dummy tasks']

class BenchExecIntegrationTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.longMessage = True
        cls.maxDiff = None

    def setUp(self):
        self.tmp = tempfile.mkdtemp(prefix="BenchExec.benchexec.integration_test")

    def tearDown(self):
        shutil.rmtree(self.tmp)

    def run_cmd(self, *args):
        try:
            output = subprocess.check_output(args=args, stderr=subprocess.STDOUT).decode()
        except CalledProcessError as e:
            print(e.output.decode())
            raise e
        print(output)
        return output

    def run_benchexec_and_compare_expected_files(self, *args, tasks=benchmark_test_tasks, name=None):
        self.run_cmd(*[benchexec, benchmark_test_file,
                       '--outputpath', self.tmp,
                       '--startTime', '2015-01-01 00:00',
                       ] + list(args))
        generated_files = set(os.listdir(self.tmp))

        expected_files = ['logfiles', 'results.txt', 'results.xml'] \
                       + ['results.'+files+'.xml' for files in tasks]
        if name is None:
            basename = 'benchmark-example-rand.2015-01-01_0000.'
        else:
            basename = 'benchmark-example-rand.' + name + '.2015-01-01_0000.'
        expected_files = set(map(lambda x : basename + x, expected_files))
        self.assertSetEqual(generated_files, expected_files, 'Set of generated files differs from set of expected files')
        # TODO find way to compare expected output to generated output

    def test_simple(self):
        self.run_benchexec_and_compare_expected_files()

    def test_simple_select_tasks(self):
        self.run_benchexec_and_compare_expected_files('--tasks', 'DTD files',
                                                      '--tasks', 'XML files',
                                                      tasks=['DTD files', 'XML files'])

    def test_simple_set_name(self):
        test_name = 'integration test'
        self.run_benchexec_and_compare_expected_files('--name', test_name, name=test_name)

    def test_simple_parallel(self):
        self.run_benchexec_and_compare_expected_files('--numOfThreads', '12')

    def test_validate_result_xml(self):
        self.run_cmd(benchexec, benchmark_test_file,
                     '--outputpath', self.tmp,
                     '--startTime', '2015-01-01 00:00',
                     )
        basename = 'benchmark-example-rand.2015-01-01_0000.'
        xml_files = ['results.xml'] + ['results.'+files+'.xml' for files in benchmark_test_tasks]
        xml_files = map(lambda x : os.path.join(self.tmp, basename + x), xml_files)

        # setup parser with DTD validation
        from lxml import etree
        class DTDResolver(etree.Resolver):
            def resolve(self, url, public_id, context):
                if public_id == result_dtd_public_id:
                    return self.resolve_filename(result_dtd, context)
                return None
        parser = etree.XMLParser(dtd_validation=True)
        parser.resolvers.add(DTDResolver())

        for xml_file in xml_files:
            etree.parse(xml_file, parser=parser)


text:
<?php

namespace OLAP;

class Fact extends Model {

    const PREFIX = 'fact_';

    /**
     * @var Dimension[]
     */
    private $dimensions = [];

    /**
     * @var Type
     */
    private $dataType;

    public function __construct($name, $dimensions = [], $options = []) {

        $this->name = $name;
        foreach ($dimensions as $dimension) {
            if (is_array($dimension) && !empty($dimension['name']) && !empty($dimension['type'])) {
                $dimension = new Dimension(
                    $dimension['name'],
                    $dimension['type'],
                    array_diff_key( $dimension, array_flip(['name', 'type']) )
                );
            }
            if ($dimension instanceof Dimension) {
                $this->dimensions[strtolower($dimension->getName())] = $dimension;
            } else {
                throw new Exception('Bad fact format');
            }
        }
        $this->options = $options;
    }

    /**
     * @return Dimension[]
     */
    public function getDimensions() {

        return $this->dimensions;
    }

    /**
     * @param $name
     * @return Dimension
     */
    public function getDimension($name) {

        return empty($this->dimensions[$name]) ? false : $this->dimensions[$name];
    }

    /**
     * @return Type
     */
    public function getDataType() {

        return $this->dataType;
    }

    /**
     * @return string
     */
    public function getParent() {

        $parent = $this->getOption('parent', null);
        return $parent ? $this->makeName($parent) : null;
    }

    public function isSpecial() {

        return $this->getOption('special', false);
    }

    /**
     * @return bool
     */
    public function isDefaultDrill() {

        return (bool)$this->getOption('default_drill', false);
    }

    /**
     * @param string $drill
     * @return bool
     */
    public function isDrill($drill) {

        return $this->name === $drill;
    }

    protected function makeName($name) {

        return self::PREFIX . $this->getOption('cube_name', 'cube') . '_' . $name;
    }
}


text: require 'modernizr-rails'


text:
//
//  FMDatabaseQueue.m
//  fmdb
//
//  Created by August Mueller on 6/22/11.
//  Copyright 2011 Flying Meat Inc. All rights reserved.
//

#import "FMDatabaseQueue.h"
#import "FMDatabase.h"

/*

 Note: we call [self retain]; before using dispatch_sync, just incase
 FMDatabaseQueue is released on another thread and we're in the middle of doing
 something in dispatch_sync

 */

@implementation FMDatabaseQueue

@synthesize path = _path;

+ (instancetype)databaseQueueWithPath:(NSString*)aPath {

    FMDatabaseQueue *q = [[self alloc] initWithPath:aPath];

    FMDBAutorelease(q);

    return q;
}

- (instancetype)initWithPath:(NSString*)aPath {

    self = [super init];

    if (self != nil) {

        _db = [FMDatabase databaseWithPath:aPath];
        FMDBRetain(_db);

        if (![_db open]) {
            NSLog(@"Could not create database queue for path %@", aPath);
            FMDBRelease(self);
            return 0x00;
        }

        _path = FMDBReturnRetained(aPath);

        _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
    }

    return self;
}

- (void)dealloc {

    FMDBRelease(_db);
    FMDBRelease(_path);

    if (_queue) {
        FMDBDispatchQueueRelease(_queue);
        _queue = 0x00;
    }
#if ! __has_feature(objc_arc)
    [super dealloc];
#endif
}

- (void)close {
    FMDBRetain(self);
    dispatch_sync(_queue, ^() {
        [_db close];
        FMDBRelease(_db);
        _db = 0x00;
    });
    FMDBRelease(self);
}

- (FMDatabase*)database {
    if (!_db) {
        _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]);

        if (![_db open]) {
            NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path);
            FMDBRelease(_db);
            _db  = 0x00;
            return 0x00;
        }
    }

    return _db;
}

- (void)inDatabase:(void (^)(FMDatabase *db))block {
    FMDBRetain(self);

    dispatch_sync(_queue, ^() {

        FMDatabase *db = [self database];
        block(db);

        if ([db hasOpenResultSets]) {
            NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]");
        }
    });

    FMDBRelease(self);
}

- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
    FMDBRetain(self);
    dispatch_sync(_queue, ^() {

        BOOL shouldRollback = NO;

        if (useDeferred) {
            [[self database] beginDeferredTransaction];
        }
        else {
            [[self database] beginTransaction];
        }

        block([self database], &shouldRollback);

        if (shouldRollback) {
            [[self database] rollback];
        }
        else {
            [[self database] commit];
        }
    });

    FMDBRelease(self);
}

- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
    [self beginTransaction:YES withBlock:block];
}

- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
    [self beginTransaction:NO withBlock:block];
}

#if SQLITE_VERSION_NUMBER >= 3007000
- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block {

    static unsigned long savePointIdx = 0;
    __block NSError *err = 0x00;
    FMDBRetain(self);
    dispatch_sync(_queue, ^() {

        NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];

        BOOL shouldRollback = NO;

        if ([[self database] startSavePointWithName:name error:&err]) {

            block([self database], &shouldRollback);

            if (shouldRollback) {
                [[self database] rollbackToSavePointWithName:name error:&err];
            }
            else {
                [[self database] releaseSavePointWithName:name error:&err];
            }

        }
    });
    FMDBRelease(self);
    return err;
}
#endif

@end


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Serverless\V1\Service;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\ListResource;
use Twilio\Rest\Serverless\V1\Service\Environment\DeploymentList;
use Twilio\Rest\Serverless\V1\Service\Environment\LogList;
use Twilio\Rest\Serverless\V1\Service\Environment\VariableList;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
 *
 * @property VariableList $variables
 * @property DeploymentList $deployments
 * @property LogList $logs
 * @method \Twilio\Rest\Serverless\V1\Service\Environment\VariableContext variables(string $sid)
 * @method \Twilio\Rest\Serverless\V1\Service\Environment\DeploymentContext deployments(string $sid)
 * @method \Twilio\Rest\Serverless\V1\Service\Environment\LogContext logs(string $sid)
 */
class EnvironmentContext extends InstanceContext {
    protected $_variables;
    protected $_deployments;
    protected $_logs;

    /**
     * Initialize the EnvironmentContext
     *
     * @param Version $version Version that contains the resource
     * @param string $serviceSid The SID of the Service to fetch the Environment
     *                           resource from
     * @param string $sid The SID of the Environment resource to fetch
     */
    public function __construct(Version $version, $serviceSid, $sid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = ['serviceSid' => $serviceSid, 'sid' => $sid, ];

        $this->uri = '/Services/' . \rawurlencode($serviceSid) . '/Environments/' . \rawurlencode($sid) . '';
    }

    /**
     * Fetch the EnvironmentInstance
     *
     * @return EnvironmentInstance Fetched EnvironmentInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): EnvironmentInstance {
        $payload = $this->version->fetch('GET', $this->uri);

        return new EnvironmentInstance(
            $this->version,
            $payload,
            $this->solution['serviceSid'],
            $this->solution['sid']
        );
    }

    /**
     * Delete the EnvironmentInstance
     *
     * @return bool True if delete succeeds, false otherwise
     * @throws TwilioException When an HTTP error occurs.
     */
    public function delete(): bool {
        return $this->version->delete('DELETE', $this->uri);
    }

    /**
     * Access the variables
     */
    protected function getVariables(): VariableList {
        if (!$this->_variables) {
            $this->_variables = new VariableList(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['sid']
            );
        }

        return $this->_variables;
    }

    /**
     * Access the deployments
     */
    protected function getDeployments(): DeploymentList {
        if (!$this->_deployments) {
            $this->_deployments = new DeploymentList(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['sid']
            );
        }

        return $this->_deployments;
    }

    /**
     * Access the logs
     */
    protected function getLogs(): LogList {
        if (!$this->_logs) {
            $this->_logs = new LogList($this->version, $this->solution['serviceSid'], $this->solution['sid']);
        }

        return $this->_logs;
    }

    /**
     * Magic getter to lazy load subresources
     *
     * @param string $name Subresource to return
     * @return ListResource The requested subresource
     * @throws TwilioException For unknown subresources
     */
    public function __get(string $name): ListResource {
        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown subresource ' . $name);
    }

    /**
     * Magic caller to get resource contexts
     *
     * @param string $name Resource to return
     * @param array $arguments Context parameters
     * @return InstanceContext The requested resource context
     * @throws TwilioException For unknown resource
     */
    public function __call(string $name, array $arguments): InstanceContext {
        $property = $this->$name;
        if (\method_exists($property, 'getContext')) {
            return \call_user_func_array(array($property, 'getContext'), $arguments);
        }

        throw new TwilioException('Resource does not have a context');
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Serverless.V1.EnvironmentContext ' . \implode(' ', $context) . ']';
    }
}


text:
package org.apache.derby.client.net;

import java.sql.SQLException;
import java.sql.SQLType;
import org.apache.derby.client.am.Cursor;
import org.apache.derby.client.am.SqlException;
import org.apache.derby.client.am.Utils42;

class NetResultSet42 extends NetResultSet
{

    NetResultSet42(NetAgent netAgent,
        NetStatement netStatement,
        Cursor cursor,
        int qryprctyp,  //protocolType, CodePoint.FIXROWPRC |
                        //              CodePoint.LMTBLKPRC
        int sqlcsrhld, // holdOption, 0xF0 for false (default) | 0xF1 for true.
        int qryattscr, // scrollOption, 0xF0 for false (default) | 0xF1 for true.
        int qryattsns, // sensitivity, CodePoint.QRYUNK |
                       //              CodePoint.QRYINS |
                       //              CodePoint.QRYSNSSTC
        int qryattset, // rowsetCursor, 0xF0 for false (default) | 0xF1 for true.
        long qryinsid, // instanceIdentifier, 0 (if not returned, check default) or number
        int actualResultSetType,
        int actualResultSetConcurrency,
        int actualResultSetHoldability) //throws DisconnectException
    {
        super(netAgent, netStatement, cursor, qryprctyp, sqlcsrhld, qryattscr,
              qryattsns, qryattset, qryinsid, actualResultSetType,
              actualResultSetConcurrency, actualResultSetHoldability);
    }

    public void updateObject
        ( int columnIndex, Object x, SQLType targetSqlType )
        throws SQLException
    {
        checkClosed( "updateObject" );
        updateObject( columnIndex, x, Utils42.getTypeAsInt( this.agent_, targetSqlType ) );
    }

    public void updateObject
        ( int columnIndex, Object x, SQLType targetSqlType, int scaleOrLength )
        throws SQLException
    {
        checkClosed( "updateObject" );
        updateObject( columnIndex, x, Utils42.getTypeAsInt( this.agent_, targetSqlType ) );
        // the client driver doesn't seem to adjust the scale, unlike the embedded driver
    }

    public void updateObject
        ( String columnName, Object x, SQLType targetSqlType )
        throws SQLException
    {
        checkClosed( "updateObject" );
        updateObject( columnName, x, Utils42.getTypeAsInt( this.agent_, targetSqlType ) );
    }

    public void updateObject
        ( String columnName, Object x, SQLType targetSqlType, int scaleOrLength )
        throws SQLException
    {
        checkClosed( "updateObject" );
        try {
            updateObject( findColumnX( columnName, "updateObject" ), x, targetSqlType, scaleOrLength );
        } catch (SqlException se) { throw se.getSQLException(); }
    }

    private void    checkClosed( String methodName )
        throws SQLException
    {
        try { checkForClosedResultSet( methodName ); } catch (SqlException se)
        { throw se.getSQLException(); }
    }

}


text:
var _ = require('underscore');
var $ = require('jquery');
var	Backbone = require('backbone');
var ListView = require('../../base/ListView');
var config = require('../../conf');

Backbone.$ = $;

//** Category模型
var Category = Backbone.Model.extend({
	idAttribute: '_id',
	urlRoot: config.api.host + '/public/product/categories',
	defaults: {
	},
});
//** Product模型
var Product = Backbone.Model.extend({
	idAttribute: '_id',
	urlRoot: config.api.host + '/public/products1',
	defaults: {
		goods: {},
		bonus: {
			income: 0,
			times: 1,
		},
	},
	parse: function(response){
		if(response.stack && response.name && response.message){
			return window.location.hash = 'notFound';
		}
		return response;
	},
});

//** Product集合
var ProductCollection = Backbone.Collection.extend({
	model: Product,
	url: config.api.host + '/public/products1',
});

//** 列表子视图
var ProductListView = ListView.extend({
	el: '#list',
	template: _.template($('#tpl-product-item').html()),

	initialize: function(options){
		this.collection = new ProductCollection();
		ListView.prototype.initialize.apply(this,options);
	},
	getNewItemView: function(model){
		var item = this.template({model: model.toJSON()});
		var $item = $(item);
		$item.find('img').attr('src', model.get('thumbnail_url'));
		return $item.html();
	},
});

exports = module.exports = Backbone.View.extend({

	el: '#content',
	template: _.template($('#tpl-category-product-index').html()),

	initialize: function(options) {
		this.router = options.router;
		this.model = new Category({_id: options.id});
		this.model.on('change', this.modelChanged, this);
		this.on('load', this.load, this);
	},

	events: {
		'scroll': 'scroll',
		'click .back': 'back',
		'click .search': 'search',
		'click .order': 'productOrder',
		'click .recommend': 'productRecommend',
		'click .wechat': 'wechat',
		'click .sms': 'sms',
	},

	load: function() {
		var that = this;
		this.loaded = true;
		this.model.fetch({
			xhrFields: {
				withCredentials: true
			},
		});
	},

	modelChanged: function(){
		this.render();
		this.listView = new ProductListView({
			el: '#list',
		});
		this.listView.collection.url = config.api.host + '/public/products1?action=category&category=' + encodeURIComponent(this.model.get('name')) + '&uid=' + encodeURIComponent((this.router && this.router.account && this.router.account.email) || '');
		this.listView.trigger('load');
	},

	scroll: function() {
		if(this.listView) this.listView.scroll();
		return false;
	},
	back: function(){
		this.router.navigate('category/index',{trigger: true, replace: true});
		return false;
	},

	search: function(){
		this.$('#search').show();
		return false;
	},

	productOrder: function(evt){
		var id = this.$(evt.currentTarget).closest('.item').attr('id');
		this.router.navigate('product/order/'+ id,{trigger: true});
		return false;
	},

	productRecommend: function(evt){
		var id = this.$(evt.currentTarget).closest('.item').attr('id');
		this.router.navigate('product/recommend/'+ id,{trigger: true});
		return false;
	},

	wechat: function(evt){
		var id = this.$(evt.currentTarget).closest('.item').attr('id');
		window.location.href = config.api.host + '/sns/weixin/share/' + config.wechat.appid + '/' + id + '/' + this.router.account.id;
		return false;
	},

	sms: function(evt){
		var id = this.$(evt.currentTarget).closest('.item').attr('id');
		var productName = this.$(evt.currentTarget).closest('.item').attr('data');
		$.ajax({
			url: config.api.host + '/s', //** 短连接地址
			type: 'POST',
			xhrFields: {
				withCredentials: true
			},
			data: {
				original: config.api.host + '/sns/web/sale/' + id + '/' + this.router.account.id,
			},
			crossDomain: true,
		}).done(function(data) {
			var shortCode = data.shortCode;
			var smsBody = '贵州联通沃产品有礼了:' + productName + '产品抢先订。' + config.api.host + '/s/' + shortCode;
			if(/iPhone/.test(navigator.userAgent)){
				window.location.href="sms:sms:&body=" + smsBody;
			}else{
				window.location.href="sms:?body=" + smsBody;
			}
		});
		return false;
	},

	render: function() {
		this.$el.html(this.template({model: this.model.toJSON()}));
		return this;
	},
});


text:
module PageHelper

  def ensure_path path
    expect(page.current_path).to eq path
  end
  def visit_path path
    visit path
    expect(status_code).to be 200
    expect(page).not_to have_css(".translation_missing")
    ensure_path path
  end

  def ensure_clerk
    clerk = Clerk.first
    clerk = create :clerk unless clerk
    expect(clerk).not_to be nil
    clerk
  end

  def sign_in
    clerk = ensure_clerk
    visit OfficeClerk::Engine.routes.url_helpers.sign_in_path
    fill_in "email" , :with => clerk.email
    fill_in "password" , :with => "password"
    click_button I18n.t(:sign_in)
    expect(page).to have_content I18n.t(:basket)
    clerk
  end

  def expect_basket_total price
    expect(find(".total").text).to include( price.round(2).to_s.sub(".",",")) # TODO remove the format hack
  end
end
RSpec.configure do |config|
  config.include PageHelper
end


text:
"use strict";

const COLON               = Symbol.for('COLON');
const NAME                = Symbol.for('NAME');
const ASTERISK            = Symbol.for('ASTERISK');
const COMMENT             = Symbol.for('COMMENT');
const COMMA               = Symbol.for('COMMA');
const EXCLAMATION         = Symbol.for('EXCLAMATION');
const SEMICOLON           = Symbol.for('SEMICOLON');
const EQUALS              = Symbol.for('EQUALS');
const CLOSE_CURLY_BRACKET = Symbol.for('CLOSE_CURLY_BRACKET');
const EOF                 = Symbol.for('EOF');

const stylecow = require('../index');

stylecow.Declaration = class Declaration extends require('./classes/node-collection-vendor') {

    static create (reader, parent) {
        let element;

        if (reader.currToken === NAME) {
            element = (new stylecow.Declaration(reader.data())).setNameWithVendor(reader.getStringAndMove());
        } else if (reader.currToken === ASTERISK && reader.nextToken === NAME) { //ie
            reader.move();
            element = (new stylecow.Declaration(reader.data())).setNameWithVendor('*' + reader.getStringAndMove());
        } else {
            return;
        }

        reader.skipAll(COMMENT);
        reader.skip(COLON) || reader.error();

        //ms filter
        //Search by "=" before ";" to detect if it's a ms filter
        if (element.name === 'filter' && (element.vendor === 'ms' || reader.searchNext([CLOSE_CURLY_BRACKET, SEMICOLON, EQUALS, EOF]) === EQUALS)) {
            element.vendor = 'ms';

            const value = new stylecow.Value(reader.data());
            element.push(value);

            if (reader.currToken === NAME && reader.currStr === 'none') {
                value.push(stylecow.Keyword.create(reader, element) || reader.error());
            } else {
                const filter = (new stylecow.String(reader.data())).setName('');

                value.push(filter);

                do {
                    if (reader.currToken !== COMMENT) {
                        filter.name += reader.currStr;
                    }
                } while (reader.move() && reader.currToken !== SEMICOLON && reader.currToken !== CLOSE_CURLY_BRACKET);
            }
        } else {
            do {
                element.push(stylecow.Value.create(reader, element) || reader.error());

            } while (reader.skip(COMMA));
        }

        if (reader.currToken === EXCLAMATION) {
            element.push(stylecow.Bang.create(reader, element) || reader.error());
        }

        reader.skip(SEMICOLON);

        return element;
    }

    constructor(data) {
        super(data, 'Declaration');
    }

    toString () {
        let string = this.getNameWithVendor() + ': ' + this.getChildren('Value').join(', ');

        if (this.hasChild('Bang')) {
            string += ' ' + this.getChild('Bang');
        }

        return string + ';';
    }

    toCode (code) {
        code.appendStyle('declaration-before');
        code.append(this.getNameWithVendor(), this);
        code.appendStyle('declaration-colon-before');
        code.append(':');
        code.appendStyle('declaration-colon-after');

        const values = this.getChildren('Value');
        const latest = values.length - 1;

        values.forEach(function (child, k) {
            child.toCode(code);

            if (k !== latest) {
                code.appendStyle('declaration-comma-before');
                code.append(',');
                code.appendStyle('declaration-comma-after');
            }
        });

        if (this.hasChild('Bang')) {
            code.append(' ');
            this.getChild('Bang').toCode(code);
        }

        code.append(';');
        code.appendStyle('declaration-after');
    }
}


text:
package natlab;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.framework.TestCase;
import beaver.Scanner;
import beaver.Symbol;

/**
 * Parent class of the generated NatlabScannerTests class.
 * Provides helper methods to keep NatlabScannerTests short.
 */
class ScannerTestBase extends TestCase {
	private static final Pattern SYMBOL_PATTERN = Pattern.compile("^\\s*([_A-Z]+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*(?:\\s(\\d+))?\\s*(?:\\s=(.*))?$");

	/* Compare the output of the scanner with a list of expected symbols and an optional exception. */
	static void checkScan(NatlabScanner scanner, List<Symbol> symbols, List<Symbol> comments, Scanner.Exception exception)
			throws IOException, Scanner.Exception {
		int tokenNum = 0;
		for(Symbol expected : symbols) {
			try {
				Symbol actual = scanner.nextToken();
				assertEquals("Token #" + tokenNum, actual, expected);
				tokenNum++;
			} catch(Scanner.Exception e) {
				assertEquals(e.getMessage(), e, exception);
				return;
			}
		}
		try {
			short actualId = scanner.nextToken().getId();
			short expectedId = NatlabParser.Terminals.EOF;
			if(actualId != expectedId) {
				fail("Token #" + tokenNum + ": incorrect token type - " +
						"expected: " + expectedId + " (" + NatlabParser.Terminals.NAMES[expectedId] + ") " +
						"but was: " + actualId + " (" + NatlabParser.Terminals.NAMES[actualId] + ")");
			}
		} catch(Scanner.Exception e) {
			assertEquals(e.getMessage(), e, exception);
		}
		List<Symbol> actualComments = scanner.getCommentBuffer().pollAllComments();
		assertEquals("Number of comments: ", comments.size(), actualComments.size());
		for(int commentNum = 0; commentNum < comments.size(); commentNum++) {
			assertEquals("Comment #" + commentNum + ": ", actualComments.get(commentNum), comments.get(commentNum));
		}
	}

	/* Construct a scanner that will read from the specified file. */
	static NatlabScanner getScanner(String filename) throws FileNotFoundException {
		return new NatlabScanner(new BufferedReader(new FileReader(filename)));
	}

	/*
	 * Read symbols from the .out file.
	 * Returns an exception if there is an exception line and null otherwise.
	 */
	static Scanner.Exception parseSymbols(String filename, /*OUT*/ List<Symbol> symbols, /*OUT*/ List<Symbol> comments)
			throws IOException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
		BufferedReader in = new BufferedReader(new FileReader(filename));
		while(in.ready()) {
			String line = in.readLine();
			if(isExceptionLine(line)) {
				return parseException(line);
			}
			if(isCommentLine(line)) {
				comments.add(parseComment(line));
			} else {
				symbols.add(parseSymbol(line));
			}
		}
		in.close();
		return null;
	}

	/* Returns true if the line should be treated as an exception line. */
	private static boolean isExceptionLine(String line) {
		return line.charAt(0) == '~';
	}

	/*
	 * Constructs a Scanner.Exception from a line of text.
	 * Format:
	 *   ~ start_line start_col
	 */
	private static Scanner.Exception parseException(String line) {
		StringTokenizer tokenizer = new StringTokenizer(line.substring(1));
		assertEquals("Number of tokens in exception line: " + line, 2, tokenizer.countTokens());
		int lineNum = Integer.parseInt(tokenizer.nextToken());
		int colNum = Integer.parseInt(tokenizer.nextToken());
		return new Scanner.Exception(lineNum, colNum, null);
	}

	/* Returns true if the line should be treated as a non-token comment line. */
	private static boolean isCommentLine(String line) {
		return line.charAt(0) == '#';
	}

	/*
	 * Constructs a Symbol from a line of text.
	 * Format:
	 *   # TYPE start_line start_col length [=value]
	 *   e.g. # FOR 2 1 3
	 *        # IDENTIFIER 3 2 1 =x
	 */
	private static Symbol parseComment(String line)
			throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
		return parseSymbol(line.substring(1));
	}

	/*
	 * Constructs a Symbol from a line of text.
	 * Format:
	 *   TYPE start_line start_col length [=value]
	 *   e.g. FOR 2 1 3
	 *        IDENTIFIER 3 2 1 =x
	 */
	private static Symbol parseSymbol(String line)
			throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
		Matcher matcher = SYMBOL_PATTERN.matcher(line);
		if(!matcher.matches()) {
			fail("Invalid line: " + line);
		}
		String idString = matcher.group(1);
		short id = NatlabParser.Terminals.class.getField(idString).getShort(null); //null since the field is static
		int lineNum = Integer.parseInt(matcher.group(2));
		int colNum = Integer.parseInt(matcher.group(3));
		String value = matcher.group(6);
		if(matcher.group(5) == null) {
			int length = Integer.parseInt(matcher.group(4));
			return new Symbol(id, lineNum, colNum, length, value);
		} else {
			int endLine = Integer.parseInt(matcher.group(4));
			int endCol = Integer.parseInt(matcher.group(5));
			int startPos = Symbol.makePosition(lineNum, colNum);
			int endPos = Symbol.makePosition(endLine, endCol);
			return new Symbol(id, startPos, endPos, value);
		}
	}

	/* Checks deep equality of two Symbols (complexity comes from giving nice error messages). */
	public static void assertEquals(String msg, Symbol actual, Symbol expected) {
		final short expectedId = expected.getId();
		final short actualId = actual.getId();
		if(actualId != expectedId) {
			fail(msg + ": incorrect token type - " +
					"expected: " + expectedId + " (" + NatlabParser.Terminals.NAMES[expectedId] + ") " +
					"but was: " + actualId + " (" + NatlabParser.Terminals.NAMES[actualId] + ")");
		}
		final String expectedValue = (String) expected.value;
		final String actualValue = ScannerTestTool.stringifyValue(actual.value);
		if(((actualValue == null || expectedValue == null) && (actualValue != expectedValue)) ||
				(actualValue != null && !actualValue.equals(expectedValue))) {
			fail(msg + " - " + NatlabParser.Terminals.NAMES[actualId] + ": incorrect token value - " +
					"expected: " + expectedValue + " " +
					"but was: " + actualValue);

		}
		final int expectedStart = expected.getStart();
		final int actualStart = actual.getStart();
		if(actualStart != expectedStart) {
			fail(msg + " - " + getSymbolString(actual) + ": incorrect start position - " +
					"expected: line " + Symbol.getLine(expectedStart) + " col " + Symbol.getColumn(expectedStart) + " " +
					"but was: line " + Symbol.getLine(actualStart) + " col " + Symbol.getColumn(actualStart));
		}
		final int expectedEnd = expected.getEnd();
		final int actualEnd = actual.getEnd();
		if(actualEnd != expectedEnd) {
			fail(msg + " - " + getSymbolString(actual) + ": incorrect end position - " +
					"expected: line " + Symbol.getLine(expectedEnd) + " col " + Symbol.getColumn(expectedEnd) + " " +
					"but was: line " + Symbol.getLine(actualEnd) + " col " + Symbol.getColumn(actualEnd));
		}
	}

	/* Checks deep equality of two Scanner.Exceptions. */
	public static void assertEquals(String msg, Scanner.Exception actual, Scanner.Exception expected) {
		if(actual == null) {
			if(expected == null) {
				return;
			} else {
				fail("Actual exception was unexpectedly null (expected: [" + actual.line + ", " + actual.column + "] " + expected + ")");
			}
		} else if(expected == null) {
			fail("Unexpected exception: [" + actual.line + ", " + actual.column + "] " + actual);
		}
		assertEquals(msg + " - exception line number", actual.line, expected.line);
		assertEquals(msg + " - exception column number", actual.column, expected.column);
	}

	/* Returns a pretty-printed version of a Symbol. */
	protected static String getSymbolString(Symbol symbol) {
		return NatlabParser.Terminals.NAMES[symbol.getId()] + (symbol.value == null ? "" : "(" + symbol.value + ")");
	}
}


text:
/**
 * Fake ORM to use for migrations
 */
export default function Store() {
  const store = {
    logs: [],
  };

  /**
   * Get the value at the specified key
   * @param  {Strig} key
   * @return {Promise} promise
   */
  this.get = key => new Promise((resolve) => {
    setImmediate(() => {
      resolve(store[key]);
    });
  });

  /**
   * Add entry to logs
   * @param  {Object} args
   * @param  {String} args.version
   * @param  {String} args.direction
   * @param  {String} args.event
   * @return {Promise} promise
   */
  this.log = ({ version, direction, event }) => new Promise((resolve) => {
    setImmediate(() => {
      store.logs.push({ version, direction, event });
      resolve();
    });
  });

  /**
   * Set the value at the specified key
   * @param  {String} key
   * @param  {*} val
   * @return {Promise} promise
   */
  this.set = (key, val) => new Promise((resolve) => {
    setImmediate(() => {
      store[key] = val;
      resolve();
    });
  });
}


text:
using System;
using System.Threading;

//Jeffrey Richter - Concurrent Affairs

namespace FluorineFx.Util
{
    internal class AsyncResultNoResult : IAsyncResult
    {
        // Fields set at construction which never change while operation is pending
        private readonly AsyncCallback _asyncCallback;
        private readonly Object _asyncState;

        // Fields set at construction which do change after operation completes
        private const Int32 StatePending = 0;
        private const Int32 StateCompletedSynchronously = 1;
        private const Int32 StateCompletedAsynchronously = 2;
        private Int32 _completedState = StatePending;

        // Field that may or may not get set depending on usage
#if NET_1_1
		private object _asyncWaitHandle;
#else
        private ManualResetEvent _asyncWaitHandle;
#endif

        // Fields set when operation completes
        private Exception _exception;

        public AsyncResultNoResult(AsyncCallback asyncCallback, Object state)
        {
            _asyncCallback = asyncCallback;
            _asyncState = state;
        }

        public void SetAsCompleted(Exception exception, Boolean completedSynchronously)
        {
            // Passing null for exception means no error occurred.
            // This is the common case
            _exception = exception;

            // The m_CompletedState field MUST be set prior calling the callback
            Int32 prevState = Interlocked.Exchange(ref _completedState, completedSynchronously ? StateCompletedSynchronously : StateCompletedAsynchronously);
            if (prevState != StatePending)
                throw new InvalidOperationException("You can set a result only once");

            // If the event exists, set it
            if (_asyncWaitHandle != null)
#if NET_1_1
				(_asyncWaitHandle as ManualResetEvent).Set();
#else
				_asyncWaitHandle.Set();
#endif

            // If a callback method was set, call it
            if (_asyncCallback != null) _asyncCallback(this);
        }

        public void EndInvoke()
        {
            // This method assumes that only 1 thread calls EndInvoke
            // for this object
            if (!IsCompleted)
            {
                // If the operation isn't done, wait for it
                AsyncWaitHandle.WaitOne();
                AsyncWaitHandle.Close();
                _asyncWaitHandle = null;  // Allow early GC
            }

            // Operation is done: if an exception occured, throw it
            if (_exception != null) throw _exception;
        }

        #region Implementation of IAsyncResult

        public Object AsyncState { get { return _asyncState; } }

        public Boolean CompletedSynchronously
        {
            get
            {
#if SILVERLIGHT
                return _completedState == StateCompletedSynchronously;
#else
                return Thread.VolatileRead(ref _completedState) == StateCompletedSynchronously;
#endif
            }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                if (_asyncWaitHandle == null)
                {
                    Boolean done = IsCompleted;
                    ManualResetEvent mre = new ManualResetEvent(done);
                    if (Interlocked.CompareExchange(ref _asyncWaitHandle, mre, null) != null)
                    {
                        // Another thread created this object's event; dispose
                        // the event we just created
                        mre.Close();
                    }
                    else
                    {
                        if (!done && IsCompleted)
                        {
                            // If the operation wasn't done when we created
                            // the event but now it is done, set the event
#if NET_1_1
							(_asyncWaitHandle as ManualResetEvent).Set();
#else
							_asyncWaitHandle.Set();
#endif
                        }
                    }
                }
#if NET_1_1
				return _asyncWaitHandle as ManualResetEvent;
#else
				return _asyncWaitHandle;
#endif
			}
        }

        public Boolean IsCompleted
        {
            get
            {
#if SILVERLIGHT
                return _completedState != StatePending;
#else
                return Thread.VolatileRead(ref _completedState) != StatePending;
#endif
            }
        }
        #endregion
    }
}


text:
package org.elasticsearch.xpack.sql.execution.search.extractor;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.sql.SqlException;
import org.elasticsearch.xpack.sql.type.DataType;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
import static org.hamcrest.Matchers.is;

public class FieldHitExtractorTests extends AbstractWireSerializingTestCase<FieldHitExtractor> {
    public static FieldHitExtractor randomFieldHitExtractor() {
        String hitName = randomAlphaOfLength(5);
        String name = randomAlphaOfLength(5) + "." + hitName;
        return new FieldHitExtractor(name, null, randomBoolean(), hitName);
    }

    @Override
    protected FieldHitExtractor createTestInstance() {
        return randomFieldHitExtractor();
    }

    @Override
    protected Reader<FieldHitExtractor> instanceReader() {
        return FieldHitExtractor::new;
    }

    @Override
    protected FieldHitExtractor mutateInstance(FieldHitExtractor instance) throws IOException {
        return new FieldHitExtractor(instance.fieldName() + "mutated", null, true, instance.hitName());
    }

    public void testGetDottedValueWithDocValues() {
        String grandparent = randomAlphaOfLength(5);
        String parent = randomAlphaOfLength(5);
        String child = randomAlphaOfLength(5);
        String fieldName = grandparent + "." + parent + "." + child;

        FieldHitExtractor extractor = new FieldHitExtractor(fieldName, null, true);

        int times = between(1, 1000);
        for (int i = 0; i < times; i++) {

            List<Object> documentFieldValues = new ArrayList<>();
            if (randomBoolean()) {
                documentFieldValues.add(randomValue());
            }

            SearchHit hit = new SearchHit(1);
            DocumentField field = new DocumentField(fieldName, documentFieldValues);
            hit.fields(singletonMap(fieldName, field));
            Object result = documentFieldValues.isEmpty() ? null : documentFieldValues.get(0);
            assertEquals(result, extractor.extract(hit));
        }
    }

    public void testGetDottedValueWithSource() throws Exception {
        String grandparent = randomAlphaOfLength(5);
        String parent = randomAlphaOfLength(5);
        String child = randomAlphaOfLength(5);
        String fieldName = grandparent + "." + parent + "." + child;

        FieldHitExtractor extractor = new FieldHitExtractor(fieldName, null, false);

        int times = between(1, 1000);
        for (int i = 0; i < times; i++) {
            /* We use values that are parsed from json as "equal" to make the
             * test simpler. */
            Object value = randomValue();
            SearchHit hit = new SearchHit(1);
            XContentBuilder source = JsonXContent.contentBuilder();
            boolean hasGrandparent = randomBoolean();
            boolean hasParent = randomBoolean();
            boolean hasChild = randomBoolean();
            boolean hasSource = hasGrandparent && hasParent && hasChild;

            source.startObject();
            if (hasGrandparent) {
                source.startObject(grandparent);
                if (hasParent) {
                    source.startObject(parent);
                    if (hasChild) {
                        source.field(child, value);
                        if (randomBoolean()) {
                            source.field(fieldName + randomAlphaOfLength(3), value + randomAlphaOfLength(3));
                        }
                    }
                    source.endObject();
                }
                source.endObject();
            }
            source.endObject();
            BytesReference sourceRef = BytesReference.bytes(source);
            hit.sourceRef(sourceRef);
            Object extract = extractor.extract(hit);
            assertEquals(hasSource ? value : null, extract);
        }
    }

    public void testGetDocValue() {
        String fieldName = randomAlphaOfLength(5);
        FieldHitExtractor extractor = new FieldHitExtractor(fieldName, null, true);

        int times = between(1, 1000);
        for (int i = 0; i < times; i++) {
            List<Object> documentFieldValues = new ArrayList<>();
            if (randomBoolean()) {
                documentFieldValues.add(randomValue());
            }
            SearchHit hit = new SearchHit(1);
            DocumentField field = new DocumentField(fieldName, documentFieldValues);
            hit.fields(singletonMap(fieldName, field));
            Object result = documentFieldValues.isEmpty() ? null : documentFieldValues.get(0);
            assertEquals(result, extractor.extract(hit));
        }
    }

    public void testGetDate() {
        long millis = 1526467911780L;
        List<Object> documentFieldValues = Collections.singletonList(Long.toString(millis));
        SearchHit hit = new SearchHit(1);
        DocumentField field = new DocumentField("my_date_field", documentFieldValues);
        hit.fields(singletonMap("my_date_field", field));
        FieldHitExtractor extractor = new FieldHitExtractor("my_date_field", DataType.DATE, true);
        assertEquals(new DateTime(millis, DateTimeZone.UTC), extractor.extract(hit));
    }

    public void testGetSource() throws IOException {
        String fieldName = randomAlphaOfLength(5);
        FieldHitExtractor extractor = new FieldHitExtractor(fieldName, null, false);

        int times = between(1, 1000);
        for (int i = 0; i < times; i++) {
            /* We use values that are parsed from json as "equal" to make the
             * test simpler. */
            Object value = randomValue();
            SearchHit hit = new SearchHit(1);
            XContentBuilder source = JsonXContent.contentBuilder();
            source.startObject(); {
                source.field(fieldName, value);
                if (randomBoolean()) {
                    source.field(fieldName + "_random_junk", value + "_random_junk");
                }
            }
            source.endObject();
            BytesReference sourceRef = BytesReference.bytes(source);
            hit.sourceRef(sourceRef);
            assertEquals(value, extractor.extract(hit));
        }
    }

    public void testToString() {
        assertEquals("hit.field@hit", new FieldHitExtractor("hit.field", null, true, "hit").toString());
    }

    public void testMultiValuedDocValue() {
        String fieldName = randomAlphaOfLength(5);
        FieldHitExtractor fe = new FieldHitExtractor(fieldName, null, true);
        SearchHit hit = new SearchHit(1);
        DocumentField field = new DocumentField(fieldName, asList("a", "b"));
        hit.fields(singletonMap(fieldName, field));
        SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit));
        assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported"));
    }

    public void testMultiValuedSourceValue() throws IOException {
        String fieldName = randomAlphaOfLength(5);
        FieldHitExtractor fe = new FieldHitExtractor(fieldName, null, false);
        SearchHit hit = new SearchHit(1);
        XContentBuilder source = JsonXContent.contentBuilder();
        source.startObject(); {
            source.field(fieldName, asList("a", "b"));
        }
        source.endObject();
        BytesReference sourceRef = BytesReference.bytes(source);
        hit.sourceRef(sourceRef);
        SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit));
        assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported"));
    }

    public void testSingleValueArrayInSource() throws IOException {
        String fieldName = randomAlphaOfLength(5);
        FieldHitExtractor fe = new FieldHitExtractor(fieldName, null, false);
        SearchHit hit = new SearchHit(1);
        XContentBuilder source = JsonXContent.contentBuilder();
        Object value = randomValue();
        source.startObject(); {
            source.field(fieldName, Collections.singletonList(value));
        }
        source.endObject();
        BytesReference sourceRef = BytesReference.bytes(source);
        hit.sourceRef(sourceRef);
        assertEquals(value, fe.extract(hit));
    }

    public void testExtractSourcePath() {
        FieldHitExtractor fe = new FieldHitExtractor("a.b.c", null, false);
        Object value = randomValue();
        Map<String, Object> map = singletonMap("a", singletonMap("b", singletonMap("c", value)));
        assertThat(fe.extractFromSource(map), is(value));
    }

    public void testExtractSourceIncorrectPath() {
        FieldHitExtractor fe = new FieldHitExtractor("a.b.c.d", null, false);
        Object value = randomNonNullValue();
        Map<String, Object> map = singletonMap("a", singletonMap("b", singletonMap("c", value)));
        SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map));
        assertThat(ex.getMessage(), is("Cannot extract value [a.b.c.d] from source"));
    }

    public void testMultiValuedSource() {
        FieldHitExtractor fe = new FieldHitExtractor("a", null, false);
        Object value = randomValue();
        Map<String, Object> map = singletonMap("a", asList(value, value));
        SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map));
        assertThat(ex.getMessage(), is("Arrays (returned by [a]) are not supported"));
    }

    public Object randomValue() {
        Supplier<Object> value = randomFrom(Arrays.asList(
                () -> randomAlphaOfLength(10),
                ESTestCase::randomLong,
                ESTestCase::randomDouble,
                () -> null));
        return value.get();
    }

    public Object randomNonNullValue() {
        Supplier<Object> value = randomFrom(Arrays.asList(
                () -> randomAlphaOfLength(10),
                ESTestCase::randomLong,
                ESTestCase::randomDouble));
        return value.get();
    }
}


text:
package bd.com.ronnie.lekhoni2.enumeration;

public enum Status {

    ACTIVE, INACTIVE, BLOCKED

}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'plants'
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.TenancyConfig {

  /// Holder for reflection information generated from tenancy_config/default_templates.proto
  public static partial class DefaultTemplatesReflection {

    #region Descriptor
    /// File descriptor for tenancy_config/default_templates.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static DefaultTemplatesReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CiZ0ZW5hbmN5X2NvbmZpZy9kZWZhdWx0X3RlbXBsYXRlcy5wcm90bxIaaG9s",
            "bXMudHlwZXMudGVuYW5jeV9jb25maWcaInByaW1pdGl2ZS90ZW1wbGF0ZV9p",
            "bmRpY2F0b3IucHJvdG8i0wIKEERlZmF1bHRUZW1wbGF0ZXMSVgokcmVzZXJ2",
            "YXRpb25fY29uZmlybWF0aW9uX3RlbXBsYXRlX2lkGAEgASgLMiguaG9sbXMu",
            "dHlwZXMucHJpbWl0aXZlLlRlbXBsYXRlSW5kaWNhdG9yEkwKGmFycml2YWxf",
            "bGV0dGVyX3RlbXBsYXRlX2lkGAIgASgLMiguaG9sbXMudHlwZXMucHJpbWl0",
            "aXZlLlRlbXBsYXRlSW5kaWNhdG9yEk4KHGluZGl2aWR1YWxfZm9saW9fdGVt",
            "cGxhdGVfaWQYAyABKAsyKC5ob2xtcy50eXBlcy5wcmltaXRpdmUuVGVtcGxh",
            "dGVJbmRpY2F0b3ISSQoXZ3JvdXBfZm9saW9fdGVtcGxhdGVfaWQYBCABKAsy",
            "KC5ob2xtcy50eXBlcy5wcmltaXRpdmUuVGVtcGxhdGVJbmRpY2F0b3JCK1oN",
            "dGVuYW5jeWNvbmZpZ6oCGUhPTE1TLlR5cGVzLlRlbmFuY3lDb25maWdiBnBy",
            "b3RvMw=="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.TemplateIndicatorReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.DefaultTemplates), global::HOLMS.Types.TenancyConfig.DefaultTemplates.Parser, new[]{ "ReservationConfirmationTemplateId", "ArrivalLetterTemplateId", "IndividualFolioTemplateId", "GroupFolioTemplateId" }, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  public sealed partial class DefaultTemplates : pb::IMessage<DefaultTemplates> {
    private static readonly pb::MessageParser<DefaultTemplates> _parser = new pb::MessageParser<DefaultTemplates>(() => new DefaultTemplates());
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pb::MessageParser<DefaultTemplates> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::HOLMS.Types.TenancyConfig.DefaultTemplatesReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public DefaultTemplates() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public DefaultTemplates(DefaultTemplates other) : this() {
      ReservationConfirmationTemplateId = other.reservationConfirmationTemplateId_ != null ? other.ReservationConfirmationTemplateId.Clone() : null;
      ArrivalLetterTemplateId = other.arrivalLetterTemplateId_ != null ? other.ArrivalLetterTemplateId.Clone() : null;
      IndividualFolioTemplateId = other.individualFolioTemplateId_ != null ? other.IndividualFolioTemplateId.Clone() : null;
      GroupFolioTemplateId = other.groupFolioTemplateId_ != null ? other.GroupFolioTemplateId.Clone() : null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public DefaultTemplates Clone() {
      return new DefaultTemplates(this);
    }

    /// Field number for the "reservation_confirmation_template_id" field.
    public const int ReservationConfirmationTemplateIdFieldNumber = 1;
    private global::HOLMS.Types.Primitive.TemplateIndicator reservationConfirmationTemplateId_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.TemplateIndicator ReservationConfirmationTemplateId {
      get { return reservationConfirmationTemplateId_; }
      set {
        reservationConfirmationTemplateId_ = value;
      }
    }

    /// Field number for the "arrival_letter_template_id" field.
    public const int ArrivalLetterTemplateIdFieldNumber = 2;
    private global::HOLMS.Types.Primitive.TemplateIndicator arrivalLetterTemplateId_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.TemplateIndicator ArrivalLetterTemplateId {
      get { return arrivalLetterTemplateId_; }
      set {
        arrivalLetterTemplateId_ = value;
      }
    }

    /// Field number for the "individual_folio_template_id" field.
    public const int IndividualFolioTemplateIdFieldNumber = 3;
    private global::HOLMS.Types.Primitive.TemplateIndicator individualFolioTemplateId_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.TemplateIndicator IndividualFolioTemplateId {
      get { return individualFolioTemplateId_; }
      set {
        individualFolioTemplateId_ = value;
      }
    }

    /// Field number for the "group_folio_template_id" field.
    public const int GroupFolioTemplateIdFieldNumber = 4;
    private global::HOLMS.Types.Primitive.TemplateIndicator groupFolioTemplateId_;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::HOLMS.Types.Primitive.TemplateIndicator GroupFolioTemplateId {
      get { return groupFolioTemplateId_; }
      set {
        groupFolioTemplateId_ = value;
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override bool Equals(object other) {
      return Equals(other as DefaultTemplates);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public bool Equals(DefaultTemplates other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (!object.Equals(ReservationConfirmationTemplateId, other.ReservationConfirmationTemplateId)) return false;
      if (!object.Equals(ArrivalLetterTemplateId, other.ArrivalLetterTemplateId)) return false;
      if (!object.Equals(IndividualFolioTemplateId, other.IndividualFolioTemplateId)) return false;
      if (!object.Equals(GroupFolioTemplateId, other.GroupFolioTemplateId)) return false;
      return true;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override int GetHashCode() {
      int hash = 1;
      if (reservationConfirmationTemplateId_ != null) hash ^= ReservationConfirmationTemplateId.GetHashCode();
      if (arrivalLetterTemplateId_ != null) hash ^= ArrivalLetterTemplateId.GetHashCode();
      if (individualFolioTemplateId_ != null) hash ^= IndividualFolioTemplateId.GetHashCode();
      if (groupFolioTemplateId_ != null) hash ^= GroupFolioTemplateId.GetHashCode();
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void WriteTo(pb::CodedOutputStream output) {
      if (reservationConfirmationTemplateId_ != null) {
        output.WriteRawTag(10);
        output.WriteMessage(ReservationConfirmationTemplateId);
      }
      if (arrivalLetterTemplateId_ != null) {
        output.WriteRawTag(18);
        output.WriteMessage(ArrivalLetterTemplateId);
      }
      if (individualFolioTemplateId_ != null) {
        output.WriteRawTag(26);
        output.WriteMessage(IndividualFolioTemplateId);
      }
      if (groupFolioTemplateId_ != null) {
        output.WriteRawTag(34);
        output.WriteMessage(GroupFolioTemplateId);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public int CalculateSize() {
      int size = 0;
      if (reservationConfirmationTemplateId_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationConfirmationTemplateId);
      }
      if (arrivalLetterTemplateId_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrivalLetterTemplateId);
      }
      if (individualFolioTemplateId_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(IndividualFolioTemplateId);
      }
      if (groupFolioTemplateId_ != null) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(GroupFolioTemplateId);
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(DefaultTemplates other) {
      if (other == null) {
        return;
      }
      if (other.reservationConfirmationTemplateId_ != null) {
        if (reservationConfirmationTemplateId_ == null) {
          reservationConfirmationTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
        }
        ReservationConfirmationTemplateId.MergeFrom(other.ReservationConfirmationTemplateId);
      }
      if (other.arrivalLetterTemplateId_ != null) {
        if (arrivalLetterTemplateId_ == null) {
          arrivalLetterTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
        }
        ArrivalLetterTemplateId.MergeFrom(other.ArrivalLetterTemplateId);
      }
      if (other.individualFolioTemplateId_ != null) {
        if (individualFolioTemplateId_ == null) {
          individualFolioTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
        }
        IndividualFolioTemplateId.MergeFrom(other.IndividualFolioTemplateId);
      }
      if (other.groupFolioTemplateId_ != null) {
        if (groupFolioTemplateId_ == null) {
          groupFolioTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
        }
        GroupFolioTemplateId.MergeFrom(other.GroupFolioTemplateId);
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void MergeFrom(pb::CodedInputStream input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            input.SkipLastField();
            break;
          case 10: {
            if (reservationConfirmationTemplateId_ == null) {
              reservationConfirmationTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
            }
            input.ReadMessage(reservationConfirmationTemplateId_);
            break;
          }
          case 18: {
            if (arrivalLetterTemplateId_ == null) {
              arrivalLetterTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
            }
            input.ReadMessage(arrivalLetterTemplateId_);
            break;
          }
          case 26: {
            if (individualFolioTemplateId_ == null) {
              individualFolioTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
            }
            input.ReadMessage(individualFolioTemplateId_);
            break;
          }
          case 34: {
            if (groupFolioTemplateId_ == null) {
              groupFolioTemplateId_ = new global::HOLMS.Types.Primitive.TemplateIndicator();
            }
            input.ReadMessage(groupFolioTemplateId_);
            break;
          }
        }
      }
    }

  }

  #endregion

}

#endregion Designer generated code


text:
© {{ site.time | date: '%Y' }} {{ site.title }} Criado com: Jekyll Visitante:

        {% if site.social.linkedin %}

        {% endif %}
        {% if site.social.twitter %}

        {% endif %}
        {% if site.social.github %}

        {% endif %}
        {% if site.social.gplus %}

        {% endif %}
        {% if site.social.email %}

        {% endif %}


text:
package net.openhft.chronicle.hash.serialization.impl;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import net.openhft.chronicle.hash.serialization.SizedReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class StringBuilderSizedReader
        implements SizedReader<StringBuilder>, EnumMarshallable<StringBuilderSizedReader> {
    public static final StringBuilderSizedReader INSTANCE = new StringBuilderSizedReader();

    private StringBuilderSizedReader() {
    }

    @NotNull
    @Override
    public StringBuilder read(Bytes in, long size, @Nullable StringBuilder using) {
        if (0 > size || size > Integer.MAX_VALUE)
            throw new IllegalStateException("positive int size expected, " + size + " given");
        int csLen = (int) size;
        if (using == null) {
            using = new StringBuilder(csLen);
        } else {
            using.setLength(0);
            using.ensureCapacity(csLen);
        }
        BytesUtil.parseUtf8(in, using, csLen);
        return using;
    }

    @NotNull
    @Override
    public StringBuilderSizedReader readResolve() {
        return INSTANCE;
    }
}


text:
import sys
import types
from celery.tests.utils import unittest

from celery.utils import serialization
from celery.utils.serialization import subclass_exception
from celery.utils.serialization import \
        find_nearest_pickleable_exception as fnpe
from celery.utils.serialization import UnpickleableExceptionWrapper
from celery.utils.serialization import get_pickleable_exception as gpe

from celery import states
from celery.backends.base import BaseBackend, KeyValueStoreBackend
from celery.backends.base import BaseDictBackend
from celery.utils import gen_unique_id

class wrapobject(object):

    def __init__(self, *args, **kwargs):
        self.args = args

Oldstyle = types.ClassType("Oldstyle", (), {})
Unpickleable = subclass_exception("Unpickleable", KeyError, "foo.module")
Impossible = subclass_exception("Impossible", object, "foo.module")
Lookalike = subclass_exception("Lookalike", wrapobject, "foo.module")
b = BaseBackend()

class test_serialization(unittest.TestCase):

    def test_create_exception_cls(self):
        self.assertTrue(serialization.create_exception_cls("FooError", "m"))
        self.assertTrue(serialization.create_exception_cls("FooError",
                                                            "m",
                                                            KeyError))

class test_BaseBackend_interface(unittest.TestCase):

    def test_get_status(self):
        self.assertRaises(NotImplementedError,
                b.get_status, "SOMExx-N0Nex1stant-IDxx-")

    def test__forget(self):
        self.assertRaises(NotImplementedError,
                b.forget, "SOMExx-N0Nex1stant-IDxx-")

    def test_store_result(self):
        self.assertRaises(NotImplementedError,
                b.store_result, "SOMExx-N0nex1stant-IDxx-", 42, states.SUCCESS)

    def test_reload_task_result(self):
        self.assertRaises(NotImplementedError,
                b.reload_task_result, "SOMExx-N0nex1stant-IDxx-")

    def test_reload_taskset_result(self):
        self.assertRaises(NotImplementedError,
                b.reload_taskset_result, "SOMExx-N0nex1stant-IDxx-")

    def test_get_result(self):
        self.assertRaises(NotImplementedError,
                b.get_result, "SOMExx-N0nex1stant-IDxx-")

    def test_restore_taskset(self):
        self.assertRaises(NotImplementedError,
                b.restore_taskset, "SOMExx-N0nex1stant-IDxx-")

    def test_save_taskset(self):
        self.assertRaises(NotImplementedError,
                b.save_taskset, "SOMExx-N0nex1stant-IDxx-", "blergh")

    def test_get_traceback(self):
        self.assertRaises(NotImplementedError,
                b.get_traceback, "SOMExx-N0nex1stant-IDxx-")

    def test_forget(self):
        self.assertRaises(NotImplementedError,
                b.forget, "SOMExx-N0nex1stant-IDxx-")

class test_exception_pickle(unittest.TestCase):

    def test_oldstyle(self):
        self.assertIsNone(fnpe(Oldstyle()))

    def test_BaseException(self):
        self.assertIsNone(fnpe(Exception()))

    def test_get_pickleable_exception(self):
        exc = Exception("foo")
        self.assertEqual(gpe(exc), exc)

    def test_unpickleable(self):
        self.assertIsInstance(fnpe(Unpickleable()), KeyError)
        self.assertIsNone(fnpe(Impossible()))

class test_prepare_exception(unittest.TestCase):

    def test_unpickleable(self):
        x = b.prepare_exception(Unpickleable(1, 2, "foo"))
        self.assertIsInstance(x, KeyError)
        y = b.exception_to_python(x)
        self.assertIsInstance(y, KeyError)

    def test_impossible(self):
        x = b.prepare_exception(Impossible())
        self.assertIsInstance(x, UnpickleableExceptionWrapper)
        y = b.exception_to_python(x)
        self.assertEqual(y.__class__.__name__, "Impossible")
        if sys.version_info < (2, 5):
            self.assertTrue(y.__class__.__module__)
        else:
            self.assertEqual(y.__class__.__module__, "foo.module")

    def test_regular(self):
        x = b.prepare_exception(KeyError("baz"))
        self.assertIsInstance(x, KeyError)
        y = b.exception_to_python(x)
        self.assertIsInstance(y, KeyError)

class KVBackend(KeyValueStoreBackend):

    def __init__(self, *args, **kwargs):
        self.db = {}
        super(KVBackend, self).__init__(KeyValueStoreBackend)

    def get(self, key):
        return self.db.get(key)

    def set(self, key, value):
        self.db[key] = value

    def delete(self, key):
        self.db.pop(key, None)

class DictBackend(BaseDictBackend):

    def _save_taskset(self, taskset_id, result):
        return "taskset-saved"

    def _restore_taskset(self, taskset_id):
        if taskset_id == "exists":
            return {"result": "taskset"}

    def _get_task_meta_for(self, task_id):
        if task_id == "task-exists":
            return {"result": "task"}

class test_BaseDictBackend(unittest.TestCase):

    def setUp(self):
        self.b = DictBackend()

    def test_save_taskset(self):
        self.assertEqual(self.b.save_taskset("foofoo", "xxx"),
                         "taskset-saved")

    def test_restore_taskset(self):
        self.assertIsNone(self.b.restore_taskset("missing"))
        self.assertIsNone(self.b.restore_taskset("missing"))
        self.assertEqual(self.b.restore_taskset("exists"), "taskset")
        self.assertEqual(self.b.restore_taskset("exists"), "taskset")
        self.assertEqual(self.b.restore_taskset("exists", cache=False),
                         "taskset")

    def test_reload_taskset_result(self):
        self.b._cache = {}
        self.b.reload_taskset_result("exists")
        self.b._cache["exists"] = {"result": "taskset"}

    def test_reload_task_result(self):
        self.b._cache = {}
        self.b.reload_task_result("task-exists")
        self.b._cache["task-exists"] = {"result": "task"}

class test_KeyValueStoreBackend(unittest.TestCase):

    def setUp(self):
        self.b = KVBackend()

    def test_get_store_delete_result(self):
        tid = gen_unique_id()
        self.b.mark_as_done(tid, "Hello world")
        self.assertEqual(self.b.get_result(tid), "Hello world")
        self.assertEqual(self.b.get_status(tid), states.SUCCESS)
        self.b.forget(tid)
        self.assertEqual(self.b.get_status(tid), states.PENDING)

    def test_get_missing_meta(self):
        self.assertIsNone(self.b.get_result("xxx-missing"))
        self.assertEqual(self.b.get_status("xxx-missing"), states.PENDING)

    def test_save_restore_taskset(self):
        tid = gen_unique_id()
        self.b.save_taskset(tid, "Hello world")
        self.assertEqual(self.b.restore_taskset(tid), "Hello world")

    def test_restore_missing_taskset(self):
        self.assertIsNone(self.b.restore_taskset("xxx-nonexistant"))

class test_KeyValueStoreBackend_interface(unittest.TestCase):

    def test_get(self):
        self.assertRaises(NotImplementedError, KeyValueStoreBackend().get,
                "a")

    def test_set(self):
        self.assertRaises(NotImplementedError, KeyValueStoreBackend().set,
                "a", 1)

    def test_cleanup(self):
        self.assertFalse(KeyValueStoreBackend().cleanup())

    def test_delete(self):
        self.assertRaises(NotImplementedError, KeyValueStoreBackend().delete,
                "a")

    def test_forget(self):
        self.assertRaises(NotImplementedError, KeyValueStoreBackend().forget,
                "a")


text:
"""
permutation_sequence.py

Created by Shengwei on 2014-07-15.
"""

# https://oj.leetcode.com/problems/permutation-sequence/

"""
The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.
"""

fac_cache = {0: 1, 1: 1}
def fac(n):
    cached_fac = fac_cache.get(n)
    if cached_fac:
        return cached_fac
    res = n * fac(n - 1)
    fac_cache[n] = res
    return res

def get_perm(nums, k):
    # for the first k number of elements, their first a few
    # characters don't change but only a consecutive sequence
    # such as, '1234xxxx'

    # actually start the loop from the right most end,
    # the index in nums should be -i
    for i in xrange(1, len(nums) + 1):
        if fac(i) < k:
            continue
        # at this point, fac(i) >= k so the kth element
        # can be composed by the last i number of elements
        # i.e., nums[-i:]

        # how many (i-1)! in k, which indicates which should be
        # the first char in the permutation of nums[-i:]
        m = (k - 1) / fac(i - 1)

        # nth element to pick in the next iteration
        n = k % fac(i - 1)

        prefix = ''.join(map(str, nums[:-i]))
        middle = nums[-i + m]
        rest = nums[-i:]
        rest.remove(middle)

        if n == 0:
            # k == (m+1)*(i-1)!, the last element composed of
            # nums[-i:], which is reversed consecutive sequence
            # note: the edge case is i*(i-1)! which is the last
            # element of all permutation of `nums`
            rest = ''.join(map(str, reversed(rest)))
        else:
            rest = get_perm(rest, n)
        return prefix + str(middle) + rest

    # k > (len(nums))!
    return ''

class Solution:
    # @return a string
    def getPermutation(self, n, k):
        return get_perm(range(1, n + 1), k)


text:
package org.springframework.batch.item.database;

import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemStreamReader;
import org.springframework.batch.item.database.orm.Hibernate5QueryProvider;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import java.util.Map;

/**
 * {@link ItemStreamReader} for reading database records built on top of Hibernate. It
 * executes the HQL query when initialized iterates over the result set as
 * {@link #read()} method is called, returning an object corresponding to
 * current row. The query can be set directly using
 * {@link #setQueryString(String)}, a named query can be used by
 * {@link #setQueryName(String)}, or a query provider strategy can be supplied
 * via {@link #setQueryProvider(Hibernate5QueryProvider)}.
 *
 *
 *

 * The reader can be configured to use either {@link StatelessSession}
 * sufficient for simple mappings without the need to cascade to associated
 * objects or standard hibernate {@link Session} for more advanced mappings or
 * when caching is desired. When stateful session is used it will be cleared in
 * the {@link #update(ExecutionContext)} method without being flushed (no data
 * modifications are expected).
 *

 *
 * The implementation is not thread-safe.
 *
 * @author Robert Kasanicky
 * @author Dave Syer
 */
public class Hibernate5CursorItemReader<T> extends AbstractItemCountingItemStreamItemReader<T>
        implements InitializingBean {

    private Hibernate5ItemReaderHelper<T> helper = new Hibernate5ItemReaderHelper<T>();

    public Hibernate5CursorItemReader() {
        setName(ClassUtils.getShortName(HibernateCursorItemReader.class));
    }

    private ScrollableResults cursor;

    private boolean initialized = false;

    private int fetchSize;

    private Map<String, Object> parameterValues;

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.state(fetchSize >= 0, "fetchSize must not be negative");
        helper.afterPropertiesSet();
    }

    /**
     * The parameter values to apply to a query (map of name:value).
     *
     * @param parameterValues the parameter values to set
     */
    public void setParameterValues(Map<String, Object> parameterValues) {
        this.parameterValues = parameterValues;
    }

    /**
     * A query name for an externalized query. Either this or the {
     * {@link #setQueryString(String) query string} or the {
     * {@link #setQueryProvider(Hibernate5QueryProvider) query provider} should
     * be set.
     *
     * @param queryName name of a hibernate named query
     */
    public void setQueryName(String queryName) {
        helper.setQueryName(queryName);
    }

    /**
     * Fetch size used internally by Hibernate to limit amount of data fetched
     * from database per round trip.
     *
     * @param fetchSize the fetch size to pass down to Hibernate
     */
    public void setFetchSize(int fetchSize) {
        this.fetchSize = fetchSize;
    }

    /**
     * A query provider. Either this or the {{@link #setQueryString(String)
     * query string} or the {{@link #setQueryName(String) query name} should be
     * set.
     *
     * @param queryProvider Hibernate query provider
     */
    public void setQueryProvider(Hibernate5QueryProvider queryProvider) {
        helper.setQueryProvider(queryProvider);
    }

    /**
     * A query string in HQL. Either this or the {
     * {@link #setQueryProvider(Hibernate5QueryProvider) query provider} or the {
     * {@link #setQueryName(String) query name} should be set.
     *
     * @param queryString HQL query string
     */
    public void setQueryString(String queryString) {
        helper.setQueryString(queryString);
    }

    /**
     * The Hibernate SessionFactory to use the create a session.
     *
     * @param sessionFactory the {@link SessionFactory} to set
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        helper.setSessionFactory(sessionFactory);
    }

    /**
     * Can be set only in uninitialized state.
     *
     * @param useStatelessSession true to use
     * {@link StatelessSession} false to use standard hibernate
     * {@link Session}
     */
    public void setUseStatelessSession(boolean useStatelessSession) {
        helper.setUseStatelessSession(useStatelessSession);
    }

    @Override
    protected T doRead() throws Exception {
        if (cursor.next()) {
            Object[] data = cursor.get();

            if (data.length > 1) {
                // If there are multiple items this must be a projection
                // and T is an array type.
                @SuppressWarnings("unchecked")
                T item = (T) data;
                return item;
            }
            else {
                // Assume if there is only one item that it is the data the user
                // wants.
                // If there is only one item this is going to be a nasty shock
                // if T is an array type but there's not much else we can do...
                @SuppressWarnings("unchecked")
                T item = (T) data[0];
                return item;
            }

        }
        return null;
    }

    /**
     * Open hibernate session and create a forward-only cursor for the query.
     */
    @Override
    protected void doOpen() throws Exception {
        Assert.state(!initialized, "Cannot open an already opened ItemReader, call close first");
        cursor = helper.getForwardOnlyCursor(fetchSize, parameterValues);
        initialized = true;
    }

    /**
     * Update the context and clear the session if stateful.
     *
     * @param executionContext the current {@link ExecutionContext}
     * @throws ItemStreamException if there is a problem
     */
    @Override
    public void update(ExecutionContext executionContext) throws ItemStreamException {
        super.update(executionContext);
        helper.clear();
    }

    /**
     * Wind forward through the result set to the item requested. Also clears
     * the session every now and then (if stateful) to avoid memory problems.
     * The frequency of session clearing is the larger of the fetch size (if
     * set) and 100.
     *
     * @param itemIndex the first item to read
     * @throws Exception if there is a problem
     * @see AbstractItemCountingItemStreamItemReader#jumpToItem(int)
     */
    @Override
    protected void jumpToItem(int itemIndex) throws Exception {
        int flushSize = Math.max(fetchSize, 100);
        helper.jumpToItem(cursor, itemIndex, flushSize);
    }

    /**
     * Close the cursor and hibernate session.
     */
    @Override
    protected void doClose() throws Exception {

        initialized = false;

        if (cursor != null) {
            cursor.close();
        }

        helper.close();

    }
}


text:
See also [net-messages](../net-messages) for regular net-messages.

This example shows how to have the parser deal with encrypted net-messages.

For Valve MM games, the decryption key can be obtained from `.dem.info` files using `MatchInfoDecryptionKey()`.
The key then needs to be passed to `ParserConfig.NetMessageDecryptionKey`.

## Run

    go run enc_net_nsg.go -demo path/to/demo.dem -info path/to/demo.dem.info

This prints chat messages from the passed demo (assuming the `.dem.info` file contains the correct decryption key).


text:
using System;
using System.Linq;

namespace Orleankka
{
    public abstract class Ref
    {
        public static Ref Deserialize(string path)
        {
            if (ClientRef.Satisfies(path))
                return ClientRef.Deserialize(path);

            return ActorRef.Deserialize(ActorPath.Deserialize(path));
        }

        public abstract string Serialize();
    }
}


text:
"""ContentSecurityPolicySettings API Tests for Version 1.0.

This is a testing template for the generated ContentSecurityPolicySettingsAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.content_security_policy_settings import (
    ContentSecurityPolicySettingsAPI,
)

class TestContentSecurityPolicySettingsAPI(unittest.TestCase):
    """Tests for the ContentSecurityPolicySettingsAPI."""

    def setUp(self):
        self.client = ContentSecurityPolicySettingsAPI(
            secrets.instance_address, secrets.access_token
        )

    def test_get_current_settings_for_account_or_course_courses(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.get_current_settings_for_account_or_course_courses method."""
        course_id = None  # Change me!!

        r = self.client.get_current_settings_for_account_or_course_courses(course_id)

    def test_get_current_settings_for_account_or_course_accounts(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.get_current_settings_for_account_or_course_accounts method."""
        account_id = None  # Change me!!

        r = self.client.get_current_settings_for_account_or_course_accounts(account_id)

    def test_enable_disable_or_clear_explicit_csp_setting_courses(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.enable_disable_or_clear_explicit_csp_setting_courses method."""
        # This method utilises the PUT request method and will make changes to the Canvas instance. This needs consideration.
        pass

    def test_enable_disable_or_clear_explicit_csp_setting_accounts(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.enable_disable_or_clear_explicit_csp_setting_accounts method."""
        # This method utilises the PUT request method and will make changes to the Canvas instance. This needs consideration.
        pass

    def test_lock_or_unlock_current_csp_settings_for_sub_accounts_and_courses(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.lock_or_unlock_current_csp_settings_for_sub_accounts_and_courses method."""
        # This method utilises the PUT request method and will make changes to the Canvas instance. This needs consideration.
        pass

    def test_add_allowed_domain_to_account(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.add_allowed_domain_to_account method."""
        # This method utilises the POST request method and will make changes to the Canvas instance. This needs consideration.
        pass

    def test_add_multiple_allowed_domains_to_account(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.add_multiple_allowed_domains_to_account method."""
        # This method utilises the POST request method and will make changes to the Canvas instance. This needs consideration.
        pass

    def test_retrieve_reported_csp_violations_for_account(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.retrieve_reported_csp_violations_for_account method."""
        account_id = None  # Change me!!

        r = self.client.retrieve_reported_csp_violations_for_account(account_id)

    def test_remove_domain_from_account(self):
        """Integration test for the ContentSecurityPolicySettingsAPI.remove_domain_from_account method."""
        account_id = None  # Change me!!
        domain = None  # Change me!!

        r = self.client.remove_domain_from_account(account_id, domain)


text:
package org.guvnor.asset.management.client.editors.repository.wizard.pages;

import java.util.List;

import org.uberfire.client.mvp.UberView;
import org.uberfire.commons.data.Pair;

public interface RepositoryInfoPageView
        extends
        UberView<RepositoryInfoPageView.Presenter> {

    String NOT_SELECTED = "NOT_SELECTED";

    interface Presenter {

        void onNameChange();

        void onOUChange();

        void onManagedRepositoryChange();

    }

    String getName();

    void setName( String name );

    void setNameErrorMessage( String message );

    void clearNameErrorMessage( );

    void initOrganizationalUnits( List<Pair<String, String>> organizationalUnits );

    String getOrganizationalUnitName();

    void setVisibleOU( boolean visible );

    void setValidOU( boolean ouValid );

    boolean isManagedRepository();

    void enabledManagedRepositoryCreation( boolean enabled );

    void alert( String message );

}


text:
package main

import (
	"fmt"
	"os"
	"syscall"

	"github.com/codegangsta/cli"
)

func execManpage(sec, page string) {
	if err := syscall.Exec("/usr/bin/env", []string{"/usr/bin/env", "man", sec, page}, os.Environ()); err != nil {
		fmt.Println("Exec error:", err)
	}
	os.Exit(1)
}

func main() {

	// Rather than using the built-in help printer, display the bundled manpages.
	cli.HelpPrinter = func(templ string, data interface{}) {
		if cmd, ok := data.(cli.Command); ok {
			switch cmd.Name {
			case "encrypt", "decrypt", "keygen":
				execManpage("1", "ejson-"+cmd.Name)
			}
		}
		execManpage("1", "ejson")
	}

	app := cli.NewApp()
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "keydir, k",
			Value:  "/opt/ejson/keys",
			Usage:  "Directory containing EJSON keys",
			EnvVar: "EJSON_KEYDIR",
		},
	}
	app.Usage = "manage encrypted secrets using public key encryption"
	app.Version = VERSION
	app.Author = "Burke Libbey"
	app.Email = "burke.libbey@shopify.com"
	app.Commands = []cli.Command{
		{
			Name:      "encrypt",
			ShortName: "e",
			Usage:     "(re-)encrypt one or more EJSON files",
			Action: func(c *cli.Context) {
				if err := encryptAction(c.Args()); err != nil {
					fmt.Println("Encryption failed:", err)
					os.Exit(1)
				}
			},
		},
		{
			Name:      "decrypt",
			ShortName: "d",
			Usage:     "decrypt an EJSON file",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "o",
					Usage: "print output to the provided file, rather than stdout",
				},
			},
			Action: func(c *cli.Context) {
				if err := decryptAction(c.Args(), c.GlobalString("keydir"), c.String("o")); err != nil {
					fmt.Println("Decryption failed:", err)
					os.Exit(1)
				}
			},
		},
		{
			Name:      "keygen",
			ShortName: "g",
			Usage:     "generate a new EJSON keypair",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "write, w",
					Usage: "rather than printing both keys, print the public and write the private into the keydir",
				},
			},
			Action: func(c *cli.Context) {
				if err := keygenAction(c.Args(), c.GlobalString("keydir"), c.Bool("write")); err != nil {
					fmt.Println("Key generation failed:", err)
					os.Exit(1)
				}
			},
		},
	}
	if err := app.Run(os.Args); err != nil {
		fmt.Println("Unexpected failure:", err)
		os.Exit(1)
	}
}


text:
package org.apache.bookkeeper.bookie;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.util.DiskChecker;

/**
 * Read Only Entry Logger.
 */
public class ReadOnlyEntryLogger extends EntryLogger {

    public ReadOnlyEntryLogger(ServerConfiguration conf) throws IOException {
        super(conf, new LedgerDirsManager(conf, conf.getLedgerDirs(),
                new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())));
    }

    @Override
    protected boolean removeEntryLog(long entryLogId) {
        // can't remove entry log in readonly mode
        return false;
    }

    @Override
    public synchronized long addEntry(long ledgerId, ByteBuffer entry) throws IOException {
        throw new IOException("Can't add entry to a readonly entry logger.");
    }
}


text:
require_relative '../../../test_helper'
require_relative '../../../../lib/automation_object/blue_print/composite/screen'

# Test AutomationObject::BluePrint::Composite::Screen
class TestBluePrintCompositeScreen < Minitest::Test
  def setup
    @mock = mock
    @subject = AutomationObject::BluePrint::Composite::Screen.new(@mock)
  end

  def test_load
    @mock.expects(:load).returns({})
    assert_equal({}, @subject.load)
  end

  def test_accept
    @mock.expects(:accept).returns({})
    assert_equal({}, @subject.accept)
  end

  def test_dismiss
    @mock.expects(:dismiss).returns({})
    assert_equal({}, @subject.dismiss)
  end

  def test_modals
    @mock.expects(:modals).returns({})
    assert_equal({}, @subject.modals)
  end

  def test_elements
    @mock.expects(:elements).returns({})
    assert_equal({}, @subject.elements)
  end

  def test_element_arrays
    @mock.expects(:element_arrays).returns({})
    assert_equal({}, @subject.element_arrays)
  end

  def test_element_hashes
    @mock.expects(:element_hashes).returns({})
    assert_equal({}, @subject.element_hashes)
  end

  def test_automatic_onload_modals
    @mock.expects(:element_hashes).returns({})
    assert_equal({}, @subject.element_hashes)
  end

  def test_automatic_modal_changes
    @mock.expects(:automatic_modal_changes).returns({})
    assert_equal({}, @subject.automatic_modal_changes)
  end
end