text:
import * as yargs from 'yargs';
import * as util from 'util';
import {exec} from "child_process";
import * as stream from "stream";
import * as fs from "fs";
import {ranking} from "./ranking";
import {constraints} from "./constraints";
import {assert, eq, not, or, iteFromDictFlipKeyValue, capitalizeFirstLetter} from "./helpers";
import { FIELDS, QUERIES, Fields, Query } from './queries';
import {PRIMITIVE_MARKS} from 'vega-lite/build/src/mark';
import {CHANNELS} from 'vega-lite/build/src/channel';
import {AGGREGATE_OPS}  from 'vega-lite/build/src/aggregate';

// parse args
const argv = yargs.argv;

const types = `
(set-option :produce-unsat-cores true)
; data related types

(declare-datatypes () ((RawType
StringType FloatType IntegerType DateType BooleanType
)))

(declare-datatypes () ((Field
(mk-field (name String) (type RawType) (cardinality Int))
)))

; encoding related types

(declare-datatypes () ((Marktype
${PRIMITIVE_MARKS.map(mark => capitalizeFirstLetter(mark) + 'Mark').join(' ')}
)))

(declare-datatypes () ((Channel
${CHANNELS.map(channel => capitalizeFirstLetter(channel) + 'Channel').join(' ')}
)))

(declare-datatypes () ((EncodingType
Quantitative Ordinal Nominal
)))

(declare-datatypes () ((AggFunc
; TODO: add 'Aggregate' postfix
None ${AGGREGATE_OPS.map(agg => capitalizeFirstLetter(agg)).join(' ')}
)))

(declare-datatypes () ((Scale
(mk-scale (zero bool) (log bool))
)))

(declare-datatypes () ((Encoding
(mk-enc (channel Channel) (field Field) (type EncodingType) (binned Bool) (agg AggFunc) (scale Scale))
)))
`;

const nullEnc = `
(declare-const nullEnc Encoding)
`;

const countField = `
(declare-const countField Field)
${assert(eq("(name countField)", '"*"'))}
${assert(eq("(type countField)", "IntegerType"))}
`

const markDeclaration = `
(declare-const mark Marktype)
`

function addGetXGetYEnc(encs){
  const getXEncDict = {};
  encs.forEach((enc, i) => {
    getXEncDict[enc] = `(channel ${enc})`;
  });

  let dim = "X";
  const getXEncFunc = `(define-fun get${dim}Enc () Encoding
           ${iteFromDictFlipKeyValue(dim + "Channel", getXEncDict, "nullEnc")}
        )`;

  dim = "Y";
  const getYEncFunc = `(define-fun get${dim}Enc () Encoding
           ${iteFromDictFlipKeyValue(dim + "Channel", getXEncDict, "nullEnc")}
        )`;

  return getXEncFunc + '\n' + getYEncFunc;
}

function solve(getUnsatCore: boolean, encs: string[]){
  let solve = `
    ; get output
    (check-sat)
    `;

  if (getUnsatCore){
    solve+=`
      (echo "Unsat Core:")
      (get-unsat-core)`
  } else {
    solve+=`
      ${encs.map(e => `(get-value (${e}))`).join("\n")}
      (get-value (mark))
      (get-model)
      (echo "Spec:")
      (get-value (mark))
      ${encs.map(e => `(get-value (${e}))`).join("\n")}
    `;
  }
  return solve;
}

//function debugRanking(fields: Fields, query: Query, encs, produceUnsatCore: boolean){
function debugRanking(){
  //return encs.map((e) => ` (get-value (`)
  return "(get-value (pen mpen gx gy nullEnc))";
}

function callZ3(program: string, callback: (output: string) => void) {
  console.time("z3");

  // execute in z3
  const child = exec("z3 /dev/fd/0", function (err, stdout, stderr) {
    if (err) {
      console.error(err);
    }
    if (stderr) {
      console.error(stderr);
    }

    if (argv["v"]) {
      console.timeEnd("z3");
    }

    callback(stdout);
  });

  const stdinStream = new stream.Readable();

  stdinStream.push(program);  // Add data to the internal queue for users of the stream to consume
  stdinStream.push(null);   // Signals the end of the stream (EOF)
  stdinStream.pipe(child.stdin);
}

function buildProgram(fields: Fields, query: Query, produceUnsatCore: boolean) {
  let program = "";

  program += types;
  program += markDeclaration;
  program += countField;
  program += nullEnc;

  // add fields
  fields.forEach(f => {
    const name = f.name + "Field";
    program += `(declare-const ${name} Field)
    `;
    program += assert(eq(`(name ${name})`, `"${f.name}"`)) + "\n";
    program += assert(eq(`(type ${name})`, `${f.type}Type`)) + "\n";
    program += assert(eq(`(cardinality ${name})`, `${f.cardinality}`)) + "\n";
  });

  // add null field
    const nullname = "nullField";

    program += `(declare-const ${nullname} Field)
    `;
    program += assert(eq(`(name ${nullname})`, `"nullfield"`)) + "\n";
    program += assert(eq(`(field nullEnc)`, nullname)) + "\n";

  // add mark type constraint
  if (query.mark) {
    program += assert(eq("mark", `${capitalizeFirstLetter(query.mark)}Mark`));
  }

  // add encodings
  const encs: string[] = [];
  if (query.encodings) {
    query.encodings.forEach((e, i) => {
      const enc = `e${i}`;
      program += `(declare-const ${enc} Encoding)`;
      program += assert(not(eq(enc, "nullEnc")));
      if (e.field) {
        program += assert(eq(`(name (field ${enc}))`, `"${e.field}"`));
      }
      if (e.type) {
        program += assert(eq(`(type ${enc})`, `${capitalizeFirstLetter(e.type)}`));
      }
      if (e.channel) {
        program += assert(eq(`(channel ${enc})`, `${capitalizeFirstLetter(e.channel)}Channel`));
      }
      if (e.aggregate) {
        program += assert(eq(`(agg ${enc})`, `${capitalizeFirstLetter(e.aggregate)}`));
      }
      if (e.binned !== undefined) {
        if (e.binned) {
          program += assert(`(binned ${enc})`);
        } else {
          program += assert(not(`(binned ${enc})`));
        }
      }
      if (e.scale !== undefined) {
        if (e.scale.log === true) {
          program += assert(`(log (scale ${enc}))`);
        } else if (e.scale.log === false) {
          program += assert(not(`(log (scale ${enc}))`));
        }

        if (e.scale.zero === true) {
          program += assert(`(zero (scale ${enc}))`);
        } else if (e.scale.zero === false) {
          program += assert(not(`(zero (scale ${enc}))`));
        }
      }

      encs.push(enc);
    });
  }

  // add constraints

  if (encs.length === 0) {
    // we need at least one channel
    program += assert("false");
  } else {

    program += addGetXGetYEnc(encs);
    const {hard, soft}  = constraints(encs, fields.map(f => f.name));
    program += hard.join(" ");

    if (!produceUnsatCore) {
      program += soft.join(" ");
    }
  }

  if (!produceUnsatCore) {
    const [defs, minimizeStmt] = ranking(fields, query, encs)
    program += defs;
    program += minimizeStmt;

  }

  program += solve(produceUnsatCore, encs);
  program += debugRanking()

  return program;
} // END buildProgram

function makeIterator(array: string[]) {
  let nextIndex = 0;

  return {
    next: () => {
      return nextIndex < array.length ?
      {value: array[nextIndex++], done: false} :
      {value: '', done: true};
    }
  };
}

function parse(stdout) {
  const lines = makeIterator(stdout.split('\n'));

  let marktype = '';
  let encoding = {};

  let next = lines.next();

  // find marktype def
  while (next.value !== "Spec:" && !next.done) {
    next = lines.next();
  }

  if (next.done) {
    throw new Error("No marktype found");
  }

  next = lines.next();
  (next.value.replace as any)(
    /\(\(mark (\w+)Mark\)\)/gi,
    (_, $1) => {
      marktype = $1.toLowerCase();
    }
  )
  next = lines.next();

  while (!next.done) {
    let line = next.value;
    next = lines.next();
    while (!next.done && !next.value.startsWith("((e")) {
      line += ` ${next.value.trim()}`;
      next = lines.next();
    }

    (line.replace as any)(
      // ((e0 (mk-enc     XChannel (mk-field    "str1"     String   3) Ordinal false   Min (mk-scale   true   false))))
      //                  $1                      $2         $3    $4      $5    $6    $7               $8     $9
      /\(\(e\d* \(mk-enc (\w+)Channel \(mk-field "(\w+|\*)" (\w+) (\d+)\) (\w+) (\w+) (\w+) \(mk-scale (\w+) (\w+)\)\)\)\)/gi,
      (_, $1, $2, $3, $4, $5, $6, $7, $8, $9) => {
        const enc: any = {
          field: $2,
          type: $5.toLowerCase()
        }

        if ($6 === "true") {
          enc.bin = true;
        }

        if ($7 !== "None") {
          enc.aggregate = $7.toLowerCase()
        }

        enc.scale = {};
        if ($8 === "true") {
          enc.scale.zero = true;
        }

        if ($9 === "true") {
          enc.scale.log = true;
        }

        if (Object.keys(enc.scale).length === 0) {
          delete enc.scale;
        }

        encoding[$1.toLowerCase()] = enc;
      }
    )
  }

  const spec = {
    mark: marktype,
    encoding: encoding
  };

  return spec;
}

const query = QUERIES[parseInt(argv.query) || 0];

function run(produceUnsatCore) {
  const program = buildProgram(FIELDS, query, produceUnsatCore);

  if (argv["d"]) {
    console.log("Writing out.z3");
    fs.writeFile("out.z3", program, () => {});
  }

  callZ3(program, (output) => {
    if (!produceUnsatCore && output.startsWith("unsat")) {
      console.warn("Program was unsat");
      return run(true);
    }

    if (argv["v"]) {
      console.log("Output from z3:");
      console.log(output);
    }

    if (!produceUnsatCore) {
      const vl = argv["vl"]
      if (vl) {
        const spec: any = parse(output);
        spec.data = query.data;

        if (argv["v"]) {
          console.log(`Writing ${vl}`);
          console.log(util.inspect(spec, false, null));
        }

        fs.writeFile(vl, JSON.stringify(spec, null, ' '), () => {});
      }
    }
  });
}

run(false);


text:
import Quill from './core/quill';

import Block, { BlockEmbed } from './blots/block';
import Break from './blots/break';
import Container from './blots/container';
import Cursor from './blots/cursor';
import Embed from './blots/embed';
import Inline from './blots/inline';
import Scroll from './blots/scroll';
import TextBlot from './blots/text';

import Clipboard from './modules/clipboard';
import History from './modules/history';
import Keyboard from './modules/keyboard';
import Uploader from './modules/uploader';
import Delta, { Op, OpIterator, AttributeMap } from 'quill-delta';

export { Delta, Op, OpIterator, AttributeMap };

Quill.register({
  'blots/block': Block,
  'blots/block/embed': BlockEmbed,
  'blots/break': Break,
  'blots/container': Container,
  'blots/cursor': Cursor,
  'blots/embed': Embed,
  'blots/inline': Inline,
  'blots/scroll': Scroll,
  'blots/text': TextBlot,

  'modules/clipboard': Clipboard,
  'modules/history': History,
  'modules/keyboard': Keyboard,
  'modules/uploader': Uploader,
});

export default Quill;

redpajama_set_name: RedPajamaGithub


text:
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextTestProgressListener.h>
#include <stdexcept>

#ifndef CPPUNIT_INIT_BUNDLES_TESTS
#define CPPUNIT_INIT_BUNDLES_TESTS
#endif

 int
 main( int argc, char* argv[] )
 {
   CPPUNIT_INIT_BUNDLES_TESTS;

   std::string testPath = (argc > 1) ? std::string(argv[1]) : "";

   // Create the event manager and test controller
   CppUnit::TestResult controller;

   // Add a listener that colllects test result
   CppUnit::TestResultCollector result;
   controller.addListener( &result );

   // Add a listener that print dots as test run.
   CppUnit::TextTestProgressListener progress;
   controller.addListener( &progress );

   // Add the top suite to the test runner
   CppUnit::TestRunner runner;
   runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
   try
   {
     std::cout << "Running "  <<  testPath;
     runner.run( controller, testPath );

     std::cerr << std::endl;

     // Print test in a compiler compatible format.
     CppUnit::CompilerOutputter outputter( &result, std::cerr );
     outputter.write();
   }
   catch ( std::invalid_argument &e )  // Test path not resolved
   {
     std::cerr  <<  std::endl
                <<  "ERROR: "  <<  e.what()
                << std::endl;
     return 0;
   }

   return result.wasSuccessful() ? 0 : 1;
 }


text:
.class public final Lo/kB;
.super Ljava/lang/Object;

# annotations
.annotation runtime Lo/jE;
.end annotation

# direct methods
.method public static ˊ(Landroid/content/Context;Z)V
    .locals 3

    invoke-static {p0}, Lo/kB;->ˋ(Landroid/content/Context;)Landroid/content/SharedPreferences;

    move-result-object v1

    invoke-interface {v1}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor;

    move-result-object v2

    const-string v0, "use_https"

    invoke-interface {v2, v0, p1}, Landroid/content/SharedPreferences$Editor;->putBoolean(Ljava/lang/String;Z)Landroid/content/SharedPreferences$Editor;

    invoke-interface {v2}, Landroid/content/SharedPreferences$Editor;->commit()Z

    return-void
.end method

.method public static ˊ(Landroid/content/Context;)Z
    .locals 3

    invoke-static {p0}, Lo/kB;->ˋ(Landroid/content/Context;)Landroid/content/SharedPreferences;

    move-result-object v2

    const-string v0, "use_https"

    const/4 v1, 0x1

    invoke-interface {v2, v0, v1}, Landroid/content/SharedPreferences;->getBoolean(Ljava/lang/String;Z)Z

    move-result v0

    return v0
.end method

.method private static ˋ(Landroid/content/Context;)Landroid/content/SharedPreferences;
    .locals 2

    const-string v0, "admob"

    const/4 v1, 0x0

    invoke-virtual {p0, v0, v1}, Landroid/content/Context;->getSharedPreferences(Ljava/lang/String;I)Landroid/content/SharedPreferences;

    move-result-object v0

    return-object v0
.end method


text:
<?php
// PHP Layers Menu 3.2.0-rc (C) 2001-2004 Marco Pratesi - http://www.marcopratesi.it/

/**
* This file contains the code of the PlainMenu class.
* @package PHPLayersMenu
*/

/**
* This is the PlainMenu class of the PHP Layers Menu library.
*
* This class depends on the LayersMenuCommon class and on the PEAR conforming version of the PHPLib Template class, i.e. on HTML_Template_PHPLIB.  It provides plain menus, that to do not require JavaScript to work.
*
* @version 3.2.0-rc
* @package PHPLayersMenu
*/
class PlainMenu extends LayersMenuCommon
{

/**
* The template to be used for the Plain Menu
*/
var $plainMenuTpl;
/**
* An array where we store the Plain Menu code for each menu
* @access private
* @var array
*/
var $_plainMenu;

/**
* The template to be used for the Horizontal Plain Menu
*/
var $horizontalPlainMenuTpl;
/**
* An array where we store the Horizontal Plain Menu code for each menu
* @access private
* @var array
*/
var $_horizontalPlainMenu;

/**
* The constructor method; it initializates some variables
* @return void
*/
function PlainMenu()
{
	$this->LayersMenuCommon();

	$this->plainMenuTpl = $this->tpldir . 'layersmenu-plain_menu.ihtml';
	$this->_plainMenu = array();

	$this->horizontalPlainMenuTpl = $this->tpldir . 'layersmenu-horizontal_plain_menu.ihtml';
	$this->_horizontalPlainMenu = array();
}

/**
* The method to set the dirroot directory
* @access public
* @return boolean
*/
function setDirroot($dirroot)
{
	$oldtpldir = $this->tpldir;
	if ($foobar = $this->setDirrootCommon($dirroot)) {
		$this->updateTpldir($oldtpldir);
	}
	return $foobar;
}

/**
* The method to set the tpldir directory
* @access public
* @return boolean
*/
function setTpldir($tpldir)
{
	$oldtpldir = $this->tpldir;
	if ($foobar = $this->setTpldirCommon($tpldir)) {
		$this->updateTpldir($oldtpldir);
	}
	return $foobar;
}

/**
* The method to update the templates directory path to the new tpldir
* @access private
* @return void
*/
function updateTpldir($oldtpldir)
{
	$oldlength = strlen($oldtpldir);
	$foobar = strpos($this->plainMenuTpl, $oldtpldir);
	if (!($foobar === false || $foobar != 0)) {
		$this->plainMenuTpl = $this->tpldir . substr($this->plainMenuTpl, $oldlength);
	}
	$foobar = strpos($this->horizontalPlainMenuTpl, $oldtpldir);
	if (!($foobar === false || $foobar != 0)) {
		$this->horizontalPlainMenuTpl = $this->tpldir . substr($this->horizontalPlainMenuTpl, $oldlength);
	}
}

/**
* The method to set plainMenuTpl
* @access public
* @return boolean
*/
function setPlainMenuTpl($plainMenuTpl)
{
	if (str_replace('/', '', $plainMenuTpl) == $plainMenuTpl) {
		$plainMenuTpl = $this->tpldir . $plainMenuTpl;
	}
	if (!file_exists($plainMenuTpl)) {
		$this->error("setPlainMenuTpl: file $plainMenuTpl does not exist.");
		return false;
	}
	$this->plainMenuTpl = $plainMenuTpl;
	return true;
}

/**
* Method to prepare a new Plain Menu.
*
* This method processes items of a menu to prepare and return
* the corresponding Plain Menu code.
*
* @access public
* @param string $menu_name the name of the menu whose items have to be processed
* @return string
*/
function newPlainMenu(
	$menu_name = ''	// non consistent default...
	)
{
	$plain_menu_blck = '';
	$t = new Template_PHPLIB();
	$t->setFile('tplfile', $this->plainMenuTpl);
	$t->setBlock('tplfile', 'template', 'template_blck');
	$t->setBlock('template', 'plain_menu_cell', 'plain_menu_cell_blck');
	$t->setVar('plain_menu_cell_blck', '');
	for ($cnt=$this->_firstItem[$menu_name]; $cnt<=$this->_lastItem[$menu_name]; $cnt++) {
		if ($this->tree[$cnt]['text'] == '---') {
			continue;	// separators are significant only for layers-based menus
		}
		$nbsp = '';
		for ($i=1; $i<$this->tree[$cnt]['level']; $i++) {
			$nbsp .= '   ';
		}
		$t->setVar(array(
			'nbsp'		=> $nbsp,
			'href'		=> $this->tree[$cnt]['parsed_href'],
			'title'		=> $this->tree[$cnt]['parsed_title'],
			'target'	=> $this->tree[$cnt]['parsed_target'],
			'text'		=> $this->tree[$cnt]['parsed_text']
		));
		$plain_menu_blck .= $t->parse('plain_menu_cell_blck', 'plain_menu_cell', false);
	}
	$t->setVar('plain_menu_cell_blck', $plain_menu_blck);
	$this->_plainMenu[$menu_name] = $t->parse('template_blck', 'template');

	return $this->_plainMenu[$menu_name];
}

/**
* Method that returns the code of the requested Plain Menu
* @access public
* @param string $menu_name the name of the menu whose Plain Menu code
*   has to be returned
* @return string
*/
function getPlainMenu($menu_name)
{
	return $this->_plainMenu[$menu_name];
}

/**
* Method that prints the code of the requested Plain Menu
* @access public
* @param string $menu_name the name of the menu whose Plain Menu code
*   has to be printed
* @return void
*/
function printPlainMenu($menu_name)
{
	print $this->_plainMenu[$menu_name];
}

/**
* The method to set horizontalPlainMenuTpl
* @access public
* @return boolean
*/
function setHorizontalPlainMenuTpl($horizontalPlainMenuTpl)
{
	if (str_replace('/', '', $horizontalPlainMenuTpl) == $horizontalPlainMenuTpl) {
		$horizontalPlainMenuTpl = $this->tpldir . $horizontalPlainMenuTpl;
	}
	if (!file_exists($horizontalPlainMenuTpl)) {
		$this->error("setHorizontalPlainMenuTpl: file $horizontalPlainMenuTpl does not exist.");
		return false;
	}
	$this->horizontalPlainMenuTpl = $horizontalPlainMenuTpl;
	return true;
}

/**
* Method to prepare a new Horizontal Plain Menu.
*
* This method processes items of a menu to prepare and return
* the corresponding Horizontal Plain Menu code.
*
* @access public
* @param string $menu_name the name of the menu whose items have to be processed
* @return string
*/
function newHorizontalPlainMenu(
	$menu_name = ''	// non consistent default...
	)
{
	$horizontal_plain_menu_blck = '';
	$t = new Template_PHPLIB();
	$t->setFile('tplfile', $this->horizontalPlainMenuTpl);
	$t->setBlock('tplfile', 'template', 'template_blck');
	$t->setBlock('template', 'horizontal_plain_menu_cell', 'horizontal_plain_menu_cell_blck');
	$t->setVar('horizontal_plain_menu_cell_blck', '');
	$t->setBlock('horizontal_plain_menu_cell', 'plain_menu_cell', 'plain_menu_cell_blck');
	$t->setVar('plain_menu_cell_blck', '');
	for ($cnt=$this->_firstItem[$menu_name]; $cnt<=$this->_lastItem[$menu_name]; $cnt++) {
		if ($this->tree[$cnt]['text'] == '---') {
			continue;	// separators are significant only for layers-based menus
		}
		if ($this->tree[$cnt]['level'] == 1 && $cnt > $this->_firstItem[$menu_name]) {
			$t->parse('horizontal_plain_menu_cell_blck', 'horizontal_plain_menu_cell', true);
			$t->setVar('plain_menu_cell_blck', '');
		}
		$nbsp = '';
		for ($i=1; $i<$this->tree[$cnt]['level']; $i++) {
			$nbsp .= '   ';
		}
		$t->setVar(array(
			'nbsp'		=> $nbsp,
			'href'		=> $this->tree[$cnt]['parsed_href'],
			'title'		=> $this->tree[$cnt]['parsed_title'],
			'target'	=> $this->tree[$cnt]['parsed_target'],
			'text'		=> $this->tree[$cnt]['parsed_text']
		));
		$t->parse('plain_menu_cell_blck', 'plain_menu_cell', true);
	}
	$t->parse('horizontal_plain_menu_cell_blck', 'horizontal_plain_menu_cell', true);
	$this->_horizontalPlainMenu[$menu_name] = $t->parse('template_blck', 'template');

	return $this->_horizontalPlainMenu[$menu_name];
}

/**
* Method that returns the code of the requested Horizontal Plain Menu
* @access public
* @param string $menu_name the name of the menu whose Horizontal Plain Menu code
*   has to be returned
* @return string
*/
function getHorizontalPlainMenu($menu_name)
{
	return $this->_horizontalPlainMenu[$menu_name];
}

/**
* Method that prints the code of the requested Horizontal Plain Menu
* @access public
* @param string $menu_name the name of the menu whose Horizontal Plain Menu code
*   has to be printed
* @return void
*/
function printHorizontalPlainMenu($menu_name)
{
	print $this->_horizontalPlainMenu[$menu_name];
}

} /* END OF CLASS */

?>


text:
namespace BeyondThemes.BeyondAdmin
{
    using System;
    using System.Collections.Generic;

    public partial class Glo_Clase
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Glo_Clase()
        {
            this.Dir_Establecimientos = new HashSet<Dir_Establecimientos>();
        }

        public int IdActividad { get; set; }
        public int IdGrupo { get; set; }
        public string GlosaClase { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Dir_Establecimientos> Dir_Establecimientos { get; set; }
        public virtual Glo_Grupo Glo_Grupo { get; set; }
    }
}


text:
"""Simple wrapper over Gremlin language."""

# TODO: make a proper PyPi package with this class?

class GremlinQuery:
    """Simple wrapper over Gremlin language."""

    def __init__(self):
        """Initialize the object with a start of query."""
        self.query = 'g.V()'

    def has(self, name, value):
        """Add (another) 'has' clause into the query."""
        self.query += '.has("{name}", "{value}")'.format(name=name, value=value)
        return self

    def out(self, name):
        """Add an 'out' clause into the query."""
        self.query += '.out("{name}")'.format(name=name)
        return self

    def valueMap(self):
        """Append a clause to retrieve map of values to the query."""
        self.query += '.valueMap()'
        return self

    def count(self):
        """Add a 'count' clause at the end of the query."""
        self.query += '.count()'
        return self

    def first(self):
        """Append a clause to get the first result from a list."""
        self.query += '[0]'
        return self

    def value(self, value):
        """Append a clause to read the given value from the dictionary."""
        self.query += '.value("{value}")'.format(value=value)
        return self

    def __repr__(self):
        """Return an official represenation of the object, same as __str__ here."""
        return self.query

    def ___str___(self):
        """Return an informal represenation of the object, same as __repr__ here."""
        return self.query


text:
void TextTagManager_Init();
void TextTagManager_Update(); //ʱ»úÕÒ²»×¼

war3::CTextTagManager* GetJassTTM();
war3::CTextTagManager* GetMapTTM();

war3::CTextTagManager* CreateTextTagManager(const char* fontName, double size); //´´½¨³öÀ´³ý·ÇÌ滻ϵͳԭÓеģ¬·ñÔò²»ÏÔʾ
void DestroyTextTagManager(war3::CTextTagManager* m);

uint32_t TTMCreateTag(war3::CTextTagManager* m, const char* text, double size);
void TTMSetTagPos(war3::CTextTagManager* m, uint32_t tagId, float x, float y, float heightOffset);
void TTMSetTagPos3D(war3::CTextTagManager* m, uint32_t tagId, float x, float y, float z);
void TTMSetTagText(war3::CTextTagManager* m, uint32_t tagId, const char* text, float size);
void TTMSetTagColor(war3::CTextTagManager* m, uint32_t tagId, uint32_t color);
void TTMSetTagVelocity(war3::CTextTagManager* m, uint32_t tagId, float x, float y);
void TTMSetTagVisibility(war3::CTextTagManager* m, uint32_t tagId, bool v);
void TTMSetTagSuspended(war3::CTextTagManager* m, uint32_t tagId, bool v);
void TTMSetTagPermanent(war3::CTextTagManager* m, uint32_t tagId, bool v);
void TTMSetTagAge(war3::CTextTagManager* m, uint32_t tagId, float v);
void TTMSetTagLifespan(war3::CTextTagManager* m, uint32_t tagId, float v);
void TTMSetTagFadepoint(war3::CTextTagManager* m, uint32_t tagId, float v);
uint32_t TTMDestroyTag(war3::CTextTagManager* m, uint32_t tagId);

#endif


text:
package org.elasticsearch.index.query;

import org.apache.lucene.search.Query;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser;

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

/**
 *
 */
public class SpanOrQueryParser implements QueryParser {

    public static final String NAME = "span_or";

    @Inject
    public SpanOrQueryParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME, Strings.toCamelCase(NAME)};
    }

    @Override
    public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        float boost = 1.0f;
        String queryName = null;

        List<SpanQuery> clauses = new ArrayList<>();

        String currentFieldName = null;
        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_ARRAY) {
                if ("clauses".equals(currentFieldName)) {
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        Query query = parseContext.parseInnerQuery();
                        if (!(query instanceof SpanQuery)) {
                            throw new QueryParsingException(parseContext, "spanOr [clauses] must be of type span query");
                        }
                        clauses.add((SpanQuery) query);
                    }
                } else {
                    throw new QueryParsingException(parseContext, "[span_or] query does not support [" + currentFieldName + "]");
                }
            } else {
                if ("boost".equals(currentFieldName)) {
                    boost = parser.floatValue();
                } else if ("_name".equals(currentFieldName)) {
                    queryName = parser.text();
                } else {
                    throw new QueryParsingException(parseContext, "[span_or] query does not support [" + currentFieldName + "]");
                }
            }
        }
        if (clauses.isEmpty()) {
            throw new QueryParsingException(parseContext, "spanOr must include [clauses]");
        }

        SpanOrQuery query = new SpanOrQuery(clauses.toArray(new SpanQuery[clauses.size()]));
        query.setBoost(boost);
        if (queryName != null) {
            parseContext.addNamedQuery(queryName, query);
        }
        return query;
    }
}


text:
package org.gradle.groovy.scripts;

import groovy.lang.Binding;
import groovy.lang.MissingMethodException;
import groovy.lang.MissingPropertyException;
import org.gradle.api.internal.DynamicObjectAware;
import org.gradle.api.internal.DynamicObjectUtil;
import org.gradle.api.internal.ProcessOperations;
import org.gradle.api.internal.file.FileOperations;
import org.gradle.internal.logging.StandardOutputCapture;
import org.gradle.internal.metaobject.AbstractDynamicObject;
import org.gradle.internal.metaobject.BeanDynamicObject;
import org.gradle.internal.metaobject.DynamicInvokeResult;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.internal.service.ServiceRegistry;

import java.io.PrintStream;
import java.util.Map;

public abstract class BasicScript extends org.gradle.groovy.scripts.Script implements org.gradle.api.Script, FileOperations, ProcessOperations, DynamicObjectAware {
    private StandardOutputCapture standardOutputCapture;
    private Object target;
    private ScriptDynamicObject dynamicObject = new ScriptDynamicObject(this);

    public void init(Object target, ServiceRegistry services) {
        standardOutputCapture = services.get(StandardOutputCapture.class);
        setScriptTarget(target);
    }

    public Object getScriptTarget() {
        return target;
    }

    private void setScriptTarget(Object target) {
        this.target = target;
        this.dynamicObject.setTarget(target);
    }

    public StandardOutputCapture getStandardOutputCapture() {
        return standardOutputCapture;
    }

    public PrintStream getOut() {
        return System.out;
    }

    @Override
    public Object getProperty(String property) {
        return dynamicObject.getProperty(property);
    }

    @Override
    public void setProperty(String property, Object newValue) {
        dynamicObject.setProperty(property, newValue);
    }

    public Map<String, ?> getProperties() {
        return dynamicObject.getProperties();
    }

    public boolean hasProperty(String property) {
        return dynamicObject.hasProperty(property);
    }

    @Override
    public Object invokeMethod(String name, Object args) {
        return dynamicObject.invokeMethod(name, (Object[]) args);
    }

    @Override
    public DynamicObject getAsDynamicObject() {
        return dynamicObject;
    }

    /**
     * This is a performance optimization which avoids using BeanDynamicObject to wrap the Script object.
     * Using BeanDynamicObject would be wasteful, because most of the interesting properties and methods
     * are delegated to the script target. Doing this delegation explicitly avoids
     * us going through the methodMissing/propertyMissing protocol that BeanDynamicObject would use.
     */
    private static final class ScriptDynamicObject extends AbstractDynamicObject {

        private final Binding binding;
        private final DynamicObject scriptObject;
        private DynamicObject dynamicTarget;

        ScriptDynamicObject(BasicScript script) {
            this.binding = script.getBinding();
            scriptObject = new BeanDynamicObject(script).withNotImplementsMissing();
            dynamicTarget = scriptObject;
        }

        public void setTarget(Object target) {
            dynamicTarget = DynamicObjectUtil.asDynamicObject(target);
        }

        @Override
        public Map<String, ?> getProperties() {
            return dynamicTarget.getProperties();
        }

        @Override
        public boolean hasMethod(String name, Object... arguments) {
            return scriptObject.hasMethod(name, arguments) || dynamicTarget.hasMethod(name, arguments);
        }

        @Override
        public boolean hasProperty(String name) {
            return binding.hasVariable(name) || scriptObject.hasProperty(name) || dynamicTarget.hasProperty(name);
        }

        @Override
        public DynamicInvokeResult tryInvokeMethod(String name, Object... arguments) {
            DynamicInvokeResult result = scriptObject.tryInvokeMethod(name, arguments);
            if (result.isFound()) {
                return result;
            }
            return dynamicTarget.tryInvokeMethod(name, arguments);
        }

        @Override
        public DynamicInvokeResult tryGetProperty(String property) {
            if (binding.hasVariable(property)) {
                return DynamicInvokeResult.found(binding.getVariable(property));
            }
            DynamicInvokeResult result = scriptObject.tryGetProperty(property);
            if (result.isFound()) {
                return result;
            }
            return dynamicTarget.tryGetProperty(property);
        }

        @Override
        public DynamicInvokeResult trySetProperty(String property, Object newValue) {
            return dynamicTarget.trySetProperty(property, newValue);
        }

        @Override
        public MissingPropertyException getMissingProperty(String name) {
            return dynamicTarget.getMissingProperty(name);
        }

        @Override
        public MissingMethodException methodMissingException(String name, Object... params) {
            return dynamicTarget.methodMissingException(name, params);
        }

        @Override
        public MissingPropertyException setMissingProperty(String name) {
            return dynamicTarget.setMissingProperty(name);
        }

        @Override
        public String getDisplayName() {
            return dynamicTarget.toString();
        }
    }

}


text:
<?php

namespace Magento\ConfigurableProduct\Test\Block\Adminhtml\Product;

use Magento\Ui\Test\Block\Adminhtml\DataGrid;

class AttributesGrid extends DataGrid
{
    /**
     * @var string
     */
    protected $selectItem = '[data-action=select-row]';

    /**
     * @var array
     */
    protected $filters = [
        'frontend_label' => [
            'selector' => '[name="frontend_label"]',
        ],
    ];
}


text:
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
 *******************************************************************************
 * Copyright (C) 2015-2016, International Business Machines Corporation and
 * others. All Rights Reserved.
 *******************************************************************************
 */
package android.icu.impl;

import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.icu.impl.locale.AsciiUtil;
import android.icu.util.UResourceBundle;
import android.icu.util.UResourceBundleIterator;

/**
 * @author markdavis
 * @hide Only a subset of ICU is exposed in Android
 *
 */
public class ValidIdentifiers {

    public enum Datatype {
        currency,
        language,
        region,
        script,
        subdivision,
        unit,
        variant,
        u,
        t,
        x,
        illegal
    }

    public enum Datasubtype {
        deprecated,
        private_use,
        regular,
        special,
        unknown,
        macroregion,
    }

    public static class ValiditySet {
        public final Set<String> regularData;
        public final Map<String,Set<String>> subdivisionData;
        public ValiditySet(Set<String> plainData, boolean makeMap) {
            if (makeMap) {
                HashMap<String,Set<String>> _subdivisionData = new HashMap<String,Set<String>>();
                for (String s : plainData) {
                    int pos = s.indexOf('-'); // read v28 data also
                    int pos2 = pos+1;
                    if (pos < 0) {
                        pos2 = pos = s.charAt(0) < 'A' ? 3 : 2;
                    }
                    final String key = s.substring(0, pos);
                    final String subdivision = s.substring(pos2);

                    Set<String> oldSet = _subdivisionData.get(key);
                    if (oldSet == null) {
                        _subdivisionData.put(key, oldSet = new HashSet<String>());
                    }
                    oldSet.add(subdivision);
                }
                this.regularData = null;
                HashMap<String,Set<String>> _subdivisionData2 = new HashMap<String,Set<String>>();
                // protect the sets
                for (Entry<String, Set<String>> e : _subdivisionData.entrySet()) {
                    Set<String> value = e.getValue();
                    // optimize a bit by using singleton
                    Set<String> set = value.size() == 1 ? Collections.singleton(value.iterator().next())
                            : Collections.unmodifiableSet(value);
                    _subdivisionData2.put(e.getKey(), set);
                }

                this.subdivisionData = Collections.unmodifiableMap(_subdivisionData2);
            } else {
                this.regularData = Collections.unmodifiableSet(plainData);
                this.subdivisionData = null;
            }
        }

        public boolean contains(String code) {
            if (regularData != null) {
                return regularData.contains(code);
            } else {
                int pos = code.indexOf('-');
                String key = code.substring(0,pos);
                final String value = code.substring(pos+1);
                return contains(key, value);
            }
        }

        public boolean contains(String key, String value) {
            Set<String> oldSet = subdivisionData.get(key);
            return oldSet != null && oldSet.contains(value);
        }

        @Override
        public String toString() {
            if (regularData != null) {
                return regularData.toString();
            } else {
                return subdivisionData.toString();
            }
        }
    }

    private static class ValidityData {
        static final Map<Datatype,Map<Datasubtype,ValiditySet>> data;
        static {
            Map<Datatype, Map<Datasubtype, ValiditySet>> _data = new EnumMap<Datatype,Map<Datasubtype,ValiditySet>>(Datatype.class);
            UResourceBundle suppData = UResourceBundle.getBundleInstance(
                    ICUData.ICU_BASE_NAME,
                    "supplementalData",
                    ICUResourceBundle.ICU_DATA_CLASS_LOADER);
            UResourceBundle validityInfo = suppData.get("idValidity");
            for(UResourceBundleIterator datatypeIterator = validityInfo.getIterator();
                    datatypeIterator.hasNext();) {
                UResourceBundle datatype = datatypeIterator.next();
                String rawKey = datatype.getKey();
                Datatype key = Datatype.valueOf(rawKey);
                Map<Datasubtype,ValiditySet> values = new EnumMap<Datasubtype,ValiditySet>(Datasubtype.class);
                for(UResourceBundleIterator datasubtypeIterator = datatype.getIterator();
                        datasubtypeIterator.hasNext();) {
                    UResourceBundle datasubtype = datasubtypeIterator.next();
                    String rawsubkey = datasubtype.getKey();
                    Datasubtype subkey = Datasubtype.valueOf(rawsubkey);
                    // handle single value specially
                    Set<String> subvalues = new HashSet<String>();
                    if (datasubtype.getType() == UResourceBundle.STRING) {
                        addRange(datasubtype.getString(), subvalues);
                    } else {
                        for (String string : datasubtype.getStringArray()) {
                            addRange(string, subvalues);
                        }
                    }
                    values.put(subkey, new ValiditySet(subvalues, key == Datatype.subdivision));
                }
                _data.put(key, Collections.unmodifiableMap(values));
            }
            data = Collections.unmodifiableMap(_data);
        }
        private static void addRange(String string, Set<String> subvalues) {
            string = AsciiUtil.toLowerString(string);
            int pos = string.indexOf('~');
            if (pos < 0) {
                subvalues.add(string);
            } else {
                StringRange.expand(string.substring(0,pos), string.substring(pos+1), false, subvalues);
            }
        }
    }

    public static Map<Datatype, Map<Datasubtype, ValiditySet>> getData() {
        return ValidityData.data;
    }

    /**
     * Returns the Datasubtype containing the code, or null if there is none.
     */
    public static Datasubtype isValid(Datatype datatype, Set<Datasubtype> datasubtypes, String code) {
        Map<Datasubtype, ValiditySet> subtable = ValidityData.data.get(datatype);
        if (subtable != null) {
            for (Datasubtype datasubtype : datasubtypes) {
                ValiditySet validitySet = subtable.get(datasubtype);
                if (validitySet != null) {
                    if (validitySet.contains(AsciiUtil.toLowerString(code))) {
                        return datasubtype;
                    }
                }
            }
        }
        return null;
    }

    public static Datasubtype isValid(Datatype datatype, Set<Datasubtype> datasubtypes, String code, String value) {
        Map<Datasubtype, ValiditySet> subtable = ValidityData.data.get(datatype);
        if (subtable != null) {
            code = AsciiUtil.toLowerString(code);
            value = AsciiUtil.toLowerString(value);
            for (Datasubtype datasubtype : datasubtypes) {
                ValiditySet validitySet = subtable.get(datasubtype);
                if (validitySet != null) {
                    if (validitySet.contains(code, value)) {
                        return datasubtype;
                    }
                }
            }
        }
        return null;
    }
}


text:
require 'file_system/directory/directory_creator'
require 'file_system/link/symbolic_link_creator'
require 'file_system/file/file_creator'

module FileSystem
  class Traverser
    attr_accessor :root_dir, :dir_stack, :options, :reference_hash, :dirs_only

    ONLY_DIRS = 'ONLY_DIRS'
    REVERT    = 'REVERT'
    ALIAS     = 'ALIAS'
    REF       = 'REF'
    DIR       = 'DIR'

    def initialize(root_dir, options = {})
      @root_dir ||= root_dir
      @dir_stack = []
      @options = options
      @dirs_only = false
    end

    def traverse(obj, &blk)
      case obj
      when Hash
        handle_hash(obj, &blk)
      when Array
        handle_list(obj, &blk)
      else
        handle_single(obj, &blk)
      end
    end

    def current_dir
      File.join(root_dir, dir_stack.join('/'))
    end

    def visit_dir(name)
      dir_stack.push name
    end

    def leave_dir
      dir_stack.pop
    end

  protected
    def handle_hash(obj, &blk)
      # Forget keys because I don't know what to do with them
      obj.each do |dir_name, dir_content|
        blk.call(create_directory dir_name)
        traverse(dir_content, &blk)
        leave_dir
      end
    end

    def handle_list(obj, &blk)
      obj.each do |dir_content|
        traverse(dir_content, &blk)
      end
    end

    def handle_single(obj, &blk)
      if obj
        return if parse_meta(obj)
        file_name = obj
        if ref?(obj)
          blk.call(create_symbolic_link ref_name(obj), name(obj))
          return
        end
        name = name(obj)
        if alias?(obj)
          create_reference alias_name(obj), name
        end
        handle_single_entry(name, &blk)
      end
    end

    def handle_single_entry(file_name, &blk)
      if enforce_dir? file_name
        dir_name = file_name.gsub( /\s#{DIR}\s/, '').strip
        blk.call(create_directory dir_name)
        leave_dir
      else
        blk.call(create_file file_name)
      end
    end

    def enforce_dir?(file_name)
      dirs_only || !/\sDIR\s/.match(file_name).nil?
    end

    def create_reference(alias_name, name)
      @reference_hash ||= {}
      dir = File.join(root_dir, dir_stack.join(File::SEPARATOR), name)
      @reference_hash.merge!({alias_name.to_sym => dir})
    end

    def create_directory(name)
      return FileSystem::FakeDirectory.new(self, name) if options[:fake]
      FileSystem::DirectoryCreator.new(self, name)
    end

    def create_file(name)
      return FileSystem::FakeFile.new(self, name) if options[:fake]
      FileSystem::FileCreator.new(self, name)
    end

    def create_symbolic_link(ref_name, new_name)
      old_name = reference_hash[ref_name.to_sym].strip
      # puts "create_symbolic_link: r:#{ref_name}, n:#{new_name}, o:#{old_name}"
      return FileSystem::FakeSymbolicLink.new(self, old_name, new_name) if options[:fake]
      FileSystem::SymbolicLinkCreator.new(self, old_name, new_name)
    end

    def parse_meta(key, value = "")
      if revert?(key, value)
        @dirs_only = false
        return true
      end
      if only_dirs?(key, value)
        @dirs_only = true
        return true
      end
      false
    end

    def only_dirs?(key, value = "")
      key == ONLY_DIRS || key == 'meta' && value == ONLY_DIRS
    end

    def revert?(key, value = "")
      key == REVERT || key == 'meta' && value == REVERT
    end

    def name(value)
      value = value.gsub(/\s#{ALIAS}\s/, ',').gsub(/\s#{REF}\s/, ',')
      value.split(',').first.strip
    end

    def alias?(value)
      value.include?(ALIAS)
    end

    def alias_name(value)
      value.split(ALIAS).last.strip
    end

    def ref?(value)
      value.include?(REF)
    end

    def ref_name(value)
      value.split(REF).last.strip
    end

    def dirs_only?
      dirs_only
    end

  end
end


text:
using System;

class PrintCurrentDate      //Create a console application that prints the current date and time
    {
        static void Main()
        {
            Console.WriteLine(DateTime.Now);
        }
    }


text:
namespace hobbes { namespace str {

std::string env(const std::string& varname);
void env(const std::string& varname, const std::string& value);

typedef std::vector<std::string>  seq;
typedef std::vector<seq>          seqs;
typedef std::vector<unsigned int> lengths;

void repeat(unsigned int n, const std::string& s, seq* out);
seq repeat(unsigned int n, const std::string& s);

template <typename C>
  unsigned int maxSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::max<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

template <typename C>
  unsigned int minSize(unsigned int d, const std::vector<C>& vs) {
    if (vs.size() == 0) {
      return d;
    } else {
      unsigned int r = vs[0].size();
      for (unsigned int i = 1; i < vs.size(); ++i) {
        r = std::min<unsigned int>(r, vs[i].size());
      }
      return r;
    }
  }

unsigned int tableCols(const seqs& tbl);
unsigned int tableRows(const seqs& tbl);
unsigned int maxStrLen(const seq&  col);
lengths maxStrLen(const seqs& tbl);
std::string pad(size_t n);
std::string leftAlign(size_t w, const std::string& x);
std::string rightAlign(size_t w, const std::string& x);
seq leftAlign(const seq& col);
seq rightAlign(const seq& col);
seqs leftAlign(const seqs& tbl);
seqs rightAlign(const seqs& tbl);
void printLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printRightAlignedTable(std::ostream& out, const seqs& tbl);
std::string showLeftAlignedTable(const seqs& tbl);
std::string showRightAlignedTable(const seqs& tbl);
void printHeadlessLeftAlignedTable(std::ostream& out, const seqs& tbl);
void printHeadlessRightAlignedTable(std::ostream& out, const seqs& tbl);

template <typename T>
  bool is(const std::string& x) {
    std::istringstream ss(x);
    T dummy;
    ss >> dummy;
    return bool(ss);
  }

template <typename T>
  T to(const std::string& x) {
    std::istringstream ss(x);
    T r = T();
    ss >> r;
    return r;
  }

template <typename T>
  bool to(const std::string& x, T& out) {
    std::istringstream ss(x);
    ss >> out;
    return bool(ss);
  }

template <typename T>
  bool to(const char* b, const char* e, T* out) {
    std::istringstream ss(std::string(b, e));
    ss >> *out;
    return bool(ss);
  }

template <typename T>
  std::string from(const T& x) {
    std::ostringstream ss;
    ss << x;
    return ss.str();
  }

std::string demangle(const char* tn);
std::string demangle(const std::type_info& ti);

template <typename T>
  std::string demangle() {
    return demangle(typeid(T));
  }

template <typename Char>
  std::basic_string<Char> trim(const std::basic_string<Char>& s) {
    if (s.empty()) return s;

    size_t begin = 0;
    size_t end   = 0;

    for (size_t i = 0; i < s.size(); ++i) {
      int c = static_cast<int>(s[i]);
      if (!std::isspace(c) && c != 0) {
        begin = i;
        break;
      }
    }

    // finally, find the last non-whitespace character
    for (size_t i = s.size(); i > 0; --i) {
      int c = static_cast<int>(s[i-1]);
      if (!std::isspace(c) && c != 0) {
        end = i;
        break;
      }
    }

    if (begin == end) {
      return "";
    } else {
      return s.substr(begin, end - begin);
    }
  }

template <typename Char>
  std::pair< std::basic_string<Char>, std::basic_string<Char> > trim(const std::pair< std::basic_string<Char>, std::basic_string<Char> >& p) {
    return std::pair< std::basic_string<Char>, std::basic_string<Char> >(trim<Char>(p.first), trim<Char>(p.second));
  }

template <typename Char>
  std::vector< std::basic_string<Char> > trim(const std::vector< std::basic_string<Char> >& ss) {
    std::vector< std::basic_string<Char> > result;
    for (typename std::vector< std::basic_string<Char> >::const_iterator s = ss.begin(); s != ss.end(); ++s) {
      result.push_back(trim<Char>(*s));
    }
    return result;
  }

template <typename Char>
  std::basic_string<Char> trimq(const std::basic_string<Char>& s, Char q = static_cast<Char>('"')) {
    if (s.size() == 0) {
      return s;
    } else if (s.size() == 1) {
      return (s[0] == q) ? std::basic_string<Char>() : s;
    } else {
      const Char* b = s.c_str();
      const Char* e = b + s.size() - 1;
      if (*b == q) {
        ++b;
      }
      if (*e == q) {
        --e;
      }
      return std::basic_string<Char>(b, e + 1);
    }
  }

// replace [a b c b] [b c] [e] -> [a e b]
template <typename Char>
  std::basic_string<Char> replace(const std::basic_string<Char>& src, const std::basic_string<Char>& old_substr, const std::basic_string<Char>& new_substr) {
    if (old_substr.empty()) {
      return src;
    }

    typedef typename std::basic_string<Char>::size_type SZT;
    std::basic_string<Char> result;
    SZT                     sz     = src.find(old_substr);
    SZT                     lsz    = 0;

    while (sz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.begin() + sz);
      result += new_substr;

      lsz = sz + old_substr.size();
      sz  = src.find(old_substr, lsz);
    }

    if (lsz != std::basic_string<Char>::npos) {
      result += std::string(src.begin() + lsz, src.end());
    }

    return result;
  }

bool isNyb(char);
char denyb(char);
unsigned char dehex(const std::string&);
std::vector<unsigned char> dehexs(const std::string&);
char nyb(unsigned char x);
std::string hex(unsigned char);
std::string hex(const std::vector<unsigned char>&);
std::string hex(const unsigned char*, size_t);

std::string escape(const std::string&);
std::string unescape(const std::string&);

bool endsWith(const std::string& s, const std::string& sfx);

typedef std::pair<std::string, std::string> pair;

inline pair trim(const pair& p) {
  return pair(trim(p.first), trim(p.second));
}

pair splitAt(const std::string& s, unsigned int i);
pair lsplit(const std::string& s, const std::string& ss);
pair rsplit(const std::string& s, const std::string& ss);
seq csplit(const std::string& s, const std::string& ss);
pair readWhile(bool (*P)(char), const std::string& s);

bool isDigit(char c);
bool isNotDigit(char c);

unsigned int firstFailIndex(bool (*P)(char), const std::string& s);

// reverse csplit
std::string cdelim(const seq& ss, const std::string& d);

// common containers for strings
typedef std::set<std::string> set;
std::string show(const set&);

typedef std::map<std::string, std::string> named_strings;
std::string show(const named_strings&);

// process a string by 'expanding' embedded variables/expressions and unescaping sequences
template <typename T>
  T foldWithFormat(const std::string& str, const T& s, T (*constF)(const T&, const std::string&), T (*expF)(const T&, const std::string&)) {
    T r = s;

    std::ostringstream b;
    int x = 0;
    int bc = 0;

    for (size_t i = 0; i < str.size(); ++i) {
      char c = str[i];

      switch (x) {
      // process unformatted text (decide whether to start variables or unescape)
      case 0: {
          switch (c) {
          case '\\':
            x = 1;
            break;

          case '$':
            r = constF(r, b.str());
            b.str("");
            x = 2;
            break;

          default:
            b << c;
            break;
          }
          break;
        }
      // unescape
      case 1: {
          b << c;
          x = 0;
          break;
        }
      // process variables
      case 2: {
          if (c != '{') {
            b << c;
            x = 3;
          } else {
            bc = 1;
            x = 4;
          }
          break;
        }
      // process variable short-names (may only be alphanumeric)
      case 3: {
          if (std::isalnum(c) != 0 || c == '_') {
            b << c;
          } else {
            --i;
            r = expF(r, b.str());
            b.str("");
            x = 0;
          }
          break;
        }
      // process variable 'expressions' (may be anything delimited by braces)
      case 4: {
          if (c == '}') {
            if (bc == 1) {
              r = expF(r, b.str());
              b.str("");
              x = 0;
            } else {
              --bc;
              b << '}';
            }
          } else {
            if (c == '{') {
              ++bc;
            }
            b << c;
          }
          break;
        }
      }
    }

    if (x < 3) {
      r = constF(r, b.str());
    } else if (x == 3) {
      r = expF(r, b.str());
    }

    return r;
  }

// slurp the entire contents of an input stream into a string
inline std::string slurp(std::istream& in) {
  std::ostringstream ss;
  ss << in.rdbuf();
  return ss.str();
}

// generate?
inline seq strings() { return seq(); }
inline seq strings(const std::string& a0) { seq r; r.push_back(a0); return r; }
inline seq strings(const std::string& a0, const std::string& a1) { seq r; r.push_back(a0); r.push_back(a1); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); return r; }
inline seq strings(const std::string& a0, const std::string& a1, const std::string& a2, const std::string& a3, const std::string& a4, const std::string& a5) { seq r; r.push_back(a0); r.push_back(a1); r.push_back(a2); r.push_back(a3); r.push_back(a4); r.push_back(a5); return r; }

// read a char definition like 'c' or 'd' or '\0'
char readCharDef(const std::string&);

// convenience functions for expanding environment variable references in strings and paths
std::string expandVars(const std::string&);
std::string expandPath(const std::string&); // same as 'expandVars' but expand '~' to home directory

// display a byte count in typical units
std::string showDataSize(size_t bytes);

// char set utilities
inline std::string charRange(char low, char high) {
  std::ostringstream ss;
  if (low < high) {
    for (char c = low; c <= high; ++c) {
      ss << c;
    }
  } else {
    for (char c = low; c >= high; --c) {
      ss << c;
    }
  }
  return ss.str();
}

inline std::string printableChars() {
  return charRange(0x20, 0x7e);
}

inline std::string difference(const std::string& x, const std::string& y) {
  return fromSet<std::string>(setDifference(toSet(x), toSet(y)));
}

// a set of strings represented as a prefix tree
class ptnode;

class prefix_tree {
public:
  prefix_tree(const seq&);
  prefix_tree(const set&);
  ~prefix_tree();

  std::map<size_t, seq> rankedMatches(const std::string&, size_t maxDist) const;
  seq closestMatches(const std::string&, size_t maxDist) const;
private:
  ptnode* root;
};

// how far is one string from another string?
size_t editDistance(const std::string&, const std::string&);

// find the strings out of a set that are at most the given edit distance away from an input string
seq closestMatches(const std::string&, const set&, size_t maxDist);
seq closestMatches(const std::string&, const seq&, size_t maxDist);

// ensure that a string has a given suffix (add it if it's not there)
std::string mustEndWith(const std::string&, const std::string&);

// get a set of filesystem objects matching a pattern
str::seq paths(const std::string& p);

}}

#endif


text:
goog.provide('audioCat.action.track.SnapToGridAction');

goog.require('audioCat.action.Action');
goog.require('audioCat.state.editMode.EditModeName');

/**
 * Toggles snapping to grid while moving sections.
 * @param {!audioCat.state.editMode.EditModeManager} editModeManager Manages the
 *     current edit mode.
 * @param {!audioCat.ui.message.MessageManager} messageManager Issues requests
 *     to display messages to the user.
 * @constructor
 * @extends {audioCat.action.Action}
 */
audioCat.action.track.SnapToGridAction = function(
    editModeManager,
    messageManager) {
  goog.base(this);

  /**
   * @private {!audioCat.state.editMode.EditModeManager}
   */
  this.editModeManager_ = editModeManager;

  /**
   * @private {!audioCat.ui.message.MessageManager}
   */
  this.messageManager_ = messageManager;
};
goog.inherits(audioCat.action.track.SnapToGridAction, audioCat.action.Action);

/** @override */
audioCat.action.track.SnapToGridAction.prototype.doAction = function() {
  var mode = /** @type {!audioCat.state.editMode.SelectEditMode} */(
      this.editModeManager_.getEditModeByName(
          audioCat.state.editMode.EditModeName.SELECT));
  var newSnapToGridState = !mode.getSnapToGridState();
  mode.setSnapToGridState(newSnapToGridState);
  this.messageManager_.issueMessage(newSnapToGridState ?
      'Now, sections will snap to grid upon move.' :
      'Snap to grid turned off.');
};


text:
package jgf_mpj_benchmarks.section1;

import jgf_mpj_benchmarks.jgfutil.*;
//import jgfutil.*;
import mpi.*;

public class JGFBarrierBench implements JGFSection1{

  public  static  int nprocess;
  public  static  int rank;

  private static final int INITSIZE = 1;
  private static final int MAXSIZE = 1000000;
  private static final double TARGETTIME = 10.0;

  public JGFBarrierBench(int rank, int nprocess) {
	this.rank = rank;
        this.nprocess=nprocess;
  }

  public void JGFrun() throws MPIException {

    int size;
    double [] time = new double[1];

/* Create the timer */
      if(rank==0){
        JGFInstrumentor.addTimer("Section1:Barrier", "barriers");
      }

      time[0] = 0.0;
      size=INITSIZE;

      MPI.COMM_WORLD.Barrier();

/* Start the timer */
      while (time[0] < TARGETTIME && size < MAXSIZE){
        if(rank==0){
          JGFInstrumentor.resetTimer("Section1:Barrier");
          JGFInstrumentor.startTimer("Section1:Barrier");
        }

/* Carryout the barrier operation */
        for (int k=0; k<size; k++){
          MPI.COMM_WORLD.Barrier();
        }

/* Stop the timer */
        if(rank==0){
          JGFInstrumentor.stopTimer("Section1:Barrier");
          time[0] = JGFInstrumentor.readTimer("Section1:Barrier");
          JGFInstrumentor.addOpsToTimer("Section1:Barrier",(double) size);
        }

/* Broadcast time to the other processes */
        MPI.COMM_WORLD.Barrier();
        MPI.COMM_WORLD.Bcast(time,0,1,MPI.DOUBLE,0);
        size *=2;
      }

/* Print the timing information */
        if(rank==0){
          JGFInstrumentor.printperfTimer("Section1:Barrier");
        }

  }

  public static void main(String[] argv) throws MPIException{
  }

  public JGFBarrierBench(String[] argv) throws Exception {

/* Initialise MPI */
     MPI.Init(argv);
     rank = MPI.COMM_WORLD.Rank();
     nprocess = MPI.COMM_WORLD.Size();

     if(rank==0){
     JGFInstrumentor.printHeader(1,0,nprocess);
     }
     JGFBarrierBench ba = new JGFBarrierBench(rank, nprocess);
     ba.JGFrun();

/* Finalise MPI */
     MPI.Finalize();

  }

}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 19.1.2.1
description: Invoked with a source which does not have a descriptor for an own property
info: >
    [...]
    5. For each element nextSource of sources, in ascending index order,
       [...]
       c. Repeat for each element nextKey of keys in List order,
          i. Let desc be from.[[GetOwnProperty]](nextKey).
          ii. ReturnIfAbrupt(desc).
          iii. if desc is not undefined and desc.[[Enumerable]] is true, then
features: [Proxy]
---*/

var callCount = 0;
var target = {};
var result;
var source = new Proxy({}, {
  ownKeys: function() {
    callCount += 1;
    return ['missing'];
  }
});

result = Object.assign(target, source);

assert.sameValue(callCount, 1, 'Proxy trap was invoked exactly once');
assert.sameValue(
  Object.hasOwnProperty.call(target, 'missing'),
  false,
  'An own property was not created for a property without a property descriptor'
);
assert.sameValue(result, target);


text:
using System;
using System.Linq;
using Faithlife.Build;
using static Faithlife.Build.BuildUtility;
using static Faithlife.Build.DotNetRunner;

return BuildRunner.Execute(args, build =>
{
	var gitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? "");

	var dotNetBuildSettings = new DotNetBuildSettings
	{
		NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
		PackageSettings = new DotNetPackageSettings
		{
			GitLogin = gitLogin,
			PushTagOnPublish = x => $"v{x.Version}",
		},
	};

	build.AddDotNetTargets(dotNetBuildSettings);

	build.Target("generate-docs")
		.Describe("Generates documentation")
		.DependsOn("build")
		.Does(() => GenerateDocs(verify: false));

	build.Target("verify-docs")
		.Describe("Verifies generated documentation")
		.DependsOn("build")
		.Does(() => GenerateDocs(verify: true));

	build.Target("test")
		.DependsOn("verify-docs");

	void GenerateDocs(bool verify)
	{
		var configuration = dotNetBuildSettings.GetConfiguration();
		var projects = new[]
		{
			("XmlDocMarkdown.Core", "../src/XmlDocMarkdown.Core"),
			("ExampleAssembly", "../tests/ExampleAssembly"),
		};
		var xmlDocGenPath = FindFiles($"tools/XmlDocGen/bin/{configuration}/net*/XmlDocGen.dll").First();
		foreach (var (assembly, sourcePath) in projects)
			RunDotNet(xmlDocGenPath, assembly, "docs", verify ? "--verify" : null, "--source", sourcePath, "--newline", "lf", "--clean");
	}
});


text:
using Foundation;
using System;
using System.CodeDom.Compiler;

namespace HelloWorld.iOS.Views
{
    [Register ("LoginView")]
    partial class LoginView
    {
        [Outlet]
        UIKit.UIButton LoginButton { get; set; }

        [Outlet]
        UIKit.UITextField PasswordTextField { get; set; }

        [Outlet]
        UIKit.UITextField UserNameTextField { get; set; }

        void ReleaseDesignerOutlets ()
        {
            if (LoginButton != null) {
                LoginButton.Dispose ();
                LoginButton = null;
            }

            if (PasswordTextField != null) {
                PasswordTextField.Dispose ();
                PasswordTextField = null;
            }

            if (UserNameTextField != null) {
                UserNameTextField.Dispose ();
                UserNameTextField = null;
            }
        }
    }
}


text:
package com.github.gtache.lsp.settings;

import com.github.gtache.lsp.PluginMain;
import com.github.gtache.lsp.client.languageserver.serverdefinition.UserConfigurableServerDefinition;
import com.github.gtache.lsp.client.languageserver.serverdefinition.UserConfigurableServerDefinition$;
import com.github.gtache.lsp.requests.Timeout;
import com.github.gtache.lsp.requests.Timeouts;
import com.github.gtache.lsp.utils.ApplicationUtils$;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

@State(name = "LSPState", storages = @Storage(file = "LSPState.xml"))

/**
 * Class representing the state of the LSP settings
 */
public final class LSPState implements PersistentStateComponent<LSPState> {

    private static final Logger LOG = Logger.getInstance(LSPState.class);

    //Must be public to be saved
    public boolean logServersOutput;
    public boolean alwaysSendRequests;
    public Map<String, String[]> extToServ;
    public Map<Timeouts, Integer> timeouts;
    public List<String> coursierResolvers;
    public Map<String[], String[]> forcedAssociations;

    public LSPState() {
        alwaysSendRequests = false;
        extToServ = new LinkedHashMap<>(10);
        timeouts = new EnumMap<>(Timeouts.class);
        coursierResolvers = new ArrayList<>(5);
        forcedAssociations = new HashMap<>(10);
    }

    @Nullable
    public static LSPState getInstance() {
        try {
            return ServiceManager.getService(LSPState.class);
        } catch (final Exception e) {
            LOG.warn("Couldn't load LSPState : " + e);
            ApplicationUtils$.MODULE$.invokeLater(() -> Messages.showErrorDialog("Couldn't load LSP settings, you will need to reconfigure them.", "LSP plugin"));
            return null;
        }
    }

    public List<String> getCoursierResolvers() {
        return coursierResolvers;
    }

    public void setCoursierResolvers(final Collection<String> coursierResolvers) {
        this.coursierResolvers = new ArrayList<>(coursierResolvers);
    }

    public Map<String, UserConfigurableServerDefinition> getExtToServ() {
        return UserConfigurableServerDefinition$.MODULE$.fromArrayMap(extToServ);
    }

    public void setExtToServ(final Map<String, UserConfigurableServerDefinition> extToServ) {
        this.extToServ = UserConfigurableServerDefinition$.MODULE$.toArrayMap(extToServ);
    }

    public boolean isAlwaysSendRequests() {
        return alwaysSendRequests;
    }

    public void setAlwaysSendRequests(final boolean b) {
        this.alwaysSendRequests = b;
    }

    public boolean isLoggingServersOutput() {
        return logServersOutput;
    }

    public void setLogServersOutput(final boolean b) {
        this.logServersOutput = b;
    }

    public Map<Timeouts, Integer> getTimeouts() {
        return timeouts;
    }

    public void setTimeouts(final Map<Timeouts, Integer> timeouts) {
        this.timeouts = new EnumMap<>(timeouts);
    }

    public Map<String[], String[]> getForcedAssociations() {
        return forcedAssociations;
    }

    public void setForcedAssociations(final Map<String[], String[]> forcedAssociations) {
        this.forcedAssociations = new HashMap<>(forcedAssociations);
    }

    @Override
    public int hashCode() {
        return Boolean.hashCode(logServersOutput) +
                17 * Boolean.hashCode(alwaysSendRequests) +
                3 * extToServ.hashCode() +
                7 * timeouts.hashCode() +
                11 * coursierResolvers.hashCode() +
                13 * forcedAssociations.hashCode();
    }

    @Override
    public boolean equals(final Object that) {
        if (that instanceof LSPState) {
            final LSPState thatS = (LSPState) that;
            return logServersOutput == thatS.logServersOutput &&
                    alwaysSendRequests == thatS.alwaysSendRequests &&
                    extToServ.equals(thatS.extToServ) &&
                    timeouts.equals(thatS.timeouts) &&
                    coursierResolvers.equals(thatS.coursierResolvers) &&
                    forcedAssociations.equals(thatS.forcedAssociations);
        }
        return false;
    }

    @Override
    public LSPState getState() {
        return this;
    }

    @Override
    public void loadState(@NotNull final LSPState lspState) {
        try {
            XmlSerializerUtil.copyBean(lspState, this);
            LOG.info("LSP State loaded");
            if (extToServ != null) {
                PluginMain.setExtToServerDefinition(UserConfigurableServerDefinition$.MODULE$.fromArrayMap(extToServ));
            }
            if (timeouts != null && !timeouts.isEmpty()) {
                Timeout.setTimeouts(timeouts);
            }
            if (forcedAssociations != null) {
                PluginMain.setForcedAssociations(forcedAssociations);
            }
        } catch (final Exception e) {
            LOG.warn("Couldn't load LSPState : " + e);
            ApplicationUtils$.MODULE$.invokeLater(() -> Messages.showErrorDialog("Couldn't load LSP settings, you will need to reconfigure them.", "LSP plugin"));
        }
    }

}


text:
package elasticsearchservice

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestElasticsearch(t *testing.T) {
	assert := assert.New(t)

	svc := New(nil)
	assert.Nil(svc)

	config := NewConfig()
	svc = New(config)
	assert.NotNil(svc)
}


text:
rest-router
===========

PHP REST Router


text:
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
moment = require('moment');
today = moment("2015-11-9 9:02 AM", "YYYY-MM-DD hh:mm A"); //global instance of right now in moment
var config = require('./config.js');

//Set-up database
var mongoose = require('mongoose');
mongoose.connect(config.database, function(err) {
    if (err) {
        console.log('Database connection error', err);
    } else {
        console.log('Database connection successful');
    }
});

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// ROUTES FOR OUR API
// =============================================================================
var router = require('./routes/schedule.js'); // get an instance of the express Router
var router2 = express.Router();

router2.get('/', function(req, res) {
    res.json({
        message: "API v2 OK"
    });
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api OR /apiv2 (depending on which router is used)
app.use('/schedule', router);
app.use('/apiv2', router2);

module.exports = app;


text:
import { Coin } from '../../../cosmos/base/v1beta1/coin';
import { Writer, Reader } from 'protobufjs/minimal';
export declare const protobufPackage = "cosmos.bank.v1beta1";
/** Params defines the parameters for the bank module. */
export interface Params {
    sendEnabled: SendEnabled[];
    defaultSendEnabled: boolean;
}
/**
 * SendEnabled maps coin denom to a send_enabled status (whether a denom is
 * sendable).
 */
export interface SendEnabled {
    denom: string;
    enabled: boolean;
}
/** Input models transaction input. */
export interface Input {
    address: string;
    coins: Coin[];
}
/** Output models transaction outputs. */
export interface Output {
    address: string;
    coins: Coin[];
}
/**
 * Supply represents a struct that passively keeps track of the total supply
 * amounts in the network.
 * This message is deprecated now that supply is indexed by denom.
 *
 * @deprecated
 */
export interface Supply {
    total: Coin[];
}
/**
 * DenomUnit represents a struct that describes a given
 * denomination unit of the basic token.
 */
export interface DenomUnit {
    /** denom represents the string name of the given denom unit (e.g uatom). */
    denom: string;
    /**
     * exponent represents power of 10 exponent that one must
     * raise the base_denom to in order to equal the given DenomUnit's denom
     * 1 denom = 1^exponent base_denom
     * (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with
     * exponent = 6, thus: 1 atom = 10^6 uatom).
     */
    exponent: number;
    /** aliases is a list of string aliases for the given denom */
    aliases: string[];
}
/**
 * Metadata represents a struct that describes
 * a basic token.
 */
export interface Metadata {
    description: string;
    /** denom_units represents the list of DenomUnit's for a given coin */
    denomUnits: DenomUnit[];
    /** base represents the base denom (should be the DenomUnit with exponent = 0). */
    base: string;
    /**
     * display indicates the suggested denom that should be
     * displayed in clients.
     */
    display: string;
    /** name defines the name of the token (eg: Cosmos Atom) */
    name: string;
    /**
     * symbol is the token symbol usually shown on exchanges (eg: ATOM). This can
     * be the same as the display.
     */
    symbol: string;
}
export declare const Params: {
    encode(message: Params, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): Params;
    fromJSON(object: any): Params;
    toJSON(message: Params): unknown;
    fromPartial(object: DeepPartial<Params>): Params;
};
export declare const SendEnabled: {
    encode(message: SendEnabled, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): SendEnabled;
    fromJSON(object: any): SendEnabled;
    toJSON(message: SendEnabled): unknown;
    fromPartial(object: DeepPartial<SendEnabled>): SendEnabled;
};
export declare const Input: {
    encode(message: Input, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): Input;
    fromJSON(object: any): Input;
    toJSON(message: Input): unknown;
    fromPartial(object: DeepPartial<Input>): Input;
};
export declare const Output: {
    encode(message: Output, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): Output;
    fromJSON(object: any): Output;
    toJSON(message: Output): unknown;
    fromPartial(object: DeepPartial<Output>): Output;
};
export declare const Supply: {
    encode(message: Supply, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): Supply;
    fromJSON(object: any): Supply;
    toJSON(message: Supply): unknown;
    fromPartial(object: DeepPartial<Supply>): Supply;
};
export declare const DenomUnit: {
    encode(message: DenomUnit, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): DenomUnit;
    fromJSON(object: any): DenomUnit;
    toJSON(message: DenomUnit): unknown;
    fromPartial(object: DeepPartial<DenomUnit>): DenomUnit;
};
export declare const Metadata: {
    encode(message: Metadata, writer?: Writer): Writer;
    decode(input: Reader | Uint8Array, length?: number): Metadata;
    fromJSON(object: any): Metadata;
    toJSON(message: Metadata): unknown;
    fromPartial(object: DeepPartial<Metadata>): Metadata;
};
declare type Builtin = Date | Function | Uint8Array | string | number | undefined;
export declare type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? {
    [K in keyof T]?: DeepPartial<T[K]>;
} : Partial<T>;
export {};


text:
<# VE_XD7Role\VE_XD7Role.Resources.psd1 #>
ConvertFrom-StringData @'
    XenDesktopSDKNotFoundError       = Citrix XenDesktop 7.x Powershell SDK/Snap-in was not found.
    UserNameNotFullyQualifiedWarning = The Citrix XenDesktop 7.x administrator reference '{0}' is not fully qualified. Specify the administrator's Domain\\UserName or Domain\\GroupName to avoid any ambiguity.
    MissingRoleMember                = Citrix XenDesktop 7.x account/group '{0}' is missing and will be added.
    SurplusRoleMember                = Citrix XenDesktop 7.x account/group '{0}' is surplus and will be removed.
    AddingRoleMember                 = Adding Citrix XenDesktop 7.x Administrator '{0}' to role '{1}'.
    RemovingRoleMember               = Removing Citrix XenDesktop 7.x Administrator '{0}' from role '{1}'.
    ResourceInDesiredState           = Citrix XenDesktop 7.x Role '{0}' is in the desired state.
    ResourceNotInDesiredState        = Citrix XenDesktop 7.x Role '{0}' is NOT in the desired state.
    InvokingScriptBlockWithParams    = Invoking script block with parameters: '{0}'.
'@


text:
{% extends "admin/base_site.html" %}

{% load staticfiles admin_list i18n future %}

{% block extrastyle %}
    <link rel="stylesheet" type="text/css" href="{% static "grappelli/css/changelist.css" %}" />
    {% if not actions_on_top and not actions_on_bottom %}

    {% endif %}

{% endblock %}

{% block javascripts %}
    {% url "admin:jsi18n" as jsi18nurl %}

    {{ block.super }}
    {{ media }}

    {% if is_popup %}

    {% endif %}
    {% if action_form %}

    {% endif %}
{% endblock %}

{% block content %}

        {% block object-tools %}
            {% if has_add_permission %}

                    {% block object-tools-items %}

                            {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}

                    {% endblock %}

            {% endif %}
        {% endblock %}

        {% if cl.formset.errors %}

            {% blocktrans count cl.formset.errors|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

{% for error in cl.formset.non_field_errors %}
{{ error }}
{% endfor %}

        {% endif %}

                <form action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}

                {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}

                {% if cl.formset %}
                    {{ cl.formset.management_form }}
                {% endif %}

                    {% block result_list %}
                        {% if action_form and actions_on_top and cl.full_result_count and cl.result_count %}{% admin_actions %}{% endif %}
                        {% result_list cl %}
                        {% if action_form and actions_on_bottom and cl.full_result_count and cl.result_count %}{% admin_actions %}{% endif %}
                    {% endblock %}
                    {% block pagination %}{% pagination cl %}{% endblock %}

                {% if cl.formset and cl.result_count %}

                        <input type="submit" name="_save" class="default" value="{% trans 'Save' %}"/>

                {% endif %}
                </form>

            {% block filters %}
                {% if cl.has_filters or cl.search_fields or cl.date_hierarchy %}

                        {% ifnotequal cl.result_count cl.full_result_count %}

{% trans 'Results' %}

{% blocktrans with cl.result_count as counter %}{{ counter }} found{% endblocktrans %}

                                {% blocktrans with cl.full_result_count as full_result_count %}{{ full_result_count }} total{% endblocktrans %}

                        {% endifnotequal %}

                        {% block search %}{% search_form cl %}{% endblock %}

                        {% block date_hierarchy %}{% date_hierarchy cl %}{% endblock %}

                        {% if cl.has_filters %}

{% trans 'Filter' %}

                            {% for spec in cl.filter_specs %}{% admin_list_filter cl spec %}{% endfor %}

                        {% endif %}

                {% endif %}
            {% endblock %}

{% endblock %}


text:
module OrientdbBinary
  class Database
    class Cluster
      attr_reader :name, :location, :database, :segment_name, :segment_id, :cluster_type, :cluster_id

      TYPES = {
        local: "PHYSICAL",
        plocal: "PHYSICAL",
        memory: "MEMORY"
      }

      # Initialize connection to clusters
      #
      # @since 1.0
      def self.initialize_with(database)
        Cluster.new(database)
      end

      # Initialize connection to clusters
      #
      # @since 1.0
      def initialize(database)
        @database = database
      end

      # Lists all clusters in database
      #
      # @since 1.0
      def list
        database.clusters
      end

      # Search for cluster by keyword
      #
      # @param [Hash] key => value Possible values of key: :name, :cluster_id
      #
      # @return Cluster
      #
      # @since 1.0
      def find(arg)
        key = arg.keys.first
        val = arg[key]

        clust = list.select {|cluster| cluster["#{key}".to_sym] == val}.first

        if clust
          _clust = {}

          cluster = Cluster.new self.database
          clust.each_pair { |k,v| _clust[k] = v }

          return cluster.new _clust
        end
        nil
      end

      def count(**args)
        args[:cluster_ids] = args[:cluster_ids] ? args[:cluster_ids] : convert_names_to_ids(args)

        args[:cluster_count] = args[:cluster_ids].length
        database.connection.protocol::DataclusterCount.new(params(args)).process(database.connection)[:records_count]
      end

      def data_range
        args[:cluster_id] = convert_name_to_id(args[:cluster_name], args[:cluster_id])

        database.connection.protocol::DataclusterDatarange.new(params(args)).process(database.connection)
      end

      # Initialize cluster params
      #
      # @param [String, Symbol] name
      #
      # @since 1.0
      def new(name:, segment_name: nil, segment_id: nil, location: nil, cluster_type: nil, cluster_id: -1)
        @name = name.to_s
        @location = location || @name + "_cluster"
        @cluster_type = cluster_type || TYPES[database.storage.to_sym]
        @cluster_id = cluster_id
        @segment = segment_name
        @segment_id = segment_id

        self
      end

      # Creates data cluster with provided data
      #
      # @return [Integer] segment id
      #
      # @since 1.0
      def create!
        unless segment_id
          database.connection.protocol::DataclusterAdd.new(params).process(database.connection)
        end
      end

      # Removes cluster by its name or id
      #
      # @return [True, False] True if succeed, false if not
      #
      # @since 1.0
      def drop!
        args[:cluster_id] = convert_name_to_id(args[:cluster_name], args[:cluster_id])
        database.connection.protocol::DataclusterDrop.new(params(args)).process(database.connection)
      end

      private

      # Creates params from data
      #
      # @api private
      #
      # @since 1.0
      def params(args)
        args.merge({ session: database.connection.session, name: name, location: location, cluster_type: cluster_type,  segment_name: segment_name, cluster_id: cluster_id })
      end

      def convert_name_to_id(name, id)
        if name and not id
          if (_cluster = find(cluster_name: name))
            id = cluster[:cluster_id]
          end
        end
        id
      end

      def convert_names_to_ids(args)
        ids = []
        unless args[:cluster_ids]
          ids = args[:cluster_names].map do |name|
            convert_name_to_id(name, nil)
          end
        end
        ids
      end
    end
  end
end


text:
import perdido from 'perdido'; // eslint-disable-line import/no-unresolved
import {jssSetup, jssReset, testMethod} from './helpers';

afterEach(jssReset);
beforeEach(jssSetup);

/* eslint-disable max-len */
describe('Perdido Align Flex', () => {
  beforeEach(() => {
    perdido.gutter = '30px';
    perdido.flex = false;
    perdido.cycle = -1;
    perdido.offsetDir = 'row';
  });

  testMethod('can support resetting alignment', perdido.align('reset', {flex: true}), [
    'a {\n  display: initial;\n}',
    'a > * {\n  justify-content: inherit;\n  align-items: inherit;\n}',
  ]);

  testMethod('can support aligning horizontally', perdido.align('horizontal', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: inherit;\n}',
  ]);

  testMethod('can support aligning verticaly', perdido.align('vertical', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: inherit;\n  align-items: center;\n}',
  ]);

  testMethod('can support aligning top left', perdido.align('top-left', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-start;\n  align-items: flex-start;\n}'
  ]);

  testMethod('can support aligning top center', perdido.align('top-center', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: flex-start;\n}'
  ]);

  testMethod('can support aligning top', perdido.align('top', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: flex-start;\n}'
  ]);

  testMethod('can support aligning top right', perdido.align('top-right', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-end;\n  align-items: flex-start;\n}'
  ]);

  testMethod('can support aligning middle left', perdido.align('middle-left', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-start;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning left', perdido.align('left', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-start;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning middle center', perdido.align('middle-center', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning center', perdido.align('center', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning middle right', perdido.align('middle-right', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-end;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning right', perdido.align('right', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-end;\n  align-items: center;\n}'
  ]);

  testMethod('can support aligning bottom left', perdido.align('bottom-left', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-start;\n  align-items: flex-end;\n}'
  ]);

  testMethod('can support aligning bottom center', perdido.align('bottom-center', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: flex-end;\n}'
  ]);

  testMethod('can support aligning bottom', perdido.align('bottom', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: center;\n  align-items: flex-end;\n}'
  ]);

  testMethod('can support aligning bottom right', perdido.align('bottom-right', {flex: true}), [
    'a {\n  display: flex;\n}',
    'a > * {\n  justify-content: flex-end;\n  align-items: flex-end;\n}'
  ]);
});
/* eslint-enable max-len */


text:
import * as React from 'react';
import styles from './ScriptEditor.module.scss';
import { IScriptEditorProps } from './IScriptEditorProps';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { loadStyles } from '@microsoft/load-themed-styles';
require('./overrides.css');

export default class ScriptEditor extends React.Component<IScriptEditorProps, any> {
    constructor() {
        super();

        this._showDialog = this._showDialog.bind(this);
        this._closeDialog = this._closeDialog.bind(this);
        this._cancelDialog = this._cancelDialog.bind(this);
        this._onScriptEditorTextChanged = this._onScriptEditorTextChanged.bind(this);

        const uiFabricCSS: string = `
    .pnp-bgColor-themeDark, .pnp-bgColor-themeDark--hover:hover {
      background-color: "[theme:themeDark, default:#005a9e]";
    }
    `;
        loadStyles(uiFabricCSS);
        this.state = {
            showDialog: false
        };
    }

    public componentDidMount(): void {
        this.setState({ script: this.props.script, loaded: this.props.script });
    }
    private _showDialog() {
        this.setState({ showDialog: true });
    }

    private _closeDialog() {
        this.setState({ showDialog: false });
        this.props.save(this.state.script);
    }

    private _cancelDialog() {
        this.props.save(this.state.loaded);
        this.setState({ showDialog: false, script: this.state.loaded });
    }

    private _onScriptEditorTextChanged(text: string) {
        this.setState({ script: text });
    }

    public render(): React.ReactElement<IScriptEditorProps> {
        const viewMode = ;

        return (

                        <div className={`ms-Grid-row pnp-bgColor-themeDark ms-fontColor-white ${styles.row}`}>

                                {this.props.title}

                                <DefaultButton description='Opens the snippet dialog' onClick={this._showDialog}>Edit snippet</DefaultButton>

                <Dialog
                    isOpen={this.state.showDialog}
                    type={DialogType.normal}
                    onDismiss={this._closeDialog}
                    title='Embed'
                    subText='Paste your script, markup or embed code below. Note that scripts will only run in view mode.'
                    isBlocking={true}
                    className={'ScriptPart'}
                >
                    <TextField multiline rows={15} onChanged={this._onScriptEditorTextChanged} value={this.state.script} />
                    <DialogFooter>
                        <PrimaryButton onClick={this._closeDialog}>Save</PrimaryButton>
                        <DefaultButton onClick={this._cancelDialog}>Cancel</DefaultButton>
                    </DialogFooter>
                    {viewMode}
                </Dialog>

);
    }
}


text:
/**
 * @file KeyPointsFilter_.cpp
 * @brief mex interface for KeyPointsFilter
 * @author Amro
 * @date 2015
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check the number of arguments
    nargchk(nrhs>=2 && nlhs<=1);

    // Argument vector
    vector<MxArray> rhs(prhs, prhs+nrhs);
    string method(rhs[0].toString());
    vector<KeyPoint> keypoints(rhs[1].toVector<KeyPoint>());

    // Operation switch
    if (method == "removeDuplicated") {
        nargchk(nrhs==2 && nlhs<=1);
        KeyPointsFilter::removeDuplicated(keypoints);
    }
    else if (method == "retainBest") {
        nargchk(nrhs==3 && nlhs<=1);
        int npoints = rhs[2].toInt();
        KeyPointsFilter::retainBest(keypoints, npoints);
    }
    else if (method == "runByImageBorder") {
        nargchk(nrhs==4 && nlhs<=1);
        Size imageSize(rhs[2].toSize());
        int borderSize = rhs[3].toInt();
        KeyPointsFilter::runByImageBorder(keypoints, imageSize, borderSize);
    }
    else if (method == "runByKeypointSize") {
        nargchk((nrhs==3 || nrhs==4) && nlhs<=1);
        float minSize = rhs[2].toFloat();
        float maxSize = (nrhs==4) ? rhs[3].toFloat() : FLT_MAX;
        KeyPointsFilter::runByKeypointSize(keypoints, minSize, maxSize);
    }
    else if (method == "runByPixelsMask") {
        nargchk(nrhs==3 && nlhs<=1);
        Mat mask(rhs[2].toMat(CV_8U));
        KeyPointsFilter::runByPixelsMask(keypoints, mask);
    }
    else
        mexErrMsgIdAndTxt("mexopencv:error",
            "Unrecognized operation %s", method.c_str());

    plhs[0] = MxArray(keypoints);
}


text:
"""
@file
@brief Helpers for pip.

.. versionadded:: 1.5
"""
try:
    from pip._internal.utils.compat import stdlib_pkgs
except ImportError:
    stdlib_pkgs = None

class Distribution:
    """
    Common interface for old and recent pip packages.

    .. versionadded:: 1.5
    """

    def __init__(self, dist):
        self.dist = dist

    def __getattr__(self, attr):
        if attr == 'key':
            if hasattr(self.__dict__['dist'], 'key'):
                return self.__dict__['dist'].key
            return self.__dict__['dist'].canonical_name
        if attr == 'dist':
            return self.__dict__['dist']
        if attr in {'_get_metadata', 'requires', 'PKG_INFO', 'project_name'}:
            if hasattr(self.__dict__['dist'], attr):
                return getattr(self.__dict__['dist'], attr)
            return getattr(self.__dict__['dist']._dist, attr)
        return getattr(self.__dict__['dist'], attr)

def get_installed_distributions(local_only=True, skip=stdlib_pkgs,
                                include_editables=True, editables_only=False,
                                user_only=False, use_cmd=False):
    """
    Directs call to function *get_installed_distributions* from :epkg:`pip`.

    Return a list of installed Distribution objects.

    :param local_only: if True (default), only return installations
        local to the current virtualenv, if in a virtualenv.
    :param skip: argument is an iterable of lower-case project names to
        ignore; defaults to ``pip.compat.stdlib_pkgs`` (if *skip* is None)
    :param editables: if False, don't report editables.
    :param editables_only: if True , only report editables.
    :param user_only: if True , only report installations in the user
        site directory.
    :param use_cmd: if True, use a different process (updated package list)
    :return: list of installed Distribution objects.

    .. versionadded:: 1.5
    """
    if use_cmd:
        raise NotImplementedError("use_cmd should be False")
    try:
        from pip._internal.metadata import get_default_environment
        return list(map(Distribution,
                        get_default_environment().iter_installed_distributions(
                            local_only=local_only, skip=skip,
                            include_editables=include_editables,
                            editables_only=editables_only,
                            user_only=user_only)))

    except ImportError:
        from pip._internal.utils.misc import get_installed_distributions as getd
        return list(map(Distribution, getd(
            local_only=local_only, skip=skip,
            include_editables=include_editables,
            editables_only=editables_only,
            user_only=user_only, use_cmd=use_cmd)))


text:
<?php

namespace CrudGenerator\Generators\Strategies;

/**
 * Base code generator, extends it and implement doGenerate method
 * to make you own Generator
 *
 * @author Stéphane Demonchaux
 */
interface StrategyInterface
{
    /**
     * @param  array       $datas
     * @param  string      $skeletonDir
     * @param  string      $pathTemplate
     * @param  string      $pathTo
     * @return string|null
     */
    public function generateFile(array $datas, $skeletonDir, $pathTemplate, $pathTo);
}