text:
const sinon = require('sinon'),
    should = require('should'),
    rewire = require('rewire'),
    fs = require('fs-extra'),
    path = require('path'),
    configUtils = require('../../../utils/configUtils'),
    common = require('../../../../server/lib/common'),
    loadSettings = rewire('../../../../server/services/settings/loader'),
    sandbox = sinon.sandbox.create();

describe('UNIT > Settings Service:', function () {
    beforeEach(function () {
        configUtils.set('paths:contentPath', path.join(__dirname, '../../../utils/fixtures/'));
    });

    afterEach(function () {
        sandbox.restore();
        configUtils.restore();
    });

    describe('Settings Loader', function () {
        const yamlStubFile = {
            routes: null,
            collections: {
                '/': {
                    permalink: '{globals.permalinks}',
                    template: ['home', 'index']
                }
            },
            taxonomies: {tag: '/tag/{slug}/', author: '/author/{slug}/'}
        };
        let yamlParserStub;

        beforeEach(function () {
            yamlParserStub = sinon.stub();
        });

        it('can find yaml settings file and returns a settings object', function () {
            const fsReadFileSpy = sandbox.spy(fs, 'readFileSync');
            const expectedSettingsFile = path.join(__dirname, '../../../utils/fixtures/settings/goodroutes.yaml');

            yamlParserStub.returns(yamlStubFile);
            loadSettings.__set__('yamlParser', yamlParserStub);

            const setting = loadSettings('goodroutes');
            should.exist(setting);
            setting.should.be.an.Object().with.properties('routes', 'collections', 'taxonomies');
            // There are 4 files in the fixtures folder, but only 1 supported and valid yaml files
            fsReadFileSpy.calledOnce.should.be.true();
            fsReadFileSpy.calledWith(expectedSettingsFile).should.be.true();
            yamlParserStub.callCount.should.be.eql(1);
        });

        it('can handle errors from YAML parser', function (done) {
            yamlParserStub.throws(new common.errors.GhostError({
                message: 'could not parse yaml file',
                context: 'bad indentation of a mapping entry at line 5, column 10'
            }));

            loadSettings.__set__('yamlParser', yamlParserStub);

            try {
                loadSettings('goodroutes');
                done(new Error('Loader should fail'));
            } catch (err) {
                should.exist(err);
                err.message.should.be.eql('could not parse yaml file');
                err.context.should.be.eql('bad indentation of a mapping entry at line 5, column 10');
                yamlParserStub.calledOnce.should.be.true();
                done();
            }
        });

        it('throws error if file can\'t be accessed', function (done) {
            const expectedSettingsFile = path.join(__dirname, '../../../utils/fixtures/settings/routes.yaml');
            const fsError = new Error('no permission');
            fsError.code = 'EPERM';

            const originalFn = fs.readFileSync;
            const fsReadFileStub = sandbox.stub(fs, 'readFileSync').callsFake(function (filePath, options) {
                if (filePath.match(/routes\.yaml/)) {
                    throw fsError;
                }

                return originalFn(filePath, options);
            });

            yamlParserStub = sinon.spy();
            loadSettings.__set__('yamlParser', yamlParserStub);

            try {
                loadSettings('routes');
                done(new Error('Loader should fail'));
            } catch (err) {
                err.message.should.match(/Error trying to load YAML setting for routes from/);
                fsReadFileStub.calledWith(expectedSettingsFile).should.be.true();
                yamlParserStub.calledOnce.should.be.false();
                done();
            }
        });
    });
});


text:
import json

from pygal.maps.world import World
from pygal.style import RotateStyle

from country_codes import get_country_code

# Load the data into a list.
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

# Build a dictionary of population data.
cc_populations = {}
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))
        code = get_country_code(country_name)
        if code:
            cc_populations[code] = population

# Group the countries into 3 population levels.
cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
for cc, pop in cc_populations.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop

# See how many countries are in each level.
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))

wm_style = RotateStyle('#336699')
wm = World(style=wm_style)
wm.title = 'World Population in 2010, by Country'
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('world_population.svg')

redpajama_set_name: RedPajamaGithub


text:
<?php

/* smileRHBundle:Default:modifierPersonnel.html.twig */
class __TwigTemplate_f9670540ccafbb0f3057ab4cb56b3f9fe36897b1f9b200e767f44268b6f6ea24 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("::base_template.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'breadcumb' => array($this, 'block_breadcumb'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base_template.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_breadcumb($context, array $blocks = array())
    {
        // line 4
        echo "
env->getExtension('routing')->getPath("smilegestion_personnel_listPersonnel");
        echo "\">Gestion des membres du personnel

Modifier un membre

";
    }

    // line 8
    public function block_content($context, array $blocks = array())
    {
        // line 9
        echo "

            <form enctype=\"multipart/form-data\" method=\"POST\" class=\"fos_user_registration_register form-horizontal\">
               ";
        // line 14
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'errors');
        echo "
               <fieldset>
                    <legend>Identification</legend>

                        env, $this->env->getExtension('assets')->getAssetUrl(("uploads/avatars/" . $this->getAttribute((isset($context["personnel"]) ? $context["personnel"] : null), "avatarName", array()))), "html", null, true);
        echo "\" id=\"profile-avatar\" />

                        Photo

                              ";
        // line 24
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "avatar", array()), 'widget', array("attr" => array("class" => "form-control", "id" => "uploader")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "profil", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 30
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "profil", array()), 'label');
        echo "

                            ";
        // line 32
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "profil", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "login", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 37
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "login", array()), 'label');
        echo "

                            ";
        // line 39
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "login", array()), 'widget', array("attr" => array("class" => "form-control", "readonly" => "readonly")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nom", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 43
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nom", array()), 'label');
        echo "

                            ";
        // line 45
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nom", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "prenom", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 50
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "prenom", array()), 'label');
        echo "

                            ";
        // line 52
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "prenom", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "sitMat", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 57
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "sitMat", array()), 'label');
        echo "

                        ";
        // line 59
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "sitMat", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nbreEnft", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 63
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nbreEnft", array()), 'label');
        echo "

                        ";
        // line 65
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "nbreEnft", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

                 </fieldset>

                <fieldset>
                    <legend>Contacts</legend>

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fixe", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 73
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fixe", array()), 'label');
        echo "

                            ";
        // line 75
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fixe", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "mobile", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 80
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "mobile", array()), 'label');
        echo "

                            ";
        // line 82
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "mobile", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "email", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                        ";
        // line 87
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "email", array()), 'label');
        echo "

                            ";
        // line 89
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "email", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

                </fieldset>

                <fieldset>
                    <legend>Autres</legend>

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "service", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 97
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "service", array()), 'label');
        echo "

                        ";
        // line 99
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "service", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "groupe", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 104
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "groupe", array()), 'label');
        echo "

                        ";
        // line 106
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "groupe", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "contrat", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 113
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "contrat", array()), 'label');
        echo "

                        ";
        // line 115
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "contrat", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "affection", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 119
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "affection", array()), 'label');
        echo "

                        ";
        // line 121
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "affection", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fonction", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 126
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fonction", array()), 'label');
        echo "

                        ";
        // line 128
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "fonction", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

env, $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "dateEntree", array()), 'errors')) > 0)) {
            echo " has-error ";
        }
        echo "\">
                    ";
        // line 135
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "dateEntree", array()), 'label');
        echo "

                        ";
        // line 137
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "dateEntree", array()), 'widget', array("attr" => array("class" => "form-control")));
        echo "

                </fieldset>
                 ";
        // line 143
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'rest');
        echo "

                        <input type=\"submit\" class=\"btn btn-success\" value=\"Valider\" />
                        env->getExtension('routing')->getPath("smilegestion_personnel_listPersonnel");
        echo "\" class=\"btn btn-danger\">Annuler

            </form>

";
    }

    public function getTemplateName()
    {
        return "smileRHBundle:Default:modifierPersonnel.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  368 => 147,  361 => 143,  352 => 137,  347 => 135,  341 => 134,  332 => 128,  327 => 126,  321 => 125,  314 => 121,  309 => 119,  303 => 118,  297 => 115,  292 => 113,  286 => 112,  277 => 106,  272 => 104,  266 => 103,  259 => 99,  254 => 97,  248 => 96,  238 => 89,  233 => 87,  227 => 86,  220 => 82,  215 => 80,  209 => 79,  202 => 75,  197 => 73,  191 => 72,  181 => 65,  176 => 63,  170 => 62,  164 => 59,  159 => 57,  153 => 56,  146 => 52,  141 => 50,  135 => 49,  128 => 45,  123 => 43,  117 => 42,  111 => 39,  106 => 37,  100 => 36,  93 => 32,  88 => 30,  82 => 29,  74 => 24,  65 => 18,  58 => 14,  51 => 9,  48 => 8,  40 => 4,  37 => 3,  11 => 1,);
    }
}


text:
namespace content {

// Contents of the initial message sent from the zygote to the browser when it
// is ready to go.
static const char kZygoteHelloMessage[] = "ZYGOTE_OK";

// File descriptors initialized by the Zygote Host
const int kZygoteSocketPairFd = 3;
const int kZygoteRendererSocketFd = 5;
// This file descriptor is special. It is passed to the Zygote and a setuid
// helper will be called to locate the process of the Zygote on the system.
// This mechanism is used when multiple PID namespaces exist because of the
// setuid sandbox.
// It is very important that this file descriptor does not exist in multiple
// processes.
// This number must be kept in sync in sandbox/linux/suid/sandbox.c
const int kZygoteIdFd = 7;

// These are the command codes used on the wire between the browser and the
// zygote.
enum {
  // Fork off a new renderer.
  kZygoteCommandFork = 0,

  // Reap a renderer child.
  kZygoteCommandReap = 1,

  // Check what happend to a child process.
  kZygoteCommandGetTerminationStatus = 2,

  // Read a bitmask of kSandboxLinux*
  kZygoteCommandGetSandboxStatus = 3
};

}  // namespace content

#endif  // CONTENT_COMMON_ZYGOTE_COMMANDS_LINUX_H_


text:
var $ = require("jquery");
var _ = require("underscore");

var Backbone = require("backbone");

var App = require('../app');
var barcode = require("../lib/barcode");

var BarcodeView = Backbone.View.extend({
  scan: function(success) {
    var bookmanage = require("../bookmanage");
    console.log("render scan barcode");

    barcode.scan(
      function(result){
      if(result.cancelled == 0) {
          if(result.format != "EAN_13") {
              App.app.alert("错误的图书条码", "扫描错误");
          } else {
               success(result.text);
          }
      }
    },
      function(error) {
        App.app.alert(error, 'bkr');
      }
    );
  },
})

module.exports = BarcodeView;


text:
<?php declare(strict_types=1);
////////////////////////////////////////////////////////////////////////////////
//             ___________                     __   __  _____
//             \_   _____/______ __ __   _____/  |_|__|/ ____\__ __
//              |    __) \_  __ \  |  \_/ ___\   __\  \   __<   |  |
//              |     \   |  | \/  |  /\  \___|  | |  ||  |  \___  |
//              \___  /   |__|  |____/  \___  >__| |__||__|  / ____|
//                  \/                      \/               \/
// -----------------------------------------------------------------------------
//                          https://github.com/fructify
//
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

namespace Fructify\Services;

use Closure;
use stdClass;
use Relay\Runner;
use DI\Annotation\Inject;
use YaLinqo\Enumerable as Linq;
use Fructify\Contracts\IKernel;
use Fructify\Contracts\IMiddleware;
use Symfony\Component\Finder\SplFileInfo;
use Psr\Http\Message\ResponseInterface as IResponse;
use Interop\Container\ContainerInterface as IContainer;
use Zend\Diactoros\Response\EmitterInterface as IEmitter;
use Psr\Http\Message\ServerRequestInterface as IServerRequest;
use Dflydev\Symfony\FinderFactory\FinderFactoryInterface as IFinderFactory;

/**
 * This class basically wraps around the "relay/relay" php package.
 *
 * @see: http://relayphp.com/
 */
class Middleware implements IMiddleware
{
    /**
     * @Inject
     * @var IContainer
     */
    private $container;

    /**
     * @Inject
     * @var IKernel
     */
    private $kernel;

    /**
     * @Inject
     * @var IServerRequest
     */
    private $request;

    /**
     * @Inject
     * @var IResponse
     */
    private $response;

    /**
     * @Inject
     * @var IEmitter
     */
    private $emitter;

    /**
     * @Inject
     * @var IFinderFactory
     */
    private $finder;

    /**
     * @Inject("config")
     * @var stdClass
     */
    private $config;

    public function dispatch()
    {
        $runner = new Runner($this->buildQueue(), function($file)
        {
            return $this->resolve($file);
        });

        $output = $runner($this->request, $this->response);

        $this->emitter->emit($output);

        exit;
    }

    /**
     * Creates an array of file paths that contain middleware.
     *
     * The middleware files are hierarchical, allowing the child theme to
     * override any middleware that we provide by default. The array is also
     * sorted by filename. So the child theme can "insert" it's middleware
     * in the desired order.
     *
     * @return string[]
     */
    private function buildQueue(): array
    {
        $queue = [];

        // Where is our middleware located?
        $parentMiddleware = $this->config->paths->theme->parent->middleware;
        $childMiddleware = $this->config->paths->theme->child->middleware;

        // Loop through our middleware files
        foreach ($this->finder->createFinder()->files()->name('*.php')->in($parentMiddleware) as $file)
        {
            if ($this->kernel->childHasMiddleware())
            {
                // Only register one of our middleware files if the
                // child theme does not have the same middleware file.
                if (!file_exists(str_replace($parentMiddleware, $childMiddleware, $file)))
                {
                    $queue[] = $file;
                }
            }
            else
            {
                $queue[] = $file;
            }
        }

        // Now lets loop through the child theme middleware files.
        if ($this->kernel->childHasMiddleware())
        {
            foreach ($this->finder->createFinder()->files()->name('*.php')->in($childMiddleware) as $file)
            {
                $queue[] = $file;
            }
        }

        // Ensure the middleware queue is sorted.
        return Linq::from($queue)->orderBy('$v')->toArray();
    }

    /**
     * Used by Relay\Runner when it dispatches the middleware stack.
     *
     * @param  SplFileInfo $file
     * @return Closure
     */
    private function resolve(SplFileInfo $file): Closure
    {
        return function(IServerRequest $request, IResponse $response, callable $next) use ($file)
        {
            return $this->container->call(import($file->getRealPath()),
            [
                'request' => $request,
                'response' => $response,
                'next' => $next,
                'config' => $this->config
            ]);
        };
    }
}


text:
package org.repoanalyzer.reporeader.exceptions;

public class AuthorNotFoundException extends Exception {
    public AuthorNotFoundException() {
        super("None of already existing authors contain given name nor mail");
    }
}


text:
package com.amazonaws.services.fms.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Remediation option for the rule specified in the ViolationTarget.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SecurityGroupRemediationAction implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The remediation action that will be performed.
     *

     */
    private String remediationActionType;
    /**
     *

     * Brief description of the action that will be performed.
     *

     */
    private String description;
    /**
     *

     * The final state of the rule specified in the ViolationTarget after it is remediated.
     *

     */
    private SecurityGroupRuleDescription remediationResult;
    /**
     *

     * Indicates if the current action is the default action.
     *

     */
    private Boolean isDefaultAction;

    /**
     *

     * The remediation action that will be performed.
     *

     *
     * @param remediationActionType
     *        The remediation action that will be performed.
     * @see RemediationActionType
     */

    public void setRemediationActionType(String remediationActionType) {
        this.remediationActionType = remediationActionType;
    }

    /**
     *

     * The remediation action that will be performed.
     *

     *
     * @return The remediation action that will be performed.
     * @see RemediationActionType
     */

    public String getRemediationActionType() {
        return this.remediationActionType;
    }

    /**
     *

     * The remediation action that will be performed.
     *

     *
     * @param remediationActionType
     *        The remediation action that will be performed.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see RemediationActionType
     */

    public SecurityGroupRemediationAction withRemediationActionType(String remediationActionType) {
        setRemediationActionType(remediationActionType);
        return this;
    }

    /**
     *

     * The remediation action that will be performed.
     *

     *
     * @param remediationActionType
     *        The remediation action that will be performed.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see RemediationActionType
     */

    public SecurityGroupRemediationAction withRemediationActionType(RemediationActionType remediationActionType) {
        this.remediationActionType = remediationActionType.toString();
        return this;
    }

    /**
     *

     * Brief description of the action that will be performed.
     *

     *
     * @param description
     *        Brief description of the action that will be performed.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * Brief description of the action that will be performed.
     *

     *
     * @return Brief description of the action that will be performed.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * Brief description of the action that will be performed.
     *

     *
     * @param description
     *        Brief description of the action that will be performed.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SecurityGroupRemediationAction withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * The final state of the rule specified in the ViolationTarget after it is remediated.
     *

     *
     * @param remediationResult
     *        The final state of the rule specified in the ViolationTarget after it is remediated.
     */

    public void setRemediationResult(SecurityGroupRuleDescription remediationResult) {
        this.remediationResult = remediationResult;
    }

    /**
     *

     * The final state of the rule specified in the ViolationTarget after it is remediated.
     *

     *
     * @return The final state of the rule specified in the ViolationTarget after it is remediated.
     */

    public SecurityGroupRuleDescription getRemediationResult() {
        return this.remediationResult;
    }

    /**
     *

     * The final state of the rule specified in the ViolationTarget after it is remediated.
     *

     *
     * @param remediationResult
     *        The final state of the rule specified in the ViolationTarget after it is remediated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SecurityGroupRemediationAction withRemediationResult(SecurityGroupRuleDescription remediationResult) {
        setRemediationResult(remediationResult);
        return this;
    }

    /**
     *

     * Indicates if the current action is the default action.
     *

     *
     * @param isDefaultAction
     *        Indicates if the current action is the default action.
     */

    public void setIsDefaultAction(Boolean isDefaultAction) {
        this.isDefaultAction = isDefaultAction;
    }

    /**
     *

     * Indicates if the current action is the default action.
     *

     *
     * @return Indicates if the current action is the default action.
     */

    public Boolean getIsDefaultAction() {
        return this.isDefaultAction;
    }

    /**
     *

     * Indicates if the current action is the default action.
     *

     *
     * @param isDefaultAction
     *        Indicates if the current action is the default action.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SecurityGroupRemediationAction withIsDefaultAction(Boolean isDefaultAction) {
        setIsDefaultAction(isDefaultAction);
        return this;
    }

    /**
     *

     * Indicates if the current action is the default action.
     *

     *
     * @return Indicates if the current action is the default action.
     */

    public Boolean isDefaultAction() {
        return this.isDefaultAction;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getRemediationActionType() != null)
            sb.append("RemediationActionType: ").append(getRemediationActionType()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getRemediationResult() != null)
            sb.append("RemediationResult: ").append(getRemediationResult()).append(",");
        if (getIsDefaultAction() != null)
            sb.append("IsDefaultAction: ").append(getIsDefaultAction());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SecurityGroupRemediationAction == false)
            return false;
        SecurityGroupRemediationAction other = (SecurityGroupRemediationAction) obj;
        if (other.getRemediationActionType() == null ^ this.getRemediationActionType() == null)
            return false;
        if (other.getRemediationActionType() != null && other.getRemediationActionType().equals(this.getRemediationActionType()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getRemediationResult() == null ^ this.getRemediationResult() == null)
            return false;
        if (other.getRemediationResult() != null && other.getRemediationResult().equals(this.getRemediationResult()) == false)
            return false;
        if (other.getIsDefaultAction() == null ^ this.getIsDefaultAction() == null)
            return false;
        if (other.getIsDefaultAction() != null && other.getIsDefaultAction().equals(this.getIsDefaultAction()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getRemediationActionType() == null) ? 0 : getRemediationActionType().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getRemediationResult() == null) ? 0 : getRemediationResult().hashCode());
        hashCode = prime * hashCode + ((getIsDefaultAction() == null) ? 0 : getIsDefaultAction().hashCode());
        return hashCode;
    }

    @Override
    public SecurityGroupRemediationAction clone() {
        try {
            return (SecurityGroupRemediationAction) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.fms.model.transform.SecurityGroupRemediationActionMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package core.lsmi;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.junit.Test;

import common.MidSegment;
import core.commom.BDBBtree;
import core.lsmt.IMemTable.SSTableMeta;
import core.lsmt.IPostingListIterator;
import core.lsmt.ISSTableReader;
import core.lsmt.LSMTInvertedIndex;
import core.lsmt.WritableComparableKey;
import core.lsmt.WritableComparableKey.StringKey;
import segmentation.Interval;
import util.Configuration;
import util.Pair;

public class SortedListIterTest {
	public int ExpectedResult(WritableComparableKey key, ISSTableReader reader, Interval window) throws IOException {
		int ret = 0;
		System.out.println(key);
		Pair<Integer, List<MidSegment>> cur = null;
		// 遍历所有的node,找到相关的segs
		IPostingListIterator scanner = reader.getPostingListScanner(key);
		while (scanner.hasNext()) {
			cur = scanner.next();
			for (MidSegment seg : cur.getValue()) {
				if (seg.getStart() <= window.getEnd() && seg.getEndTime() >= window.getStart()) {
					ret++;
				}
			}
		}
		scanner.close();
		return ret;
	}

	public int queryResult(WritableComparableKey key, ISSTableReader reader, Interval window) throws IOException {
		int ret = 0;
		IPostingListIterator scanner = reader.getPostingListIter(key, window.getStart(), window.getEnd());

		Pair<Integer, List<MidSegment>> cur = null;
		while (scanner.hasNext()) {
			cur = scanner.next();
			for (MidSegment seg : cur.getValue()) {
				if (seg.getStart() <= window.getEnd() && seg.getEndTime() >= window.getStart()) {
					ret++;
				}
			}
		}
		return ret;
	}

	@Test
	public void testKeyword() throws IOException {
		PropertyConfigurator.configure("conf/log4j-server2.properties");

		Configuration conf = new Configuration();
		conf.load("conf/index_twitter_lsmi.conf");

		LSMTInvertedIndex index = new LSMTInvertedIndex(conf);
		index.init();

		int ts = 606602;
		int te = 696622;
		Interval window = new Interval(0, ts, te, 0);
		System.out.println("begin to verify");
		System.out.flush();
		// 遍历所有的posting list
		try {
			for (SSTableMeta meta : index.getVersion().diskTreeMetas) {
				ListDiskBDBSSTableReader reader = (ListDiskBDBSSTableReader) index.getSSTableReader(index.getVersion(),
						meta);
				WritableComparableKey key = new StringKey("#beatcancer");
				int expect = ExpectedResult(key, reader, window);
				int answer = queryResult(key, reader, window);
				// fos.close();
				System.out.println("expected size:" + expect + "," + expect);
				Assert.assertEquals(expect, answer);
			}

		} finally {
			index.close();
		}
	}

	@Test
	public void test() throws IOException {
		PropertyConfigurator.configure("conf/log4j-server2.properties");

		Configuration conf = new Configuration();
		conf.load("conf/index_twitter_lsmi.conf");

		LSMTInvertedIndex index = new LSMTInvertedIndex(conf);
		index.init();

		int ts = 676602;
		int te = 696622;
		Interval window = new Interval(0, ts, te, 0);
		System.out.println("begin to verify");
		System.out.flush();
		// 遍历所有的posting list
		try {
			for (SSTableMeta meta : index.getVersion().diskTreeMetas) {
				ListDiskBDBSSTableReader reader = (ListDiskBDBSSTableReader) index.getSSTableReader(index.getVersion(),
						meta);
				Iterator<WritableComparableKey> iter = reader.keySetIter();
				while (iter.hasNext()) {
					WritableComparableKey key = iter.next();
					int expect = ExpectedResult(key, reader, window);
					int answer = queryResult(key, reader, window);
					// fos.close();
					System.out.println("expected size:" + expect + "," + expect);
					Assert.assertEquals(expect, answer);
				}
				((BDBBtree.BDBKeyIterator) iter).close();
			}
		} finally {
			index.close();
		}
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.zing.boundservicesample.BrainyActivity" >

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="START" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="STOP" />

    <Button
        android:id="@+id/startIntentService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Intent Service" />

    <Button
        android:id="@+id/stopIntentService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Intent Service" />

    <Button
        android:id="@+id/bindService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />

    <Button
        android:id="@+id/unbindService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />

    <Button
        android:id="@+id/messageService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Message Service" />

</LinearLayout>


text:
package com.jetbrains.rest.psi;

import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.psi.NavigatablePsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.rest.validation.RestElementVisitor;
import org.jetbrains.annotations.NotNull;

public class RestElement extends ASTWrapperPsiElement implements NavigatablePsiElement {

  public RestElement(@NotNull final ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    return "RestElement:" + getNode().getElementType().toString();
  }

  protected void acceptRestVisitor(RestElementVisitor visitor) {
    visitor.visitRestElement(this);
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof RestElementVisitor) {
      acceptRestVisitor(((RestElementVisitor)visitor));
    }
    else {
      super.accept(visitor);
    }
  }

}


text:
package ua.com.fielden.platform.entity.annotation.factory;

import java.lang.annotation.Annotation;

import ua.com.fielden.platform.entity.annotation.mutator.AfterChange;
import ua.com.fielden.platform.entity.annotation.mutator.ClassParam;
import ua.com.fielden.platform.entity.annotation.mutator.DateParam;
import ua.com.fielden.platform.entity.annotation.mutator.DateTimeParam;
import ua.com.fielden.platform.entity.annotation.mutator.DblParam;
import ua.com.fielden.platform.entity.annotation.mutator.EnumParam;
import ua.com.fielden.platform.entity.annotation.mutator.IntParam;
import ua.com.fielden.platform.entity.annotation.mutator.MoneyParam;
import ua.com.fielden.platform.entity.annotation.mutator.PropParam;
import ua.com.fielden.platform.entity.annotation.mutator.StrParam;
import ua.com.fielden.platform.entity.meta.IAfterChangeEventHandler;

public class AfterChangeAnnotation<T> {

    private final Class<? extends IAfterChangeEventHandler<T>> value;

    public AfterChangeAnnotation(final Class<? extends IAfterChangeEventHandler<T>> value) {
        this.value = value;
    }

    public AfterChange newInstance() {
        return new AfterChange() {

            @Override
            public Class<? extends Annotation> annotationType() {
                return AfterChange.class;
            }

            @Override
            public Class<? extends IAfterChangeEventHandler<?>> value() {
                return value;
            }

            @Override
            public StrParam[] str() {
                return new StrParam[0];
            }

            @Override
            public PropParam[] prop() {
                return new PropParam[0];
            }

            @Override
            public ClassParam[] non_ordinary() {
                return new ClassParam[0];
            }

            @Override
            public MoneyParam[] money() {
                return new MoneyParam[0];
            }

            @Override
            public IntParam[] integer() {
                return new IntParam[0];
            }

            @Override
            public DblParam[] dbl() {
                return new DblParam[0];
            }

            @Override
            public DateTimeParam[] date_time() {
                return new DateTimeParam[0];
            }

            @Override
            public DateParam[] date() {
                return new DateParam[0];
            }

            @Override
            public ClassParam[] clazz() {
                return new ClassParam[0];
            }

            @Override
            public EnumParam[] enumeration() {
                return new EnumParam[0];
            }
        };
    }

}


text:
package io.ray.serve.docdemo;

// docs-strategy-calc-start
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StrategyCalc {

  public static void main(String[] args) {
    long time = System.currentTimeMillis();
    String bank1 = "demo_bank_1";
    String bank2 = "demo_bank_2";
    String indicator1 = "demo_indicator_1";
    String indicator2 = "demo_indicator_2";
    Map<String, List<List<String>>> banksAndIndicators = new HashMap<>();
    banksAndIndicators.put(bank1, Arrays.asList(Arrays.asList(indicator1, indicator2)));
    banksAndIndicators.put(
        bank2, Arrays.asList(Arrays.asList(indicator1), Arrays.asList(indicator2)));

    Strategy strategy = new Strategy();
    List<String> results = strategy.calc(time, banksAndIndicators);

    System.out.println(results);
  }
}
// docs-strategy-calc-end


text:
__precompile__()
module HttpServer

using HttpCommon
using MbedTLS

include("RequestParser.jl")

export HttpHandler,
       Server,
       run,
       write,
       # from HttpCommon
       Request,
       Response,
       escapeHTML,
       parsequerystring,
       setcookie!

import Base: run, listen, close

defaultevents = Dict{ASCIIString, Function}()
defaultevents["error"]  = ( client, err )->println( err )
defaultevents["listen"] = ( saddr )      ->println("Listening on $saddr...")

"""
`HttpHandler` types are used to instantiate a `Server`.

An `HttpHandler` is responsible for the entirety of the request / response
cycle. Instantiate an `HttpHandler` with a single `Function` argument, which
becomes `HttpHandler.handle`. This handler is called on every incoming
request and passed `req::Request, res::Response`. The return value of
`HttpHandler.handle` is the response sent to the client for the given `req`.

`HttpHandler.handle` can return a `AbstractString`:

```
handler = HttpHandler() do req, res
  "Hello world!"
end
```

an HTTP status code as `Int`:

```
handler = HttpHandler() do req, res
  404
end
```

or a full `Response` instance:

```
handler = HttpHandler() do req, res
  Response(200, "Success", "Hello World!"
end
```

`HttpHandler.sock` is used internally to store the `TcpSocket` for incoming
connections.

`HttpHandler.events` is a dictionary of functions to call when certain
server events occur.
Set these functions by direct assignment:

```
handler.events["listen"] = (port) "Listening on \$port..."
```

All default events and their arguments:

* `"listen"  => (port::Int)`
* `"connect" => (client::Client)`
* `"write"   => (client::Client, res::Response)`
* `"close"   => (client::Client)`

If you want to trigger custom events on your server, use the `event`
function:

```
# listen for "foo"
handler.events["foo"] = (bar) "Hello \$bar"
# trigger "foo"
HttpServer.event(server, "foo", "Julia")
```
"""
immutable HttpHandler
    handle::Function
    sock::Base.TCPServer
    events::Dict

    HttpHandler(handle::Function, sock::Base.TCPServer) = new(handle, sock, defaultevents)
    HttpHandler(handle::Function) = new(handle, Base.TCPServer(), defaultevents)
end
handle(handler::HttpHandler, req::Request, res::Response) = handler.handle(req, res)

""" Client encapsulates a single connection

 When new connections are initialized a `Client` is created with a new id and
 the connection socket. `Client.parser` will store a `ClientParser` to handle
 all HTTP parsing for the connection lifecycle.
"""
type Client{T<:IO}
    id::Int
    sock::T
    parser::ClientParser

    Client(id::Int,sock::T) = new(id,sock)
end
Client{T<:IO}(id::Int,sock::T) = Client{T}(id,sock)

""" `WebSocketInterface` defines the abstract protocol for a WebSocketHandler.

The methods `is_websocket_handshake` and `handle` will be called if `Server.
sockets` is populated. Concrete types of `WebSocketInterface` are required
to define these methods.
"""
abstract WebSocketInterface

""" `is_websocket_handshake` should determine if `req` is a valid websocket
upgrade request.
"""
function is_websocket_handshake(handler::WebSocketInterface, req::Request)
    throw("`$(typeof(handler))` does not implement `is_websocket_handshake`.")
end

""" `handle` is called when `is_websocket_handshake` returns true, and takes
full control of the connection.
"""
function handle(handler::WebSocketInterface, req::Request, client::Client)
    throw("`$(typeof(handler))` does not implement `handle`.")
end

""" `Server` types encapsulate an `HttpHandler` and optional
`WebSocketInterface` to serve requests.

* Instantiate with both an `HttpHandler` and `WebSocketInterface` to serve
  both protocols.
* Instantiate with just an `HttpHandler` to serve only standard `Http`
* Instantiate with just a `Function` to create an `HttpHandler` automatically
* Instantiate with just a `WebSocketInterface` to only serve websockets
  requests and `404` all others.
"""
immutable Server
    http::HttpHandler
    websock::Union{Void, WebSocketInterface}
end
Server(http::HttpHandler)           = Server(http, nothing)
Server(handler::Function)           = Server(HttpHandler(handler))
Server(websock::WebSocketInterface) = Server(HttpHandler((req, res)->Response(404)), websock)

"""Triggers `event` on `server`.

If there is a function bound to `event` in `server.events` it will be called
with `args...`
"""
function event(event::AbstractString, server::Server, args...)
    haskey(server.http.events, event) && server.http.events[event](args...)
end

"""
Sets a cookie with the given name, value, and attributes on the given response object.
"""
setcookie!(r::Response, name, value=utf8(""), attrs=Dict{UTF8String, UTF8String}()) =
  setcookie!(r, Cookie(name, value, attrs))

setcookie!(r::Response, cookie::Cookie) = (r.cookies[cookie.name] = cookie; r)

import Base.write
"Converts a `Response` to an HTTP response string"
function write(io::IO, response::Response)
    write(io, join(["HTTP/1.1", response.status, HttpCommon.STATUS_CODES[response.status], "\r\n"], " "))

    response.headers["Content-Length"] = string(sizeof(response.data))
    for (header,value) in response.headers
        write(io, string(join([ header, ": ", value ]), "\r\n"))
    end
    for (cookie_name, cookie) in response.cookies
        write(io, "Set-Cookie: ", cookie_name, "=", cookie.value)
        for (attr_name, attr_val) in cookie.attrs
            write(io, "; ", attr_name)
            if !isempty(attr_val)
                write(io, "=", attr_val)
            end
        end
        write(io, "\r\n")
    end

    write(io, "\r\n")
    write(io, response.data)
end

""" Start `server` to listen on specified socket address.

    listen(server::Server, host::Base.IPAddr, port::Integer) Server

    Setup "server" so it listens on "port" on the address specified by "host".
    To listen on all interfaces pass, "IPv4(0)" or "IPv6(0)" as appropriate.
"""
function listen(server::Server, host::Base.IPAddr, port::Integer)
    Base.uv_error("listen", !bind(server.http.sock, host, UInt16(port)))
    listen(server.http.sock)
    inet = "$host:$port"
    event("listen", server, inet)
    return server
end
listen(server::Server, port::Integer) = listen(server, IPv4(0), port)

""" Start `server` to listen on named pipe/domain socket.

    listen(server::Server, path::AbstractString) Server

    Setup "server" to listen on named pipe/domain socket specified by "path".
"""
@unix_only function listen(server::Server, path::AbstractString)
    bind(server.http.sock, path) || throw(ArgumentError("could not listen on path $path"))
    Base.uv_error("listen", Base._listen(server.http.sock))
    event("listen", server, path)
    return server
end

""" Handle HTTP request from client """
function handle_http_request(server::Server)
    id_pool = 0 # Increments for each connection
    websockets_enabled = server.websock != nothing
    while true # handle requests, Base.wait_accept blocks until a connection is made
        sock = TCPSocket()
        try
            sock = accept(server.http.sock)
        catch e
            if !isopen(server.http.sock)
                # Server was closed while waiting to accept client. Exit gracefully.
                break
            end
            throw(e)
        end
        client = Client(id_pool += 1, sock)
        client.parser = ClientParser(message_handler(server, client, websockets_enabled))
        @async process_client(server, client, websockets_enabled)
    end
end

""" Handle HTTPS request from client """
function handle_https_request(server::Server, ssl_config::MbedTLS.SSLConfig)
    id_pool = 0 # Increments for each connection
    websockets_enabled = server.websock != nothing
    while true
        sess = MbedTLS.SSLContext()
        MbedTLS.setup!(sess, ssl_config)
        sock = TCPSocket()
        # set_priority_string!(sess)
        # set_credentials!(sess, cert_store)
        try
            sock = accept(server.http.sock)
        catch e
            if !isopen(server.http.sock)
                # Server was closed while waiting to accept client. Exit gracefully.
                break
            end
            throw(e)
        end
        try
            MbedTLS.set_bio!(sess, sock)
            MbedTLS.handshake(sess)
            # associate_stream(sess, client)
            # handshake!(sess)
        catch e
            println("Error establishing SSL connection: ", e)
            close(sock)
            continue
        end
        client = Client(id_pool += 1, sess)
        client.parser = ClientParser(message_handler(server, client, websockets_enabled))
        @async process_client(server, client, websockets_enabled)
    end
end

function default_ssl_config(ssl_cert, key)
    conf = MbedTLS.SSLConfig()
    entropy = MbedTLS.Entropy()
    rng = MbedTLS.CtrDrbg()
    MbedTLS.config_defaults!(conf, endpoint=MbedTLS.MBEDTLS_SSL_IS_SERVER)
    MbedTLS.seed!(rng, entropy)
    MbedTLS.rng!(conf, rng)
    MbedTLS.own_cert!(conf, ssl_cert, key)
    MbedTLS.dbg!(conf, (level, filename, number, msg)->begin
        warn("MbedTLS emitted debug info: $msg in $filename:$number")
    end)
    conf
end

function handle_https_request(server::Server, ssl_cert::Tuple{MbedTLS.CRT, MbedTLS.PKContext})
    handle_https_request(server, default_ssl_config(ssl_cert...))
end

""" `run` starts `server`

Functionality:

* Accepts incoming connections and instantiates each `Client`.
* Manages the `client.id` pool.
* Spawns a new `Task` for each connection.
* Blocks forever.

Method accepts following keyword arguments:

* host - binding address
* port - binding port
* ssl  - SSL configuration. Use this argument to enable HTTPS support.
Can be either an MbedTLS.SSLConfig object that already
has associated certificates, or a tuple of an MbedTLS.CRT (certificate) and
MbedTLS.PKContext (private key)). In the latter case, a configuration with reasonable
defaults will be used.

* socket - named pipe/domain socket path. Use this argument to enable Unix socket support.
It's available only on Unix. Network options are ignored.

Compatibility:

* for backward compatibility use `run(server::Server, port::Integer)`

Example:
```
server = Server() do req, res
  "Hello world"
end

# start server on localhost
run(server, host=IPv4(127,0,0,1), port=8000)
# or
run(server, 8000)
```
"""
function run(server::Server; args...)
    params = Dict(args)

    # parse parameters
    port = get(params, :port, 0)
    host = get(params, :host, IPv4(0))
    use_https = haskey(params, :ssl)
    use_sockets = @unix? (haskey(params, :socket) && !haskey(params, :port)) : false

    server = if use_sockets
        listen(server, params[:socket])  # start server on Unix socket
    else
        host, port
        listen(server, host, port)       # start server on network socket
    end

    if use_https
        handle_https_request(server, params[:ssl])
    else
        handle_http_request(server)
    end
end
# backward compatibility method
run(server::Server, port::Integer) = run(server, port=port)

"""Handles live connections, runs inside a `Task`.

Blocks ( yields ) until a line can be read, then passes it into `client.
parser`.
"""
function process_client(server::Server, client::Client, websockets_enabled::Bool)
    event("connect", server, client)

    while !eof(client.sock)#isopen(client.sock)
        # try
            if !upgrade(client.parser.parser)
                # IMPORTANT NOTE: This is technically incorrect as there may be data
                # in the buffer that we have not yet read. The way to deal with this
                # is to manually adjust the position of the buffer, but for that to
                # happen, we need use the return value of http_parser_execute, which
                # we don't have, since we launch websocket handlers in the callback.
                # Anyway, since there always needs to be a handshake this is probably
                # fine for now.
                data = readavailable(client.sock)
                if length(data) > 0
                    add_data(client.parser, data)
                end
            else
                wait(client.sock.closenotify)
            end
        # catch e
        #     if isa(e,GnuTLS.GnuTLSException) && e.code == -110
        #         # Because Chrome is buggy on OS X, ignore E_PREMATURE_TERMINATION
        #     else
        #         rethrow()
        #     end
        # end
    end
    event("close", server, client)
end

""" Closes the Server `server` by closing the underlying TCPServer `sock` in the HttpHandler. """
close(server::Server) = close(server.http.sock)

"Callback factory for providing `on_message_complete` for `client.parser`"
function message_handler(server::Server, client::Client, websockets_enabled::Bool)

    # Called when the `ClientParser` has finished parsing a `Request`.
    #
    # If websockets are enabled and claim this request, defer to `server.
    # websock` and return. Otherwise, call `server.http.handle` to get a
    # `Response` for the `client`. Catches any errors with `server.http.
    # handle`, returns a `500` and writes a stacktrace to `stdout`.
    #
    function on_message_complete(req::Request)
        if websockets_enabled && is_websocket_handshake(server.websock, req)
            handle(server.websock, req, client)
            return true
        end

        local response

        try
            response = handle(server.http, req, Response()) # Run the server handler
            if !isa(response, Response)                     # Promote return to Response
                response = Response(response)
            end
        catch err
            response = Response(500)
            event("error", server, client, err)
            Base.display_error(err, catch_backtrace())      # Prints backtrace without throwing
        end

        # We have a Keep-Alive header set to 0 or 1 in RequestParser
        # to denote if the client wants keep-alive or not
        # We also have to check if the server wants to close the connection
        # If this is keep-alive, we need to add Connection header with keep-alive
        local keep_alive = get(req.headers, "Keep-Alive", nothing) == "1" &&
                           get(response.headers, "Connection", nothing) != "close"
        if keep_alive
            response.headers["Connection"] = "keep-alive"
        end

        write(client.sock, response)
        event("write", server, client, response)

        if !keep_alive
            close(client.sock)
        end
    end
end

include("mimetypes.jl")

function FileResponse(filename)
    if isfile(filename)
        s = open(readbytes,filename)
        (_, ext) = splitext(filename)
        mime = length(ext)>1 && haskey(mimetypes,ext[2:end]) ? mimetypes[ext[2:end]] : "application/octet-stream"
        Response(200, Dict{AbstractString,AbstractString}([("Content-Type",mime)]), s)
    else
        Response(404, "Not Found - file $filename could not be found")
    end
end

function __init__()
    # Turn all the callbacks into C callable functions.
    global const on_message_begin_cb = cfunction(on_message_begin, HTTP_CB...)
    global const on_url_cb = cfunction(on_url, HTTP_DATA_CB...)
    global const on_status_complete_cb = cfunction(on_status_complete, HTTP_CB...)
    global const on_header_field_cb = cfunction(on_header_field, HTTP_DATA_CB...)
    global const on_header_value_cb = cfunction(on_header_value, HTTP_DATA_CB...)
    global const on_headers_complete_cb = cfunction(on_headers_complete, HTTP_CB...)
    global const on_body_cb = cfunction(on_body, HTTP_DATA_CB...)
    global const on_message_complete_cb = cfunction(on_message_complete, HTTP_CB...)
    global const on_chunk_header_cb = cfunction(on_chunk_header, HTTP_CB...)
    global const on_chunk_complete_cb = cfunction(on_chunk_complete, HTTP_CB...)
end

end # module HttpServer


text:
========================
 S3 compatibility tests
========================

This is a set of completely unofficial Amazon AWS S3 compatibility
tests, that will hopefully be useful to people implementing software
that exposes an S3-like API.

The tests only cover the REST interface.

TODO: test direct HTTP downloads, like a web browser would do.

The tests use the Boto library, so any e.g. HTTP-level differences
that Boto papers over, the tests will not be able to discover. Raw
HTTP tests may be added later.

The tests use the Nose test framework. To get started, ensure you have
the ``virtualenv`` software installed; e.g. on Debian/Ubuntu::

	sudo apt-get install python-virtualenv

and then run::

	./bootstrap

You will need to create a configuration file with the location of the
service and two different credentials, something like this::

	[DEFAULT]
	## this section is just used as default for all the "s3 *"
        ## sections, you can place these variables also directly there

	## replace with e.g. "localhost" to run against local software
	host = s3.amazonaws.com

	## uncomment the port to use something other than 80
	# port = 8080

	## say "no" to disable TLS
	is_secure = yes

	[fixtures]
	## all the buckets created will start with this prefix;
	## {random} will be filled with random characters to pad
	## the prefix to 30 characters long, and avoid collisions
	bucket prefix = YOURNAMEHERE-{random}-

	[s3 main]
	## the tests assume two accounts are defined, "main" and "alt".

	## user_id is a 64-character hexstring
	user_id = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

	## display name typically looks more like a unix login, "jdoe" etc
	display_name = youruseridhere

	## replace these with your access keys
	access_key = ABCDEFGHIJKLMNOPQRST
	secret_key = abcdefghijklmnopqrstuvwxyzabcdefghijklmn

	[s3 alt]
	## another user account, used for ACL-related tests
	user_id = 56789abcdef0123456789abcdef0123456789abcdef0123456789abcdef01234
	display_name = john.doe
	## the "alt" user needs to have email set, too
	email = john.doe@example.com
	access_key = NOPQRSTUVWXYZABCDEFG
	secret_key = nopqrstuvwxyzabcdefghijklmnabcdefghijklm

Once you have that, you can run the tests with::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests

You can specify what test(s) to run::

	S3TEST_CONF=your.conf ./virtualenv/bin/nosetests s3tests.functional.test_s3:test_object_acl_grant_public_read

Some tests have attributes set based on their current reliability and
things like AWS not enforcing their spec stricly. You can filter tests
based on their attributes::

	S3TEST_CONF=aws.conf ./virtualenv/bin/nosetests -a '!fails_on_aws'

TODO
====

- We should assume read-after-write consistency, and make the tests
  actually request such a location.

  http://aws.amazon.com/s3/faqs/#What_data_consistency_model_does_Amazon_S3_employ


text:
echo With NS 3.0 you won\'t be able to use the POSIX module.		>&4
echo Be aware that some of the tests that are run during \"make test\"	>&4
echo will fail due to the lack of POSIX support on this system.		>&4
echo									>&4
echo Also, if you have the GDBM installed, make sure the header file	>&4
echo is located at a place on the system where the C compiler will	>&4
echo find it.  By default, it is placed in /usr/local/include/gdbm.h.	>&4
echo It will not be found there.  Try moving it to			>&4
echo /NextDeveloper/Headers/bsd/gdbm.h.					>&4

ccflags="$ccflags -DUSE_NEXT_CTYPE"
POSIX_cflags='ccflags="-posix $ccflags"'
useposix='undef'
ldflags="$ldflags -u libsys_s"
libswanted="$libswanted dbm gdbm db"
#
lddlflags='-r'
# Give cccdlflags an empty value since Configure will detect we are
# using GNU cc and try to specify -fpic for cccdlflags.
cccdlflags=' '
#
i_utime='undef'
groupstype='int'
direntrytype='struct direct'
d_strcoll='undef'
# the simple program `for ($i=1;$i<38771;$i++){$t{$i}=123}' fails
# with Larry's malloc on NS 3.2 due to broken sbrk()
usemymalloc='n'
d_uname='define'

# Thanks to Etienne Grossman <etienne@isr.isr.ist.utl.pt> for sending
# the correct values for perl5.003_11 for the following 4
# variables. For older version all four were defined.
d_setsid='undef'
d_tcgetpgrp='undef'
d_tcsetpgrp='undef'
d_setpgid='undef'

#
# On some NeXT machines, the timestamp put by ranlib is not correct, and
# this may cause useless recompiles.  Fix that by adding a sleep before
# running ranlib.  The '5' is an empirical number that's "long enough."
# (Thanks to Andreas Koenig <k@franz.ww.tu-berlin.de>)
ranlib='sleep 5; /bin/ranlib'

# Doesn't support attributes, so we'll set that here.
d_attribute_format='undef'
d_attribute_malloc='undef'
d_attribute_nonnull='undef'
d_attribute_noreturn='undef'
d_attribute_pure='undef'
d_attribute_unused='undef'
d_attribute_warn_unused_result='undef'


text:
package io.rapidpro.flows.definition.tests.numeric;

import com.google.gson.JsonElement;
import io.rapidpro.expressions.EvaluationContext;
import io.rapidpro.flows.definition.Flow;
import io.rapidpro.flows.definition.FlowParseException;
import io.rapidpro.flows.definition.tests.Test;
import io.rapidpro.flows.runner.Runner;
import io.rapidpro.flows.utils.JsonUtils;

import java.math.BigDecimal;

/**
 * Test which returns whether input has a number
 */
public class HasNumberTest extends NumericTest {

    public static final String TYPE = "number";

    /**
     * @see Test#fromJson(JsonElement, Flow.DeserializationContext)
     */
    public static HasNumberTest fromJson(JsonElement elm, Flow.DeserializationContext context) throws FlowParseException {
        return new HasNumberTest();
    }

    @Override
    public JsonElement toJson() {
        return JsonUtils.object("type", TYPE);
    }

    /**
     * @see NumericTest#evaluateForDecimal(Runner, EvaluationContext, BigDecimal)
     */
    @Override
    protected boolean evaluateForDecimal(Runner runner, EvaluationContext context, BigDecimal decimal) {
        return true; // this method is only called on decimals parsed from the input
    }
}


text:
from django.views.generic import ListView

from django.contrib.auth import get_user_model

class UsersListView(ListView):

    model = get_user_model()
    template_name = "sample/users.html"

# class ProfilePage(Page):
#     user_details = UserInfo()
#     tabs = TabCollection()
#     tabs2 = TabCollection()
#
#     class Meta:
#         template_name="profile.html"
#
#
# class UserInfo(DetailComponent, TemplateView):
#
#     class Meta:
#         endpoint = 'api-user-info'
#         verb = 'GET'
#         template_name = 'userinfo.html'
#
#         list_display = [
#             {
#                 'field': 'picture',
#                 'widget': 'widget-img',
#             }, {
#                 'field': 'full_name'
#             }, {
#                 'field': 'username'
#             }
#         ]
#
#     def get_endpoint_full_url(self, **kwargs):
#         kwargs['username'] = self.request.kwargs['username']
#         return super(UserInfo, self).get_endpoint_full_url(**kwargs)
#
#
# class TabCollection(ComponentCollection, TemplateView):
#     components = [
#         ContributionsTab,
#         RepositoriesTab,
#         QctivityTab,
#     ]
#     template_name = 'tabs.html'
#
#
# class TabComponent(ComponentCollection, TemplateView):
#     template_name = 'tab.html'
#
#
# class ContributionsTab(TabComponent):
#     components = [
#         PopularRepoList,
#         ContributedToList,
#         ConttributionsList,
#     ]
#
#
# class PopularRepoList(ListComponent):
#     endpoint = 'popular_repo'
#     actions = [
#         Action('details', 'repo', params=['slug']),
#     ]
#     list_display = [
#         {
#             'field': 'is_fork',
#             'widget': 'widget-fork',G
#         }, {
#             'field': 'path'
#         }, {
#             'field': 'stars',
#             'widget': 'widget-star',
#         }
#     ]
#
#
# class ContributedToList(ListComponent):
#     endpoint = 'contributed_to_repo'
#     actions = [
#         Action('details', 'GET', 'repo', params=['slug']),
#     ]
#
#
# class ConttributionsList(ListComponent):
#     endpoint = 'contributions'


text:
package com.sleepycat.persist.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sleepycat.compat.DbCompat;
import com.sleepycat.persist.model.ClassMetadata;
import com.sleepycat.persist.model.EntityModel;
import com.sleepycat.persist.model.FieldMetadata;
import com.sleepycat.persist.raw.RawField;
import com.sleepycat.persist.raw.RawObject;
import com.sleepycat.je.utilint.IdentityHashMap;

/**
 * Format for a composite key class.
 *
 * This class is similar to ComplexFormat in that a composite key class and
 * other complex classes have fields, and the Accessor interface is used to
 * access those fields.  Composite key classes are different in the following
 * ways:
 *
 * - The superclass must be Object.  No inheritance is allowed.
 *
 * - All instance fields must be annotated with @KeyField, which determines
 *   their order in the data bytes.
 *
 * - Although fields may be reference types (primitive wrappers or other simple
 *   reference types), they are stored as if they were primitives.  No object
 *   format ID is stored, and the class of the object must be the declared
 *   classs of the field; i.e., no polymorphism is allowed for key fields.
 *   In other words, a composite key is stored as an ordinary tuple as defined
 *   in the com.sleepycat.bind.tuple package.  This keeps the key small and
 *   gives it a well defined sort order.
 *
 * - If the key class implements Comparable, it is called by the Database
 *   btree comparator.  It must therefore be available during JE recovery,
 *   before the store and catalog have been opened.  To support this, this
 *   format can be constructed during recovery.  A SimpleCatalog singleton
 *   instance is used to provide a catalog of simple types that is used by
 *   the composite key format.
 *
 * - When interacting with the Accessor, the composite key format treats the
 *   Accessor's non-key fields as its key fields.  The Accessor's key fields
 *   are secondary keys, while the composite format's key fields are the
 *   component parts of a single key.
 *
 * @author Mark Hayes
 */
public class CompositeKeyFormat extends Format {

    private static final long serialVersionUID = 306843428409314630L;

    private ClassMetadata metadata;
    private List<FieldInfo> fields;
    private transient Accessor objAccessor;
    private transient Accessor rawAccessor;
    private transient volatile Map<String, RawField> rawFields;
    private transient volatile FieldInfo[] rawInputFields;

    static String[] getFieldNameArray(List<FieldMetadata> list) {
        int index = 0;
        String[] a = new String[list.size()];
        for (FieldMetadata f : list) {
            a[index] = f.getName();
            index += 1;
        }
        return a;
    }

    /**
     * Creates a new composite key format.
     */
    CompositeKeyFormat(Catalog catalog,
                       Class cls,
                       ClassMetadata metadata,
                       List<FieldMetadata> fieldMeta) {
        this(catalog, cls, metadata, getFieldNameArray(fieldMeta));
    }

    /**
     * Reconsistitues a composite key format after a PersistComparator is
     * deserialized.
     */
    CompositeKeyFormat(Catalog catalog, Class cls, String[] fieldNames) {
        this(catalog, cls, null /*metadata*/, fieldNames);
    }

    private CompositeKeyFormat(Catalog catalog,
                               Class cls,
                               ClassMetadata metadata,
                               String[] fieldNames) {
        super(catalog, cls);
        this.metadata = metadata;

        /* Check that the superclass is Object. */
        Class superCls = cls.getSuperclass();
        if (superCls != Object.class) {
            throw new IllegalArgumentException
                ("Composite key class must be derived from Object: " +
                 cls.getName());
        }

        /* Populate fields list in fieldNames order. */
        List<FieldInfo> instanceFields =
            FieldInfo.getInstanceFields(cls, metadata);
        fields = new ArrayList<FieldInfo>(instanceFields.size());
        for (String fieldName : fieldNames) {
            FieldInfo field = null;
            for (FieldInfo tryField : instanceFields) {
                if (fieldName.equals(tryField.getName())) {
                    field = tryField;
                    break;
                }
            }
            if (field == null) {
                throw new IllegalArgumentException
                    ("Composite key field is not an instance field: " +
                     getClassName() + '.' + fieldName);
            }
            fields.add(field);
            instanceFields.remove(field);
            Class fieldCls = field.getFieldClass(getCatalog());
            if (!SimpleCatalog.isSimpleType(fieldCls) &&
                !fieldCls.isEnum()) {
                throw new IllegalArgumentException
                    ("Composite key field is not a simple type or enum: " +
                     getClassName() + '.' + fieldName);
            }
        }
        if (instanceFields.size() > 0) {
            throw new IllegalArgumentException
                ("All composite key instance fields must be key fields: " +
                 getClassName() + '.' + instanceFields.get(0).getName());
        }
    }

    List<FieldInfo> getFieldInfo() {
        return fields;
    }

    @Override
    void migrateFromBeta(Map<String, Format> formatMap) {
        super.migrateFromBeta(formatMap);
        for (FieldInfo field : fields) {
            field.migrateFromBeta(formatMap);
        }
    }

    @Override
    boolean isModelClass() {
        return true;
    }

    @Override
    public ClassMetadata getClassMetadata() {
        if (metadata == null) {
            throw DbCompat.unexpectedState(getClassName());
        }
        return metadata;
    }

    @Override
    public Map<String, RawField> getFields() {

        /*
         * Lazily create the raw type information.  Synchronization is not
         * required since this object is immutable.  If by chance we create two
         * maps when two threads execute this block, no harm is done.  But be
         * sure to assign the rawFields field only after the map is fully
         * populated.
         */
        if (rawFields == null) {
            Map<String, RawField> map = new HashMap<String, RawField>();
            for (RawField field : fields) {
                map.put(field.getName(), field);
            }
            rawFields = map;
        }
        return rawFields;
    }

    @Override
    void collectRelatedFormats(Catalog catalog,
                               Map<String, Format> newFormats) {
        /* Collect field formats. */
        for (FieldInfo field : fields) {
            field.collectRelatedFormats(catalog, newFormats);
        }
    }

    @Override
    void initialize(Catalog catalog, EntityModel model, int initVersion) {
        /* Initialize all fields. */
        for (FieldInfo field : fields) {
            field.initialize(catalog, model, initVersion);
        }
        /* Create the accessor. */
        Class type = getType();
        if (type != null) {
            if (EnhancedAccessor.isEnhanced(type)) {
                objAccessor = new EnhancedAccessor(catalog, type, fields);
            } else {
                objAccessor = new ReflectionAccessor(catalog, type, fields);
            }
        }
        rawAccessor = new RawAccessor(this, fields);
    }

    @Override
    Object newArray(int len) {
        return objAccessor.newArray(len);
    }

    @Override
    public Object newInstance(EntityInput input, boolean rawAccess) {
        Accessor accessor = rawAccess ? rawAccessor : objAccessor;
        return accessor.newInstance();
    }

    @Override
    public Object readObject(Object o, EntityInput input, boolean rawAccess)
        throws RefreshException {

        Accessor accessor = rawAccess ? rawAccessor : objAccessor;
        accessor.readCompositeKeyFields(o, input);
        return o;
    }

    @Override
    void writeObject(Object o, EntityOutput output, boolean rawAccess)
        throws RefreshException {

        Accessor accessor = rawAccess ? rawAccessor : objAccessor;
        accessor.writeCompositeKeyFields(o, output);
    }

    @Override
    Object convertRawObject(Catalog catalog,
                            boolean rawAccess,
                            RawObject rawObject,
                            IdentityHashMap converted)
        throws RefreshException {

        /*
         * Synchronization is not required since rawInputFields is immutable.
         * If by chance we create duplicate values when two threads execute
         * this block, no harm is done.  But be sure to assign the field only
         * after the values are fully populated.
         */
        FieldInfo[] myFields = rawInputFields;
        if (myFields == null) {
            myFields = new FieldInfo[fields.size()];
            fields.toArray(myFields);
            rawInputFields = myFields;
        }
        if (rawObject.getSuper() != null) {
            throw new IllegalArgumentException
                ("RawObject has too many superclasses: " +
                 rawObject.getType().getClassName());
        }
        RawObject[] objects = new RawObject[myFields.length];
        Arrays.fill(objects, rawObject);
        EntityInput in = new RawComplexInput
            (catalog, rawAccess, converted, myFields, objects);
        Object o = newInstance(in, rawAccess);
        converted.put(rawObject, o);
        return readObject(o, in, rawAccess);
    }

    @Override
    void skipContents(RecordInput input)
        throws RefreshException {

        int maxNum = fields.size();
        for (int i = 0; i < maxNum; i += 1) {
            fields.get(i).getType().skipContents(input);
        }
    }

    @Override
    void copySecKey(RecordInput input, RecordOutput output) {
        int maxNum = fields.size();
        for (int i = 0; i < maxNum; i += 1) {
            fields.get(i).getType().copySecKey(input, output);
        }
    }

    @Override
    Format getSequenceKeyFormat() {
        if (fields.size() != 1) {
            throw new IllegalArgumentException
                ("A composite key class used with a sequence may contain " +
                 "only a single key field: " + getClassName());
        }
        return fields.get(0).getType().getSequenceKeyFormat();
    }

    @Override
    boolean evolve(Format newFormatParam, Evolver evolver) {

        /* Disallow evolution to a non-composite format. */
        if (!(newFormatParam instanceof CompositeKeyFormat)) {
            evolver.addEvolveError
                (this, newFormatParam, null,
                 "A composite key class may not be changed to a different " +
                 "type");
            return false;
        }
        CompositeKeyFormat newFormat = (CompositeKeyFormat) newFormatParam;

        /* Check for added or removed key fields. */
        if (fields.size() != newFormat.fields.size()) {
            evolver.addEvolveError
                (this, newFormat,
                 "Composite key class fields were added or removed ",
                 "Old fields: " + fields +
                 " new fields: " + newFormat.fields);
            return false;
        }

        /* Check for modified key fields. */
        boolean newVersion = false;
        for (int i = 0; i < fields.size(); i += 1) {
            int result = evolver.evolveRequiredKeyField
                (this, newFormat, fields.get(i),
                 newFormat.fields.get(i));
            if (result == Evolver.EVOLVE_FAILURE) {
                return false;
            }
            if (result == Evolver.EVOLVE_NEEDED) {
                newVersion = true;
            }
        }

        /*
         * We never need to use a custom reader because the physical key field
         * formats never change.  But we do create a new evolved format when
         * a type changes (primitive <-> primitive wrapper) so that the new
         * type information is correct.
         */
        if (newVersion) {
            evolver.useEvolvedFormat(this, newFormat, newFormat);
        } else {
            evolver.useOldFormat(this, newFormat);
        }
        return true;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Linn. Soc. London 156(2): 107 (1944)

#### Original name
Meliola turraeae var. turraeae Hansf.

### Remarks
null


text:
package com.google.cloud.bigtable.grpc;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import com.google.bigtable.v1.BigtableServiceGrpc;
import com.google.bigtable.v1.CheckAndMutateRowRequest;
import com.google.bigtable.v1.MutateRowRequest;
import com.google.bigtable.v1.Mutation;
import com.google.bigtable.v1.Mutation.SetCell;
import com.google.common.base.Predicate;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import io.grpc.MethodDescriptor;

import java.util.Map;

@RunWith(JUnit4.class)
public class BigtableChannelsTest {

  @SuppressWarnings("unchecked")
  @Test
  public void createMethodRetryMap() {
    Map<MethodDescriptor<?, ?>, Predicate<?>> map = BigtableChannels.createMethodRetryMap();
    for (MethodDescriptor<?, ?> method: BigtableServiceGrpc.CONFIG.methods()) {
      if (method == BigtableServiceGrpc.CONFIG.mutateRow) {
        assertMutateRowPredicate((Predicate<MutateRowRequest>) map.get(method));
      } else if (method == BigtableServiceGrpc.CONFIG.checkAndMutateRow) {
        assertCheckAndMutateRowPredicate((Predicate<CheckAndMutateRowRequest>) map.get(method));
      } else {
        assertNull(map.get(method));
      }
    }
  }

  private static void assertMutateRowPredicate(Predicate<MutateRowRequest> predicate) {
    assertFalse(predicate.apply(null));

    MutateRowRequest.Builder request = MutateRowRequest.newBuilder();
    assertTrue(predicate.apply(request.build()));

    request.addMutations(
        Mutation.newBuilder().setSetCell(SetCell.newBuilder().setTimestampMicros(-1)));
    assertFalse(predicate.apply(request.build()));
  }

  private static void assertCheckAndMutateRowPredicate(
      Predicate<CheckAndMutateRowRequest> predicate) {
    assertFalse(predicate.apply(null));

    CheckAndMutateRowRequest.Builder request = CheckAndMutateRowRequest.newBuilder();
    assertTrue(predicate.apply(request.build()));

    request.addTrueMutations(
        Mutation.newBuilder().setSetCell(SetCell.newBuilder().setTimestampMicros(-1)));
    assertFalse(predicate.apply(request.build()));

    request.clearTrueMutations();
    request.addFalseMutations(
        Mutation.newBuilder().setSetCell(SetCell.newBuilder().setTimestampMicros(-1)));
    assertFalse(predicate.apply(request.build()));
  }
}


text:
class Tab;

namespace gfx {
class Point;
}
namespace ui {
class ListSelectionModel;
class LocatedEvent;
class MouseEvent;
}
namespace views {
class View;
}

// Controller for tabs.
class TabController {
 public:
  virtual const ui::ListSelectionModel& GetSelectionModel() = 0;

  // Returns true if multiple selection is supported.
  virtual bool SupportsMultipleSelection() = 0;

  // Selects the tab.
  virtual void SelectTab(Tab* tab) = 0;

  // Extends the selection from the anchor to |tab|.
  virtual void ExtendSelectionTo(Tab* tab) = 0;

  // Toggles whether |tab| is selected.
  virtual void ToggleSelected(Tab* tab) = 0;

  // Adds the selection from the anchor to |tab|.
  virtual void AddSelectionFromAnchorTo(Tab* tab) = 0;

  // Closes the tab.
  virtual void CloseTab(Tab* tab, CloseTabSource source) = 0;

  // Shows a context menu for the tab at the specified point in screen coords.
  virtual void ShowContextMenuForTab(Tab* tab,
                                     const gfx::Point& p,
                                     ui::MenuSourceType source_type) = 0;

  // Returns true if |tab| is the active tab. The active tab is the one whose
  // content is shown in the browser.
  virtual bool IsActiveTab(const Tab* tab) const = 0;

  // Returns true if the specified Tab is selected.
  virtual bool IsTabSelected(const Tab* tab) const = 0;

  // Returns true if the specified Tab is pinned.
  virtual bool IsTabPinned(const Tab* tab) const = 0;

  // Potentially starts a drag for the specified Tab.
  virtual void MaybeStartDrag(
      Tab* tab,
      const ui::LocatedEvent& event,
      const ui::ListSelectionModel& original_selection) = 0;

  // Continues dragging a Tab.
  virtual void ContinueDrag(views::View* view,
                            const ui::LocatedEvent& event) = 0;

  // Ends dragging a Tab. Returns whether the tab has been destroyed.
  virtual bool EndDrag(EndDragReason reason) = 0;

  // Returns the tab that contains the specified coordinates, in terms of |tab|,
  // or NULL if there is no tab that contains the specified point.
  virtual Tab* GetTabAt(Tab* tab,
                        const gfx::Point& tab_in_tab_coordinates) = 0;

  // Invoked when a mouse event occurs on |source|.
  virtual void OnMouseEventInTab(views::View* source,
                                 const ui::MouseEvent& event) = 0;

  // Returns true if |tab| needs to be painted. If false is returned the tab is
  // not painted. If true is returned the tab should be painted and |clip| is
  // set to the clip (if |clip| is empty means no clip).
  virtual bool ShouldPaintTab(const Tab* tab, gfx::Rect* clip) = 0;

  // Returns true if tabs painted in the rectangular light-bar style.
  virtual bool IsImmersiveStyle() const = 0;

 protected:
  virtual ~TabController() {}
};

#endif  // CHROME_BROWSER_UI_VIEWS_TABS_TAB_CONTROLLER_H_


text:
package com.hokolinks.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import com.hokolinks.utils.log.HokoLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Locale;
import java.util.UUID;

/**
 * Utils serves many purposes, but mostly loading and saving objects/strings to file or
 * to the SharedPreferences. It also provides utility methods to generate random UUIDs and
 * sanitizing routes.
 */
public class Utils {

    // Hoko folder name
    private static final String FOLDER_NAME = "hoko";
    // Hoko SharedPreferences key
    private static final String SHARED_PREFERENCES_STRING_KEY = "com.hoko.string";

    /**
     * Checks where the application has a given permission granted on the AndroidManifest.xml file.
     *
     * @param permission The permission to be checked.
     * @param context    A context object.
     * @return true if has permission, false otherwise.
     */
    public static boolean hasPermission(String permission, Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager.checkPermission(permission, context.getPackageName())
                    == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                HokoLog.e("Requesting permission " + permission
                        + " but it is not on the AndroidManifest.xml");
                return false;
            }
        } catch (Exception e) {
            HokoLog.e(e);
            return false;
        }
    }

    /**
     * Saves a string to the SharedPreferences with a given key.
     *
     * @param string  The string to be saved.
     * @param key     The key associated to the string value.
     * @param context A context object.
     */
    public static void saveString(String string, String key, Context context) {
        try {
            SharedPreferences sharedPreferences =
                    context.getSharedPreferences(SHARED_PREFERENCES_STRING_KEY,
                            Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, string).apply();
        } catch (NullPointerException e) {
            HokoLog.e(e);
        }
    }

    /**
     * Loads a string from the SharedPreferences with a given key.
     *
     * @param key     The key associated to the string value.
     * @param context A context object.
     * @return The string in case it exists, null otherwise.
     */
    public static String getString(String key, Context context) {
        try {
            SharedPreferences sharedPreferences =
                    context.getSharedPreferences(SHARED_PREFERENCES_STRING_KEY,
                            Context.MODE_PRIVATE);
            return sharedPreferences.getString(key, null);
        } catch (NullPointerException e) {
            HokoLog.e(e);
            return null;
        }
    }

    /**
     * Saves an object to the private filesystem of the application.
     *
     * @param object   The object to be saved, needs to implement Serializable.
     * @param filename The filename with which it should be saved.
     * @param context  A context object.
     */
    public static void saveToFile(Object object, String filename, Context context) {
        try {
            FileOutputStream fileOutputStream =
                    new FileOutputStream(fileFromFilename(filename, context));
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
        } catch (IOException | NullPointerException e) {
            HokoLog.e(e);
        }
    }

    /**
     * Loads an object from the private filesystem of the application.
     *
     * @param filename The filename from which it should be loaded.
     * @param context  A context object.
     * @return The object that was previously saved, or null.
     */
    public static Object loadFromFile(String filename, Context context) {
        try {
            FileInputStream fileInputStream =
                    new FileInputStream(fileFromFilename(filename, context));
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Object object = objectInputStream.readObject();
            objectInputStream.close();
            return object;
        } catch (FileNotFoundException e) {
            // ignore
        } catch (Exception e) {
            HokoLog.e(e);
        }
        return null;
    }

    /**
     * Generates a random UUID string adding a time factor to guarantee some more randomness.
     *
     * @return A random UUID string.
     */
    public static String generateUUID() {
        String uid = UUID.randomUUID().toString().toUpperCase(Locale.ENGLISH);
        long timeSince1970 = Calendar.getInstance().getTimeInMillis();
        return uid + "-" + tenCharEpoch(timeSince1970);
    }

    /**
     * Sanitizes a route by replacing leading and ending '/' characters.
     *
     * @param route The route string.
     * @return The sanitized route string.
     */
    public static String sanitizeRoute(String route) {
        String sanitizedRoute = route.replaceAll("^/+", "");
        sanitizedRoute = sanitizedRoute.replaceAll("/+$", "");
        return sanitizedRoute;
    }

    /**
     * Helper function to return the File from a given filename.
     *
     * @param filename The filename corresponding to the File.
     * @param context  A context object.
     * @return The File.
     */
    private static File fileFromFilename(String filename, Context context) {
        File directory = context.getDir(FOLDER_NAME, Context.MODE_PRIVATE);
        return new File(directory, filename);
    }

    /**
     * Cut and format unix epoch to 10 chars long
     *
     * @param epoch to be formated
     * @return 10 char epoch
     */
    private static String tenCharEpoch(long epoch) {
        String timeSince1970 = String.valueOf(epoch);
        if(timeSince1970.length() >= 10) {
            return timeSince1970.substring(0, 10);
        } else {
            return String.format("%010d", epoch);
        }
    }
}


text:
package com.diandi.demo.widget.gitonway.lee.niftynotification.effects;

import android.view.View;

import com.nineoldandroids.animation.ObjectAnimator;

public class Jelly extends BaseEffect {

    @Override
    protected void setInAnimation(View view) {
        getAnimatorSet().playTogether(
                ObjectAnimator.ofFloat(view, "scaleX", .3f, .5f, .9f, .8f, .9f, 1).setDuration(mDuration),
                ObjectAnimator.ofFloat(view, "scaleY", .3f, .5f, .8f, .9f, .8f, 1).setDuration(mDuration),
                ObjectAnimator.ofFloat(view, "alpha", 0, 1).setDuration(mDuration * 3 / 2)
        );
    }

    @Override
    protected void setOutAnimation(View view) {
        getAnimatorSet().playTogether(
//                ObjectAnimator.ofFloat(view, "scaleX", 1,.9f,.8f,.9f,.5f,0).setDuration(mDuration),
//                ObjectAnimator.ofFloat(view,"scaleY",1,.8f,.9f,.8f,.5f,0).setDuration(mDuration),
                ObjectAnimator.ofFloat(view, "alpha", 1, 0).setDuration(mDuration * 2 / 3)
        );
    }

    @Override
    protected long getAnimDuration(long duration) {
        return duration;
    }
}