text:
<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * The Docs controller provides access to Bonfire's documentation and allows the
 * developer to provide access to documentation for their application.
 *
 * @package Bonfire\Modules\Docs\Controllers\Docs
 * @author  Bonfire Dev Team
 * @link    http://cibonfire.com/docs
 */
class Docs extends Base_Controller
{
    protected $docsDir     = 'docs';
    protected $docsExt     = '.md';
    protected $docsGroup   = null;
    protected $docsParser  = null;
    protected $docsTypeApp = 'application';
    protected $docsTypeBf  = 'developer';
    protected $docsTypeMod = 'module';

    protected $ignoreFiles  = array('_404.md');
    protected $tocFile;

    private $showAppDocs;
    private $showDevDocs;

    //--------------------------------------------------------------------------

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->load->library('template');
        $this->load->library('assets');

        $this->load->config('docs');
        $this->lang->load('docs');

        $this->docsGroup = $this->uri->segment(2);

        // Is displaying docs permitted for this environment?
        if (config_item('docs.permitted_environments')
            && ! in_array(ENVIRONMENT, config_item('docs.permitted_environments'))
        ) {
            Template::set_message(lang('docs_env_disabled'), 'error');
            redirect();
        }

        // Was a doc group provided?
        if (! $this->docsGroup) {
            redirect('docs/' . config_item('docs.default_group'));
        }

        $this->showAppDocs = config_item('docs.show_app_docs');
        $this->showDevDocs = config_item('docs.show_dev_docs');
        $this->tocFile = config_item('docs.toc_file') ?: '_toc.ini';
        $commonmark_driver = config_item('docs.commonmark_driver');
        $this->docsParser = empty($commonmark_driver) ? null : $commonmark_driver;

        // Make sure we can still get to the search method.
        if ($this->docsGroup == 'search') {
            $this->docsGroup = false;
        } elseif ($this->docsGroup == $this->docsTypeBf
            && ! $this->showDevDocs
            && ENVIRONMENT != 'development'
        ) {
            // Are we allowed to show developer docs in this environment?
            if ($this->showAppDocs) {
                Template::set_message(lang('docs_not_allowed_dev'), 'warning');

                redirect('docs/application');
            }

            show_error(lang('docs_not_allowed'));
        }

        Template::set_theme(config_item('docs.theme'), 'docs');

        $this->load->helper('form');
    }

    /**
     * Display the list of documents available and the current document
     *
     * @return void
     */
    public function index()
    {
        $data = array();

        $content = $this->read_page($this->uri->segment_array());
        $content = $this->post_process($content);

        $data['sidebar'] = $this->build_sidebar();
        $data['content'] = $content;

        Template::set($data);
        Template::render();
    }

    /**
     * Display search results and handles the search itself.
     *
     * @return void
     */
    public function search()
    {
        $this->benchmark->mark('search_start');
        $this->load->library('docs/docsearch');

        $terms = $this->input->post('search_terms');
        if ($terms) {
            $search_folders = array();
            if ($this->showAppDocs) {
                $search_folders[] = APPPATH . $this->docsDir;
            }

            if ($this->showDevDocs) {
                $search_folders[] = BFPATH . $this->docsDir;
            }

            Template::set('results', $this->docsearch->search($terms, $search_folders));
        }

        $this->benchmark->mark('search_end');

        Template::set('search_time', $this->benchmark->elapsed_time('search_start', 'search_end'));
        Template::set('search_terms', $terms);
        Template::render();
    }

    //--------------------------------------------------------------------------
    // Private Methods
    //--------------------------------------------------------------------------

    /**
     * Builds a TOC for the sidebar out of files found in the following folders:
     *      - application/docs
     *      - bonfire/docs
     *      - {module}/docs
     *
     * @return string The HTML for the sidebar.
     */
    private function build_sidebar()
    {
        $data = array();

        // Get the list of docs based on the current docs group
        // (application-specific or developer docs)
        if ($this->docsGroup == $this->docsTypeApp) {
            $data['docs'] = $this->get_folder_files(APPPATH . $this->docsDir, $this->docsTypeApp);
        } elseif ($this->docsGroup == $this->docsTypeBf) {
            $data['docs'] = $this->get_folder_files(BFPATH . $this->docsDir, $this->docsTypeBf);
        }

        // Get the docs for the modules
        $data['module_docs'] = $this->get_module_docs();

        // Set the remaining data for the view
        $data['docsDir'] = $this->docsDir;
        $data['docsExt'] = $this->docsExt;

        return $this->post_process($this->load->view('docs/_sidebar', $data, true));
    }

    /**
     * Retrieves the list of files in a folder and preps the name and filename
     * so it's ready for creating the HTML.
     *
     * @param  String $folder The path to the folder to retrieve.
     * @param  String $type   The type of documentation being retrieved
     * ('application', 'bonfire', or the name of the module).
     * @param  Array  $ignoredFolders   A list of sub-folders we should ignore.
     *
     * @return Array  An associative array @see parse_ini_file for format
     * details.
     */
    private function get_folder_files($folder, $type, $ignoredFolders = array())
    {
        if (! is_dir($folder)) {
            return array();
        }

        // If the toc file exists in the folder, use it to build the links.
        if (is_file("{$folder}/{$this->tocFile}")) {
            return parse_ini_file("{$folder}/{$this->tocFile}", true);
        }

        // If the toc file does not exist, build the links by listing the files
        // in the directory (and any sub-directories)
        $this->load->helper('directory');
        $map = bcDirectoryMap($folder);

        // If directory_map can not open the directory or find any files inside
        // the directory, return an empty array.
        if (empty($map)) {
            return array();
        }

        // If these docs are located in the /application/docs or /bonfire/docs
        // directory, just use $this->docsGroup for the root.
        // Module docs need $this->docsGroup and $type.
        $tocRoot = $this->docsGroup;
        if ($this->docsGroup != strtolower($type)) {
            $tocRoot .= '/' . strtolower($type);
        }

        $toc = array();
        foreach ($map as $new_folder => $files) {
            // Is this a folder that should be ignored?
            if (is_string($new_folder) && in_array($new_folder, $ignoredFolders)) {
                continue;
            }

            // If $files isn't an array, then make it one so that all situations
            // may be dealt with cleanly.
            if (! is_array($files)) {
                $files = array($files);
            }

            foreach ($files as $file) {
                if (in_array($file, $this->ignoreFiles)) {
                    continue;
                }

                // The title for the index is the passed $type. Otherwise,
                // build the title from the file's name.
                if (strpos($file, 'index') === false) {
                    $title = str_replace($this->docsExt, '', $file);
                    $title = str_replace('_', ' ', $title);
                    $title = ucwords($title);

                    $toc["{$tocRoot}/{$file}"] = $title;
                } else {
                    $toc[$tocRoot] = $type;
                }
            }
        }

        return $toc;
    }

    /**
     * Checks all modules to see if they include docs and prepares their doc
     * information for use in the sidebar.
     *
     * @return array
     */
    private function get_module_docs()
    {
        $docs_modules = array();
        foreach (Modules::list_modules() as $module) {
            $ignored_folders = array();
            $path = Modules::path($module) . $this->docsDir;

            // If these are developer docs, add the folder to the path.
            if ($this->docsGroup == $this->docsTypeBf) {
                $path .= '/' . $this->docsTypeBf;
            } else {
                // For Application docs, ignore the 'developers' folder.
                $ignored_folders[] = $this->docsTypeBf;
            }

            if (is_dir($path)) {
                $files = $this->get_folder_files($path, $module, $ignored_folders);
                if (is_array($files) && count($files)) {
                    $docs_modules[$module] = $files;
                }
            }
        }
        ksort($docs_modules);

        return $docs_modules;
    }

    /**
     * Does the actual work of reading in and parsing the help file.
     *
     * @param  array  $segments The uri_segments array.
     *
     * @return string
     */
    private function read_page($segments = array())
    {
        $content = null;
        $defaultType = $this->docsTypeApp;

        // Strip the controller name
        if ($segments[1] == $this->router->class) {
            array_shift($segments);
        }

        // Is this core, app, or module?
        $type = array_shift($segments);
        if (empty($type)) {
            $type = $defaultType;
        }

        // For now, assume Markdown files are the only allowed format, with an
        // extension of '.md'
        if (count($segments)) {
            $file = implode('/', $segments) . $this->docsExt;
        } else {
            $file = 'index' . $this->docsExt;
            if ($type != $this->docsTypeMod
                && ! is_file(APPPATH . $this->docsDir . '/' . $file)
               ) {
                $type = $this->docsTypeBf;
            }
        }

        // First try to load from Activities or Bonfire.
        switch ($type) {
            case $this->docsTypeBf:
                $content = is_file(BFPATH . $this->docsDir . '/' . $file) ? file_get_contents(BFPATH . $this->docsDir . '/' . $file) : '';
                break;
            case $this->docsTypeApp:
                $content = is_file(APPPATH . $this->docsDir . '/' . $file) ? file_get_contents(APPPATH . $this->docsDir . '/' . $file) : '';
                break;
        }

        // If the file wasn't found, try to find a module with the content.
        if (empty($content)) {
            $module = array_shift($segments);

            // If anything's left on $segments, it's probably a filename
            $fileName = count($segments) ? array_shift($segments) : 'index';
            $fileName .= '.md';

            // Developer docs for modules should be found under the
            // '{module}/docs/developer' path.
            $addPath = $type == $this->docsTypeBf ? '/' . $this->docsTypeBf . '/' : '/';

            // This time, try it based on the name of the segment brought in
            list($full_path, $file) = Modules::find($fileName, $module, $this->docsDir . $addPath);
            if ($full_path) {
                $content = file_get_contents($full_path . $file);
            }
        }

        // If the content is still empty, load the application/docs/404 file
        // so that we have a customizable not found file.
        if (empty($content)) {
            $content = is_file(APPPATH . $this->docsDir  . '/_404.md') ? file_get_contents(APPPATH . $this->docsDir . '/_404.md') : '';
        }

        // Parse the file
        $this->load->library('CommonMark');
        if ($this->docsParser !== null) {
            $this->commonmark->loadDriver($this->docsParser);
        }

        $content = $this->commonmark->convert($content);

        return trim($content);
    }

    /**
     * Perform a few housekeeping tasks on a page, like rewriting URLs to full
     * URLs, not relative, ensuring they link correctly, etc.
     *
     * @param $content
     *
     * @return string   The post-processed HTML.
     */
    private function post_process($content)
    {
        $xml = new SimpleXMLElement('<?xml version="1.0" standalone="yes"?>
' . $content . '
');

        /*
         * Rewrite the URLs
         */
        foreach ($xml->xpath('//a') as $link) {
            // Grab the href value.
            $href = $link->attributes()->href;

            // If the href is null, it's probably a named anchor with no content.
            if (! $href) {
                // Make sure it has an href, else the XML will not close this
                // tag correctly.
                $link['href'] = ' ';

                // A title is needed so the XML will be built correctly.
                $link->title = '';

                continue;
            }

            // If the href starts with #, then attach the current_url to it
            if ($href != '' && substr_compare($href, '#', 0, 1) === 0) {
                $link['href'] = current_url() . $href;

                continue;
            }

            // If it's a full local path, get rid of it.
            if (strpos($href, site_url()) === 0) {
                $href = str_replace(site_url() . '/', '', $href);
            }

            // Strip out some unnecessary items, just in case they're there.
            if (substr($href, 0, strlen('docs/')) == 'docs/') {
                $href = substr($href, strlen('docs/'));
            }

            // This includes 'bonfire/' if it was missed during the conversion.
            if (substr($href, 0, strlen('bonfire/')) == 'bonfire/') {
                $href = substr($href, strlen('bonfire/'));
            }

            // If another 'group' is not already defined at the head of the link
            // then add the current group to it.
            if (strpos($href, $this->docsTypeApp) !== 0 &&
                strpos($href, $this->docsTypeBf)  !== 0 &&
                strpos($href, 'http')             !== 0
               ) {
                $href = $this->docsGroup . '/' . $href;
            }

            // Convert to full site_url
            if (strpos($href, 'http') !== 0) {
                $href = site_url('docs/'. $href);
            }

            // Save the corrected href
            $link['href'] = $href;
        }

        $content = $xml->asXML();
        $content = trim(str_replace('<?xml version="1.0" standalone="yes"?>', '', $content));

        // Clean up and style the tables
        $content = str_replace('
', '
', $content);

        return $content;
    }
}


text:
var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var mocha = require('gulp-mocha');
var jshint = require('gulp-jshint');
var beautify = require('gulp-jsbeautify');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var rimraf = require('rimraf');

/* Formats the files */
gulp.task('beautify', function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(beautify({
      "indent_size": 2,
      "indent_char": " ",
      "eol": "\n",
      "indent_level": 0,
      "indent_with_tabs": false,
      "preserve_newlines": true,
      "max_preserve_newlines": 10,
      "jslint_happy": true,
      "space_after_anon_function": false,
      "brace_style": "collapse",
      "keep_array_indentation": false,
      "keep_function_indentation": false,
      "space_before_conditional": true,
      "break_chained_methods": false,
      "eval_code": false,
      "unescape_strings": false,
      "wrap_line_length": 0,
      "wrap_attributes": "auto",
      "wrap_attributes_indent_size": 4,
      "end_with_newline": false
    }))
    .pipe(gulp.dest('./lib'));
});

/*
 * Clean the docs themes folder
 */
gulp.task('clean-docs', ['gh-pages'], function (cb) {
  rimraf('./docs/themes', cb);
});

/*
 * Creat the gh-pages branch - wont push automatically
 */
gulp.task('gh-pages', ['doc'], function() {
  return gulp.src('./docs/**/*')
    .pipe(ghPages({push:false}));
});

/* Checks the coding style and builds from ES6 to ES5*/
gulp.task('lib',['beautify'],function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write("./source maps/"))
    .pipe(gulp.dest('./src'));
});

/* Watches for changes and applies the build task*/
gulp.task('watch', function () {
  return gulp.watch('./lib/**/**/*.js', ['build']);
});

/* Runs tests */
gulp.task('mocha', ['beautify','lib'],function () {
  return gulp.src('./test/**/**/*.js', { read: false })
    .pipe(mocha())
    .once('end', function () {});
});

/* Runs the doxx command and builds the docs
 * Install other themes here, generate docs for each.
*/
gulp.task('doc', ['build'], shell.task([
  './bin/doxx --source lib --target docs/themes/doxx-theme-default --title Doxx'
]));

gulp.task('default', ['beautify', 'lib', 'watch']);

gulp.task('build', ['beautify', 'lib', 'mocha']);

gulp.task('docs', ['build', 'doc', 'gh-pages', 'clean-docs']);

gulp.task('test', ['mocha']);

redpajama_set_name: RedPajamaGithub


text:
package org.hoteia.qalingo.core.domain;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

import org.apache.commons.lang.StringUtils;

@Entity
@Table(name="TECO_CURRENCY_REFERENTIAL")
public class CurrencyReferential extends AbstractEntity<CurrencyReferential> {

	/**
	 * Generated UID
	 */
	private static final long serialVersionUID = -8773291277705820667L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    private Long id;

    @Version
    @Column(name = "VERSION", nullable = false, columnDefinition = "int(11) default 1")
    private int version;

    @Column(name = "CODE", unique = true, nullable = false)
    private String code;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DESCRIPTION")
    @Lob
    private String description;

    @Column(name = "SIGN")
    private String sign;

    @Column(name = "ABBREVIATED")
    private String abbreviated;

    @Column(name = "FORMAT_LOCALE")
    private String formatLocale;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DATE_CREATE")
    private Date dateCreate;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DATE_UPDATE")
    private Date dateUpdate;

    public CurrencyReferential() {
        this.dateCreate = new Date();
        this.dateUpdate = new Date();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

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

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getAbbreviated() {
        return abbreviated;
    }

    public void setAbbreviated(String abbreviated) {
        this.abbreviated = abbreviated;
    }

    public String getFormatLocale() {
        return formatLocale;
    }

    public Locale getLocale() {
        if(StringUtils.isNotEmpty(formatLocale)){
            String[] split = formatLocale.split("_");
            if(split.length == 1){
                return new Locale(split[0]);
            } else if(split.length == 2){
                return new Locale(split[0], split[1]);
            }
        }
        return Locale.ENGLISH;
    }

	public void setFormatLocale(String formatLocale) {
        this.formatLocale = formatLocale;
    }

	public Date getDateCreate() {
		return dateCreate;
	}

	public void setDateCreate(Date dateCreate) {
		this.dateCreate = dateCreate;
	}

	public Date getDateUpdate() {
		return dateUpdate;
	}

	public void setDateUpdate(Date dateUpdate) {
		this.dateUpdate = dateUpdate;
	}

    public NumberFormat getStandardCurrencyformat(){
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        if(StringUtils.isNotEmpty(getFormatLocale())){
            formatter = NumberFormat.getCurrencyInstance(getLocale());
        }
        Currency currency = Currency.getInstance(getCode());
        formatter.setCurrency(currency);
        return formatter;
    }

    public NumberFormat getEcoCurrencyformat(){
        NumberFormat formatter = getStandardCurrencyformat();
        formatter.setGroupingUsed(true);
        formatter.setParseIntegerOnly(false);
        formatter.setRoundingMode(RoundingMode.HALF_EVEN);

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        formatter.setMaximumIntegerDigits(1000000);
        formatter.setMinimumIntegerDigits(1);
        return formatter;
    }

    public String formatPriceWithStandardCurrencySign(BigDecimal price){
        NumberFormat formatter = getEcoCurrencyformat();
        return formatter.format(price);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        result = prime * result + ((dateCreate == null) ? 0 : dateCreate.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object sourceObj) {
        Object obj = deproxy(sourceObj);
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CurrencyReferential other = (CurrencyReferential) obj;
        if (code == null) {
            if (other.code != null)
                return false;
        } else if (!code.equals(other.code))
            return false;
        if (dateCreate == null) {
            if (other.dateCreate != null)
                return false;
        } else if (!dateCreate.equals(other.dateCreate))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "CurrencyReferential [id=" + id + ", version=" + version + ", name=" + name + ", description=" + description + ", code=" + code + ", sign=" + sign + ", abbreviated=" + abbreviated
                + ", formatLocale=" + formatLocale + ", dateCreate=" + dateCreate + ", dateUpdate=" + dateUpdate + "]";
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Web.Security;
using ScrimpNet.ServiceModel.BaseContracts;

namespace ScrimpNet.Security.Contracts
{
    [DataContract(Namespace=ContractConfig.ContractVersion)]
    public class UsernameGetByEMailRequest : SecureSessionRequestBase
    {
        [DataMember]
        public string EMailAddress { get; set; }
    }

    [DataContract(Namespace=ContractConfig.ContractVersion)]
    public class UsernameGetByEMailReply : SecureSessionReplyBase
    {
        [DataMember]
        public string Username { get; set; }
    }
}


text:
package org.apache.skywalking.oap.server.core.analysis.meter.function.sum;

import org.apache.skywalking.oap.server.core.analysis.Layer;
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
import org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue;
import org.apache.skywalking.oap.server.core.analysis.meter.function.BucketedValues;
import org.apache.skywalking.oap.server.core.analysis.meter.function.PercentileArgument;
import org.apache.skywalking.oap.server.core.analysis.metrics.DataTable;
import org.apache.skywalking.oap.server.core.analysis.metrics.IntList;
import org.apache.skywalking.oap.server.core.config.NamingControl;
import org.apache.skywalking.oap.server.core.config.group.EndpointNameGrouping;
import org.apache.skywalking.oap.server.core.storage.type.HashMapConverter;
import org.apache.skywalking.oap.server.core.storage.type.StorageBuilder;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

public class SumHistogramPercentileFunctionTest {

    private static final long[] BUCKETS = new long[] {
        0,
        50,
        100,
        250
    };

    private static final int[] RANKS = new int[] {
        50,
        90
    };

    @BeforeClass
    public static void setup() {
        MeterEntity.setNamingControl(
            new NamingControl(512, 512, 512, new EndpointNameGrouping()));
    }

    @AfterClass
    public static void tearDown() {
        MeterEntity.setNamingControl(null);
    }

    @Test
    public void testFunction() {
        PercentileFunctionInst inst = new PercentileFunctionInst();
        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                new BucketedValues(
                    BUCKETS,
                    new long[] {
                        10,
                        20,
                        30,
                        40
                    }
                ),
                RANKS
            )
        );

        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                new BucketedValues(
                    BUCKETS,
                    new long[] {
                        10,
                        20,
                        30,
                        40
                    }
                ),
                RANKS
            )
        );

        inst.calculate();
        final int[] values = inst.getValues();
        /**
         * Expected percentile dataset
         *

         *     0  , 20
         *     50 , 40
         *     100, 50 <- P50
         *     250, 80 <- P90
         *

         */
        Assert.assertArrayEquals(new int[] {
            100,
            250
        }, values);
    }

    @Test
    public void testSerialization() {
        PercentileFunctionInst inst = new PercentileFunctionInst();
        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                new BucketedValues(
                    BUCKETS,
                    new long[] {
                        10,
                        20,
                        30,
                        40
                    }
                ),
                RANKS
            )
        );

        PercentileFunctionInst inst2 = new PercentileFunctionInst();
        inst2.deserialize(inst.serialize().build());

        assertEquals(inst, inst2);
        assertEquals(inst.getSummation(), inst2.getSummation());
        assertEquals(inst.getRanks(), inst2.getRanks());
        assertEquals(0, inst2.getPercentileValues().size());
    }

    @Test
    public void testBuilder() throws IllegalAccessException, InstantiationException {
        PercentileFunctionInst inst = new PercentileFunctionInst();
        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                new BucketedValues(
                    BUCKETS,
                    new long[] {
                        10,
                        20,
                        30,
                        40
                    }
                ),
                RANKS
            )
        );
        inst.calculate();

        final StorageBuilder storageBuilder = inst.builder().newInstance();

        // Simulate the storage layer do, convert the datatable to string.
        final HashMapConverter.ToStorage toStorage = new HashMapConverter.ToStorage();
        storageBuilder.entity2Storage(inst, toStorage);
        final Map<String, Object> map = toStorage.obtain();
        map.put(
            SumHistogramPercentileFunction.SUMMATION,
            ((DataTable) map.get(SumHistogramPercentileFunction.SUMMATION)).toStorageData()
        );
        map.put(
            SumHistogramPercentileFunction.VALUE,
            ((DataTable) map.get(SumHistogramPercentileFunction.VALUE)).toStorageData()
        );
        map.put(
            SumHistogramPercentileFunction.RANKS,
            ((IntList) map.get(SumHistogramPercentileFunction.RANKS)).toStorageData()
        );

        final SumHistogramPercentileFunction inst2 = (SumHistogramPercentileFunction) storageBuilder.storage2Entity(
            new HashMapConverter.ToEntity(map));
        assertEquals(inst, inst2);
        // HistogramFunction equal doesn't include dataset.
        assertEquals(inst.getPercentileValues(), inst2.getPercentileValues());
        assertEquals(inst.getRanks(), inst2.getRanks());
    }

    @Test
    public void testFunctionWhenGroupContainsColon() {
        BucketedValues valuesA = new BucketedValues(
            BUCKETS,
            new long[] {
                10,
                20,
                30,
                40
            }
        );
        valuesA.setGroup("localhost:3306/swtest");

        PercentileFunctionInst inst = new PercentileFunctionInst();
        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                valuesA,
                RANKS
            )
        );
        BucketedValues valuesB = new BucketedValues(
            BUCKETS,
            new long[] {
                10,
                20,
                30,
                40
            }
        );
        valuesB.setGroup("localhost:3306/swtest");

        inst.accept(
            MeterEntity.newService("service-test", Layer.GENERAL),
            new PercentileArgument(
                valuesB,
                RANKS
            )
        );

        inst.calculate();
        final DataTable values = inst.getPercentileValues();
        /**
         * Expected percentile dataset
         *

         *     0  , 20
         *     50 , 40
         *     100, 60 <- P50
         *     250, 80 <- P90
         *

         */
        assertEquals(new Long(100), values.get("localhost:3306/swtest:50"));
        assertEquals(new Long(250), values.get("localhost:3306/swtest:90"));
    }

    private static class PercentileFunctionInst extends SumHistogramPercentileFunction {
        @Override
        public AcceptableValue<PercentileArgument> createNew() {
            return new SumHistogramPercentileFunctionTest.PercentileFunctionInst();
        }
    }
}


text:
// ---------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="RemoveEmptyXmlNodeTextTransformation.cs" company="Trencadis">
// Copyright (c) 2016, Trencadis, All rights reserved
// </copyright>
// ---------------------------------------------------------------------------------------------------------------------------------------

namespace Trencadis.Tools.TextTransformations.Transformations.Xml
{
    using System.Linq;
    using System.Xml.Linq;

    using Trencadis.Tools.TextTransformations.Extensions;

    /// <summary>
    /// Removes empty xml nodes when the input is a xml document or fragment.
    /// Concrete implementation if <see cref="ITextTransformation"/>
    /// </summary>
    public class RemoveEmptyXmlNodeTextTransformation : ITextTransformation
    {
        /// <summary>
        /// Transforms the input text by removing the empty xml nodes
        /// </summary>
        /// <param name="input">The input text (must be a xml document / fragment in order that any transformation to occur)</param>
        /// <returns>The transformation result</returns>
        public string ApplyTransformation(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return input;
            }

            XDocument xml;
            if ((!input.IsXml(out xml)) || (xml == null))
            {
                return input;
            }

            var emptyNodes = xml
                .Descendants()
                .Where(x => (!x.HasElements) && (!x.HasAttributes) && (string.IsNullOrWhiteSpace(x.Value)));

            if (emptyNodes != null)
            {
                emptyNodes.Remove();
            }

            return xml.ToStringWithDeclaration(SaveOptions.DisableFormatting);
        }
    }
}


text:
<?php

class SchemaModel extends Model {

	/**
	 * 定义数据表主键
	 *
	 * @access protected
	 * @return array
	 */
	protected function primaryKey() {
		return 'id';
	}

	/**
	 * 定义数据表字段信息
	 *
	 * @access protected
	 * @return array
	 */
	protected function tableFields() {
		return array('id', 'name', 'produceid', 'power','des');
	}

	/**
	 * 定义数据表名称
	 *
	 * @access protected
	 * @return array
	 */
	protected function tableName() {
		return '`schema`';
	}

}


text:
const moment             = require('moment');
const Contract           = require('./contract');
const Defaults           = require('./defaults');
const Tick               = require('./tick');
const addComma           = require('../../../_common/base/currency_base').addComma;
const elementTextContent = require('../../../_common/common_functions').elementTextContent;
const getElementById     = require('../../../_common/common_functions').getElementById;
const isVisible          = require('../../../_common/common_functions').isVisible;
const localize           = require('../../../_common/localize').localize;

/*
 * Handles barrier processing and display
 *
 * It process `Contract.barriers` and display them if its applicable
 * for current `Contract.form()
 */

const Barriers = (() => {
    let is_barrier_updated = false;

    const display = () => {
        const barriers  = Contract.barriers()[Defaults.get('underlying')];
        const form_name = Contract.form();

        // TODO: remove `reset` when API stops sending barrier for Resets in contracts_for response
        if (barriers && form_name && barriers[form_name] && !/risefall|reset/i.test(Defaults.get('formname'))) {
            const unit     = getElementById('duration_units');
            const end_time = getElementById('expiry_date');
            const is_daily = (unit && isVisible(unit) && unit.value === 'd') ||
                (end_time && isVisible(end_time) && moment(end_time.getAttribute('data-value')).isAfter(moment(), 'day'));

            const barrier = barriers[form_name][is_daily ? 'daily' : 'intraday'];
            if (barrier) {
                const current_tick   = Tick.quote();
                const decimal_places = Tick.pipSize();

                const indicative_barrier_tooltip      = getElementById('indicative_barrier_tooltip');
                const indicative_high_barrier_tooltip = getElementById('indicative_high_barrier_tooltip');
                const indicative_low_barrier_tooltip  = getElementById('indicative_low_barrier_tooltip');

                if (barrier.count === 1) {
                    getElementById('high_barrier_row').style.display = 'none';
                    getElementById('low_barrier_row').style.display  = 'none';
                    getElementById('barrier_row').setAttribute('style', '');

                    const defaults_barrier = Defaults.get('barrier');
                    const elm              = getElementById('barrier');
                    const tooltip          = getElementById('barrier_tooltip');
                    const span             = getElementById('barrier_span');
                    let barrier_def        = defaults_barrier && !isNaN(defaults_barrier) ?
                        defaults_barrier : (barrier.barrier || 0);
                    let value;
                    if (is_daily || !String(barrier.barrier).match(/^[+-]/)) {
                        if (current_tick && !isNaN(current_tick) && String(barrier_def).match(/^[+-]/)) {
                            value = (parseFloat(current_tick) + parseFloat(barrier_def)).toFixed(decimal_places);
                        } else {
                            value = parseFloat(barrier_def);
                        }
                        tooltip.style.display = 'none';
                        span.style.display    = 'inherit';
                        // no need to display indicative barrier in case of absolute barrier
                        elementTextContent(indicative_barrier_tooltip, '');
                    } else {
                        if (!String(barrier_def).match(/^[+-]/)) barrier_def = barrier.barrier; // override Defaults value, because it's changing from absolute to relative barrier
                        value                 = barrier_def;
                        span.style.display    = 'none';
                        tooltip.style.display = 'inherit';
                        if (current_tick && !isNaN(current_tick)) {
                            elementTextContent(indicative_barrier_tooltip, addComma((parseFloat(current_tick) +
                                parseFloat(barrier_def)), decimal_places));
                        } else {
                            elementTextContent(indicative_barrier_tooltip, '');
                        }
                    }
                    elm.value = elm.textContent = value;
                    Barriers.validateBarrier();
                    Defaults.set('barrier', elm.value);
                    Defaults.remove('barrier_high', 'barrier_low');
                    showHideRelativeTip(barrier.barrier, [tooltip, span]);
                    return;
                } else if (barrier.count === 2) {
                    getElementById('barrier_row').style.display = 'none';
                    getElementById('high_barrier_row').setAttribute('style', '');
                    getElementById('low_barrier_row').setAttribute('style', '');

                    const high_elm     = getElementById('barrier_high');
                    const low_elm      = getElementById('barrier_low');
                    const high_tooltip = getElementById('barrier_high_tooltip');
                    const high_span    = getElementById('barrier_high_span');
                    const low_tooltip  = getElementById('barrier_low_tooltip');
                    const low_span     = getElementById('barrier_low_span');

                    const defaults_high = Defaults.get('barrier_high');
                    const defaults_low  = Defaults.get('barrier_low');

                    let barrier_high = defaults_high && !isNaN(defaults_high) ? defaults_high : (barrier.barrier || 0);
                    let barrier_low  = defaults_low && !isNaN(defaults_low) ?
                        defaults_low : (barrier.barrier1 || 0);
                    let value_high,
                        value_low;
                    if (is_daily || !String(barrier.barrier).match(/^[+-]/)) {
                        if (current_tick && !isNaN(current_tick) && String(barrier_high).match(/^[+-]/)) {
                            value_high = (parseFloat(current_tick) + parseFloat(barrier_high)).toFixed(decimal_places);
                            value_low  = (parseFloat(current_tick) + parseFloat(barrier_low)).toFixed(decimal_places);
                        } else {
                            value_high = parseFloat(barrier_high);
                            value_low  = parseFloat(barrier_low);
                        }

                        high_span.style.display    = 'inherit';
                        high_tooltip.style.display = 'none';
                        low_span.style.display     = 'inherit';
                        low_tooltip.style.display  = 'none';

                        elementTextContent(indicative_high_barrier_tooltip, '');
                        elementTextContent(indicative_low_barrier_tooltip, '');
                    } else {
                        // override Defaults value, if it's changing from absolute to relative barrier
                        if (!String(barrier_high).match(/^[+-]/) || !String(barrier_low).match(/^[+-]/)) {
                            barrier_high = barrier.barrier;
                            barrier_low  = barrier.barrier1;
                        }
                        value_high = barrier_high;
                        value_low  = barrier_low;

                        high_span.style.display    = 'none';
                        high_tooltip.style.display = 'inherit';
                        low_span.style.display     = 'none';
                        low_tooltip.style.display  = 'inherit';

                        const barrierVal = (tick, barrier_value) => (
                            (tick + parseFloat(barrier_value)).toFixed(decimal_places)
                        );

                        if (current_tick && !isNaN(current_tick)) {
                            const tick = parseFloat(current_tick);
                            elementTextContent(indicative_high_barrier_tooltip, barrierVal(tick, barrier_high));
                            elementTextContent(indicative_low_barrier_tooltip, barrierVal(tick, barrier_low));
                        } else {
                            elementTextContent(indicative_high_barrier_tooltip, '');
                            elementTextContent(indicative_low_barrier_tooltip, '');
                        }
                    }
                    high_elm.value = high_elm.textContent = value_high;
                    low_elm.value  = low_elm.textContent  = value_low;

                    Defaults.remove('barrier');
                    showHideRelativeTip(barrier.barrier, [high_tooltip, high_span, low_tooltip, low_span]);
                    Barriers.validateBarrier();
                    Defaults.set('barrier_high', high_elm.value);
                    Defaults.set('barrier_low', low_elm.value);
                    return;
                }
            }
        }

        const elements = document.getElementsByClassName('barrier_class');
        for (let i = 0; i < elements.length; i++) {
            elements[i].style.display = 'none';
        }
        Defaults.remove('barrier', 'barrier_high', 'barrier_low');
    };

    /**
    * Validate Barriers
    */
    const validateBarrier = () => {
        const barrier_element      = getElementById('barrier');
        const barrier_high_element = getElementById('barrier_high');
        const empty = isNaN(parseFloat(barrier_element.value)) || isAbsoluteZero(barrier_element.value);

        if (isVisible(barrier_element) && empty) {
            barrier_element.classList.add('error-field');
        } else {
            barrier_element.classList.remove('error-field');
        }

        if (isVisible(barrier_high_element)) {
            const barrier_low_element     = getElementById('barrier_low');
            const error_node              = getElementById('barrier_high_error');
            const is_high_barrier_greater = +barrier_high_element.value > +barrier_low_element.value;
            barrier_high_element.classList[is_high_barrier_greater ? 'remove' : 'add']('error-field');
            error_node.classList[is_high_barrier_greater ? 'add' : 'remove']('invisible');
        }
    };

    const showHideRelativeTip = (barrier, arr_el) => {
        const has_relative_barrier = String(barrier).match(/^[+-]/);
        const barrier_text         = localize('Add +/– to define a barrier offset. For example, +0.005 means a barrier that\'s 0.005 higher than the entry spot.');
        arr_el.forEach((el) => {
            if (has_relative_barrier) {
                el.setAttribute('data-balloon', barrier_text);
                el.setAttribute('data-balloon-length', 'xlarge');
            } else {
                el.removeAttribute('data-balloon');
                el.removeAttribute('data-balloon-length');
            }
        });
    };

    const isAbsoluteZero = num => !(parseFloat(num) !== 0 || /\+|-/.test(num.toString().charAt(0)));

    return {
        display,
        validateBarrier,
        isBarrierUpdated: () => is_barrier_updated,
        setBarrierUpdate: (flag) => { is_barrier_updated = flag; },
    };
})();

module.exports = Barriers;


text:
package api_test

import (
	"fmt"
	"net/http"

	"github.com/albertoleal/features/engine"
	"github.com/apihub/apihub/requests"
	. "gopkg.in/check.v1"
)

func (s *S) TestCreateFeature(c *C) {
	featureKey := "login_via_email"
	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusCreated,
		Method:         "POST",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s", "percentage": 20, "enabled": true}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusCreated)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"enabled\":true,\"key\":\"login_via_email\",\"percentage\":20}\n")
}

func (s *S) TestCreateFeatureMissingRequiredFields(c *C) {
	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusBadRequest,
		Method:         "POST",
		Path:           "/features",
		Body:           `{"percentage": 20, "enabled": true}`,
	})

	c.Assert(code, Equals, http.StatusBadRequest)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"bad_request\",\"error_description\":\"Key cannot be empty.\"}")
}

func (s *S) TestCreateFeatureInvalidJSON(c *C) {
	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusBadRequest,
		Method:         "POST",
		Path:           "/features",
		Body:           `{"percentage": 2: "enabled": true}`,
	})

	c.Assert(code, Equals, http.StatusBadRequest)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"bad_request\",\"error_description\":\"invalid character ':' after object key:value pair\"}")
}

func (s *S) TestCreateFeatureWithExistingKey(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusBadRequest,
		Method:         "POST",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s", "percentage": 20, "enabled": true}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusBadRequest)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"bad_request\",\"error_description\":\"There's another feature for the same key value.\"}\n")
}

func (s *S) TestUpdateFeature(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "PUT",
		Path:           fmt.Sprintf("/features/%s", featureKey),
		Body:           fmt.Sprintf(`{"key": "%s", "percentage": 20, "enabled": false}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"enabled\":false,\"key\":\"login_via_email\",\"percentage\":20}\n")
}

func (s *S) TestUpdateFeatureNotFound(c *C) {
	featureKey := "login_via_email"

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusNotFound,
		Method:         "PUT",
		Path:           fmt.Sprintf("/features/%s", featureKey),
		Body:           fmt.Sprintf(`{"percentage": 20, "enabled": false}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusNotFound)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"not_found\",\"error_description\":\"Feature flag not found.\"}")
}

func (s *S) TestDeleteFeatureNotFound(c *C) {
	featureKey := "login_via_email"

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusNotFound,
		Method:         "DELETE",
		Path:           fmt.Sprintf("/features/%s", featureKey),
	})

	c.Assert(code, Equals, http.StatusNotFound)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"not_found\",\"error_description\":\"Feature flag not found.\"}")
}

func (s *S) TestDeleteFeature(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusNoContent,
		Method:         "DELETE",
		Path:           fmt.Sprintf("/features/%s", featureKey),
	})

	c.Assert(code, Equals, http.StatusNoContent)
	c.Assert(headers.Get("Content-Type"), Equals, "text/plain")
	c.Assert(string(body), Equals, "")
}

func (s *S) TestFindFeatureNotFound(c *C) {
	featureKey := "login_via_email"

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusNotFound,
		Method:         "GET",
		Path:           fmt.Sprintf("/features/%s", featureKey),
	})

	c.Assert(code, Equals, http.StatusNotFound)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"error\":\"not_found\",\"error_description\":\"Feature flag not found.\"}")
}

func (s *S) TestFindFeature(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "GET",
		Path:           fmt.Sprintf("/features/%s", featureKey),
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"enabled\":false,\"key\":\"login_via_email\",\"percentage\":0}\n")
}

func (s *S) TestValidateUserAccess(c *C) {
	featureKey := "login_via_email"
	email := "alice@example.org"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
		Users:   []*engine.User{&engine.User{Id: email}},
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	_, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "PUT",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s", "user": "%s"}`, featureKey, email),
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(string(body), Equals, "")
}

func (s *S) TestValidateDisabledFeature(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	_, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusForbidden,
		Method:         "PUT",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s"}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusForbidden)
	c.Assert(string(body), Equals, "")
}

func (s *S) TestValidateEnabledFeature(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: true,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	_, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "PUT",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s"}`, featureKey),
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(string(body), Equals, "")
}

func (s *S) TestValidateEnabledFeatureOutOfPercentage(c *C) {
	featureKey := "login_via_email"
	email := "alice@example.org"
	feature := engine.FeatureFlag{
		Key:        featureKey,
		Enabled:    true,
		Percentage: 50,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	_, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusForbidden,
		Method:         "PUT",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s", "user": "%s"}`, featureKey, email),
	})

	c.Assert(code, Equals, http.StatusForbidden)
	c.Assert(string(body), Equals, "")
}

func (s *S) TestValidateEnabledFeatureInPercentage(c *C) {
	featureKey := "login_via_email"
	email := "alice@example.org"
	feature := engine.FeatureFlag{
		Key:        featureKey,
		Enabled:    true,
		Percentage: 51,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	_, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "PUT",
		Path:           "/features",
		Body:           fmt.Sprintf(`{"key": "%s", "user": "%s"}`, featureKey, email),
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(string(body), Equals, "")
}

func (s *S) TestListAllFeatures(c *C) {
	featureKey := "login_via_email"
	feature := engine.FeatureFlag{
		Key:     featureKey,
		Enabled: false,
	}
	s.ng.UpsertFeatureFlag(feature)

	defer func() {
		ffk := engine.FeatureFlagKey{Key: featureKey}
		s.ng.DeleteFeatureFlag(ffk)
	}()

	headers, code, body, _ := httpClient.MakeRequest(requests.Args{
		AcceptableCode: http.StatusOK,
		Method:         "GET",
		Path:           "/features",
	})

	c.Assert(code, Equals, http.StatusOK)
	c.Assert(headers.Get("Content-Type"), Equals, "application/json")
	c.Assert(string(body), Equals, "{\"items\":[{\"enabled\":false,\"key\":\"login_via_email\",\"percentage\":0}],\"item_count\":1}\n")
}


text:
require 'spec_helper'

describe HealthInspector::Checklists::Cookbook do
  let(:pairing) { described_class.new(health_inspector_context, :name => "dummy") }

  it "should detect if an item does not exist locally" do
    pairing.server = "0.0.1"
    pairing.local  = nil
    pairing.validate

    pairing.errors.should_not be_empty
    pairing.errors.first.should == "exists on server but not locally"
  end

  it "should detect if an item does not exist on server" do
    pairing.server = nil
    pairing.local  = "0.0.1"
    pairing.validate

    pairing.errors.should_not be_empty
    pairing.errors.first.should == "exists locally but not on server"
  end

  it "should detect if an item is different" do
    pairing.server = "0.0.1"
    pairing.local  = "0.0.2"
    pairing.validate

    pairing.errors.should_not be_empty
    pairing.errors.first.should == "chef server has 0.0.1 but local version is 0.0.2"
  end

  it "should detect if an item is the same" do
    pairing.should_receive(:validate_changes_on_the_server_not_in_the_repo)
    pairing.server = "0.0.1"
    pairing.local  = "0.0.1"
    pairing.validate

    pairing.errors.should be_empty
  end
end


text:
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
                //global variables
		score : 0,
                enemyBaseHealth: 10,
                playerBaseHealth: 10,
                enemyCreepHealth: 10,
                playerHealth: 10,
                enemyCreepAttack: 2,
                playerAttack: 5,
                playerAttackTimer: 2000,
                enemyCreepAttackTimer: 1000,
                playerMoveSpeed: 5,
                creepMoveSpeed: 5,
                gameTimerManager: "",
                heroDeathManager: "",
                player: "",
                exp: 0,
                gold: 0,
                ability1:0,
                ability2:0,
                ability3:0,
                skill1:0,
                skill2:0,
                skill3:0,
                exp1: 0,
                exp2: 0,
                exp3: 0,
                exp4: 0,
                win: "",
                pausePos:"",
                buyscreen:"",
                buytext: ""
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

        me.state.SPENDEXP = 112;
        me.state.NEW = 113;
        me.state.LOAD = 114;

	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
                me.pool.register("player", game.PlayerEntity, true);
                me.pool.register("PlayerBase", game.PlayerBaseEntity, true);
                me.pool.register("EnemyBase", game.EnemyBaseEntity, true);
                me.pool.register("EnemyCreep", game.EnemyCreep, true);
                me.pool.register("GameTimerManager", game.GameTimerManager);
                me.pool.register("HeroDeathManager", game.HeroDeathManager);
                me.pool.register("ExperienceManager", game.ExperienceManager);
                me.pool.register("SpendGold", game.SpendGold);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
                me.state.set(me.state.SPENDEXP, new game.SpendExp());
                me.state.set(me.state.LOAD, new game.LoadProfile());
                me.state.set(me.state.NEW, new game.NewProfile());

		// Start the game.
		me.state.change(me.state.MENU);
	}
};


text:
@interface NIMSessionListViewController ()

@end

@implementation NIMSessionListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)dealloc{
    [[NIMSDK sharedSDK].conversationManager removeDelegate:self];
    [[NIMSDK sharedSDK].loginManager removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.tableFooterView  = [[UIView alloc] init];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    [[NIMSDK sharedSDK].conversationManager addDelegate:self];
    [[NIMSDK sharedSDK].loginManager addDelegate:self];

    extern NSString *const NIMKitTeamInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamInfoHasUpdatedNotification:) name:NIMKitTeamInfoHasUpdatedNotification object:nil];

    extern NSString *const NIMKitTeamMembersHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamMembersHasUpdatedNotification:) name:NIMKitTeamMembersHasUpdatedNotification object:nil];

    extern NSString *const NIMKitUserInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoHasUpdatedNotification:) name:NIMKitUserInfoHasUpdatedNotification object:nil];

    [self setupSessions];
}

- (void)setupSessions {
    _recentSessions = [self getRecentSessions];
    if (!self.recentSessions.count)
    {
        _recentSessions = [NSMutableArray array];
    }
    else
    {
        _recentSessions = [self customSortRecents:_recentSessions];
    }
}

- (NSMutableArray *)getRecentSessions {
    return [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
}

- (void)refresh{
    if (!self.recentSessions.count) {
        self.tableView.hidden = YES;
    }else{
        self.tableView.hidden = NO;
        [self customSortRecents:self.recentSessions];
    }
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NIMRecentSession *recentSession = self.recentSessions[indexPath.row];
    [self onSelectedRecent:recentSession atIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.f;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.recentSessions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellId = @"cellId";
    NIMSessionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NIMSessionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        [cell.avatarImageView addTarget:self action:@selector(onTouchAvatar:) forControlEvents:UIControlEventTouchUpInside];
    }
    NIMRecentSession *recent = self.recentSessions[indexPath.row];
    cell.nameLabel.text = [self nameForRecentSession:recent];
    [cell.avatarImageView setAvatarBySession:recent.session];
    [cell.nameLabel sizeToFit];
    cell.messageLabel.attributedText  = [self contentForRecentSession:recent];
    [cell.messageLabel sizeToFit];
    cell.timeLabel.text = [self timestampDescriptionForRecentSession:recent];
    [cell.timeLabel sizeToFit];

    [cell refresh:recent];
    return cell;
}

#pragma mark - NIMConversationManagerDelegate
- (void)didLoadAllRecentSessionCompletion {
    [self setupSessions];
    [self refresh];
}

- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount{
    [self.recentSessions addObject:recentSession];
    [self sort];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount{
    for (NIMRecentSession *recent in self.recentSessions)
    {
        if ([recentSession.session.sessionId isEqualToString:recent.session.sessionId])
        {
            [self.recentSessions removeObject:recent];
            break;
        }
    }
    NSInteger insert = [self findInsertPlace:recentSession];
    [self.recentSessions insertObject:recentSession atIndex:insert];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount
{
    //清理本地数据
    [self.recentSessions removeObject:recentSession];

    //如果删除本地会话后就不允许漫游当前会话,则需要进行一次删除服务器会话的操作
    if (self.autoRemoveRemoteSession)
    {
        [[NIMSDK sharedSDK].conversationManager deleteRemoteSessions:@[recentSession.session]
                           completion:nil];
    }
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)messagesDeletedInSession:(NIMSession *)session{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)allMessagesDeleted{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)allMessagesRead
{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (NSMutableArray *)customSortRecents:(NSMutableArray *)recentSessions
{
    return self.recentSessions;
}

#pragma mark - NIMLoginManagerDelegate
- (void)onLogin:(NIMLoginStep)step
{
    if (step == NIMLoginStepSyncOK) {
        [self refresh];
    }
}

#pragma mark - Override
- (void)onSelectedAvatar:(NSString *)userId
             atIndexPath:(NSIndexPath *)indexPath{};

- (void)onSelectedRecent:(NIMRecentSession *)recentSession atIndexPath:(NSIndexPath *)indexPath{
    NIMSessionViewController *vc = [[NIMSessionViewController alloc] initWithSession:recentSession.session];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)nameForRecentSession:(NIMRecentSession *)recent {
    if (recent.session.sessionType == NIMSessionTypeP2P) {
        return [NIMKitUtil showNick:recent.session.sessionId inSession:recent.session];
    } else if (recent.session.sessionType == NIMSessionTypeTeam) {
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:recent.session.sessionId];
        return team.teamName;
    } else if (recent.session.sessionType == NIMSessionTypeSuperTeam) {
        NIMTeam *superTeam = [[NIMSDK sharedSDK].superTeamManager teamById:recent.session.sessionId];
        return superTeam.teamName;
    } else {
        NSAssert(NO, @"");
        return nil;
    }
}

- (NSAttributedString *)contentForRecentSession:(NIMRecentSession *)recent{
    NSString *content = [self messageContent:recent.lastMessage];
    return [[NSAttributedString alloc] initWithString:content ?: @""];
}

- (NSString *)timestampDescriptionForRecentSession:(NIMRecentSession *)recent{
    if (recent.lastMessage) {
        return [NIMKitUtil showTime:recent.lastMessage.timestamp showDetail:NO];
    }
    // 服务端时间戳以毫秒为单位,需要转化
    NSTimeInterval timeSecond = recent.updateTime / 1000.0;
    return [NIMKitUtil showTime:timeSecond showDetail:NO];
}

#pragma mark - Misc

- (NSInteger)findInsertPlace:(NIMRecentSession *)recentSession{
    __block NSUInteger matchIdx = 0;
    __block BOOL find = NO;
    [self.recentSessions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NIMRecentSession *item = obj;
        if (item.lastMessage.timestamp <= recentSession.lastMessage.timestamp) {
            *stop = YES;
            find  = YES;
            matchIdx = idx;
        }
    }];
    if (find) {
        return matchIdx;
    }else{
        return self.recentSessions.count;
    }
}

- (void)sort{
    [self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NIMRecentSession *item1 = obj1;
        NIMRecentSession *item2 = obj2;
        if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
            return NSOrderedDescending;
        }
        if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
}

- (void)onTouchAvatar:(id)sender{
    UIView *view = [sender superview];
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = view.superview;
    }
    UITableViewCell *cell  = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NIMRecentSession *recent = self.recentSessions[indexPath.row];
    [self onSelectedAvatar:recent atIndexPath:indexPath];
}

#pragma mark - Private
- (NSString *)messageContent:(NIMMessage*)lastMessage{
    NSString *text = [NIMMessageUtil messageContent:lastMessage];
    if (lastMessage.session.sessionType == NIMSessionTypeP2P || lastMessage.messageType == NIMMessageTypeTip)
    {
        return text;
    }
    else
    {
        NSString *from = lastMessage.from;
        NSString *nickName = [NIMKitUtil showNick:from inSession:lastMessage.session];
        return nickName.length ? [nickName stringByAppendingFormat:@" : %@",text] : @"";
    }
}

#pragma mark - Notification
- (void)onUserInfoHasUpdatedNotification:(NSNotification *)notification{
    [self refresh];
}

- (void)onTeamInfoHasUpdatedNotification:(NSNotification *)notification{
    [self refresh];
}

- (void)onTeamMembersHasUpdatedNotification:(NSNotification *)notification{
    [self refresh];
}

@end


text:
/*
 * DO NOT EDIT THIS FILE! Automatically generated
 */

#include "base/debug.hh"

namespace Debug {

SimpleFlag Intel8254Timer("Intel8254Timer", "None");

} // namespace Debug


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Program and Configuration Playground</title>

<link rel="stylesheet" type="text/css" href="typicons.css">
</link>

Blockly Multi Playground

    <form id="options">
        <select name="toolbox" onchange="document.forms.options.submit()">
            <option value="categories">Categories</option>
            <option value="simple">Simple</option>
        </select>
    </form>

            Program
            Configuration

    <toolbox_set id="toolbox-Program" style="display: none">
    <category name="TOOLBOX_ACTION" svg="true">
        <block type="robActions_play_tone">
        <value name="FREQUENCE">
            <block type="math_number">
            <field name="NUM">300</field>
            </block>
        </value>
        <value name="DURATION">
            <block type="math_number">
            <field name="NUM">100</field>
            </block>
        </value>
        </block>
        <block type="robActions_plot_point"></block>
        <block type="robActions_serial_print">
        <value name="OUT">
            <block type="text">
            <field name="TEXT">Hallo</field>
            </block>
        </value>
        </block>
        <block type="robActions_brickLight_on"></block>
        <block type="robActions_sendData"></block>
    </category>
    <category name="TOOLBOX_SENSOR" svg="true">
        <block type="robSensors_key_getSample"></block>
        <block type="robSensors_light_getSample"></block>
        <block type="robSensors_potentiometer_getSample"></block>
        <block type="robSensors_sound_getSample"></block>
        <block type="robSensors_ultrasonic_getSample"></block>
        <block type="robSensors_humidity_getSample"></block>
        <block type="robSensors_temperature_getSample"></block>
        <block type="robSensors_lightveml_getSample"></block>
        <block type="robSensors_accelerometer_getSample"></block>
        <block type="robSensors_environmental_getSample"></block>
        <block type="robSensors_timer_getSample"></block>
        <block type="robSensors_timer_reset"></block>
    </category>
    <category name="TOOLBOX_CONTROL" svg="true">
        <block type="robControls_if"></block>
        <block type="robControls_ifElse"></block>
        <block type="robControls_loopForever"></block>
        <block type="controls_repeat"></block>
        <block type="robControls_wait_time">
        <value name="WAIT">
            <block type="math_number">
            <field name="NUM">500</field>
            </block>
        </value>
        </block>
        <block type="robControls_wait_for">
        <value name="WAIT0">
            <block type="logic_compare">
            <value name="A">
                <block type="robSensors_getSample"/>
            </value>
            <value name="B">
                <block type="math_number">
                <field name="NUM">50</field>
                </block>
            </value>
            </block>
        </value>
        </block>
    </category>
    <category name="TOOLBOX_LOGIC" svg="true">
        <block type="logic_compare"></block>
        <block type="logic_operation"></block>
        <block type="logic_boolean"></block>
    </category>
    <category name="TOOLBOX_MATH" svg="true">
        <block type="math_number"></block>
        <block type="math_arithmetic"></block>
    </category>
    <category name="TOOLBOX_TEXT" svg="true">
        <block type="text"></block>
        <block type="text_comment"></block>
        <block type="robText_join"></block>
    </category>
    <category name="TOOLBOX_VARIABLE" custom="VARIABLE" svg="true"/>
    </toolbox_set>

    <toolbox_set id="toolbox-Configuration" style="display: none">
    <category name="TOOLBOX_ACTION" svg="true">
        <block type="robConf_led"></block>
        <block type="robConf_rgbled"></block>
        <block type="robConf_buzzer"></block>
        <block type="robConf_wireless"></block>
        <block type="robConf_lcdi2c"></block>
        <block type="robConf_plotting"></block>
        <block type="robBrick_senseBox-Brick"></block>
    </category>
    <category name="TOOLBOX_SENSOR" svg="true">
        <block type="robConf_key" ></block>
        <block type="robConf_light" ></block>
        <block type="robConf_potentiometer" ></block>
        <block type="robConf_humidity" ></block>
        <block type="robConf_sound" ></block>
        <block type="robConf_lightveml" ></block>
        <block type="robConf_accelerometer" ></block>
        <block type="robConf_environmental" ></block>
    </category>
    </toolbox_set>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了"空白页"项模板

namespace LearnTHU.View
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class DetailPage : Page
    {
        public DetailPage()
        {
            this.InitializeComponent();
        }
    }
}


text:
[![Build Status](https://travis-ci.org/trenchproject/trenchproject.github.io.svg?branch=master)](https://travis-ci.org/trenchproject/trenchproject.github.io)

## Adding content.
### Pages.
There are 3 steps to adding a new page to the Trench website.

1. Create a new file in the `_pages` directory with the template `<pagename>.md`.
2. Copy and paste the following into the top of your new file, substituting all placeholders for the particular information for the new page:
```
---
permalink: <<insert permalink, like /people or /tools. this is optional, you can delete this line>>
title: <<insert title>>
author_profile: true
layout: single
header:
    overlay_image: assets/images/ashcroft.jpg
---
```
3. Place the page's content as markdown-formatted text below the above content.

When you `git add _pages/<newfile.md>` and commit and push, the page will be live at `http://trenchproject.github.io/<<pagename>>.html` or at `/<<permalink`, depending on whether you set a permalink.

### Blog Posts.
The process is similar for blog posts.

1. Create a new file in the `_posts` directory with the filename `YYYY-MM-DD-title-of-post.md`.
2. Copy and paste the following into the top of your new file, substituting all placeholders for the particular information for the new page:
```
---
title: <<insert title>>
excerpt: <<optional short description of the post>>
---
```
3. Below that content, write the post as markdown-formatted text.

Adding, committing, and pushing the above file to the repository will add the post to the list of posts at `http://trenchproject.github.io/news`, and the post will be accessible at `/news/post-title`.


text:
package net.emaze.dysfunctional.dispatching.logic;

import org.junit.Assert;
import org.junit.Test;

public class NoTest {

    @Test
    public void noJustReturnsFalse() {
        Assert.assertFalse(new No().getAsBoolean());
    }
}


text:
{% load pipeline %}

<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="{% block description %}Current and historical Municipal Finance data from the National Treasury{% endblock %}">
    <meta name="csrf-token" content="{{ csrf_token }}">
    <meta name="google-site-verification" content="wGl9Jd3oxgnbklAbePVsucACMR8g38SXoSq6hvyb9Gk" />
    <meta name="msvalidate.01" content="302E91E15E0652704A4BAA3FF1F134D3" />

    {% block head-css %}
    {% endblock %}

    {% block head-meta %}{% endblock %}

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body {% block body-attributes %}{% endblock %} class="{% block body-class %}{% endblock %}" id="{% block body-id %}{% endblock %}">

    {% block content %}
    {% endblock content %}

    {% block js %}

    {% if GOOGLE_ANALYTICS_ID %}
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', '{{ GOOGLE_ANALYTICS_ID }}', 'auto');
      ga('send', 'pageview');
    </script>
    {% endif %}

    {% endblock %}

  </body>
</html>


text:
using System;
using System.Linq;

namespace Biggy.Core {
  public class PrimaryKeyAttribute : Attribute {
    public PrimaryKeyAttribute(bool Auto) {
      this.IsAutoIncrementing = Auto;
    }
    public bool IsAutoIncrementing { get; private set; }
  }

  public class DbColumnAttribute : Attribute {
    public DbColumnAttribute(string name) {
      this.Name = name;
    }
    public string Name { get; protected set; }
  }

  public class DbTableAttribute : Attribute {
    public DbTableAttribute(string name) {
      this.Name = name;
    }
    public string Name { get; protected set; }
  }
}


text:
package play.i18n;

public interface Messages {}