text:
"use strict";

class CartesianViewport {
    minX: number;
    maxX: number;
    minY: number;
    maxY: number;
    constructor();
    constructor(minX: number, maxX: number, minY: number, maxY: number);
    constructor() {
        if (arguments.length == 0) {
            this.minX = -10;
            this.maxX = 10;
            this.minY = -10;
            this.maxY = 10;
        }
        else if (arguments.length == 4) {
            this.minX = arguments[0];
            this.maxX = arguments[1];
            this.minY = arguments[2];
            this.maxY = arguments[3];
        }
        else throw 'Can\'t construct CartesianViewport with ' + arguments.length + ' arguments';
    }

    static fromJSON(str: string) {
        var obj = JSON.parse(str);
        return new CartesianViewport(obj.minX, obj.maxX, obj.minY, obj.maxY);
    }

    zoom(zoomAmt): void {
        this.minX *= zoomAmt;
        this.maxX *= zoomAmt;
        this.minY *= zoomAmt;
        this.maxY *= zoomAmt;
    }

    isValid(): boolean {
        return this.minX < this.maxX && this.minY < this.maxY;
    }
}

interface Point {
    x: number;
    y: number;
}

interface PlottedFunction {
    colour: string;
    expression: string;
}

var functions: PlottedFunction[] = [];
var cartesianBounds: CartesianViewport = new CartesianViewport();
var mouseX = -1;

// read cartesianBounds out of url if passed
(function () {
    var serialised = getURLParameter('cartesianBounds');
    if (serialised) {
        var temp = JSON.parse(serialised);
        cartesianBounds.minX = temp.minX;
        cartesianBounds.maxX = temp.maxX;
        cartesianBounds.minY = temp.minY;
        cartesianBounds.maxY = temp.maxY;
    }
});

// take an expression, with only 'x' as a variable and a list of values for 'x' and return a list of points
function expressionToPlotPoints(expression: string, xValues: number[]): Point[] {
    var parser = math.parser();
    parser.eval('f(x) = ' + expression);
    var func = parser.get('f');
    var plotPoints: Point[] = new Array(xValues.length);
    for (var i = 0; i < xValues.length; ++i)
        plotPoints[i] = { x: xValues[i], y: func(xValues[i]) };
    return plotPoints;
}

function expressionToPlotPoint(expression: string, xValue: number): Point {
    var parser = math.parser();
    var func = parser.eval('f(x) = ' + expression);
    return { x: xValue, y: func(xValue) };
}

function setPixel(imageData: ImageData, x: number, y: number, r: number, g: number, b: number): void {
    var index = (x + y * imageData.width) * 4;
    imageData.data[index + 0] = r;
    imageData.data[index + 1] = g;
    imageData.data[index + 2] = b;
    imageData.data[index + 3] = 255;
}

function drawAxes(ctx: CanvasRenderingContext2D): void {
    var cWidth = ctx.canvas.width;
    var cHeight = ctx.canvas.height;

    var viewportWidth = Math.abs(cartesianBounds.maxX - cartesianBounds.minX);
    var viewportHeight = Math.abs(cartesianBounds.maxY - cartesianBounds.minY);

    var xAxisPosition = Math.round(cHeight - ((0 - cartesianBounds.minY) / viewportHeight * cHeight));
    var yAxisPosition = Math.round((0 - cartesianBounds.minX) / viewportWidth * cWidth);

    ctx.beginPath();

    // draw x-axis
    ctx.moveTo(0, xAxisPosition + 0.5);
    ctx.lineTo(ctx.canvas.width, xAxisPosition + 0.5);
    ctx.lineTo(ctx.canvas.width - 4.5, xAxisPosition - 3.5);
    ctx.moveTo(ctx.canvas.width, xAxisPosition + 0.5);
    ctx.lineTo(ctx.canvas.width - 4.5, xAxisPosition + 4.5);

    // draw y-axis
    ctx.moveTo(yAxisPosition + 0.5, ctx.canvas.height);
    ctx.lineTo(yAxisPosition + 0.5, 0);
    ctx.lineTo(yAxisPosition - 3.5, 4.5);
    ctx.moveTo(yAxisPosition + 0.5, 0);
    ctx.lineTo(yAxisPosition + 4.5, 4.5);

    ctx.stroke();

    ctx.font = "12px sans-serif";
    ctx.fillText('x', cWidth - ctx.measureText('x').width - 6, xAxisPosition + 10);
    ctx.fillText('f(x)', yAxisPosition - ctx.measureText('f(x)').width - 6, 10);
}

function plotFunctions(viewport: CartesianViewport, cxt: CanvasRenderingContext2D): void {
    var imageData = cxt.getImageData(0, 0, cxt.canvas.width, cxt.canvas.height);
    var cWidth = imageData.width;
    var cHeight = imageData.height;

    var viewportWidth = Math.abs(viewport.maxX - viewport.minX);
    var viewportHeight = Math.abs(viewport.maxY - viewport.minY);

    // make a list of x-values in the cartesian system that fit in the ImageData
    var xValues = [];
    for (var i = 0; i < cWidth + 1; ++i) {
        xValues.push((viewportWidth / cWidth * i) + viewport.minX);
    }

    for (var fIndex = 0; fIndex < functions.length; ++fIndex) {
        // calculate cartesian points to plot then turn them into pixels in the ImageData to set
        try {
            var cartpoints = expressionToPlotPoints(functions[fIndex].expression, xValues);
        } catch (e) {
            continue;   // on badly formed expression skip to next
        }
        //console.log(cartpoints);
        var points = [];
        for (var i = 0; i < cartpoints.length; ++i) {
            points[i] = cartesianPointToCanvasPoint(viewport, cWidth, cHeight, cartpoints[i]);
        }
        //console.log(points);

        // get components of hex colour
        var colourAsNum = parseInt(functions[fIndex].colour.substring(1), 16);
        var r = colourAsNum >> 16;
        var g = (colourAsNum >> 8) & 0xff;
        var b = colourAsNum & 0xff;

        for (var i = 1; i < points.length; ++i) {
            setPixel(imageData, points[i].x, points[i].y, r, g, b);
        }

        cxt.putImageData(imageData, 0, 0);
    }
}

function drawVerticalIntersectionLine(cxt: CanvasRenderingContext2D): void {
    var cHeight = cxt.canvas.height;
    var cWidth = cxt.canvas.width;
    if (mouseX >= 0) {
        cxt.save();
        // print dashed vertial line at mouse position
        cxt.beginPath();
        cxt.setLineDash([10, 5]);
        cxt.moveTo(mouseX + 0.5, 0);
        cxt.lineTo(mouseX + 0.5, cHeight);
        cxt.strokeStyle = '#7f7f7f';
        cxt.stroke();

        // print all x and f(x) values at the line next to the line
        var viewportWidth = Math.abs(cartesianBounds.maxX - cartesianBounds.minX);
        var xValue = mouseX / cWidth * viewportWidth + cartesianBounds.minX; // cartesian x value for mouseX

        var lineHeight = 15;
        cxt.font = 14 + "px sans-serif"

        var printList: {
            string: string;
            colour: string;
        }[] = [{ string: "x = " + xValue.toPrecision(4), colour: '#000' }];
        var width = Math.ceil(cxt.measureText(printList[printList.length - 1].string).width);
        for (var i = 0; i < functions.length; ++i) {
            try {
                var p: Point = expressionToPlotPoint(functions[i].expression, xValue);
                printList.push({ string: "f(x) = " + p.y.toPrecision(4), colour: functions[i].colour });
                width = Math.max(width, Math.ceil(cxt.measureText(printList[printList.length - 1].string).width));
            } catch (e) {
                continue;
            }
        }
        //console.log(printList);

        var leftOfLine = mouseX >= width + 2;    // if true print strings on left side of line, else right side
        var currectYInCanvas = 14;
        for (var i = 0; i < printList.length; ++i) {
            cxt.fillStyle = printList[i].colour;
            cxt.fillText(printList[i].string, leftOfLine ? (mouseX - width - 2) : mouseX + 2, currectYInCanvas);
            currectYInCanvas += lineHeight;
        }

        cxt.restore();
    }
}

// Convert a point in the cartesian system to a pixel location to plot
function cartesianPointToCanvasPoint(viewport: CartesianViewport, cWidth: number, cHeight: number, cartpoint: Point): Point {
    var viewportWidth = Math.abs(viewport.maxX - viewport.minX);
    var viewportHeight = Math.abs(viewport.maxY - viewport.minY);

    var p: Point = {
        x: Math.round((cartpoint.x - viewport.minX) / viewportWidth * cWidth),
        y: cHeight - Math.round(((cartpoint.y - viewport.minY) / viewportHeight * cHeight))
    };
    if (p.x >= cWidth)
        p.x = NaN;
    return p;
}

function canvasPointToCartesian(viewport: CartesianViewport, cWidth: number, cHeight: number, canvaspoint: Point): Point {
    var viewportWidth = Math.abs(viewport.maxX - viewport.minX);
    var viewportHeight = Math.abs(viewport.maxY - viewport.minY);
    // TODO: finish
    return {
        x: canvaspoint.x / cWidth * viewportWidth + cartesianBounds.minX,
        y: 0
    };
}

function paint(): void {
    if (!cartesianBounds.isValid())
        return;
    var cxt = (<HTMLCanvasElement> document.getElementById('plotCanvas')).getContext('2d');
    cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height);

    drawAxes(cxt);
    plotFunctions(cartesianBounds, cxt);
    drawVerticalIntersectionLine(cxt);
}

// Called when the inputs are changed to redraw the graphs and save input state to url
function update(): void {
    paint();
    // TODO: update url
}

// Ajdust the canvas size to take up optimal space. If the size is changed the graphs will be redrawn.
function fixCanvasSize(): void {
    var newSize = Math.max(Math.min(document.getElementById('plotCanvasHolder').clientWidth, window.innerHeight - $('#page-header>*').outerHeight(true) - $('#controls').outerHeight(true)) & 0xfffffff0, 224);
    var canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('plotCanvas');

    if (canvas.width != newSize) {
        canvas.width = newSize;
        canvas.height = newSize;

        update();
    }
}

$(document).ready(function () {

    var checkMinMax = function () {
        var temp = new CartesianViewport(
            parseFloat((<HTMLInputElement> document.getElementById('minX')).value),
            parseFloat((<HTMLInputElement> document.getElementById('maxX')).value),
            parseFloat((<HTMLInputElement> document.getElementById('minY')).value),
            parseFloat((<HTMLInputElement> document.getElementById('maxY')).value));
        document.getElementById('minMaxErrorMessage').hidden = temp.isValid();
    };
    var updateCartesianBoundsModel = function () {
        cartesianBounds[this.getAttribute('id')] = parseFloat(this.value);
        update();
    };
    $("#minX, #maxX, #minY, #maxY").on('input', checkMinMax);
    $("#minX, #maxX, #minY, #maxY").on('input', updateCartesianBoundsModel);

    updateCartesianBoundsView();

    fixCanvasSize();

    (<HTMLCanvasElement> document.getElementById('plotCanvas')).onwheel = function (event) {
        var wheel = event.deltaY / 120;//n or -n
        console.log(event.deltaMode);
        //console.log(wheel);

        var zoom = Math.pow(2, wheel);
        console.log(zoom);
        //console.log(zoom);

        cartesianBounds.zoom(zoom);
        updateCartesianBoundsView();
        update();

        return false;
    };

    (<HTMLCanvasElement> document.getElementById('plotCanvas')).addEventListener("mousemove", mouseMoveMouseX, false);
    (<HTMLCanvasElement> document.getElementById('plotCanvas')).addEventListener("mouseleave", mouseClearMouseX, false);

    function mouseMoveMouseX(event) {
        mouseX = event.clientX - document.getElementById('plotCanvas').getBoundingClientRect().left;
        paint();
    }

    function mouseClearMouseX(event) {
        mouseX = -1;
        paint();
    }
});
$(window).resize(fixCanvasSize);

function updateCartesianBoundsView(): void {
    (<HTMLInputElement> document.getElementById('minX')).valueAsNumber = cartesianBounds.minX;
    (<HTMLInputElement> document.getElementById('maxX')).valueAsNumber = cartesianBounds.maxX;
    (<HTMLInputElement> document.getElementById('minY')).valueAsNumber = cartesianBounds.minY;
    (<HTMLInputElement> document.getElementById('maxY')).valueAsNumber = cartesianBounds.maxY;
}

function addFunction(expressionStr: string = ""): void {
    if (typeof addFunction.counter == 'undefined')
        addFunction.counter = 1;
    else
        addFunction.counter = (addFunction.counter + 1) % 7;
    var temp = addFunction.counter;
    var colour = '#' + ('00000' + (((temp & 4) >> 2) * 0xbf0000 + ((temp & 2) >> 1) * 0xbf00 + (temp & 1) * 0xbf).toString(16)).slice(-6);

    // add new empty PlottedFunction to model
    functions.push({ colour: colour, expression: expressionStr });

    // update view
    var template = $('#function-template').html();
    var info = Mustache.to_html(template, functions[functions.length - 1]);
    $('#functionsInput').append(info);

    fixCanvasSize();
    update();
}

function updateFunctionExpression(singleFunctionView: HTMLDivElement): void {
    var $singleFunctionView = $(singleFunctionView);
    var indexInFunctions = $singleFunctionView.prevAll('div').length;   // number of previous siblings is equal to index in functions array
    functions[indexInFunctions].expression = (<HTMLInputElement> singleFunctionView.querySelector('.functionExpression')).value;
    update();
}

function updateFunctionColour(singleFunctionView: HTMLDivElement): void {
    var $singleFunctionView = $(singleFunctionView);
    var indexInFunctions = $singleFunctionView.prevAll('div').length;   // number of previous siblings is equal to index in functions array
    functions[indexInFunctions].colour = (<HTMLInputElement> singleFunctionView.querySelector('.functionColour')).value;
    update();
}

function deleteFunction(singleFunctionView: HTMLDivElement): void {
    var $singleFunctionView = $(singleFunctionView);
    var indexInFunctions = $singleFunctionView.prevAll('div').length;   // number of previous siblings is equal to index in functions array
    $singleFunctionView.remove();
    functions.splice(indexInFunctions, 1);
    fixCanvasSize();
    update();
}

// originally from http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html, edited
function getURLParameter(sParam: string) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return decodeURIComponent(sParameterName[1]);
        }
    }
}


text:
namespace Microsoft.Azure.Management.ResourceManager
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  internal static partial class SdkInfo
  {
      public static IEnumerable<Tuple<string, string, string>> ApiInfo_SubscriptionClient
      {
          get
          {
              return new Tuple<string, string, string>[]
              {
                new Tuple<string, string, string>("Resources", "Operations", "2020-01-01"),
                new Tuple<string, string, string>("SubscriptionClient", "Subscriptions", "2020-01-01"),
                new Tuple<string, string, string>("SubscriptionClient", "Tenants", "2020-01-01"),
              }.AsEnumerable();
          }
      }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package core

import utils.Randomize

/**
 * Represents a Chromosome
 * @author Eva M. Almansa
 * @version 1.0
 */
class Chromosome extends Comparable[Object] with Serializable{

  private val RANDOM_MAX = 100000000
  private val RANDOM_MIN = 0

	private var individual: Array[Byte] = null
	private var max, min, fitness: Double = 0.0
	private var evaluate: Boolean = false
	private var differents: Int = 0
	private var bitsGene: Int = 62
	private var gray: Array[Char] = null

	/**
	 * Constructor with parameters
	 * @param size length of the chromosome
	 */
	def this(size: Int){
	  this()
		min = 0.0
		max = 1.0
		evaluate = false
		individual = Array.fill(size)(0.toByte)
		for (j <- 0 to (individual.length - 1)){
			individual(j) = if(Randomize.getRandom.nextDouble < 0.5) 1 else 0 //0 (inclusive) and 1 (exclusive)
		}
		//println("Initialize: "+individual.deep.mkString(" "))
		fitness = 0
	}

	/**
	 * Constructor with parameters
	 * @param size length of the chromosome
	 * @param value value to be set
	 */
	def this(size: Int, value: Byte){
	  this()
		evaluate = false
		individual = Array.fill(size)(value)
		fitness = 0
	}

	/**
	 * Constructor with parameters
	 * @param size length of the chromosome
	 * @param pos variable id to set 0.5
	 */
	def this(size: Int, pos: Int){
	  this()
		evaluate = false
		individual = Array.fill(size)(1)
		fitness = 0
	}

	/**
	 * Constructor by one point crossover
	 * @param mom first individual
	 * @param dad second individual
	 * @param corte cut point
	 */
	def this(mom: Chromosome, dad: Chromosome, corte: Int){
	  this()
		evaluate = false
		individual = new Array[Byte](mom.size())
		for (j <- 0 to (corte - 1)){
			individual(j) = mom.useRule(j)
		}
		for (j <- corte to (individual.length - 1)){
			individual(j) = dad.useRule(j)
		}
		fitness = 0
	}

	def size(): Int = {
		individual.length
	}

	def rbSize(): Int = {
		var size: Int = 0
		for (i <- 0 to (individual.length - 1)){
			if (individual(i) == 1) size = size + 1
		}
		size
	}

	def isEvaluated(): Boolean = {
		evaluate
	}

	def evaluated(){
		evaluate = true
	}

	def useRule(pos: Int): Byte = {
		individual(pos)
		//return true
	}

	def setFitness(fitness: Double){
		this.fitness = fitness
	}

	def getFitness(): Double = fitness

	def getIndividual(): Array[Byte] = individual

	/*****************************************************************/
	/* Translations between fixed point ints and reflected Gray code */
	/*****************************************************************/
	private def Gray(binChar: Array[Char], pos: Int){
	  var aux_pos = pos
	  var i = 0
		while (i < (binChar.length - 1)){
			var a: Char = binChar(i)
			var b: Char = binChar(i+1)
      if((a & ~ b) == 1 || (~ a & b) == 1){
        gray(aux_pos) = '1'
      }else{
      	gray(aux_pos) = '0'
      }
      i = i + 2
			aux_pos = aux_pos + 1
    }
	}

	/*************************************************************************/
	/* Translations between string representation and floating point vectors */
	/*************************************************************************/
	/*def StringRep(){
		gray = new Array[Char](individualR.length*bitsGene)
		var pos = 0
		for (i <- 0 to (individualR.length - 1)){
			var bin: String = java.lang.Long.toBinaryString(java.lang.Double.doubleToRawLongBits(individualR(i)))
			var binChar: Array[Char] = bin.toCharArray()
			Gray(binChar, pos)
			pos += bitsGene
		}
	}*/

	/*def gray_(pos: Int): Char = {
		this.gray(pos)
	}*/

	/*def shift(pos: Int): Double = {
		individualR(pos)
	}*/

	/*def xPC_BLX(mom: Chromosome, dad: Chromosome, random: scala.util.Random){
		for (i <- 0 to (individualR.length - 1)){
			var I: Double = Math.abs(mom.shift(i)-dad.shift(i))
			var A1: Double = mom.shift(i)-I; if (A1 < min) A1 = min
			var C1: Double = mom.shift(i)+I; if (C1 > max) C1 = max
			individualR(i) = A1 + ((random.nextInt(RANDOM_MAX.toInt - RANDOM_MIN + 1) + RANDOM_MIN)/RANDOM_MAX.toDouble)*(C1-A1)
		}
	}*/

	/*def hamming(c: Chromosome): Int = {
		var dist: Int = 0
		StringRep()
		c.StringRep()
		for (i<-0 to (gray.length - 1)) if (c.gray(i) != gray(i)) dist += 1
		dist
	}*/

	override def clone(): Chromosome = {
		var c = new Chromosome()
		c.individual = individual.clone()
		c.fitness = fitness
		c.evaluate = false
		c.min = min
		c.max = max
		c
	}

	def differ (c: Chromosome): Array[Int] = {
		var differ: Array[Int] = new Array[Int](individual.length)
		differents = 0
		for (i <- 0 to (individual.length - 1)){
			if (individual(i) != c.useRule(i)){
				differ(differents) = i
				differents += 1
			}
		}
		return differ
	}

	def nDifferents(): Int ={
		differents
	}

	def flip(positions: Array[Int]){
		for (i <- 0 to (positions.length - 1)){
			individual(positions(i)) = if(individual(positions(i)) == 1) 0 else 1
		}
	}

	/*def flipFS(positions: Array[Int]){
    for (i <- 0 to (positions.length - 1)){
      individualFS(positions(i)) = !individualFS(positions(i))
    }
  }*/

	/*def getWeights(): Array[Double]={
		individualR
	}*/

	/**
	 * Compares the fitness of two Chrmosomes for the ordering procedure
	 * @param a Object a Chromsome
	 * @return int -1 if the current Chrosome is worst than the one that is compared, 1 for the contrary case and 0
	 * if they are equal.
	 */
	def compareTo(a: Object): Int = {
		if ( (a.asInstanceOf[Chromosome]).fitness < fitness) {
			return -1
		}
		if ( (a.asInstanceOf[Chromosome]).fitness > fitness) {
			return 1
		}
		return 0
	}

	override def toString(): String ={
	  var output = "Chromosome\n"
	  output += " Min=" + min.toString
		output += "| Max=" + max.toString
		output += "| Fitness=" + fitness.toString
		output += "| Evaluate=" + evaluate.toString
		output += "\n Individual=" + individual.deep.mkString(" ").toString
		output += "\n"
	  output
	}

}


text:
'use strict';

// level-iterator: decoding iterator for levelup instances
function iterator (db, opts) {
  if (!iterator.available(db)) {
    throw new Error('level-iterator: this database does not expose iterators')
  }

  // If db exposes iterators, assume they do the decoding
  if (typeof db.iterator === 'function') {
    return db.iterator(opts)
  }

  // If it's a levelup instance, use its codec and iterate the *DOWN db
  const codec = db._codec

  opts = codec.encodeLtgt({
    ...db.options,
    keys: true,
    values: true,
    limit: -1,
    ...( opts || {} )
  })

  opts.keyAsBuffer   = codec.keyAsBuffer(opts)
  opts.valueAsBuffer = codec.valueAsBuffer(opts)

  const iter = db.db.iterator(opts)
  const wrapper = { end: iter.end.bind(iter) }

  wrapper.next = function outerNext (cb) {
    iter.next(function innerNext (err, key, value) {
      if (err) cb(err)
      else if (key === undefined && value === undefined) cb()
      else {
        key = opts.keys ? codec.decodeKey(key, opts) : null
        value = opts.values ? codec.decodeValue(value, opts) : null

        cb(null, key, value)
      }
    })
  }

  if (typeof iter.seek === 'function') {
    wrapper.seek = function outerSeek (target) {
      iter.seek(codec.encodeKey(target, opts))
    }
  } else {
    wrapper.seek = seekNotSupported
  }

  return wrapper
}

function seekNotSupported () {
  throw new Error('level-iterator: this iterator does not support seeking')
}

iterator.available = function (db) {
  if (typeof db.iterator === 'function') return true
  if (db._codec && db.db && typeof db.db.iterator === 'function') return true
  return false
}

module.exports = iterator


text:
pcl::cloud_composer::CloudViewer::CloudViewer (QWidget* parent)
  : QTabWidget (parent)

{
  connect (this, SIGNAL (currentChanged (int)),
           this, SLOT (modelChanged (int)));
}

pcl::cloud_composer::CloudViewer::~CloudViewer ()
{

}

void
pcl::cloud_composer::CloudViewer::addModel (ProjectModel* new_model)
{
  CloudView* new_view = new CloudView (new_model);
  connect (new_model->getSelectionModel (), SIGNAL (selectionChanged (QItemSelection,QItemSelection)),
           new_view, SLOT (selectedItemChanged (QItemSelection,QItemSelection)));
  new_model->setCloudView (new_view);

  QStandardItem* title = new_model->horizontalHeaderItem (0);
  this->addTab (new_view, title->text ());

  model_view_map_.insert (new_model,new_view);

  setCurrentWidget (model_view_map_.value (new_model));
  //Refresh the view
  new_view->refresh ();

}

pcl::cloud_composer::ProjectModel*
pcl::cloud_composer::CloudViewer::getModel () const
{
  if (this->count() == 0)
    return 0;
  else
    return dynamic_cast<CloudView*> (currentWidget ())->getModel ();
}

void
pcl::cloud_composer::CloudViewer::addNewProject (ProjectModel* new_model)
{
  //If we're already there, abort
  if (new_model == getModel ())
    return;
  //Check whether we've seen the model yet
  if ( !model_view_map_.contains (new_model))
  {
    addModel (new_model);
  }
  else
  {
    setCurrentWidget (model_view_map_.value (new_model));
    //Refresh the view
    model_view_map_.value (new_model)->refresh ();
  }
}

void
pcl::cloud_composer::CloudViewer::modelChanged (int index)
{
  emit newModelSelected (getModel ());
}


text:
'use strict';

module.exports = (event, state, args, next) => {

    if (!state.builder) {
        return next('Builder.Search.selectResult: no builder instance found.');
    }

    state.builder.search.selectResult();
    next();
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTS.W._150401.Models.Domain.Model.Client.Product;
using CTS.Com.Domain.Helper;
using CTS.Com.Domain.Model;
using CTS.W._150401.Models.Domain.Object.Client;
using CTS.W._150401.Models.Domain.Dao.Client;
using CTS.Data.APStorageFiles.Domain.Utils;
using CTS.Com.Domain.Constants;

namespace CTS.W._150401.Models.Domain.Logic.Client.Product
{
    /// <summary>
    /// FilterLogic tim kiếm sản phẩm
    /// </summary>
    public class FilterLogic
    {
        #region Execute Method
        /// <summary>
        /// Xử lý filter.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        /// <returns>DataModel</returns>
        public FilterDataModel Execute(FilterDataModel inputObject)
        {
            // Kiểm tra thông tin
            Check(inputObject);
            // Lấy thông tin
            var resultObject = GetInfo(inputObject);
            // Kết quả trả về
            return resultObject;
        }
        #endregion

        #region Private Method
        /// <summary>
        /// Kiểm tra thông tin.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        private void Check(FilterDataModel inputObject)
        {
        }

        /// <summary>
        /// Lấy thông tin.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        /// <returns>DataModel</returns>
        private FilterDataModel GetInfo(FilterDataModel inputObject)
        {
            // Khởi tạo biến cục bộ
            var getResult = new FilterDataModel();

            // Map dữ liệu
            DataHelper.CopyObject(inputObject, getResult);

            // Lấy thông tin sản phẩm
            var pagerItems = GetPagerItems(inputObject);

            // Trường hợp không tìm thấy sản phẩm
            if (pagerItems.ListData.Count == decimal.Zero)
            {
                // Gán message
                getResult.Messages.Add(MessageHelper.GetMessage("I_MSG_00008"));
                // Kết quả trả về
                return getResult;
            }

            // Gán giá trị trả về
            getResult.ListData = pagerItems.ListData;
            getResult.Total = pagerItems.Total;

            // Kết quả trả về
            return getResult;
        }

        /// <summary>
        /// Lấy pager sản phẩm
        /// </summary>
        private PagerInfoModel<ItemObject> GetPagerItems(FilterDataModel inputObject)
        {
            // Khởi tạo biến cục bộ
            var pagerResult = new PagerInfoModel<ItemObject>();
            var listData = new List<ItemObject>();
            var processDao = new ItemsListDao();
            var storageFileCom = new StorageFileCom();

            // Lấy thông tin danh sách sản phẩm
            var pagerItems = processDao.GetPagerItems(inputObject);

            // Khai báo biến dùng trong loop
            ItemObject info = null;
            // Duyệt danh sách sản phẩm mới
            foreach (var item in pagerItems.ListData)
            {
                // Khởi tạo đối tượng sản phẩm mới
                info = new ItemObject();

                // Gán giá trị vào đối tượng sản phẩm mới
                info.ItemCd = item.ItemCd;
                info.ItemName = item.ItemName;
                info.ItemSearchName = item.ItemSearchName;
                info.ItemImage = storageFileCom.GetFileName(
                    Logics.LOCALE_DEFAULT,
                    item.FileCd,
                    false);

                // Thêm vào đối tượng kết quả
                listData.Add(info);
            }

            // Gán giá trị trả về
            pagerResult.ListData = listData;
            pagerResult.Total = pagerItems.Total;

            // Kết quả trả về
            return pagerResult;
        }
        #endregion
    }
}


text:
robot.model package
===================

.. automodule:: robot.model
   :members:
   :undoc-members:
   :show-inheritance:

Submodules
----------

robot.model.body module
-----------------------

.. automodule:: robot.model.body
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.configurer module
-----------------------------

.. automodule:: robot.model.configurer
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.control module
--------------------------

.. automodule:: robot.model.control
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.filter module
-------------------------

.. automodule:: robot.model.filter
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.fixture module
--------------------------

.. automodule:: robot.model.fixture
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.itemlist module
---------------------------

.. automodule:: robot.model.itemlist
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.keyword module
--------------------------

.. automodule:: robot.model.keyword
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.message module
--------------------------

.. automodule:: robot.model.message
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.metadata module
---------------------------

.. automodule:: robot.model.metadata
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.modelobject module
------------------------------

.. automodule:: robot.model.modelobject
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.modifier module
---------------------------

.. automodule:: robot.model.modifier
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.namepatterns module
-------------------------------

.. automodule:: robot.model.namepatterns
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.statistics module
-----------------------------

.. automodule:: robot.model.statistics
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.stats module
------------------------

.. automodule:: robot.model.stats
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.suitestatistics module
----------------------------------

.. automodule:: robot.model.suitestatistics
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.tags module
-----------------------

.. automodule:: robot.model.tags
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.tagsetter module
----------------------------

.. automodule:: robot.model.tagsetter
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.tagstatistics module
--------------------------------

.. automodule:: robot.model.tagstatistics
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.testcase module
---------------------------

.. automodule:: robot.model.testcase
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.testsuite module
----------------------------

.. automodule:: robot.model.testsuite
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.totalstatistics module
----------------------------------

.. automodule:: robot.model.totalstatistics
   :members:
   :undoc-members:
   :show-inheritance:

robot.model.visitor module
--------------------------

.. automodule:: robot.model.visitor
   :members:
   :undoc-members:
   :show-inheritance:


text:
<?php

namespace Inneair\Synapps\IO;

use ZipArchive;

/**
 * This class provides utilities for Zip archives management.
 */
final class ZipUtils
{
    /**
     * Prevents unwanted instantiations.
     * @codeCoverageIgnore
     */
    private function __construct()
    {
    }

    /**
     * Extracts the content of a Zip archive into a directory.
     *
     * If the target directory does not exist, it will be created.
     *
     * @param File $zipFile Zip file.
     * @param File $targetDirectory Target directory.
     * @throws IOException If the Zip archive cannot be opened, or the content cannot be extracted.
     */
    public static function extractTo(File $zipFile, File $targetDirectory)
    {
        $zipArchive = new ZipArchive();
        $result = $zipArchive->open($zipFile->getOsPath(), ZipArchive::CHECKCONS);
        if ($result !== true) {
            throw new IOException('Cannot open ZIP archive (error ' . $result . '): ' . $zipFile->getPath());
        }
        try {
            if (!@$zipArchive->extractTo($targetDirectory->getOsPath())) {
                throw new IOException('Cannot extract content of ZIP archive: ' . $zipFile->getPath());
            }
            $zipArchive->close();
        } catch (IOException $e) {
            $zipArchive->close();
            throw $e;
        }
    }
}


text:
'use strict';

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: './',

    preprocessors: {
      '**/*.html': ['ng-html2js']
    },

    ngHtml2JsPreprocessor: {
      stripPrefix: 'src/',
    },

    // list of files / patterns to load in the browser
    files: [
      // jQuery is used when testing directives
      'components/jquery/jquery.js',

      // Vendor
      'components/bower-angular/angular.js',
      'components/bower-angular-mocks/angular-mocks.js',

      // Specs helpers
      'components/jasmine-helpers/*.js',

      'components/bower-redefine/*.js',
      'components/bower-eddy-x/*.js',
      'components/dialog.js/*.js',
      'components/object-factory.js/*.js',
      'components/ng-auth-service/*.js',
      'components/ng-security-service/**/*.js',
      'components/ng-gc-dialog-directive/*.js',

      // app & specs
      'src/**/*.js',

      // templates
      'src/**/*.html'
    ],

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    frameworks: ['jasmine'],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit'
    reporters: ['dots', 'growl'],

    reportSlowerThan: 50,

    // enable / disable watching file and executing tests
    // whenever any file changes
    autoWatch: true,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: true
  });
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycopath. Mycol. appl. 35: 99 (1968)

#### Original name
Keratinophyton terreum H.S. Randhawa & R.S. Sandhu, 1964

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tridion.ContentManager;
using Tridion.ContentManager.ContentManagement;
using Dynamic = DD4T.ContentModel;
using Tridion.ContentManager.Templating;

namespace DD4T.Templates.Base.Contracts
{
    /// <summary>
    /// Defines logic for retrieving a path to which a binary file must be published
    /// </summary>
    public interface IBinaryPathProvider
    {

        /// <summary>
        /// Returns the target structure group URI where the binary should be published to
        /// </summary>
        /// <param name="componentUri">String representing the URI of the multimedia component being published</param>
        /// <returns></returns>
        TcmUri GetTargetStructureGroupUri(string componentUri);
        //string ConstructFileName(Component mmComp, string variantId, bool stripTcmUrisFromBinaryUrls, string targetStructureGroupUri);

        /// <summary>
        /// Returns a filename for an item.
        /// </summary>
        /// <remarks>Based on the properties of the item. The filename property must be set, but
        /// there can be other aspects set on the item that are taken into account in the filename</remarks>
        /// <param name="item"></param>
        /// <returns></returns>

        string GetFilename(Component mmComp, string variantId);
    }
}


text:
var redirect = require('../lib/plugins/redirect');
var express = require('express');
var supertest = require('supertest');

require('simple-errors');

describe('redirect plugin', function() {
  var server;
  var redirectOptions;

  beforeEach(function() {
    server = express();

    server.use(function(req, res, next) {
      req.ext = {clientConfig: {}};
      next();
    });

    server.use(function(req, res, next) {
      redirect(redirectOptions)(req, res, next);
    });

    server.get('/', function(req, res, next) {
      res.send('');
    });

    server.use(function(err, req, res, next) {
      if (!err.status) err.status = 500;
      if (err.status === 500 && err.log !== false) {
        process.stderr.write(err.stack);
      }
      res.status(err.status).json(Error.toJson(err));
    });
  });

  it('simple redirect', function(done) {
    redirectOptions = {
      '/blog/old-title': '/blog/new-title'
    };

    supertest(server)
      .get('/blog/old-title')
      .expect(301)
      .expect('Location', '/blog/new-title')
      .end(done);
  });

  it('rename a directory', function(done) {
    redirectOptions = {
      '/help/:pageTitle': '/support/:pageTitle'
    };

    supertest(server)
      .get('/help/how-to-do-something')
      .expect(301)
      .expect('Location', '/support/how-to-do-something')
      .end(done);
  });

  it('invalid redirect pattern causes error', function(done) {
    redirectOptions = {
      '/help/:pageTitle': '/:somethingElse/foo/:anotherParam'
    };

    supertest(server)
      .get('/help/how-to-do-something')
      .expect(500)
      .end(done);
  });

  it('allows redirect rule to be an array', function(done) {
    redirectOptions = {
      '/help/:pageTitle': [302, '/support/:pageTitle']
    };

    supertest(server)
      .get('/help/how-to')
      .expect(302)
      .expect('Location', '/support/how-to')
      .end(done);
  });

  it('skips middleware if no matches', function(done) {
    redirectOptions = {
      '/blog/post-1': '/blog/new-post1',
      '/blog/post-2': '/blog/new-post2'
    };

    supertest(server)
      .get('/blog/post-3')
      .expect(404)
      .end(done);
  });

  describe('file extension match', function() {
    before(function() {
      redirectOptions = {
        '/*.php': '/(.*)'
      };
    });

    it('at root', function(done) {
      supertest(server)
        .get('/about.php')
        .expect(301)
        .expect('Location', '/about')
        .end(done);
    });

    it('with sub-folder', function(done) {
      supertest(server)
        .get('/blog/how-to-do-something.php')
        .expect(301)
        .expect('Location', '/blog/how-to-do-something')
        .end(done);
    });
  });

  it('match querystring param', function(done) {
    redirectOptions = {
      'regex:/page.php\\?id=(:<id>[0-9]+)': '/articles/article${id}'
    };

    supertest(server)
      .get('/page.php?id=1')
      .expect(301)
      .expect('Location', '/articles/article1')
      .end(done);
  });

  it('querystring literal', function(done) {
    redirectOptions = {
      'regex:/page.php\\?id=5': '/articles/hello-world'
    };

    supertest(server)
      .get('/page.php?id=5')
      .expect(301)
      .expect('Location', '/articles/hello-world')
      .end(done);
  });

  // it('', function(done) {
  //
  // });
});


text:
namespace AssemblyToProcess
{
    using System;
    using System.Threading.Tasks;

    public abstract class AsyncDisposableBase : IAsyncDisposable
    {
        public virtual Task DisposeAsync()
        {
            return Task.FromResult(0);
        }

        public virtual void DoSomething()
        {
            Console.WriteLine("Yuhuu!");
        }

        public virtual string SayMeHelloWorld()
        {
            return "Hello World!";
        }
    }
}


text:
typedef void(^WPFilterCompletionHandler)(UIImage *processedImage);

@interface WPFilter : NSObject

@property (nonatomic, strong, readonly) NSURL *filterURL;
@property (nonatomic, copy, readonly) NSString *filterName;
@property (nonatomic, copy, readonly) NSString *filterDescription;
@property (nonatomic, assign, readonly) CGFloat formatVersion;
@property (nonatomic, copy, readonly) NSString *organizationName;
@property (nonatomic, strong, readonly) NSURL *organizationURL;
@property (nonatomic, strong, readonly) NSArray *sampleImages;
@property (nonatomic, strong, readonly) UIImage *packagingArtwork;
@property (nonatomic, strong, readonly) NSArray *processingSteps;

- (instancetype)initWithFilterAtURL:(NSURL *)filterURL;

// Processing happens on the background, but we return the completion handler
// on the main thread.
- (void)processImage:(UIImage *)image completion:(WPFilterCompletionHandler)handler;
- (void)processCGImage:(CGImageRef)image completion:(WPFilterCompletionHandler)handler;

- (NSURL *)pathURLForFilterItemNamed:(NSString *)fileName;

@end


text:
package com.example.greatbook.model.event;

/**
 * Created by MDove on 2017/8/24.
 */

public class LikeEvent {
    public String event;
    public int itemPostion;
}


text:
Intrigue-core is an API-first intelligence gathering framework for Internet reconnaissance and research.

<img src="https://raw.githubusercontent.com/intrigueio/intrigue-core/develop/doc/home.png" width="700">

To get started, follow the instructions below!

### Setting up a development environment

The following are presumed available and configured in your environment
 - redis
 - sudo
 - nmap
 - zmap
 - masscan
 - java runtime

Sudo is used to allow root access for certain commands ^ , so make sure this doesn't require a password:
```
your-username ALL = NOPASSWD: /usr/bin/masscan, /usr/sbin/zmap, /usr/bin/nmap
```

### Starting up...

Make sure you have redis installed and running. (Use Homebrew if you're on OSX).

Install all gem dependencies with Bundler (http://bundler.io/)
```
$ bundle install
```

Start the web and background workers. Intrigue will start on 127.0.0.0:7777.
```
$ foreman start
```

Now, browse to the web interface.

### Using the web interface

To use the web interface, browse to http://127.0.0.1:7777

Getting started should be pretty straightforward, try running a "dns_brute_sub" task on your domain. Now, try with the "use_file" option set to true.

### API usage via core-cli:

A command line utility has been added for convenience, core-cli.

List all available tasks:
```
$ bundle exec ./core-cli.rb list
```

Start a task:
```
$ bundle exec ./core-cli.rb start dns_lookup_forward DnsRecord#intrigue.io
```

Start a task with options:
```
$ bundle exec ./core-cli.rb start dns_brute_sub DnsRecord#intrigue.io resolver=8.8.8.8#brute_list=1,2,3,4,www#use_permutations=true
[+] Starting task
[+] Task complete!
[+] Start Results
  DnsRecord#www.intrigue.io
  IpAddress#192.0.78.13
[ ] End Results
[+] Task Log:
[ ] : Got allowed option: resolver
[ ] : Allowed option: {:name=>"resolver", :type=>"String", :regex=>"ip_address", :default=>"8.8.8.8"}
[ ] : Regex should match an IP Address
[ ] : No need to convert resolver to a string
[+] : Allowed user_option! {"name"=>"resolver", "value"=>"8.8.8.8"}
[ ] : Got allowed option: brute_list
[ ] : Allowed option: {:name=>"brute_list", :type=>"String", :regex=>"alpha_numeric_list", :default=>["mx", "mx1", "mx2", "www", "ww2", "ns1", "ns2", "ns3", "test", "mail", "owa", "vpn", "admin", "intranet", "gateway", "secure", "admin", "service", "tools", "doc", "docs", "network", "help", "en", "sharepoint", "portal", "public", "private", "pub", "zeus", "mickey", "time", "web", "it", "my", "photos", "safe", "download", "dl", "search", "staging"]}
[ ] : Regex should match an alpha-numeric list
[ ] : No need to convert brute_list to a string
[+] : Allowed user_option! {"name"=>"brute_list", "value"=>"1,2,3,4,www"}
[ ] : Got allowed option: use_permutations
[ ] : Allowed option: {:name=>"use_permutations", :type=>"Boolean", :regex=>"boolean", :default=>true}
[ ] : Regex should match a boolean
[+] : Allowed user_option! {"name"=>"use_permutations", "value"=>true}
[ ] : user_options: [{"resolver"=>"8.8.8.8"}, {"brute_list"=>"1,2,3,4,www"}, {"use_permutations"=>true}]
[ ] : Task: dns_brute_sub
[ ] : Id: fddc7313-52f6-4d5a-9aad-fd39b0428ca5
[ ] : Task entity: {"type"=>"DnsRecord", "attributes"=>{"name"=>"intrigue.io"}}
[ ] : Task options: [{"resolver"=>"8.8.8.8"}, {"brute_list"=>"1,2,3,4,www"}, {"use_permutations"=>true}]
[ ] : Option configured: resolver=8.8.8.8
[ ] : Option configured: use_file=false
[ ] : Option configured: brute_file=dns_sub.list
[ ] : Option configured: use_mashed_domains=false
[ ] : Option configured: brute_list=1,2,3,4,www
[ ] : Option configured: use_permutations=true
[ ] : Using provided brute list
[+] : Using subdomain list: ["1", "2", "3", "4", "www"]
[+] : Looks like no wildcard dns. Moving on.
[-] : Hit exception: no address for 1.intrigue.io
[-] : Hit exception: no address for 2.intrigue.io
[-] : Hit exception: no address for 3.intrigue.io
[-] : Hit exception: no address for 4.intrigue.io
[+] : Resolved Address 192.0.78.13 for www.intrigue.io
[+] : Creating entity: DnsRecord, {:name=>"www.intrigue.io"}
[+] : Creating entity: IpAddress, {:name=>"192.0.78.13"}
[ ] : Adding permutations: www1, www2
[-] : Hit exception: no address for www1.intrigue.io
[-] : Hit exception: no address for www2.intrigue.io
[+] : Ship it!
[ ] : Sending to Webhook: http://localhost:7777/v1/task_runs/fddc7313-52f6-4d5a-9aad-fd39b0428ca5
```

Check for a list of subdomains on intrigue.io:
```
$ bundle exec ./core-cli.rb start dns_brute_sub DnsRecord#intrigue.io resolver=8.8.8.8#brute_list=a,b,c,proxy,test,www
```

Check the Alexa top 1000 domains for the existence of security headers:
```
$ for x in `cat data/domains.txt | head -n 1000`; do bundle exec ./core-cli.rb start dns_brute_sub DnsRecord#$x;done
```

### API usage via rubygem
[![Gem Version](https://badge.fury.io/rb/intrigue.svg)](http://badge.fury.io/rb/intrigue)

```
$ gem install intrigue
$ irb

> require 'intrigue'
> x =  Intrigue.new

  # Create an entity hash, must have a :type key
  # and (in the case of most tasks)  a :attributes key
  # with a hash containing a :name key (as shown below)
> entity = {
    :type => "String",
    :attributes => { :name => "intrigue.io"}
  }

  # Create a list of options (this can be empty)
> options_list = [
    { :name => "resolver", :value => "8.8.8.8" }
  ]

> x.start "example", entity_hash, options_list
> id  = x.start "example", entity_hash, options_list
> puts x.get_log id
> puts x.get_result id
```

### API usage via curl:

You can use the tried and true curl utility to request a task run. Specify the task type, specify an entity, and the appropriate options:

```
$ curl -s -X POST -H "Content-Type: application/json" -d '{ "task": "example", "entity": { "type": "String", "attributes": { "name": "8.8.8.8" } }, "options": {} }' http://127.0.0.1:7777/v1/task_runs
```


text:
import Ember from 'ember';

var Router = Ember.Router.extend({
  location: KarateChessENV.locationType
});

Router.map(function() {
});

export default Router;


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe UsersController do

  describe "when creating a new user" do

#    before :each do
#      @params = {'subdomain' => "ept", 'email' => "hasni@eptcomputing.com", 'invitation_code' => "ab48f"}
#    end
#
#    it "should redirect back to /signup with bad parameters" do
#      @params.delete['email']
#      get @params
#      response.should redirect_to "http://test.host/signup"
#    end

    it "test corner cases not covered by features, e.g. attempting to create new customer from existing user with wrong password"
  end

  describe "when inviting a new user to join a customer" do
    before :each do
      @widget = mock_model Customer, {:subdomain => "widget"}
      @current_user = mock_model User, {:email => 'current.user@example.com', :customers => [@widget]}
      @current_user.should_receive(:time_zone).any_number_of_times.and_return('London')
      @current_user.should_receive(:email).any_number_of_times.and_return('current.user@example.com')
      @existing_user = mock_model User, {:email => 'existing.user@example.com', :customers => []}
      @existing_user.should_receive(:time_zone).any_number_of_times.and_return('London')
      @existing_user.should_receive(:save).any_number_of_times.and_return(true)
      @new_user = mock_model User, {:email => 'new.user@example.com', :customers => []}
      @new_user.should_receive(:time_zone).any_number_of_times.and_return('London')
      @new_user.should_receive(:save).any_number_of_times.and_return(true)
      @widget.should_receive(:users).any_number_of_times.and_return([@current_user])
      controller.should_receive(:customer_login_required).any_number_of_times.and_return(true)
      controller.should_receive(:customer_admin_required).any_number_of_times.and_return(true)
      controller.should_receive(:current_customer).any_number_of_times.and_return(@widget)
      controller.should_receive(:current_user).any_number_of_times.and_return(@current_user)
    end

    it "should detect an existing account with another customer" do
      User.should_receive(:find).with(:first, :conditions => {:email => 'existing.user@example.com'}).and_return(@existing_user)
      post :create, :user => {:email => 'EXISTING.USER@example.com'}
      response.should redirect_to("/users")
      flash[:notice].should =~ /We have sent an invitation/
      @existing_user.customers.should include(@widget)
    end

    it "should create a new passive account for an unknown address" do
      User.should_receive(:find).with(:first, :conditions => {:email => 'new.user@example.com'}).and_return(nil)
      User.should_receive(:new).with({'email' => 'new.user@example.com'}).and_return(@new_user)
      @new_user.should_receive(:state=).with('passive')
      post :create, :user => {:email => 'new.user@example.com'}
      response.should redirect_to("/users")
      flash[:notice].should =~ /We have sent an invitation/
      @new_user.customers.should include(@widget)
    end
  end

  describe "#update" do
    before :each do
      @widget = mock_model Customer, {:subdomain => "widget"}

      @admin_role = mock_model CustomerUser
      @admin = mock_model User, {:state => 'active'}
      @admin.should_receive(:link_to).any_number_of_times.and_return(@admin_role)
      @admin.should_receive(:is_admin_for?).any_number_of_times.and_return(true)
      @admin.should_receive(:can_edit_user?).any_number_of_times.and_return(true)
      @admin.should_receive(:time_zone).any_number_of_times.and_return('London')
      @admin.should_receive(:email).any_number_of_times.and_return('admin@example.com')

      @user_role = mock_model CustomerUser
      @user = mock_model User
      @user.should_receive(:link_to).any_number_of_times.and_return(@user_role)
      @user.should_receive(:is_admin_for?).any_number_of_times.and_return(false)
      @user.should_receive(:can_edit_user?).with(@user, @widget).any_number_of_times.and_return(true)
      @user.should_receive(:can_edit_user?).with(@admin, @widget).any_number_of_times.and_return(false)
      @user.should_receive(:time_zone).any_number_of_times.and_return('London')
      @user.should_receive(:email).any_number_of_times.and_return('user@example.com')

      controller.should_receive(:customer_login_required).any_number_of_times.and_return(true)
      controller.should_receive(:current_customer).any_number_of_times.and_return(@widget)
    end

    it "should allow a user to change their own details and password" do
      controller.should_receive(:current_user).any_number_of_times.and_return(@user)
      User.should_receive(:find).and_return(@user)
      @user.should_receive(:attributes=)
      @user.should_receive(:password=).with('blahblah')
      @user.should_receive(:password_confirmation=).with('blahblah')
      @user.should_receive(:save).and_return(true)
      post :update, :user => {:name => 'john smith', :email => 'blah@blah.com',
        :password => 'blahblah', :password_confirmation => 'blahblah'}
      response.should be_redirect
      flash[:notice].should =~ /have been updated/
    end

    it "should not allow an admin to change another user's password" do
      controller.should_receive(:current_user).any_number_of_times.and_return(@admin)
      User.should_receive(:find).and_return(@user)
      @user.should_receive(:attributes=)
      @user.should_not_receive(:password=)
      @user.should_receive(:save).and_return(true)
      post :update, :user => {:name => 'john smith', :email => 'blah@blah.com',
        :password => 'blahblah', :password_confirmation => 'blahblah'}
      response.should be_redirect
      flash[:notice].should =~ /have been updated/
    end

    it "should allow an admin to grant admin permissions" do
      controller.should_receive(:current_user).any_number_of_times.and_return(@admin)
      User.should_receive(:find).and_return(@user)
      @user.should_receive(:attributes=)
      @user.should_receive(:save).and_return(true)
      @user_role.should_receive(:grant_admin!)
      post :update, :user => {:name => 'john smith', :email => 'blah@blah.com'}, :grant_admin => '1'
      response.should be_redirect
      flash[:notice].should =~ /have been updated/
    end

    it "should allow an admin to revoke admin permissions" do
      controller.should_receive(:current_user).any_number_of_times.and_return(@admin)
      User.should_receive(:find).and_return(@user)
      @user.should_receive(:attributes=)
      @user.should_receive(:save).and_return(true)
      @user_role.should_receive(:revoke_admin!)
      post :update, :user => {:name => 'john smith', :email => 'blah@blah.com'}, :revoke_admin => '1'
      response.should be_redirect
      flash[:notice].should =~ /have been updated/
    end

    it "should not allow a normal user to grant admin permissions" do
      controller.should_receive(:current_user).any_number_of_times.and_return(@user)
      User.should_receive(:find).and_return(@admin)
      lambda {
        post :update, :user => {:name => 'john smith', :email => 'blah@blah.com'}, :grant_admin => '1'
      }.should raise_error(ActiveRecord::RecordNotFound)
    end
  end

  describe "#forgotten_password" do
    before :each do
      @active_user = mock_model User, {:state => 'active'}
      @active_user.should_receive(:can_reset_password?).any_number_of_times.and_return(true)
      @suspended_user = mock_model User, {:state => 'suspended'}
      @suspended_user.should_receive(:can_reset_password?).any_number_of_times.and_return(false)
    end

    it "should not require login" do
      get :forgotten_password
      response.should render_template("users/forgotten_password.html.erb")
    end

    it "should send a password email if the account is valid" do
      User.should_receive(:find_by_email).with('blah@blah.com').and_return(@active_user)
      @active_user.should_receive(:password_reset_email!)
      post :forgotten_password, :email => 'BLAH@BLAH.com'
      response.should redirect_to("/login")
      flash[:notice].should =~ /We have sent you a link/
    end

    it "should not send a password email if the account is suspended" do
      User.should_receive(:find_by_email).with('blah@blah.com').and_return(@suspended_user)
      post :forgotten_password, :email => 'BLAH@BLAH.com'
      response.should redirect_to("/forgotten_password?email=blah%40blah.com")
      flash[:error].should =~ /your account is suspended/
    end

    it "should display an error if the account is unknown" do
      User.should_receive(:find_by_email).with('blah@blah.com').and_return(nil)
      post :forgotten_password, :email => 'BLAH@BLAH.com'
      response.should redirect_to("/forgotten_password?email=blah%40blah.com")
      flash[:error].should =~ /we couldn't find/
    end
  end

end


text:
package com.app.teacup.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    private static final int CONNECT_SUCCESS = 200;

    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return (activeNetInfo != null)
                && (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI);
    }

    public static boolean isMobile(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null) && (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    public static void sendHttpRequest(final String address,
                                       final HttpCallBackListener listener) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    StringBuilder response = new StringBuilder();

                    int code = connection.getResponseCode();
                    if (CONNECT_SUCCESS == code) {
                        InputStream in = connection.getInputStream();
                        String charsetName = "gb2013";
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(in, charsetName));

                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    public static void sendHttpRequestWithCharset(final String address, final String charsetName,
                                       final HttpCallBackListener listener) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    StringBuilder response = new StringBuilder();

                    int code = connection.getResponseCode();
                    if (CONNECT_SUCCESS == code) {
                        InputStream in = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(in, charsetName));

                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    public interface HttpCallBackListener {
        void onFinish(String response);

        void onError(Exception e);
    }
}


text:
import { TaskQueue } from 'aurelia-framework';
export declare class MdcCardActions {
    private taskQueue;
    fullBleed: boolean;
    class: string;
    private elementSection;
    constructor(taskQueue: TaskQueue);
    bind(): void;
    unbind(): void;
    attached(): void;
    private fullBleedChanged(newValue);
    private decorateChildren(element);
}


text:
(function() {
    'use strict';

    angular
        .module('app.extras')
        .run(coreMenu);

    coreMenu.$inject = ['Menus'];
    function coreMenu(Menus){

        // Menus.addMenuItem('sidebar', 'Extras', 'extras', 'dropdown', null, true, null, 8, 'icon-cup');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Forum',       'extras/forum');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Mailbox',     'extras/mailbox/folder/inbox');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Timeline',    'extras/timeline');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Calendar',    'extras/calendar');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Invoice',     'extras/invoice');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Search',      'extras/search');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Todo List',   'extras/todo');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Profile',     'extras/profile');
        // Menus.addSubMenuItem('sidebar', 'extras', 'Code Editor', 'extras/code-editor');
    }

})();


text:
package ru.job4j.carMarket.model.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;

import static javax.persistence.GenerationType.IDENTITY;

@Entity
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private int id;

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

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

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

    @Column(name = "body_type")
    private String bodyType;

    @Column(name = "year_issue")
    private int yearIssue;

    @Column(name = "price")
    private int price;

    @Column(name = "path_image")
    private String pathImage;

    @Column(name = "is_sold")
    private boolean isSold;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User owner;

    public Car() {
    }

    public Car(String mark, String model, String transmission, String bodyType, int yearIssue, int price, String pathImage, User owner) {
        this.mark = mark;
        this.model = model;
        this.transmission = transmission;
        this.bodyType = bodyType;
        this.yearIssue = yearIssue;
        this.price = price;
        this.pathImage = pathImage;
        this.isSold = false;
        this.owner = owner;
    }

    public int getId() {
        return id;
    }

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

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getTransmission() {
        return transmission;
    }

    public void setTransmission(String transmission) {
        this.transmission = transmission;
    }

    public String getBodyType() {
        return bodyType;
    }

    public void setBodyType(String bodyType) {
        this.bodyType = bodyType;
    }

    public int getYearIssue() {
        return yearIssue;
    }

    public void setYearIssue(int yearIssue) {
        this.yearIssue = yearIssue;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getPathImage() {
        return pathImage;
    }

    public void setPathImage(String pathImage) {
        this.pathImage = pathImage;
    }

    public boolean getIsSold() {
        return isSold;
    }

    public void setIsSold(boolean sold) {
        this.isSold = sold;
    }

    public User getOwner() {
        return owner;
    }

    public void setOwner(User user) {
        this.owner = user;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Car)) return false;

        Car car = (Car) o;

        if (id != car.id) return false;
        if (yearIssue != car.yearIssue) return false;
        if (price != car.price) return false;
        if (isSold != car.isSold) return false;
        if (!mark.equals(car.mark)) return false;
        if (!model.equals(car.model)) return false;
        if (!transmission.equals(car.transmission)) return false;
        if (!bodyType.equals(car.bodyType)) return false;
        return pathImage.equals(car.pathImage);
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + mark.hashCode();
        result = 31 * result + model.hashCode();
        result = 31 * result + transmission.hashCode();
        result = 31 * result + bodyType.hashCode();
        result = 31 * result + yearIssue;
        result = 31 * result + price;
        result = 31 * result + pathImage.hashCode();
        result = 31 * result + (isSold ? 1 : 0);
        result = 31 * result + owner.hashCode();
        return result;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_imgpicker_content_bg"
    android:orientation="vertical">

    <TextView
        android:layout_marginBottom="10dp"
        android:id="@+id/dialog_title_tv"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/transparent"
        android:gravity="center"
        android:text="确定删除该管理员吗?"
        android:textColor="#FF000000"
        android:textSize="18sp"/>

    <View
        style="@style/line_style"
        android:layout_marginTop="@dimen/textSize_16"/>

    <!--<View-->
        <!--android:background="#ff000000"-->
        <!--android:layout_height="1dp"-->
        <!--android:layout_width="match_parent"/>-->
    <!--<View-->
    <!--style="@style/line_style"-->
    <!--android:layout_marginTop="@dimen/textSize_16"/>-->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp">

        <View
            android:id="@+id/centerIv"
            android:layout_centerInParent="true"
            style="@style/line_style_vertical" />

        <Button
            android:id="@+id/dialog_true_btn"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@id/centerIv"
            android:background="@color/transparent"
            android:text="删除"
            android:textColor="#ff0000"
            android:textSize="@dimen/textSize_16"/>
        <Button
            android:id="@+id/dialog_cancel_btn"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@id/centerIv"
            android:background="@color/transparent"
            android:text="取消"
            android:textColor="@color/new_app_color"
            android:textSize="@dimen/textSize_16"/>
    </RelativeLayout>
</LinearLayout>


text:
/*****************************************************************************
written by
   Yunhong Gu, last updated 04/29/2010
*****************************************************************************/

#include <sectorfs.h>
#include <fstream>
#include <iostream>

using namespace std;

Sector SectorFS::g_SectorClient;
Session SectorFS::g_SectorConfig;
map<string, FileTracker*> SectorFS::m_mOpenFileList;
pthread_mutex_t SectorFS::m_OpenFileLock = PTHREAD_MUTEX_INITIALIZER;

void* SectorFS::init(struct fuse_conn_info *conn)
{
   if (g_SectorClient.init(g_SectorConfig.m_ClientConf.m_strMasterIP, g_SectorConfig.m_ClientConf.m_iMasterPort) < 0)
      return NULL;
   if (g_SectorClient.login(g_SectorConfig.m_ClientConf.m_strUserName, g_SectorConfig.m_ClientConf.m_strPassword, g_SectorConfig.m_ClientConf.m_strCertificate.c_str()) < 0)
      return NULL;

   g_SectorClient.setMaxCacheSize(g_SectorConfig.m_ClientConf.m_llMaxCacheSize);

   return NULL;
}

void SectorFS::destroy(void *)
{
   g_SectorClient.logout();
   g_SectorClient.close();
}

int SectorFS::getattr(const char* path, struct stat* st)
{
   SNode s;
   int r = g_SectorClient.stat(path, s);
   if (r < 0)
      return translateErr(r);

   if (s.m_bIsDir)
      st->st_mode = S_IFDIR | 0755;
   else
      st->st_mode = S_IFREG | 0755;
   st->st_nlink = 1;
   st->st_uid = 0;
   st->st_gid = 0;
   st->st_size = s.m_llSize;
   st->st_blksize = 1024000;
   st->st_blocks = st->st_size / st->st_blksize + 1;
   st->st_atime = st->st_mtime = st->st_ctime = s.m_llTimeStamp;

   return 0;
}

int SectorFS::fgetattr(const char* path, struct stat* st , struct fuse_file_info *)
{
   return getattr(path, st);
}

int SectorFS::mknod(const char *, mode_t, dev_t)
{
   return 0;
}

int SectorFS::mkdir(const char* path, mode_t mode)
{
   int r = g_SectorClient.mkdir(path);
   if (r < 0)
      return translateErr(r);

   return 0;
}

int SectorFS::unlink(const char* path)
{
   if (g_SectorClient.remove(path) < 0)
      return -1;

   return 0;
}

int SectorFS::rmdir(const char* path)
{
   if (g_SectorClient.remove(path) < 0)
      return -1;

   return 0;
}

int SectorFS::rename(const char* src, const char* dst)
{
   int r = g_SectorClient.move(src, dst);
   if (r < 0)
      return translateErr(r);

   return 0;
}

int SectorFS::statfs(const char* path, struct statvfs* buf)
{
   SysStat s;
   int r = g_SectorClient.sysinfo(s);
   if (r < 0)
      return translateErr(r);

   buf->f_namemax = 256;
   buf->f_bsize = 1024;
   buf->f_frsize = buf->f_bsize;
   buf->f_blocks = (s.m_llAvailDiskSpace + s.m_llTotalFileSize) / buf->f_bsize;
   buf->f_bfree = buf->f_bavail = s.m_llAvailDiskSpace / buf->f_bsize;
   buf->f_files = s.m_llTotalFileNum;
   buf->f_ffree = 0xFFFFFFFFULL;

   return 0;
}

int SectorFS::utime(const char* path, struct utimbuf* ubuf)
{
    return g_SectorClient.utime(path, ubuf->modtime);;
}

int SectorFS::utimens(const char* path, const struct timespec tv[2])
{
   return g_SectorClient.utime(path, tv[1].tv_sec);
}

int SectorFS::opendir(const char *, struct fuse_file_info *)
{
   return 0;
}

int SectorFS::readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* info)
{
   vector<SNode> filelist;
   int r = g_SectorClient.list(path, filelist);
   if (r < 0)
      return translateErr(r);

   for (vector<SNode>::iterator i = filelist.begin(); i != filelist.end(); ++ i)
   {
      struct stat st;
      if (i->m_bIsDir)
         st.st_mode = S_IFDIR | 0755;
      else
         st.st_mode = S_IFREG | 0755;
      st.st_nlink = 1;
      st.st_uid = 0;
      st.st_gid = 0;
      st.st_size = i->m_llSize;
      st.st_blksize = 1024000;
      st.st_blocks = st.st_size / st.st_blksize + 1;
      st.st_atime = st.st_mtime = st.st_ctime = i->m_llTimeStamp;

      filler(buf, i->m_strName.c_str(), &st, 0);
   }

   struct stat st;
   st.st_mode = S_IFDIR | 0755;
   st.st_nlink = 1;
   st.st_uid = 0;
   st.st_gid = 0;
   st.st_size = 4096;
   st.st_blksize = 1024000;
   st.st_blocks = st.st_size / st.st_blksize + 1;
   st.st_atime = st.st_mtime = st.st_ctime = 0;
   filler(buf, ".", &st, 0);
   filler(buf, "..", &st, 0);

   return 0;
}

int SectorFS::fsyncdir(const char *, int, struct fuse_file_info *)
{
   return 0;
}

int SectorFS::releasedir(const char *, struct fuse_file_info *)
{
   return 0;
}

int SectorFS::chmod(const char *, mode_t)
{
   return 0;
}

int SectorFS::chown(const char *, uid_t, gid_t)
{
   return 0;
}

int SectorFS::create(const char* path, mode_t, struct fuse_file_info* info)
{
   SectorFile* f = g_SectorClient.createSectorFile();
   int r = f->open(path, SF_MODE::WRITE);
   if (r < 0)
      return translateErr(r);
   f->close();
   g_SectorClient.releaseSectorFile(f);

   return open(path, info);
}

int SectorFS::truncate(const char *, off_t)
{
   return 0;
}

int SectorFS::ftruncate(const char* path, off_t offset, struct fuse_file_info *)
{
   return truncate(path, offset);
}

int SectorFS::open(const char* path, struct fuse_file_info* fi)
{
   pthread_mutex_lock(&m_OpenFileLock);
   map<string, FileTracker*>::iterator i = m_mOpenFileList.find(path);
   if (i != m_mOpenFileList.end())
   {
      i->second->m_iCount ++;
      pthread_mutex_unlock(&m_OpenFileLock);
      return 0;
   }

   SectorFile* f = g_SectorClient.createSectorFile();

   int permission = SF_MODE::READ;
   if (fi->flags & O_WRONLY)
      permission = SF_MODE::WRITE;
   else if (fi->flags & O_RDWR)
      permission = SF_MODE::READ | SF_MODE::WRITE;

   int r = f->open(path, permission);
   if (r < 0)
   {
      g_SectorClient.releaseSectorFile(f);
      pthread_mutex_unlock(&m_OpenFileLock);
      return translateErr(r);
   }

   FileTracker* t = new FileTracker;
   t->m_strName = path;
   t->m_iCount = 1;
   t->m_pHandle = f;

   m_mOpenFileList[path] = t;

   pthread_mutex_unlock(&m_OpenFileLock);
   return 0;
}

int SectorFS::read(const char* path, char* buf, size_t size, off_t offset, struct fuse_file_info* info)
{
   pthread_mutex_lock(&m_OpenFileLock);
   map<string, FileTracker*>::iterator t = m_mOpenFileList.find(path);
   if (t == m_mOpenFileList.end())
   {
      pthread_mutex_unlock(&m_OpenFileLock);
      return -EBADF;
   }
   SectorFile* h = t->second->m_pHandle;
   pthread_mutex_unlock(&m_OpenFileLock);

   // FUSE read buffer is too small; we use prefetch buffer to improve read performance
   int r = h->read(buf, offset, size, g_SectorConfig.m_ClientConf.m_iFuseReadAheadBlock);
   if (r == 0)
      r = h->read(buf, offset, size, g_SectorConfig.m_ClientConf.m_iFuseReadAheadBlock);

   return r;
}

int SectorFS::write(const char* path, const char* buf, size_t size, off_t offset, struct fuse_file_info* info)
{
   pthread_mutex_lock(&m_OpenFileLock);
   map<string, FileTracker*>::iterator t = m_mOpenFileList.find(path);
   if (t == m_mOpenFileList.end())
   {
      pthread_mutex_unlock(&m_OpenFileLock);
      return -EBADF;
   }
   SectorFile* h = t->second->m_pHandle;
   pthread_mutex_unlock(&m_OpenFileLock);

   return h->write(buf, offset, size);
}

int SectorFS::flush (const char *, struct fuse_file_info *)
{
   return 0;
}

int SectorFS::fsync(const char *, int, struct fuse_file_info *)
{
   return 0;
}

int SectorFS::release(const char* path, struct fuse_file_info* info)
{
   pthread_mutex_lock(&m_OpenFileLock);
   map<string, FileTracker*>::iterator t = m_mOpenFileList.find(path);
   if (t == m_mOpenFileList.end())
   {
      pthread_mutex_unlock(&m_OpenFileLock);
      return -EBADF;
   }

   t->second->m_iCount --;

   if (t->second->m_iCount > 0)
   {
      pthread_mutex_unlock(&m_OpenFileLock);
      return 0;
   }

   t->second->m_pHandle->close();
   g_SectorClient.releaseSectorFile(t->second->m_pHandle);
   delete t->second;
   m_mOpenFileList.erase(t);

   pthread_mutex_unlock(&m_OpenFileLock);
   return 0;
}

int SectorFS::access(const char *, int)
{
   return 0;
}

int SectorFS::lock(const char *, struct fuse_file_info *, int cmd, struct flock *)
{
   return 0;
}

int SectorFS::translateErr(int sferr)
{
   switch (sferr)
   {
   case SectorError::E_PERMISSION:
      return -EACCES;

   case SectorError::E_NOEXIST:
      return -ENOENT;

   case SectorError::E_EXIST:
      return -EEXIST;
   }

   return -1;
}


text:
package com.programmerr47.whitecodetesttask.api.requests.requestParams;

import com.programmerr47.whitecodetesttask.api.accessoryEnums.DisplayType;
import com.programmerr47.whitecodetesttask.api.accessoryEnums.Permissions;

import java.util.List;

/**
 * Class that represents params for authorization url
 *
 * @author Michael Spitsin
 * @since 2014-08-21
 */
public class AuthorizationParams implements RequestParams {
    private static final String CLIENT_ID_PARAM_NAME = "client_id";
    private static final String SCOPE_PARAM_NAME = "scope";
    private static final String REDIRECT_URI_PARAM_NAME = "redirect_uri";
    private static final String DISPLAY_PARAM_NAME = "display";
    private static final String VERSION_PARAM_NAME = "v";
    private static final String RESPONSE_TYPE_PARAM_NAME = "response_type";
    private static final String REVOKE_PARAM_NAME = "revoke";

    private String appId;
    private List<Permissions> permissions;
    private String redirectUrl;
    private DisplayType displayType;
    private String apiVersion;
    private String responseType = "token";
    private String revoke;

    private AuthorizationParams(Builder builder) {
        this.appId = builder.appId;
        this.permissions = builder.permissions;
        this.redirectUrl = builder.redirectUrl;
        this.displayType = builder.displayType;
        this.apiVersion = builder.apiVersion;
        this.revoke = builder.revoke;
    }

    @Override
    public String getQuery() {
        StringBuilder result = new StringBuilder();

        ParamUtils.addParameterIfNeed(result, CLIENT_ID_PARAM_NAME, appId);
        ParamUtils.addCollectionParametersIfNeed(result, SCOPE_PARAM_NAME, permissions);
        ParamUtils.addParameterIfNeed(result, REDIRECT_URI_PARAM_NAME, redirectUrl);
        ParamUtils.addParameterIfNeed(result, DISPLAY_PARAM_NAME, displayType);
        ParamUtils.addParameterIfNeed(result, VERSION_PARAM_NAME, apiVersion);
        ParamUtils.addParameterIfNeed(result, RESPONSE_TYPE_PARAM_NAME, responseType);
        ParamUtils.addParameterIfNeed(result, REVOKE_PARAM_NAME, revoke);

        return ParamUtils.removeFirstCharacterIfDelimiter(result.toString());
    }

    @Override
    public String toString() {
        return getQuery();
    }

    public static class Builder {
        private String appId;
        private List<Permissions> permissions;
        private String redirectUrl;
        private DisplayType displayType;
        private String apiVersion;
        private String revoke;

        public Builder setAppId(String appId) {
            this.appId = appId;
            return this;
        }

        public Builder setPermissions(List<Permissions> permissions) {
            this.permissions = permissions;
            return this;
        }

        public Builder setRedirectUrl(String redirectUrl) {
            this.redirectUrl = redirectUrl;
            return this;
        }

        public Builder setDisplayType(DisplayType displayType) {
            this.displayType = displayType;
            return this;
        }

        public Builder setApiVersion(String apiVersion) {
            this.apiVersion = apiVersion;
            return this;
        }

        public Builder setRevoke(String revoke) {
            this.revoke = revoke;
            return this;
        }

        public AuthorizationParams build() {
            return new AuthorizationParams(this);
        }
    }
}


text:
/*
 * This application is used by the various plugin test-scripts as a framework
 * for testing the various plugins.
 */

#include <config.h>

#include <stdlib.h>

#include <stdio.h>

#include <fcntl.h>

#include <sys/types.h>
#include <unistd.h>

#include <zmq.h>

#include <time.h>

#include <libguardian/libguardian.h>

#ifndef PLUGINDIR
#define PLUGINDIR "../../plugins"
#endif

#ifndef PLUGINSUBDIR
#define PLUGINSUBDIR ".libs/"
#endif

#define BUFFER_SIZE 1024

int
main (int argc, char **argv)
{
    GuardianPlugin *plugin;
    char *plugin_path = malloc (200);
    GuardianError *error = NULL;

    char buffer[BUFFER_SIZE];

    if (argc < 2)
    {
        fprintf (stderr, "No plugin-name provided\n");
        return 1;
    }

    read (stdin, buffer, BUFFER_SIZE);

    sprintf (plugin_path, "%s/%s/%s%s.so", PLUGINDIR, argv[1], PLUGINSUBDIR, argv[1]);

    int fd = open(plugin_path, O_RDONLY);
    if (fd == -1) {
        fprintf(stderr, "Open Failed");
    }

    fprintf(stderr, "Loading plugin: %s\n", plugin_path);

    plugin = guardian_plugin_load ( plugin_path, &error );
    if (plugin)
    {
        fprintf(stderr, "Plugin %s Loaded\n", argv[1]);
    }
    else
    {
        fprintf(stderr, "%s\n", guardian_error_get_msg (error));
        exit(1);
    }

    exit(0);
}


text:
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Venture.Users.Data
{
    public class UsersContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>
    {
        public UsersContext(DbContextOptions<UsersContext> options)
            : base(options)
        { }
    }
}


text:
#region Licence

#endregion

using System;

namespace WmcSoft.Business
{
    public interface IUniqueIdentifier<T> where T : IEquatable<T>
    {
        T Id { get; }
    }
}


text:
<?php

namespace WebinoAppLib\Application;

/**
 * Class ConfiguredApplication
 */
final class ConfiguredApplication extends AbstractConfiguredApplication
{

}


text:
package org.apache.camel.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

public class HashMapHeadersMapFactoryRouteTest extends ContextTestSupport {

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext context = super.createCamelContext();
        context.setHeadersMapFactory(new HashMapHeadersMapFactory());
        return context;
    }

    @Test
    public void testHashMapHeaders() throws Exception {
        getMockEndpoint("mock:result").expectedHeaderReceived("foo", 123);
        getMockEndpoint("mock:result").expectedHeaderReceived("FOO", 456);
        getMockEndpoint("mock:result").expectedHeaderReceived("Bar", "yes");

        Map<String, Object> headers = new HashMap<>();
        headers.put("foo", 123);
        headers.put("FOO", 456);
        headers.put("Bar", "yes");

        template.sendBodyAndHeaders("direct:start", "Hello World", headers);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .to("mock:result");
            }
        };
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.07 at 08:01:35 PM IST
//

package com.mozu.qbintegration.model.qbmodel.allgen;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="BarCodeValue" minOccurs="0">
 *           <simpleType>
 *             <restriction base="{}STRTYPE">
 *               <maxLength value="50"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *         <element ref="{}AssignEvenIfUsed" minOccurs="0"/>
 *         <element ref="{}AllowOverride" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "barCodeValue",
    "assignEvenIfUsed",
    "allowOverride"
})
@XmlRootElement(name = "BarCode")
public class BarCode {

    @XmlElement(name = "BarCodeValue")
    protected String barCodeValue;
    @XmlElement(name = "AssignEvenIfUsed")
    protected String assignEvenIfUsed;
    @XmlElement(name = "AllowOverride")
    protected String allowOverride;

    /**
     * Gets the value of the barCodeValue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBarCodeValue() {
        return barCodeValue;
    }

    /**
     * Sets the value of the barCodeValue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBarCodeValue(String value) {
        this.barCodeValue = value;
    }

    /**
     * Gets the value of the assignEvenIfUsed property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAssignEvenIfUsed() {
        return assignEvenIfUsed;
    }

    /**
     * Sets the value of the assignEvenIfUsed property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAssignEvenIfUsed(String value) {
        this.assignEvenIfUsed = value;
    }

    /**
     * Gets the value of the allowOverride property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAllowOverride() {
        return allowOverride;
    }

    /**
     * Sets the value of the allowOverride property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAllowOverride(String value) {
        this.allowOverride = value;
    }

}


text:
"""
Placeholder.
"""
import click
import sys
from riscyas.instruction.utils.parse import AS_Parser

@click.command()
@click.argument('infile', type=click.File('r'))
@click.argument('outfile', type=click.File('wb'), nargs=-1)
@click.option('--text', is_flag=True, default=False)
def cli(infile, outfile, text):
    if not outfile:
        outfile = sys.stdout
    else:
        outfile = outfile[0]
    asssemble(infile, outfile, textmode=text)

def asssemble(instream, out_bytestream, textmode):
    for instruction in AS_Parser(instream):
        if textmode:
            out_bytestream.write(str([hex(c) for c in instruction]) + '\n')
        else:
            out_bytestream.write(instruction)


text:
package com.javarush.test.level19.lesson03.task02;

/* Адаптер
Используйте класс AdapterFileOutputStream, чтобы адаптировать FileOutputStream к новому интерфейсу AmigoStringWriter
*/

import java.io.FileOutputStream;
import java.io.IOException;

public class AdapterFileOutputStream implements AmigoStringWriter
{
    FileOutputStream fileOutputStream;

    public AdapterFileOutputStream(FileOutputStream fileOutputStream)
    {
        this.fileOutputStream = fileOutputStream;
    }

    @Override
    public void flush() throws IOException
    {
        this.fileOutputStream.flush();
    }

    @Override
    public void writeString(String s) throws IOException
    {
        byte[] StringToBytes = s.getBytes();
        this.fileOutputStream.write(StringToBytes);
    }

    @Override
    public void close() throws IOException
    {
        this.fileOutputStream.close();
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NgxPaginationModule } from 'ngx-pagination';
import { ModalModule } from 'ngx-bootstrap';
import { LogoComponent } from './logo.component';

describe('HelpComponent', () => {
  let component: LogoComponent;
  let fixture: ComponentFixture<LogoComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        LogoComponent
      ],
      imports: [
        NgxPaginationModule,
        ModalModule.forRoot()
      ],
      providers: [
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LogoComponent);
    component = fixture.componentInstance;
  });

  it('should be created', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

});


text:
<?php

use App\Models\Email;

class EmailController extends \Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        // Get all the emails.
        $applicant_emails = Email::where('recipient', '=', 'applicant')->get()->toArray();
        $recommender_emails = Email::where('recipient', '=', 'recommender')->get()->toArray();
        $group_emails = Email::where('recipient', '=', 'group')->get()->toArray();

        return view('admin.settings.emails.edit')->with(compact('applicant_emails', 'recommender_emails', 'group_emails'));
    }

    public function update()
    {
        $input = Input::all();
        foreach ($input as $key => $field) {
            if ($key != '_token') {
                $email = Email::whereId($field['id'])->firstOrFail();
                $email->subject = $field['subject'];
                $email->body = $field['body'];
                $email->save();
            }
        }

        return redirect()->route('emails')->with('flash_message', ['text' => 'Success: Email settings have been saved!', 'class' => 'alert-success']);
    }

    public function testEmail()
    {
        return view('admin.settings.emails.test');
    }

    public function sendTestEmail()
    {
        // Build and send email
        $input = Input::all();
        $email = Email::firstOrCreate([
            'key' => 'test',
            'recipient' => 'test',
        ]);

        $email->fill(['subject' => $input['subject'], 'body' => $input['body']]);
        $email->save();
        $email->sendEmail($email->key, $email->recipient, $input['recipient']);

        return redirect()->route('emails.test')->with('flash_message', ['text' => 'Success: Test email has been sent!', 'class' => 'alert-success']);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TRL.Common.Models;
using TRL.Common.Data;
using TRL.Common;

namespace TRL.Configuration
{
    public class BarSettingsFactory:IGenericFactory<BarSettings>
    {
        private StrategyHeader strategyHeader;
        private string prefix;

        private BarSettingsFactory() { }

        public BarSettingsFactory(StrategyHeader strategyHeader, string prefix)
        {
            this.strategyHeader = strategyHeader;
            this.prefix = prefix;
        }

        public BarSettings Make()
        {
            try
            {
                return new BarSettings(this.strategyHeader,
                    AppSettings.GetStringValue(String.Concat(this.prefix, "_BarSettings_Symbol")),
                    AppSettings.GetValue<int>(String.Concat(this.prefix, "_BarSettings_Interval")),
                    AppSettings.GetValue<int>(String.Concat(this.prefix, "_BarSettings_Period")));
            }
            catch
            {
                return null;
            }
        }
    }
}


text:
module Overcover

  class GitReporter

    class << self

      def on_hook(sample = false)
        # find files changed in the last 5 days
        git_log = `git log --pretty="format:" -1 --name-only`
        files = git_log.split("\n")
        files.uniq!

        # check they still exist
        files.reject! { |f| !File.exists?(f) }
        files.reject! { |f| f.empty? }

        files.map! { |f| './' + f }

        changed_specs = files.select { |f| f =~ /_spec.rb/ }

        # filter out the ones that we actually care about
        touched_files = files.select { |f| Overcover::RspecCollector.should_analyse?(f) }

        reporter = Overcover::Reporter.new
        specs = []
        touched_files.each do |f|
          covering = reporter.specs_for(f)
          if covering.nil?
            $stderr.puts "WARNING: No specs have been recorded covering #{f}"
          end
          if sample
            specs << covering.shuffle.take(3) unless covering.nil?
          else
            specs << covering
          end
        end
        specs = specs.flatten.uniq

        on_hook = (specs + changed_specs).flatten.uniq

        $stderr.puts "Sampling: this will choose 3 specs for each changed file"
        $stderr.puts "Changed files: #{files.count}"
        $stderr.puts "    changed specs: #{changed_specs.count}"
        $stderr.puts "    changed files: #{touched_files.count}"
        $stderr.puts "    covered by: #{specs.count} specs"
        $stderr.puts "    will run: #{on_hook.count} specs"

        on_hook.each do |f|
          puts f
        end

      end

    end

  end

end


text:
<?php

class Ess_M2ePro_Model_Ebay_Template_OtherCategory_SnapshotBuilder
    extends Ess_M2ePro_Model_Template_SnapshotBuilder_Abstract
{
    //########################################

    public function getSnapshot()
    {
        $data = $this->_model->getData();

        foreach ($data as &$value) {
            $value !== null && !is_array($value) && $value = (string)$value;
        }

        return $data;
    }

    //########################################
}


text:
"""
Identities module widgets
"""

WIDGETS = {'widget_contact_me': {'title': 'My Contact Card',
                            'size': "95%"}}

def get_widgets(request):
    "Returns a set of all available widgets"

    return WIDGETS