text:
"use strict"
console.log = console.log;//to be reassigned later
var Calc = require("../calc/index.js").Calc;
var Calc = new Calc();
var Position = require("../position/index.js").Position;
Number.isInteger = Number.isInteger || function(value) {
	return typeof value === "number" &&
    isFinite(value) &&
    Math.floor(value) === value;
};
function Troop(isGround, typeName, PUAPDO, AIString, defense, attack, ID, weapon, game, health, userName, logger, chat) {
	this.game = game;
	this.typeName = typeName;
	this.logger = logger;
	this.chat = chat;
	this.isGround = isGround;
	this.ai = this.assignAI(AIString);
	this.shieldDirection;
	this.attack = attack;
	this.id = ID;
	this.weapon = weapon;
	this.weapon.owner = this;
	this.world = game.world;
	this.PUAPDO = PUAPDO;//Persistent User Accessible Player Dependant Object
	this.actionPoints = 0;//TODO might change this.
	this.safeLog = function(string){
		if(typeof string === "string"){
			this.logger.log(string);
		}else{
			throw new Error("Error. safeLog was not given a string as a parameter");
		}
	}.bind(this);
	this.safeChat = function(message,person){
		if(typeof person === "string" && game.players[person]){
			if(typeof message === "string"){
				this.game.players[person].chat.log(message);
			}else{
				throw new Error("Error. safeChat was not given a String as the first parameters");
			}
		}else{
			throw new Error("Error. safeChat was not given a String for the second parameter, or that person does not exist");
		}
	}.bind(this);
	this.safeMove = function(xTranslation, yTranslation){
		if (Number.isInteger(xTranslation) && Number.isInteger(yTranslation)) {
			var position = this.World.troopPosition(this.id);
			if((position.x + xTranslation >= 0 && position.x + xTranslation < World.map.xLength) && (position.y + yTranslation >= 0 && position.y + yTranslation < World.map.yLength)){
				this.move(xTranslation, yTranslation);
			}else{
				throw new Error("Error. safeMove was not given values in the correct range.");
			}
		} else {
			throw new Error("Error. safeMove was not given integers as parameters");
		}
	}.bind(this);
	this.safeMoveTo = function(xPosition,yPosition){
		if (Number.isInteger(xPosition) && Number.isInteger(yPosition)) {
			if((xPosition >= 0 && xPosition < World.xLength) && (yPosition >= 0 && yPosition < World.map.yLength)){
				this.moveTo(xPosition,yPosition);
			}else{
				throw new Error("Error. safeMoveTo was not given values in the correct range.");
			}
		}else{
			throw new Error("Error. safeMoveTo was not given integers as parameters");
		}
	}.bind(this);
	this.safeAttackAt = function(xAttack,yAttack){
		if (Number.isInteger(xAttack) && Number.isInteger(yAttack)) {
			if((xAttack >= 0 && xAttack < this.World.xLength) && (yAttack >= 0 && yAttack < this.World.map.yLength)){
				this.AttackAt();
			}else{
				throw new Error("Error. safeAttack was not given values in the correct range.");
			}
		}else{
			throw new Error("Error. safeAttackAt was not given integers as parameters");
		}
	}.bind(this);
	this.safeAttack = function(angleOfAttack){
		if(true/*(angleOfAttack) && (typeof angleOfAttack === "number")*/){
			this.attack(Calc.anglizer(angleOfAttack));
		}else{
			throw new Error("Error. safeAttack was not given a number as a parameter");
		}
	}.bind(this);
	this.safeDefend = function(isActive, direction){
		if(typeof isActive === "boolean" && (!direction || typeof direction === "number")){
			this.defend(isActive, Calc.anglizer(direction));
		}else{
			throw new Error("Error. safeDefend was not given a ");
		}
	}.bind(this);
	this.safeCoordIsValid = function(xCoord, yCoord){
		if(typeof xCoord === "number" && typeof yCoord === "number"){
			return this.coordIsValid(xCoord,yCoord);
		}
	}.bind(this);

}
//NOTE: the world will be asked to do the attacking, moving, and manage things like this
//TODO Figure out all necessary actions.
Troop.prototype.move = function(xTranslation,yTranslation){
	this.world.move(this.id,xTranslation,yTranslation);
}
Troop.prototype.assignAI = function(AIString){
	try{
		return new Function("troopClone,worldClone,log,chat,PUAPDO,move,moveTo,attack,defend,coordIsValid,actionExceedsLimit,input",AIString);
	}catch(err){//TODO
		this.logger.log("Error. assignAI could not create the function from the string provided.");
		return function(){}//so nothing breaks;
	}
}
Troop.prototype.moveTo = function(xPosition,yPosition){
	this.world.moveTo(this.id,xPosition,yPosition);
}
Troop.prototype.defend = function(isActive, direction){//direction is int 0-359
	if(isActive){this.shieldDirection = Calc.anglizer(direction);}
	else{this.shieldDirection = null;}
}
Troop.prototype.attack = function(direction){//direction is int 0-359
	this.world.attack(this.id,direction,this.weapon);
}
Troop.prototype.attackAt = function(xAttack,yAttack){
	this.world.attackAt(this.id,xAttack,yAttack,this.weapon);
}
Troop.prototype.takeTurn = function(userInput) {
	var blank = {};
	blank.ai = this.ai;//Make sure "this" points to a blank object, and not a useful one.
	blank.ai(this.clone(),this.world.clone(),this.safeLog,this.safeChat,this.PUAPDO,this.safeMove,this.safeMoveTo,this.safeAttack,this.safeAttackAt,this.safeDefend,this.safeCoordIsValid,this.safeActionExceedsLimit,userInput);
}
Troop.prototype.clone = function(world){//World is not required used if you don't want it to clone the world (avoid circular references)
  //var clonedTroop = new Troop()
  //clonedTroop.typeName = this.typeName;
  //clonedTroop.ai = this.ai;
  //clonedTroop.position = (this.position.clone || function(value) {
  //  return value
  //})(this.position);//just in case i decide to remove position cloning, or haven't made it yet etc.
  //TODO
}
Troop.prototype.coordIsValid = function(xCoordinate,yCoordinate){
	if(xCoordinate > 0 && yCoordinate > 0){
		if(xCoordinate < this.world.map.xLength && yCoordinate < this.world.map.yLength){
			return true;
		}
	}
	return false;
}
Troop.prototype.actionExceedsLimit = function(action){
	//Need to determine action "prices"
}
Troop.prototype.toString = function(){
	return this.typeName + " is at " + this.x + "," + this.y//+ this.x + "," + this.y;
}
exports.Troop = Troop;


text:
#ifndef IENTITYMANAGER_H
#define IENTITYMANAGER_H

#include "imodule.h"
#include "iutil.h"
#include "imath.h"

#include <iostream>
#include <map>
#include <vector>

using namespace std;

class IEntity {
private:
    float angle;
    long zIndex;
    unsigned long entIndex;
public:
    IEntity();
    ~IEntity();

    virtual void spawn();
    virtual void setOrigin( Vector2Df pos );
    virtual void setAngle( float angle );
    virtual void think();
    virtual void render();
    virtual void remove();
    bool operator== ( const IEntity& ent );
    const char *getClassName();
    unsigned long getEntIndex();

    virtual void setZIndex( long z );
    virtual long getZIndex() { return zIndex; };

    char internalClassName;
    Vector2Df origin;
};

typedef IEntity* EntityFactoryFn();

class IEntityManagerModule : public IModule {
public:
    typedef map<const char *, EntityFactoryFn *, cmp_str> FactoryMap;
    typedef vector<IEntity *> EntityMap;
    unsigned int index;
public:
    virtual void init( IModuleManager* modulemanager ) = 0;
    virtual void release() = 0;
    virtual void update() = 0;
    virtual void render() = 0;
    virtual void registerEntity( const char *classname, EntityFactoryFn *factory ) = 0;
    virtual IEntity *createEntity( const char *classname ) = 0;
    virtual void spawnEntity( IEntity *ent ) = 0;
    virtual void removeEntity( IEntity *ent ) = 0;
    virtual IEntity *findEntityByClass( const char *classname ) = 0;
    virtual EntityMap findEntitiesByClass( const char *classname ) = 0;
    virtual void sort() = 0;

};

extern IEntityManagerModule *entitymanager;

class EntityFactoryRegister {
public:
    EntityFactoryRegister( const char *classname, EntityFactoryFn *fn ) {
        entitymanager->registerEntity(classname, fn);
    }
};

#define REGISTER_CLASS( className, class )\
IEntity* __class__EntityFactory()\
{\
class *temp = new class;\
strcpy( &temp->internalClassName, #className );\
return (IEntity *)temp;\
}\
EntityFactoryRegister __class__( #className, &__class__EntityFactory );\

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.semagrow.geospatial.algebra.strdf;

import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.eclipse.rdf4j.query.algebra.evaluation.function.Function;
import org.eclipse.rdf4j.query.algebra.evaluation.function.geosparql.Intersection;
import org.semagrow.geospatial.vocabulary.STRDF;

public class StIntersection implements Function {

	@Override
    public String getURI() {
        return STRDF.intersection.toString();
    }

    @Override
    public Value evaluate(ValueFactory valueFactory, Value... values) throws ValueExprEvaluationException {
        return new Intersection().evaluate(valueFactory, values);
    }

}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.fkmsoft.libs.inputtextdialog">

    <application android:allowBackup="true"
>

    </application>

</manifest>


text:
name 'aws_cloudfront_plugin'
type 'plugin'
rs_ca_ver 20161221
short_description "Amazon Web Services - CloudFront"
long_description "Version: 1.0"
package "plugins/rs_aws_cloudfront"
import "sys_log"

plugin "rs_aws_cloudfront" do
  endpoint do
    default_scheme "https"
    path "/2017-10-30"
    request_content_type "application/xml"
  end

  # https://docs.aws.amazon.com/cloudfront/latest/APIReference/Welcome.html
  type "distribution" do
    href_templates "/distribution/{{//Distribution/Id}}"

    field "distribution_config" do
      alias_for "DistributionConfig"
      type "composite"
      required true
      location "body"
    end

    output "ActiveTrustedSigners","ARN","DistributionConfig","DomainName","Id","InProgressInvalidationBatches","LastModifiedTime","Status"

    # https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html
    action "create" do
      verb "POST"
      path "/distribution"
      output_path "//Distribution"
    end

    # hhttps://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DeleteDistribution.html
    action "destroy" do
      verb "DELETE"
      path "$href"

      field "if_match" do
        alias_for "If-Match"
        location "header"
      end
    end

    # https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetDistribution.html
    action "get" do
      verb "GET"
      path "$href"
      output_path "//Distribution"
    end

    action "show" do
      verb "GET"
      path "distribution/$id"
      output_path "//Distribution"

      field "id" do
        location "path"
      end
    end

    # https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_GetDistributionConfig.html
    action "get_config" do
      verb "GET"
      path "$href/config"
    end

    # https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListDistributions.html
    action "list" do
      verb "GET"
      path "/distribution"
      output_path "//DistributionList/Items/DistributionSummary/"
    end

    # https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html
    action "update" do
      verb "PUT"
      path "$href/config"
      output_path "//Distribution"

      field "if_match" do
        alias_for "If-Match"
        location "header"
      end
    end

    provision "provision_distribution"

    delete    "delete_distribution"
  end

end

resource_pool "cloudfront" do
  plugin $rs_aws_cloudfront
  host "cloudfront.amazonaws.com"
  auth "key", type: "aws" do
    version     4
    service    'cloudfront'
    region     'us-east-1'
    access_key cred('AWS_ACCESS_KEY_ID')
    secret_key cred('AWS_SECRET_ACCESS_KEY')
  end
end

define provision_distribution(@declaration) return @resource do
  sub on_error: stop_debugging() do
    call start_debugging()
    $object = to_object(@declaration)
    $fields = $object["fields"]
    call sys_log.detail("fields: "+to_s($fields))
    @operation = rs_aws_cloudfront.distribution.create($fields)
    $status = @operation.Status
    sub on_error: skip do
      while $status != "Deployed" do
        $status = @operation.Status
        sleep(10)
      end
    end
    @resource = @operation.get()
    call stop_debugging()
  end
end

define delete_distribution(@declaration) do
#  call start_debugging()
#  sub on_error: stop_debugging() do
#    # Get Config
#    $id = @declaration.Id
#    call get_config($id) retrieve $config1,$etag1

    # EDIT: Update entire hash
#    $config1["Enabled"] = "false"
#    @declaration.update(if_match: $etag1, distribution_config: $config1)
#    $status = @my_distribution.Status
#    while $status != "Deployed" do
#      $status = @my_distribution.Status
#      sleep(10)
#    end

    # Delete
#    call get_config($id) retrieve $config2,$etag2
#    @declaration.destroy(if_match: $etag2)
#  end
#  call stop_debugging()
end

define get_config($distribution_id) return $config,$etag do
  call rs_aws_cloudfront.start_debugging()
  sub on_error: rs_aws_cloudfront.stop_debugging() do
    $response = http_get(
      url: 'https://cloudfront.amazonaws.com/2017-10-30/distribution/'+$distribution_id+"/config",
      signature: { type: "aws" }
    )
    $etag = $response["headers"]["Etag"]
    call sys_log.detail("ETAG: "+ to_s($etag))
    $config = $response["body"]["Distribution"]
  end
  call rs_aws_cloudfront.stop_debugging()
end

define start_debugging() do
  if $$debugging == false || logic_and($$debugging != false, $$debugging != true)
    initiate_debug_report()
    $$debugging = true
  end
end

define stop_debugging() do
  if $$debugging == true
    $debug_report = complete_debug_report()
    call sys_log.detail($debug_report)
    $$debugging = false
  end
end


text:
import { ComponentClass, StatelessComponent } from "react";

export type ComponentConstructor<P> = ComponentClass<P> | StatelessComponent<P>;

export interface IContainerModule<T> {
    [id: string]: T;
}


text:
package com.rollsoftware.br.lfms.db.impl.service;

import com.rollsoftware.br.common.db.entity.ObjectInterface;
import com.rollsoftware.br.common.db.service.AbstractServiceFacade;
import com.rollsoftware.br.common.db.service.ServiceFacade;
import com.rollsoftware.br.common.db.service.ServiceFacadeTest;
import com.rollsoftware.br.lfms.db.impl.entity.Investor;
import com.rollsoftware.br.lfms.db.impl.repo.InvestorRepository;
import com.rollsoftware.br.test.util.EntityManagerInterface;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

/**
 *
 * @author Rogério
 * @date October, 2017
 */
public class InvestorServiceTest extends ServiceFacadeTest {

    private AbstractServiceFacade rest;

    private ObjectInterface.ObjectDataInterfacePK entityPK;
    private ObjectInterface entity;

    public InvestorServiceTest(EntityManagerInterface emInterface) {
        super(emInterface);
    }

    @Override
    public AbstractServiceFacade getInstance() {
        return rest;
    }

    @Override
    public AbstractServiceFacade getNewInstance(EntityManager em) {
        return createServiceFacade(em);
    }

    @Override
    public <ODPK extends ObjectInterface.ObjectDataInterfacePK>
            ODPK getEntityPK() {
        return (ODPK) entityPK;
    }

    @Override
    public <ODPK extends ObjectInterface.ObjectDataInterfacePK>
            ODPK getEntityPK_NotFound() {
        return (ODPK) new Investor.ObjectDataPK("", "");
    }

    @Override
    public <T extends ObjectInterface> Class<T> getEntityClass() {
        return (Class<T>) Investor.class;
    }

    protected <T extends ServiceFacade>
            T createServiceFacade() {
        return createServiceFacade(
                new InvestorRepository(), getEntityManager());
    }

    protected <T extends ServiceFacade>
            T createServiceFacade(EntityManager em) {
        return createServiceFacade(
                new InvestorRepository(), em);
    }

    protected <T extends ServiceFacade>
            T createServiceFacade(
                    InvestorRepository repo, EntityManager em) {
        return (T) new InvestorService(repo, em);
    }

    @Override
    public <T extends ObjectInterface> T getEntity() {
        return (T) entity;
    }

    @Override
    public <T extends ObjectInterface> T createEntity() {
        Investor investor = new Investor();

        investor.setUUID("uuid" + Math.random());

        investor.setName("name" + Math.random());

        investor.generateUUID();

        return (T) investor;
    }

    @BeforeClass
    public static void setUpClass() {
        ServiceFacadeTest.setUpClass();
    }

    @AfterClass
    public static void tearDownClass() {
        ServiceFacadeTest.tearDownClass();
    }

    @Before
    @Override
    public void setUp() throws SQLException {
        try {
            super.setUp();
            entity = createEntity();

            save(entity);

            entityPK = entity.getODPK();

            rest = createServiceFacade();
        } catch (Throwable ex) {
            throw ex;
        }
    }

    @After
    @Override
    public void tearDown() throws SQLException {
        super.tearDown();
    }
}


text:
package com.mauriciotogneri.dry.compiler.runtime.variable;

import com.mauriciotogneri.dry.compiler.runtime.Context;
import com.mauriciotogneri.dry.compiler.runtime.Expression;
import com.mauriciotogneri.dry.compiler.runtime.constant.Constant;

public class VariableArray extends Variable
{
    private final Expression key;

    public VariableArray(String name, Expression key)
    {
        super(name);

        this.key = key;
    }

    public void set(Constant key, Constant constant, Context context)
    {
        context.set(this, key, constant);
    }

    @Override
    public Constant evaluate(Context context)
    {
        return context.get(this, key.evaluate(context));
    }
}


text:
<?php
/**
 * Description of PdfTest
 *
 * @author Menno Dekker <menno.dekker@erasmusmc.nl>
 */
class Gems_Pdf_PdfTest extends Gems_Test_TestAbstract {

    public function setUp() {
        parent::setUp();

        $settings         = new Zend_Config_Ini(GEMS_ROOT_DIR . '/configs/project.example.ini', APPLICATION_ENV);
        $settings         = $settings->toArray();
        $settings['salt'] = 'vadf2646fakjndkjn24656452vqk';
        $project          = new Gems_Project_ProjectSettings($settings);

        \Zend_Registry::set('project', $project);
    }

    public function testRender() {
        $pdf      = \Zend_Pdf::load(__DIR__ . '/MSWord.pdf');
        $expected = \Zend_Pdf::load(__DIR__ . '/MSWordExpected.pdf');
        $gemsPdf  = $this->loader->getPdf();

        // Start code to expose protected method
        $addTokenToDocument = function(\Zend_Pdf $pdf, $tokenId, $surveyId) {
            return $this->addTokenToDocument($pdf, $tokenId, $surveyId);
        };

        $testObject = $addTokenToDocument->bindTo($gemsPdf, $gemsPdf);
        // End code to expose protected method
        $testObject($pdf, "abcd-efgh", 1);

        // fix the date to prevent differences
        $pdf->properties['ModDate'] = 'D:' . str_replace(':', "'", date('YmdHisP', 1458048768)) . "'";

        // Uncomment to update the test pdf
        /*
          $stream = fopen(__DIR__ . '/MSWordExpected.pdf', 'w');
          $pdf->render(false, $stream);
          fclose($stream);
         */

        // This will trigger the warning in #812: Warning when printing a survey pdf that was created using Word
        // This warning will cause the test to fail
        $pdf->render();

        $this->assertEquals($expected->getMetadata(), $pdf->getMetadata());
        $this->assertEquals($expected->properties, $pdf->properties);
    }

}


text:
using System;
using System.Collections;

namespace Nini.Util
{
	/// <include file='OrderedListEnumerator.xml' path='//Class[@name="OrderedListEnumerator"]/docs/*' />
	public class OrderedListEnumerator : IDictionaryEnumerator
	{
		#region Private variables
		int index = -1;
		ArrayList list;
		#endregion

		#region Constructors
		/// <summary>
		/// Instantiates an ordered list enumerator with an ArrayList.
		/// </summary>
		internal OrderedListEnumerator (ArrayList arrayList)
		{
			list = arrayList;
		}
		#endregion

		#region Public properties
		/// <include file='OrderedListEnumerator.xml' path='//Property[@name="Current"]/docs/*' />
		object IEnumerator.Current
		{
			get
			{
				if (index < 0 || index >= list.Count)
					throw new InvalidOperationException ();

				return list[index];
			}
		}

		/// <include file='OrderedListEnumerator.xml' path='//Property[@name="CurrentStrong"]/docs/*' />
		public DictionaryEntry Current
		{
			get
			{
				if (index < 0 || index >= list.Count)
					throw new InvalidOperationException ();

				return (DictionaryEntry)list[index];
			}
		}

		/// <include file='OrderedListEnumerator.xml' path='//Property[@name="Entry"]/docs/*' />
		public DictionaryEntry Entry
		{
			get { return (DictionaryEntry) Current; }
		}

		/// <include file='OrderedListEnumerator.xml' path='//Property[@name="Key"]/docs/*' />
		public object Key
		{
			get { return Entry.Key; }
		}

		/// <include file='OrderedListEnumerator.xml' path='//Property[@name="Value"]/docs/*' />
		public object Value
		{
			get { return Entry.Value; }
		}
		#endregion

		#region Public methods
		/// <include file='OrderedListEnumerator.xml' path='//Method[@name="MoveNext"]/docs/*' />
		public bool MoveNext ()
		{
			index++;
			if (index >= list.Count)
				return false;

			return true;
		}

		/// <include file='OrderedListEnumerator.xml' path='//Method[@name="Reset"]/docs/*' />
		public void Reset ()
		{
			index = -1;
		}
		#endregion
	}
}


text:
using System;
using System.Windows;
using System.Windows.Media;

namespace Gold_Client.View.TabWindows
{
    public partial class AdminControl
    {

        public AdminControl()
        {
            InitializeComponent();
        }
        private void BackgroundRedSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateRectangleColors();
        }

        private void BackgroundGreenSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateRectangleColors();
        }

        private void BackgroundBlueSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateRectangleColors();
        }

        private void UpdateRectangleColors()
        {

            Color clr = Color.FromArgb(255, Convert.ToByte(RedSlider.Value),
                Convert.ToByte(GreenSlider.Value), Convert.ToByte(BlueSlider.Value));

            rectangle1.Fill = new SolidColorBrush(clr);
        }

        private void ForegroundRedSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateLaberColors();
        }

        private void ForegroundGreenSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateLaberColors();
        }

        private void ForegroundBlueSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateLaberColors();
        }

        private void UpdateLaberColors()
        {
            Color clr = Color.FromArgb(255, Convert.ToByte(ForegroundRedSlider.Value),
                Convert.ToByte(ForegroundGreenSlider.Value), Convert.ToByte(ForegroundBlueSlider.Value));

            label1.Foreground = new SolidColorBrush(clr);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}


text:
using System;

using Foundation;
using AppKit;

namespace MessageBusMac
{
	public partial class AppDelegate : NSApplicationDelegate
	{
		MainWindowController mainWindowController;

		public AppDelegate()
		{
		}

		public override void FinishedLaunching(NSObject notification)
		{
			mainWindowController = new MainWindowController();
			mainWindowController.Window.MakeKeyAndOrderFront(this);
		}
	}
}


text: A collection of small tools for Chrome.


text:
<!--sidebar [ngClass]="{'hidden': !menuState}"></sidebar-->
<div class="search-container" [ngClass]="{'has-sidebar': menuState, 'no-sidebar': !menuState}">
    <menu-bar (menuButton)="menuStateChange($event)" [searchView]="true" (searchTerm)="newSearch($event)"></menu-bar>
    <thumbnail-grid [fullscreen]="true" [searched]="true" [header]="'Search Results for ' + displayTerm" [catalog]="filteredCatalog" [route]="'/view'"></thumbnail-grid>
</div>


text:
package com.javarush.task.task10.task1017;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

/*
Безопасное извлечение из списка
*/

public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 20; i++) {
            int x = Integer.parseInt(reader.readLine());
            list.add(x);
        }

        System.out.println(safeGetElement(list, 5, 1));
        System.out.println(safeGetElement(list, 20, 7));
        System.out.println(safeGetElement(list, -5, 9));
    }

    public static int safeGetElement(ArrayList<Integer> list, int index, int defaultValue) {
        //напишите тут ваш код
        try {
            return list.get(index);
        }
        catch (IndexOutOfBoundsException e) {
            return defaultValue;
        }
    }

}


text:
package com.insightfullogic.slab.implementation;

import com.insightfullogic.slab.SlabOptions;

public class MemoryCalculation {

    public static long calculateAllocation(int numberOfObjects, int sizeInBytes, SlabOptions options) {
        long baseSize = calculateBaseSize(numberOfObjects, sizeInBytes);

        return realignSizeOrAddress(options, baseSize);
    }

    private static long realignSizeOrAddress(SlabOptions options, long baseSize) {
        if(!options.hasSlabAlignment()) {
            return baseSize;
        }

        long misalignment = calculateMisAlignment(options, baseSize);
        if (misalignment == 0)
            return baseSize;

        return calculateRealignedSize(options, baseSize, misalignment);
    }

    private static long calculateRealignedSize(SlabOptions options, long baseSize, long misalignment) {
        long overrun = options.getSlabAlignment() - misalignment;
        return baseSize + overrun;
    }

    private static long calculateMisAlignment(SlabOptions options, long baseSize) {
        return baseSize % options.getSlabAlignment();
    }

    private static long calculateBaseSize(int numberOfObjects, long sizeInBytes) {
        return sizeInBytes * numberOfObjects;
    }

    public static long calculateAddress(long allocatedAddress, SlabOptions options) {
        return realignSizeOrAddress(options, allocatedAddress);
//        if (!options.hasSlabAlignment())
//            return allocatedAddress;
//
//        int slabAlignment = options.getSlabAlignment();
//        long misalignment = allocatedAddress % slabAlignment;
//        if (misalignment == 0)
//            return allocatedAddress;
//
//        long overrun = slabAlignment - misalignment;
//        return allocatedAddress + overrun;
    }

}


text:
#pragma once
#include <GLFW\glfw3.h>

#define DEFAULT_TITLE "Doxel Engine"

class Window
{
public:
	/*
	Create a window object.
	Note: this call doesn't initialize the window, it only creates the object.
	*/
	Window();
	/*
	Destroy the window, call dipose() instead.
	*/
	~Window();
	/*
	Initialize the window.
	Input:
		- int width - the width of the desired window.
		- int height - the height of the desired window.
		- char* title - the title of the desired window. will be set to DEFAULT_TITLE if empty.
	*/
	void init(int width, int height, char* title = DEFAULT_TITLE);
	/*
	This Function will dispose the window.
	Note: this doesn't terminate glfw, remember to call glfwTerminate you are no longer in need of glfw.
	*/
	void dispose();
	/*
	This function updates the window.
	* swap the buffers.
	* poll events.
	*/
	void update();

	/*
	This function will set the window to close.
	*/
	void setWindowClose();
	/*
	This function will return true when the window needs to close
	*/
	bool shouldWindowClose();
	/*
	This function will return the aspect ratio of the screen.
	*/
	float getAspectRatio() { return (float)(m_width / m_height); }

	GLFWwindow *getGlfwWindow() { return m_window; }

	int getWidth() { return m_width; }
	int getHeight() { return m_height; }

private:
	GLFWwindow* m_window = nullptr;
	int m_width = 0, m_height = 0;
	char* m_title;

};


text:
ACCEPTED

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

#### Published in
Cuad. Bot. Canaria 17:21. 1973

#### Original name
null

### Remarks
null


text:
Java-Based-Spring-Configuration
===============================

Java Based Spring Configuration Hello World


text:
A simple service to parse the git log of an application to a readable changelog.

## Requirements
#### Mandatory Requirements
- [PHP](https://php.net) >= 5.6.4
- [Carbon](http://carbon.nesbot.com/) >= 1.18: Used to format the date of the git commits

#### Optional Requirements
- An existing [>= Laravel 5.3](https://laravel.com/docs/master/installation) project to use the global view variable `$gitVersion`

## Installation

1. To get started, install the Git ChangeLog service via the Composer package manager:

    ```bash
    composer require epicarrow/git-changelog
    ```

2. Optional: If you are using Laravel and you want to use the global view variable `$gitVersion` add the following entry to your providers array in `config/app.php`:

    ```php
    'providers' => [
       ...
       ...
       EpicArrow\GitChangeLog\Providers\GitChangeLogServiceProvider::class
    ]
    ```

## Documentation
### Services
The following services are currently available:

___

```php
EpicArrow\GitChangeLog\GitChangeLog::get([int $count = null])
```
Fetches the latest unique git commits. If two contiguous commits have the same commit message only one commit will be
retrieved.

**Parameters:**
- `$count` (_int_): The number of results to retrieve.

**Return Values:**

The retrieved commits as an `array` of `EpicArrow\GitChangeLog\Models\Commit`s.

___

```php
EpicArrow\GitChangeLog\GitChangeLog::version()
```
Gets the latest version of the git repository.

**Return Values:**

The retrieved latest version of the git repository as a `string` or `null` if no version exists.

___

### Global Variables
If you are using Laravel and you've registered the `GitChangeLogServiceProvider` within your `config/app.php` providers array
you can access the following variables from every blade view:
- `$gitVersion`: Corresponds to the service `EpicArrow\GitChangeLog\GitChangeLog::version()` and gets you the latest version of the git repository.

### The commit model `EpicArrow\GitChangeLog\Models\Commit`
When retrieving the latest git commit through this service you will get an `array` of `EpicArrow\GitChangeLog\Models\Commit`s. This model has the following properties:
- `$id`(_string_): The commit hash/id
- `$date`(_Carbon\Carbon_): The date of the commit
- `$message`(_string_): The commit message
- `$version`(_string|null_): The version (tag) the commit belongs to
- `$author`(_string_): The author of the commit
- `$email`(_string_): The author's email address of the commit
- `$merge`(_string|null_): The merge info of the commit


text: A bunch of simple 3ds homebrew app showcasing various graphical features of the 3ds.


text:
package com.snowplowanalytics.snowplow.tracker;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class Subject {

    private HashMap<String, String> standardPairs;

    public Subject() {
        standardPairs = new HashMap<String, String>();

        // Default Timezone
        TimeZone tz = Calendar.getInstance().getTimeZone();
        this.setTimezone(tz.getID());
    }

    public void setUserId(String userId) {
        this.standardPairs.put(Parameter.UID, userId);
    }

    public void setScreenResolution(int width, int height) {
        String res = Integer.toString(width) + "x" + Integer.toString(height);
        this.standardPairs.put(Parameter.RESOLUTION, res);
    }

    public void setViewPort(int width, int height) {
        String res = Integer.toString(width) + "x" + Integer.toString(height);
        this.standardPairs.put(Parameter.VIEWPORT, res);
    }

    public void setColorDepth(int depth) {
        this.standardPairs.put(Parameter.COLOR_DEPTH, Integer.toString(depth));
    }

    public void setTimezone(String timezone) {
        this.standardPairs.put(Parameter.TIMEZONE, timezone);
    }

    public void setLanguage(String language) {
        this.standardPairs.put(Parameter.LANGUAGE, language);
    }

    public Map<String, String> getSubject() {
        return this.standardPairs;
    }
}


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\datecontrol\DateControl;

/**
 * @var yii\web\View $this
 * @var common\models\AccountSopLookup $model
 * @var yii\widgets\ActiveForm $form
 */
?>

<div class="account-sop-lookup-form">

    <?php $form = ActiveForm::begin(['type'=>ActiveForm::TYPE_HORIZONTAL]); echo Form::widget([

    'model' => $model,
    'form' => $form,
    'columns' => 1,
    'attributes' => [

'created'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Created...']],

'account'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Account...', 'maxlength'=>50]],

'sop'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Sop...', 'maxlength'=>50]],

'contact'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Contact...', 'maxlength'=>50]],

'name'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Name...', 'maxlength'=>100]],

'street'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Street...', 'maxlength'=>200]],

'town'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Town...', 'maxlength'=>200]],

'city'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter City...', 'maxlength'=>200]],

'country'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Country...', 'maxlength'=>200]],

'postcode'=>['type'=> Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter Postcode...', 'maxlength'=>200]],

    ]

    ]);
    echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']);
    ActiveForm::end(); ?>

</div>


text:
            simple-a (form with ng-submit): {{message}}

            error: {{error}}

        {{username}}
        <form name="searchUser" ng-submit="search(username)">
            <input type="search" required placeholder="user to search" ng-model="username">
            <input type="submit" value="search">
        </form>

            git user: {{user.login}}


text:
import React from 'react';
import classNames from 'classnames';
import Link from './Link';

let ListItem = React.createClass({
    propTypes:{
        divider: React.PropTypes.bool,
        navigate: React.PropTypes.bool
    },

    getDefaultProps(){
        return {
            divider: false,
            navigate: false
        }
    },

    render(){
        let {divider, navigate, children, href, push, ...other} = this.props;
        let navigateClass = 'navigate-right';
        let itemClass = divider ? 'table-view-divider' : 'table-view-cell';

        return (
            <li
                {...other}
                className = {classNames(itemClass, this.props.className)}>
                { navigate || href || push ? <Link className={navigate ? navigateClass : ''} href={href} push={push}>{children}</Link> : children }
            </li>
        )
    }
});

export default ListItem;


text:
package services

import org.apache.commons.mail._
import play.api.Play.current
import models.domain.User

object EmailNotification {

	val smtpsHost = current.configuration.getString("smtps.host").getOrElse("none")
	val smtpsPort = current.configuration.getString("smtps.port").getOrElse("25")
	val smtpsPortInt = Integer.valueOf(smtpsPort).intValue
	val smtpsSsl = current.configuration.getBoolean("smtps.ssl").getOrElse(false)
	val smtpsEmail = current.configuration.getString("smtps.email").getOrElse("props@nurun.com")

	def send( fromEmails: List[String], toEmails: List[String], subject: String, content: String) {

		val email = new HtmlEmail()
		email.setHostName(smtpsHost)
		email.setSslSmtpPort(smtpsPort)
		email.setSmtpPort(smtpsPortInt)
		email.setSSLOnConnect(smtpsSsl)

		try {
			email.setFrom(smtpsEmail)
      toEmails foreach { toEmail =>
        email.addTo(toEmail)
      }
      fromEmails foreach { fromEmail =>
        email.addCc(fromEmail)
      }
			email.setSubject(subject)
			email.setHtmlMsg(content)
			email.send()
			println("Props sent from [" + fromEmails.mkString(", ") + "] to ["  + toEmails.mkString(", ") + "]")
		} catch {
			case e: Exception =>
        println("oops")
        throw e
		}
	}

	private def mailMessage(senders: String, url: String, recipient: User): String =
	   	s"Hi ${recipient.firstName}! Props to you! You have received Kudos from $senders. You can see it here."

  def sendNotification(card_id: Int) = {
    CardService.getCard(card_id) map { card =>
      val senders = card.senders.map(_.email)
      val appRoot = current.configuration.getString("appRoot").getOrElse("")
      card.recipients foreach { recipient =>
        val url = s"$appRoot/"
        val subject = s"Props to ${recipient.firstName} ${recipient.lastName}!"
        val message = mailMessage(senders.mkString(", "), url, recipient)
        println(s"$recipient: $message")
        EmailNotification.send(senders, List(recipient.email), subject, message)
      }
    }
  }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4016
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TABS_UserControls.usercontrols {

    public partial class contactus {

        /// <summary>
        /// txtFName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtFName;

        /// <summary>
        /// rfv1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfv1;

        /// <summary>
        /// txtLName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtLName;

        /// <summary>
        /// rfv2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfv2;

        /// <summary>
        /// txtEmail control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtEmail;

        /// <summary>
        /// rfv3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfv3;

        /// <summary>
        /// rev1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RegularExpressionValidator rev1;

        /// <summary>
        /// txtSchool control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtSchool;

        /// <summary>
        /// txtJob control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtJob;

        /// <summary>
        /// txtComment control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtComment;

        /// <summary>
        /// rfv6 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfv6;

        /// <summary>
        /// btnSubmit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnSubmit;
    }
}


text:
<TITLE>Review for Bogus (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Bogus (1996)

reviewed by
Scott Renshaw

                                  BOGUS
                       A film review by Scott Renshaw
                        Copyright 1996 Scott Renshaw

Starring:  Whoopi Goldberg, Gerard Depardieu, Haley Joel Osment.
Screenplay:  Alvin Sargent.
Director:  Norman Jewison.
Reviewed by Scott Renshaw.

     It is a frustrating thing to watch a high concept get in the way of a
perfectly good film.  In BOGUS, there is a scene in which the Jimmy
Stewart classic HARVEY is showing on a television, and the reference makes
you suspect that someone went into a pitch meeting to describe BOGUS as
"HARVEY, but you can see the rabbit...and he's Gerard Depardieu."  BOGUS
could have been -- and should have been -- a simple story of mutual need,
and there are plenty of reasons to believe it could have been a rather
good one.  Instead, poster-driven film-making has turned out yet another
promising but disappointing effort.

    BOGUS begins in Las Vegas, where 7-year-old Albert Franklin (Haley
Joel Osment) is living with his mother Lorraine (Nancy Travis), a circus
performer.  When Lorraine is killed in a car accident, Albert is left in
Lorraine's will to the care of her foster sister Harriet (Whoopi
Goldberg), whom she had not seen in many years.  Harriet, a serious-minded
businesswoman living in Newark, NJ, claims she doesn't "have a maternal
bone in (her) body," but she agrees to take Albert in when the only other
option is state care.  Still, Harriet has difficulty relating to the young
boy, who has chosen to relate instead to an imaginary friend who emerged
from a coloring book, a Frenchman called Bogus (Depardieu).

     There are a lot of things right with BOGUS, beginning with the
performances.  Whoopi Goldberg apparently decided to shake off a string of
one-note trash-talkers and turn in some of her best work in years; Harriet
is not the typical Whoopi wiseacre, although she still gets in a few
decent lines.  Instead, she is a woman dedicated to over-compensating for
a harsh childhood by becoming a more successful adult.  Shaggy-haired
Haley Joel Osment hovers just this side of precocity, doing surprisingly
little posing and emoting as the smart but lonely Albert, and he really
seems to work well with other actors.  The connection between Goldberg and
Osment develops slowly, but eventually it seems quite genuine.  And
Depardieu, who is genetically incapable of sleep-walking through a
performance, has the ideal comical demeanor for his role.

     That role, unfortunately, is the real problem with BOGUS, because
someone should have realized that its central conceit was a big mistake.
It is evident enough in the fact that Depardieu really has nothing to do
but strike an offended pose when someone doesn't believe in him or feed
Albert lines like a French TelePrompter.  Bogus is a prop, not a
character -- he is required strictly to smile benignly and to offer
advice which one would expect from a child psychologist rather than an
imaginary playmate.

     The more substantial issue from a structural standpoint is that
screenwriter Alvin Sargent never commits to whom this story is about, and
Bogus is the crutch which allows him to do it.  When Albert and Bogus are
conversing, BOGUS is about a boy in need of comfort, and that is _not_
what it should be about.  This is Harriet's story, and we should watch her
grow into an understanding of what her life is missing through her
attempts to understand what Albert's life is missing.  By attempting to
place those two stories on an equal footing, Sargent and director Norman
Jewison diminish both of them.  They also end up condescending both to
Harriet and to the audience, because we should no more be able to see
Bogus than we are able to see Harvey.  Harriet's doubts are given no
weight, and there is a strange lack of trust in the audience demonstrated
by the refusal to allow our imaginations -- which the story seems to value
so greatly -- do their work.

     I am certain that some viewers will find the more fanciful elements
in BOGUS enchanting.  These same viewers might also consider my
pooh-poohing of those elements so much humbuggery, but to do so is to
misunderstand my meaning.  BOGUS should be fanciful; it simply didn't need
to be obvious.  Imagine the story with a boy fond of magic, chatting with
an invisible friend instead of grieving, and the severe Harriet (whom we
see in a wonderful scene reacting so violently to a gathering of children
that she actually knocks several of them over) struggling to connect with
Albert by re-connecting with a childhood she feels she never had.  Imagine
more time spent establishing Harriet's workaholic character, and less time
spent on goofy scenes like Albert's defense of Bogus in his classroom.
BOGUS is far from a bad film -- Goldberg is too good, and there are some
solid laughs -- but there is a far more affecting film to be found
somewhere where a tale of redemption and imagination takes precedence over
how easy it will be to construct an advertising campaign.

     On the Renshaw scale of 0 to 10 Bogus journeys:  6.

                     Visit Scott Renshaw's MoviePage
                 http://www-leland.stanford.edu/~srenshaw
      Receive Scott Renshaw's pre-release reviews directly via email!
      Write to srenshaw@leland.stanford.edu for subscription details.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package xray

import (
	"time"

	"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"

	corecommon "github.com/jfrog/jfrog-cli-core/v2/common/commands"
	corecommondocs "github.com/jfrog/jfrog-cli-core/v2/docs/common"
	"github.com/jfrog/jfrog-cli-core/v2/xray/commands/curl"
	"github.com/jfrog/jfrog-cli-core/v2/xray/commands/offlineupdate"
	"github.com/jfrog/jfrog-cli/docs/common"
	auditgodocs "github.com/jfrog/jfrog-cli/docs/xray/auditgo"
	"github.com/jfrog/jfrog-cli/docs/xray/auditgradle"
	"github.com/jfrog/jfrog-cli/docs/xray/auditmvn"
	auditnpmdocs "github.com/jfrog/jfrog-cli/docs/xray/auditnpm"
	auditpipdocs "github.com/jfrog/jfrog-cli/docs/xray/auditpip"
	curldocs "github.com/jfrog/jfrog-cli/docs/xray/curl"
	offlineupdatedocs "github.com/jfrog/jfrog-cli/docs/xray/offlineupdate"
	scandocs "github.com/jfrog/jfrog-cli/docs/xray/scan"
	"github.com/jfrog/jfrog-cli/scan"
	"github.com/jfrog/jfrog-cli/utils/cliutils"
	"github.com/jfrog/jfrog-client-go/utils/errorutils"
	"github.com/urfave/cli"
)

const DateFormat = "2006-01-02"

func GetCommands() []cli.Command {
	return cliutils.GetSortedCommands(cli.CommandsByName{
		{
			Name:            "curl",
			Flags:           cliutils.GetCommandFlags(cliutils.XrCurl),
			Aliases:         []string{"cl"},
			Usage:           curldocs.GetDescription(),
			HelpName:        corecommondocs.CreateUsage("xr curl", curldocs.GetDescription(), curldocs.Usage),
			UsageText:       curldocs.GetArguments(),
			ArgsUsage:       common.CreateEnvVars(),
			BashComplete:    corecommondocs.CreateBashCompletionFunc(),
			SkipFlagParsing: true,
			Action:          curlCmd,
		},
		{
			Name:         "audit-mvn",
			Flags:        cliutils.GetCommandFlags(cliutils.AuditMvn),
			Aliases:      []string{"am"},
			Usage:        auditmvn.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr audit-mvn", auditmvn.GetDescription(), auditmvn.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return scan.AuditSpecificCmd(c, coreutils.Maven)
			},
		},
		{
			Name:         "audit-gradle",
			Flags:        cliutils.GetCommandFlags(cliutils.AuditGradle),
			Aliases:      []string{"ag"},
			Usage:        auditgradle.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr audit-gradle", auditgradle.GetDescription(), auditgradle.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return scan.AuditSpecificCmd(c, coreutils.Gradle)
			},
		},
		{
			Name:         "audit-npm",
			Flags:        cliutils.GetCommandFlags(cliutils.AuditNpm),
			Aliases:      []string{"an"},
			Usage:        auditnpmdocs.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr audit-npm", auditnpmdocs.GetDescription(), auditnpmdocs.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return scan.AuditSpecificCmd(c, coreutils.Npm)
			},
		},
		{
			Name:         "audit-go",
			Flags:        cliutils.GetCommandFlags(cliutils.AuditGo),
			Aliases:      []string{"ago"},
			Usage:        auditgodocs.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr audit-go", auditgodocs.GetDescription(), auditgodocs.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return scan.AuditSpecificCmd(c, coreutils.Go)
			},
		},
		{
			Name:         "audit-pip",
			Flags:        cliutils.GetCommandFlags(cliutils.AuditPip),
			Aliases:      []string{"ap"},
			Usage:        auditpipdocs.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr audit-pip", auditpipdocs.GetDescription(), auditpipdocs.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return scan.AuditSpecificCmd(c, coreutils.Pip)
			},
		},
		{
			Name:         "scan",
			Flags:        cliutils.GetCommandFlags(cliutils.XrScan),
			Aliases:      []string{"s"},
			Usage:        scandocs.GetDescription(),
			UsageText:    scandocs.GetArguments(),
			HelpName:     corecommondocs.CreateUsage("xr scan", scandocs.GetDescription(), scandocs.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action: func(c *cli.Context) error {
				return cliutils.RunCmdWithDeprecationWarning("scan", "xr", c, scan.ScanCmd)
			},
		},
		{
			Name:         "offline-update",
			Usage:        offlineupdatedocs.GetDescription(),
			HelpName:     corecommondocs.CreateUsage("xr offline-update", offlineupdatedocs.GetDescription(), offlineupdatedocs.Usage),
			ArgsUsage:    common.CreateEnvVars(),
			Flags:        cliutils.GetCommandFlags(cliutils.OfflineUpdate),
			Aliases:      []string{"ou"},
			BashComplete: corecommondocs.CreateBashCompletionFunc(),
			Action:       offlineUpdates,
		},
	})
}

func getOfflineUpdatesFlag(c *cli.Context) (flags *offlineupdate.OfflineUpdatesFlags, err error) {
	flags = new(offlineupdate.OfflineUpdatesFlags)
	flags.Version = c.String("version")
	flags.License = c.String("license-id")
	flags.Target = c.String("target")
	if len(flags.License) < 1 {
		return nil, errorutils.CheckErrorf("the --license-id option is mandatory")
	}
	flags.IsDBSyncV3 = c.Bool(cliutils.DBSyncV3)
	flags.IsDBSyncV3PeriodicUpdate = c.Bool(cliutils.PeriodicDBSyncV3)
	if flags.IsDBSyncV3 {
		return
	}
	if flags.IsDBSyncV3PeriodicUpdate {
		return nil, errorutils.CheckErrorf("the %s option is only valid with %s", cliutils.PeriodicDBSyncV3, cliutils.DBSyncV3)
	}
	from := c.String("from")
	to := c.String("to")
	if len(to) > 0 && len(from) < 1 {
		return nil, errorutils.CheckErrorf("the --from option is mandatory, when the --to option is sent")
	}
	if len(from) > 0 && len(to) < 1 {
		return nil, errorutils.CheckErrorf("the --to option is mandatory, when the --from option is sent")
	}
	if len(from) > 0 && len(to) > 0 {
		flags.From, err = dateToMilliseconds(from)
		err = errorutils.CheckError(err)
		if err != nil {
			return
		}
		flags.To, err = dateToMilliseconds(to)
		err = errorutils.CheckError(err)
	}
	return
}

func dateToMilliseconds(date string) (dateInMillisecond int64, err error) {
	t, err := time.Parse(DateFormat, date)
	if errorutils.CheckError(err) != nil {
		return
	}
	dateInMillisecond = t.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
	return
}

func offlineUpdates(c *cli.Context) error {
	offlineUpdateFlags, err := getOfflineUpdatesFlag(c)
	if err != nil {
		return err
	}

	return offlineupdate.OfflineUpdate(offlineUpdateFlags)
}

func curlCmd(c *cli.Context) error {
	if show, err := cliutils.ShowCmdHelpIfNeeded(c, c.Args()); show || err != nil {
		return err
	}
	if c.NArg() < 1 {
		return cliutils.WrongNumberOfArgumentsHandler(c)
	}
	xrCurlCmd, err := newXrCurlCommand(c)
	if err != nil {
		return err
	}
	return corecommon.Exec(xrCurlCmd)
}

func newXrCurlCommand(c *cli.Context) (*curl.XrCurlCommand, error) {
	curlCommand := corecommon.NewCurlCommand().SetArguments(cliutils.ExtractCommand(c))
	xrCurlCommand := curl.NewXrCurlCommand(*curlCommand)
	xrDetails, err := xrCurlCommand.GetServerDetails()
	if err != nil {
		return nil, err
	}
	if xrDetails.XrayUrl == "" {
		return nil, errorutils.CheckErrorf("No Xray servers configured. Use the 'jf c add' command to set the Xray server details.")
	}
	xrCurlCommand.SetServerDetails(xrDetails)
	xrCurlCommand.SetUrl(xrDetails.XrayUrl)
	return xrCurlCommand, err
}


text:
namespace base {

class Value;

}  // namespace base

namespace policy {

class PolicyBundle;
class Schema;

namespace android {

// Populates natives policies from Java key/value pairs. With its associated
// java classes, allows transforming Android |Bundle|s into |PolicyBundle|s.
class POLICY_EXPORT PolicyConverter {
 public:
  explicit PolicyConverter(const Schema* policy_schema);
  ~PolicyConverter();

  // Returns a policy bundle containing all policies collected since the last
  // call to this method.
  std::unique_ptr<PolicyBundle> GetPolicyBundle();

  base::android::ScopedJavaLocalRef<jobject> GetJavaObject();

  // To be called from Java:
  void SetPolicyBoolean(JNIEnv* env,
                        const base::android::JavaRef<jobject>& obj,
                        const base::android::JavaRef<jstring>& policyKey,
                        jboolean value);
  void SetPolicyInteger(JNIEnv* env,
                        const base::android::JavaRef<jobject>& obj,
                        const base::android::JavaRef<jstring>& policyKey,
                        jint value);
  void SetPolicyString(JNIEnv* env,
                       const base::android::JavaRef<jobject>& obj,
                       const base::android::JavaRef<jstring>& policyKey,
                       const base::android::JavaRef<jstring>& value);
  void SetPolicyStringArray(JNIEnv* env,
                            const base::android::JavaRef<jobject>& obj,
                            const base::android::JavaRef<jstring>& policyKey,
                            const base::android::JavaRef<jobjectArray>& value);

  // Converts the passed in value to the type desired by the schema. If the
  // value is not convertible, it is returned unchanged, so the policy system
  // can report the error.
  // Note that this method will only look at the type of the schema, not at any
  // additional restrictions, or the schema for value's items or properties in
  // the case of a list or dictionary value.
  // Public for testing.
  static base::Optional<base::Value> ConvertValueToSchema(base::Value value,
                                                          const Schema& schema);

  // Public for testing.
  static base::Value ConvertJavaStringArrayToListValue(
      JNIEnv* env,
      const base::android::JavaRef<jobjectArray>& array);

 private:
  const Schema* const policy_schema_;

  std::unique_ptr<PolicyBundle> policy_bundle_;

  base::android::ScopedJavaGlobalRef<jobject> java_obj_;

  void SetPolicyValue(const std::string& key, base::Value raw_value);

  DISALLOW_COPY_AND_ASSIGN(PolicyConverter);
};

}  // namespace android
}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_BROWSER_ANDROID_POLICY_CONVERTER_H


text:
#include "gtest.h"

#include <scraps/random.h>

using namespace scraps;

TEST(utility, UniformDistribution) {
    std::random_device rd;
    std::mt19937 gen(rd());
    {
        auto result = UniformDistribution(0, 17, gen);
        EXPECT_GE(result, 0);
        EXPECT_LE(result, 17);

        result = UniformDistribution(7, 7, gen);
        EXPECT_EQ(result, 7);
    }

    {
        auto result = UniformDistribution<int>(gen);
        EXPECT_LE(std::numeric_limits<int>::min(), result);
        EXPECT_LE(result, std::numeric_limits<int>::max());
    }

    {
        auto result = UniformDistribution(-7ms, 12ms, gen);
        EXPECT_GE(result, -7ms);
        EXPECT_LE(result, 12ms);

        result = UniformDistribution(7ms, 7ms, gen);
        EXPECT_EQ(result, 7ms);

        result = UniformDistribution(-7ms, 12s, gen);
        EXPECT_GE(result, -7ms);
        EXPECT_LE(result, 12s);
    }

    {
        auto result = UniformDistribution(1.0f, 123.456, gen);
        EXPECT_GE(result, 1.0);
        EXPECT_LE(result, 123.456);
    }

    {
        auto now = std::chrono::steady_clock::now();
        auto result = UniformDistribution(now, now + 10s, gen);
        EXPECT_GE(result, now);
        EXPECT_LE(result, now + 10s);
    }

    {
        auto result = UniformDistribution(1, 123.456, gen);
        EXPECT_GE(result, 1.0);
        EXPECT_LE(result, 123.456);
    }

    {
        auto result = UniformDistribution<int>(gen);
        EXPECT_GE(result, 0);
        EXPECT_LE(result, std::numeric_limits<int>::max());
    }

    {
        auto result = UniformDistribution<float>(gen);
        EXPECT_GE(result, 0);
        EXPECT_LE(result, 1);
    }
}

TEST(utility, RandomBytes) {
    std::random_device rd;
    std::mt19937 rng{rd()};
    const auto value = RandomBytes(32, rng);

    EXPECT_EQ(32, value.size());
}


text:
package com.palantir.atlasdb.versions;

import com.google.common.base.Suppliers;
import java.io.PrintStream;
import java.util.Optional;
import java.util.function.Supplier;

public final class AtlasDbVersion {
    public static final String REPORT_VERSION_PROPERTY = "atlasdb.report.version";
    public static final String REPORT_VERSION_DEFAULT = "false";
    public static final String VERSION_UNKNOWN_STRING = "VERSION UNKNOWN";

    private static volatile boolean versionPrinted = false;

    private static final Supplier<String> version = Suppliers.memoize(AtlasDbVersion::readVersion);

    private AtlasDbVersion() {
        // static class
    }

    public static String ensureVersionReported() {
        return ensureVersionReported(System.out);
    }

    public static String ensureVersionReported(PrintStream writer) {
        boolean shouldReportVersion =
                Boolean.parseBoolean(System.getProperty(REPORT_VERSION_PROPERTY, REPORT_VERSION_DEFAULT));
        if (!versionPrinted && shouldReportVersion) {
            writer.println("AtlasDB Version: " + version.get());
            versionPrinted = true;
        }
        return version.get();
    }

    public static String readVersion() {
        return Optional.ofNullable(AtlasDbVersion.class.getPackage().getImplementationVersion())
                .orElse(VERSION_UNKNOWN_STRING);
    }
}


text:
import { init } from '../htmlnano';
import safePreset from '../../lib/presets/safe';
import maxPreset from '../../lib/presets/max';

describe('removeComments', () => {
    context('safe (default)', () => {
        const options = {
            removeComments: safePreset.removeComments,
        };

        it('should remove HTML comments', () => {
            return init(
                '

 ',
                '

 ',
                options
            );
        });

        it('should not remove  and ', () => {
            return init(
                'this text will not be indexed',
                'this text will not be indexed',
                options
            );
        });

        it('should not remove  and ', () => {
            return init(
                'Bad visitors won\'t see my phone number, 555-555-5555',
                'Bad visitors won\'t see my phone number, 555-555-5555',
                options
            );
        });

        it('should not remove conditional comments ', () => {
            return init(
                '',
                '',
                options
            );
        });

        it('should not remove excerpt comments ', () => {
            return init(
                'Lorem ipsum dolor sit amet  consectetur adipiscing elit',
                'Lorem ipsum dolor sit amet  consectetur adipiscing elit',
                options
            );
        });
    });

    context('all', () => {
        const options = {
            removeComments: maxPreset.removeComments,
        };

        it('should remove  and ', () => {
            return init(
                'this text will not be indexed',
                'this text will not be indexed',
                options
            );
        });

        it('should remove  and ', () => {
            return init(
                'Bad visitors won\'t see my phone number, 555-555-5555',
                'Bad visitors won\'t see my phone number, 555-555-5555',
                options
            );
        });

        it('should remove conditional comments', () => {
            return init(
                '',
                '',
                options
            );
        });

        it('should remove excerpt comments ', () => {
            return init(
                'Lorem ipsum dolor sit amet  consectetur adipiscing elit',
                'Lorem ipsum dolor sit amet  consectetur adipiscing elit',
                options
            );
        });
    });
});


text:
namespace base {
class CancelableSyncSocket;
class ReadOnlySharedMemoryRegion;
}  // namespace base

namespace media {

class MEDIA_EXPORT AudioInputDelegate {
 public:
  // An AudioInputDelegate must not call back to its EventHandler in its
  // constructor.
  class MEDIA_EXPORT EventHandler {
   public:
    virtual ~EventHandler() = 0;

    // Called when the underlying stream is ready for recording.
    virtual void OnStreamCreated(
        int stream_id,
        base::ReadOnlySharedMemoryRegion shared_memory_region,
        std::unique_ptr<base::CancelableSyncSocket> socket,
        bool initially_muted) = 0;

    // Called if stream encounters an error and has become unusable.
    virtual void OnStreamError(int stream_id) = 0;
  };

  virtual ~AudioInputDelegate() = 0;

  virtual int GetStreamId() = 0;

  // Stream control:
  virtual void OnRecordStream() = 0;
  virtual void OnSetVolume(double volume) = 0;
  virtual void OnSetOutputDeviceForAec(
      const std::string& raw_output_device_id) = 0;
};

}  // namespace media

#endif  // MEDIA_AUDIO_AUDIO_INPUT_DELEGATE_H_


text:
module TsPath {
    export interface PathCommand { (context: CanvasRenderingContext2D): void; }
    interface CharacterChecker { (current: string): boolean; }
    interface CommandParser { (stream: TextStream): PathCommand[]; }

    enum FillRule {
        EvenOdd = 0,
        NonZero = 1
    }

    var _wsChars = [" ", "\t"];
    var _commandChars = ["M", "L", "C", "Q", "A", "Z"];

    class Point {
        private _xCoordinate: number;
        private _yCoordinate: number;

        get X(): number { return this._xCoordinate; }
        get Y(): number { return this._yCoordinate; }

        constructor(x: number, y: number) {
            this._xCoordinate = x;
            this._yCoordinate = y;
        }
    }

    class TextStream {
        private _char: string;
        private _source: string;
        private _position: number;

        get Current(): string { return this._char; }

        MoveNext() {
            this._char = (++this._position < this._source.length) ? this._source[this._position] : null;
            return (this._char !== null);
        }

        Reset() { this._char = this._source[this._position = 0]; }

        constructor(source: string) {
            this._source = source;
            this.Reset();
        }
    }

    module CommandFactory {
        export var createFillRuleCommand = (fillRule: FillRule): PathCommand =>
            (c => c.msFillRule = fillRule === FillRule.EvenOdd ? "evenodd" : "nonzero");

        export var createMoveToCommand = (p: Point): PathCommand =>
            (c => c.moveTo(p.X, p.Y));

        export var createLineToCommand = (p: Point): PathCommand =>
            (c => c.lineTo(p.X, p.Y));

        export var createCubicBezierCurveCommand = (cp1: Point, cp2: Point, ep: Point): PathCommand =>
            (c => c.bezierCurveTo(cp1.X, cp1.Y, cp2.X, cp2.Y, ep.X, ep.Y));

        export var createQuadraticBezierCurveCommand = (cp: Point, ep: Point): PathCommand =>
            (c => c.quadraticCurveTo(cp.X, cp.Y, ep.X, ep.Y));

        export var createEllipticalArcCommand = (center: Point, radius: number, startAngle: number, endAngle: number, counterClockwise: boolean): PathCommand =>
            (c => c.arc(center.X, center.Y, radius, startAngle, endAngle, counterClockwise));

        export var createClosePathCommand = (): PathCommand =>
            (c => c.closePath());
    }

    export module PathParser {
        var isCommandCharacter: CharacterChecker = current => _commandChars.indexOf(current) !== -1;
        var isWhitespaceCharacter: CharacterChecker = current => _wsChars.indexOf(current) !== -1;
        var isNegativeSign: CharacterChecker = current => current === "-";
        var isComma: CharacterChecker = current => current === ",";
        var isDecimal: CharacterChecker = current => current === ".";
        var isDigit: CharacterChecker = current => !isNaN(parseInt(current, 10));

        var skipWhitespace = (stream: TextStream) => {
            while (isWhitespaceCharacter(stream.Current) && stream.MoveNext()) { }
        };

        var skipComma = (stream: TextStream) => {
            if (isComma(stream.Current)) stream.MoveNext();
        };

        var skipArgumentSeparator = (stream: TextStream) => {
            skipWhitespace(stream);
            skipComma(stream);
            skipWhitespace(stream);
        };

        var readNumber = (stream: TextStream) => {
            var readNextDigits = (s: TextStream) => {
                var digits = "";
                while (isDigit(s.Current)) {
                    digits += s.Current;
                    s.MoveNext();
                }
                return digits;
            };

            var numStr = "";

            if (isNegativeSign(stream.Current)) {
                numStr += stream.Current;
                stream.MoveNext();
            }

            if (isDigit(stream.Current)) { numStr += readNextDigits(stream); }

            if (isDecimal(stream.Current)) {
                numStr += stream.Current;
                stream.MoveNext();

                if (isDigit(stream.Current)) {
                    numStr += readNextDigits(stream);

                    if (stream.Current === "E") {
                        numStr += stream.Current;
                        stream.MoveNext();
                        if (isNegativeSign(stream.Current)) {
                            numStr += stream.Current;
                            stream.MoveNext();
                        }

                        if (!isDigit(stream.Current)) throw "Invalid number";
                        numStr += readNextDigits(stream);
                    }
                }
            }

            return Number(numStr);
        }

        var readNumberAndSkipSeparator = (stream: TextStream) => {
            var num = readNumber(stream);
            skipArgumentSeparator(stream);

            return num;
        }

        var readNumberAndSkipWhitespace = (stream: TextStream) => {
            var num = readNumber(stream);
            skipWhitespace(stream);

            return num;
        }

        var readPoint = (stream: TextStream) => {
            var x = readNumberAndSkipSeparator(stream);
            var y = readNumber(stream);

            return new Point(x, y);
        }

        var readPointAndSkipSeparator = (stream: TextStream) => {
            var point = readPoint(stream);
            skipArgumentSeparator(stream);

            return point;
        }

        var readPointAndSkipWhitespace = (stream: TextStream) => {
            var point = readPoint(stream);
            skipWhitespace(stream);

            return point;
        }

        var parseFillStyleCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing fill style command";

            var resolveRule = (num: number) => {
                switch (num) {
                    case 0: return FillRule.EvenOdd;
                    case 1: return FillRule.NonZero;
                }

                throw "Invalid fill style option. Valid options are 0 (evenodd) and 1 (nonzero)";
            };

            var fillRule = resolveRule(readNumberAndSkipWhitespace(stream));

            return [CommandFactory.createFillRuleCommand(fillRule)];
        }

        var parseMoveToCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing move to command";
            skipWhitespace(stream);

            var p = readPointAndSkipWhitespace(stream);

            return [CommandFactory.createMoveToCommand(p)];
        }

        var parseLineToCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing line to command";
            skipWhitespace(stream);

            var commands: PathCommand[] = [];

            while (!isCommandCharacter(stream.Current) && stream.Current != null) {
                var p = readPointAndSkipWhitespace(stream);
                commands.push(CommandFactory.createLineToCommand(p));
            }

            return commands;
        }

        var parseCubicBezierCurveCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing line to command";
            skipWhitespace(stream);

            var commands: PathCommand[] = [];

            while (!isCommandCharacter(stream.Current) && stream.Current != null) {
                var cp1 = readPointAndSkipSeparator(stream);
                var cp2 = readPointAndSkipSeparator(stream);
                var ep = readPointAndSkipSeparator(stream);
                commands.push(CommandFactory.createCubicBezierCurveCommand(cp1, cp2, ep));
            }

            return commands;
        }

        var parseQuadraticBezierCurveCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing line to command";
            skipWhitespace(stream);

            var commands: PathCommand[] = [];

            while (!isCommandCharacter(stream.Current) && stream.Current != null) {
                var cp = readPointAndSkipSeparator(stream);
                var ep = readPointAndSkipSeparator(stream);

                commands.push(CommandFactory.createQuadraticBezierCurveCommand(cp, ep));
            }

            return commands;
        }

        var parseEllipticalArcCommand: CommandParser = stream => {
            if (!stream.MoveNext()) throw "Unexpected end of stream while parsing line to command";
            skipWhitespace(stream);

            var commands: PathCommand[] = [];

            while (!isCommandCharacter(stream.Current) && stream.Current != null) {
                var center = readPointAndSkipSeparator(stream);
                var radius = readNumberAndSkipSeparator(stream);
                var startAngle = readNumberAndSkipSeparator(stream);
                var endAngle = readNumberAndSkipSeparator(stream);
                var ccw = readNumberAndSkipSeparator(stream) === 1;
                commands.push(CommandFactory.createEllipticalArcCommand(center, radius, startAngle, endAngle, ccw));
            }

            return commands;
        }

        var parseClosePathCommand: CommandParser = stream => {
            stream.MoveNext();
            skipWhitespace(stream);

            return [CommandFactory.createClosePathCommand()];
        }

        var getCommandParser = ((commandMappings) => {
            return (command: string) => {
                var cmd = commandMappings[command];
                if (!cmd) throw "Invalid command";

                return cmd;
            }
        })({ "F": parseFillStyleCommand,
             "M": parseMoveToCommand,
             "L": parseLineToCommand,
             "C": parseCubicBezierCurveCommand,
             "Q": parseQuadraticBezierCurveCommand,
             "A": parseEllipticalArcCommand,
             "Z": parseClosePathCommand });

        var resolveCommand = (validCommands: string[], current: string) => {
            if (validCommands.indexOf(current) !== -1) return getCommandParser(current);

            throw "Invalid command";
        }

        export var Parse = (path: string): PathCommand[] => {
            if (path === null || path === "") return [];

            var resolveInitialCommand =
                ((commands: string[]) => current => resolveCommand(commands, current))(["F", "M"]);

            var resolveSecondaryCommand =
                ((commands: string[]) => current => resolveCommand(commands, current))(["M", "L", "C", "Q", "A", "Z"]);

            var stream = new TextStream(path.toUpperCase().trim());

            var commands = resolveInitialCommand(stream.Current)(stream);

            while (true) {
                commands = commands.concat(resolveSecondaryCommand(stream.Current)(stream));

                if (stream.Current != null && isCommandCharacter(stream.Current)) continue;
                if (!stream.MoveNext()) break;
            }

            return commands;
        }
    }
}

module CanvasHelper {
    var defaultOptions = {
        penColor: "black",
        fillRule: "evenodd",
        lineWidth: 1,
        xScale: 1,
        xTransform: 0,
        yScale: 1,
        yTransform: 0
    };

    export var clearCanvas = (canvas: HTMLCanvasElement) => {
        var context = canvas.getContext("2d");
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.clearRect(0, 0, canvas.width, canvas.height);
    }

    export var drawPath = (canvas: HTMLCanvasElement, pathText: string, options?: any) => {
        var context = canvas.getContext("2d");

        if (options) {
            context.lineWidth = options.strokeThickness || 1;
            context.strokeStyle = options.strokeStyle || defaultOptions.penColor;
            context.fillStyle = options.fillStyle || defaultOptions.penColor;
            context.scale(options.scaleX || defaultOptions.xScale, options.scaleY || defaultOptions.yScale);
            context.translate(options.translateX || defaultOptions.xTransform, options.translateY || defaultOptions.yTransform);
        } else {
            context.lineWidth = defaultOptions.lineWidth;
            context.strokeStyle = defaultOptions.penColor;
            context.fillStyle = defaultOptions.penColor;
        }

        context.beginPath();

        TsPath.PathParser.Parse(pathText).forEach(c => c(context));

        context.stroke();
        context.fill(context.msFillRule || defaultOptions.fillRule);
    }
}


text:
package net.xeger.ssh.launchers.windows;

import net.xeger.ssh.*;

import java.io.*;

public class PuTTY extends SimpleWindowsLauncher {
    private File _exe = null;

    public PuTTY(Launchpad l) {
        super(l);

        _exe = findProgramFile("PuTTY", "putty");

        if(_exe == null) {
            _exe = findExecutable("putty");
        }

        if( !isPlatform("Windows") || null == _exe ) {
            throw new RuntimeException("Wrong OS, or PuTTY not found in path.");
        }
    }

    public boolean canPublicKeyAuth() {
        return true;
    }

    public boolean canPasswordAuth() {
        return true;
    }

    public String getFriendlyName() {
        return "PuTTY";
    }

    public boolean supportsKeyFormat(KeyFormat format) {
        return (format == KeyFormat.PUTTY);
    }

    @Override
    public void run(String user, String host, File id)
        throws IOException
    {
        String[] cmd = {
            _exe.getCanonicalPath(),
            "-i",
            id.getCanonicalPath(),
            String.format("%s@%s", user, host)
        };

        getRuntime().exec(cmd);
    }

    public void run(String user, String host, String password)
        throws IOException
    {
        String[] cmd = {
            _exe.getCanonicalPath(),
            "-pw",
            password,
            String.format("%s@%s", user, host)
        };

        getRuntime().exec(cmd);
    }
}


text:
ALTER TABLE states DROP CONSTRAINT states_userid_pkgname_key_key;
ALTER TABLE states DROP COLUMN key;
ALTER TABLE states DROP COLUMN value;
ALTER TABLE states ADD COLUMN state jsonb;


text:
/*
 *    sha1.cpp
 *
 *    Copyright (C) 1998
 *    Paul E. Jones <paulej@arid.us>
 *    All Rights Reserved.
 *
 *****************************************************************************
 *    $Id: sha1.cpp,v 1.9 2004/03/27 18:02:20 paulej Exp $
 *****************************************************************************
 *
 *    Description:
 *         This class implements the Secure Hashing Standard as defined
 *         in FIPS PUB 180-1 published April 17, 1995.
 *
 *         The Secure Hashing Standard, which uses the Secure Hashing
 *         Algorithm (SHA), produces a 160-bit message digest for a
 *         given data stream.  In theory, it is highly improbable that
 *         two messages will produce the same message digest.  Therefore,
 *         this algorithm can serve as a means of providing a "fingerprint"
 *         for a message.
 *
 *    Portability Issues:
 *         SHA-1 is defined in terms of 32-bit "words".  This code was
 *         written with the expectation that the processor has at least
 *         a 32-bit machine word size.  If the machine word size is larger,
 *         the code should still function properly.  One caveat to that
 *        is that the input functions taking characters and character arrays
 *        assume that only 8 bits of information are stored in each character.
 *
 *    Caveats:
 *         SHA-1 is designed to work with messages less than 2^64 bits long.
 *         Although SHA-1 allows a message digest to be generated for
 *         messages of any number of bits less than 2^64, this implementation
 *         only works with messages with a length that is a multiple of 8
 *         bits.
 *
 */

#include "sha1.h"

/*
 *    SHA1
 *
 *    Description:
 *        This is the constructor for the sha1 class.
 *
 *    Parameters:
 *        None.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
SHA1::SHA1()
{
    Reset();
}

/*
 *    ~SHA1
 *
 *    Description:
 *        This is the destructor for the sha1 class
 *
 *    Parameters:
 *        None.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
SHA1::~SHA1()
{
    // The destructor does nothing
}

/*
 *    Reset
 *
 *    Description:
 *        This function will initialize the sha1 class member variables
 *        in preparation for computing a new message digest.
 *
 *    Parameters:
 *        None.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::Reset()
{
    Length_Low            = 0;
    Length_High            = 0;
    Message_Block_Index    = 0;

    H[0]        = 0x67452301;
    H[1]        = 0xEFCDAB89;
    H[2]        = 0x98BADCFE;
    H[3]        = 0x10325476;
    H[4]        = 0xC3D2E1F0;

    Computed    = false;
    Corrupted    = false;
}

/*
 *    Result
 *
 *    Description:
 *        This function will return the 160-bit message digest into the
 *        array provided.
 *
 *    Parameters:
 *        message_digest_array: [out]
 *            This is an array of five unsigned integers which will be filled
 *            with the message digest that has been computed.
 *
 *    Returns:
 *        True if successful, false if it failed.
 *
 *    Comments:
 *
 */
bool SHA1::Result(unsigned *message_digest_array)
{
    int i;                                    // Counter

    if (Corrupted)
    {
        return false;
    }

    if (!Computed)
    {
        PadMessage();
        Computed = true;
    }

    for(i = 0; i < 5; i++)
    {
        message_digest_array[i] = H[i];
    }

    return true;
}

/*
 *    Input
 *
 *    Description:
 *        This function accepts an array of octets as the next portion of
 *        the message.
 *
 *    Parameters:
 *        message_array: [in]
 *            An array of characters representing the next portion of the
 *            message.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::Input(    const unsigned char    *message_array,
                    unsigned             length)
{
    if (!length)
    {
        return;
    }

    if (Computed || Corrupted)
    {
        Corrupted = true;
        return;
    }

    while(length-- && !Corrupted)
    {
        Message_Block[Message_Block_Index++] = (*message_array & 0xFF);

        Length_Low += 8;
        Length_Low &= 0xFFFFFFFF;                // Force it to 32 bits
        if (Length_Low == 0)
        {
            Length_High++;
            Length_High &= 0xFFFFFFFF;            // Force it to 32 bits
            if (Length_High == 0)
            {
                Corrupted = true;                // Message is too long
            }
        }

        if (Message_Block_Index == 64)
        {
            ProcessMessageBlock();
        }

        message_array++;
    }
}

/*
 *    Input
 *
 *    Description:
 *        This function accepts an array of octets as the next portion of
 *        the message.
 *
 *    Parameters:
 *        message_array: [in]
 *            An array of characters representing the next portion of the
 *            message.
 *        length: [in]
 *            The length of the message_array
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::Input(    const char    *message_array,
                    unsigned     length)
{
    Input((unsigned char *) message_array, length);
}

/*
 *    Input
 *
 *    Description:
 *        This function accepts a single octets as the next message element.
 *
 *    Parameters:
 *        message_element: [in]
 *            The next octet in the message.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::Input(unsigned char message_element)
{
    Input(&message_element, 1);
}

/*
 *    Input
 *
 *    Description:
 *        This function accepts a single octet as the next message element.
 *
 *    Parameters:
 *        message_element: [in]
 *            The next octet in the message.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::Input(char message_element)
{
    Input((unsigned char *) &message_element, 1);
}

/*
 *    operator<<
 *
 *    Description:
 *        This operator makes it convenient to provide character strings to
 *        the SHA1 object for processing.
 *
 *    Parameters:
 *        message_array: [in]
 *            The character array to take as input.
 *
 *    Returns:
 *        A reference to the SHA1 object.
 *
 *    Comments:
 *        Each character is assumed to hold 8 bits of information.
 *
 */
SHA1& SHA1::operator<<(const char *message_array)
{
    const char *p = message_array;

    while(*p)
    {
        Input(*p);
        p++;
    }

    return *this;
}

/*
 *    operator<<
 *
 *    Description:
 *        This operator makes it convenient to provide character strings to
 *        the SHA1 object for processing.
 *
 *    Parameters:
 *        message_array: [in]
 *            The character array to take as input.
 *
 *    Returns:
 *        A reference to the SHA1 object.
 *
 *    Comments:
 *        Each character is assumed to hold 8 bits of information.
 *
 */
SHA1& SHA1::operator<<(const unsigned char *message_array)
{
    const unsigned char *p = message_array;

    while(*p)
    {
        Input(*p);
        p++;
    }

    return *this;
}

/*
 *    operator<<
 *
 *    Description:
 *        This function provides the next octet in the message.
 *
 *    Parameters:
 *        message_element: [in]
 *            The next octet in the message
 *
 *    Returns:
 *        A reference to the SHA1 object.
 *
 *    Comments:
 *        The character is assumed to hold 8 bits of information.
 *
 */
SHA1& SHA1::operator<<(const char message_element)
{
    Input((unsigned char *) &message_element, 1);

    return *this;
}

/*
 *    operator<<
 *
 *    Description:
 *        This function provides the next octet in the message.
 *
 *    Parameters:
 *        message_element: [in]
 *            The next octet in the message
 *
 *    Returns:
 *        A reference to the SHA1 object.
 *
 *    Comments:
 *        The character is assumed to hold 8 bits of information.
 *
 */
SHA1& SHA1::operator<<(const unsigned char message_element)
{
    Input(&message_element, 1);

    return *this;
}

/*
 *    ProcessMessageBlock
 *
 *    Description:
 *        This function will process the next 512 bits of the message
 *        stored in the Message_Block array.
 *
 *    Parameters:
 *        None.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *        Many of the variable names in this function, especially the single
 *         character names, were used because those were the names used
 *          in the publication.
 *
 */
void SHA1::ProcessMessageBlock()
{
    const unsigned K[] =     {                 // Constants defined for SHA-1
                                0x5A827999,
                                0x6ED9EBA1,
                                0x8F1BBCDC,
                                0xCA62C1D6
                            };
    int         t;                            // Loop counter
    unsigned     temp;                        // Temporary word value
    unsigned    W[80];                        // Word sequence
    unsigned    A, B, C, D, E;                // Word buffers

    /*
     *    Initialize the first 16 words in the array W
     */
    for(t = 0; t < 16; t++)
    {
        W[t] = ((unsigned) Message_Block[t * 4]) << 24;
        W[t] |= ((unsigned) Message_Block[t * 4 + 1]) << 16;
        W[t] |= ((unsigned) Message_Block[t * 4 + 2]) << 8;
        W[t] |= ((unsigned) Message_Block[t * 4 + 3]);
    }

    for(t = 16; t < 80; t++)
    {
       W[t] = CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
    }

    A = H[0];
    B = H[1];
    C = H[2];
    D = H[3];
    E = H[4];

    for(t = 0; t < 20; t++)
    {
        temp = CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0];
        temp &= 0xFFFFFFFF;
        E = D;
        D = C;
        C = CircularShift(30,B);
        B = A;
        A = temp;
    }

    for(t = 20; t < 40; t++)
    {
        temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
        temp &= 0xFFFFFFFF;
        E = D;
        D = C;
        C = CircularShift(30,B);
        B = A;
        A = temp;
    }

    for(t = 40; t < 60; t++)
    {
        temp = CircularShift(5,A) +
                ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
        temp &= 0xFFFFFFFF;
        E = D;
        D = C;
        C = CircularShift(30,B);
        B = A;
        A = temp;
    }

    for(t = 60; t < 80; t++)
    {
        temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
        temp &= 0xFFFFFFFF;
        E = D;
        D = C;
        C = CircularShift(30,B);
        B = A;
        A = temp;
    }

    H[0] = (H[0] + A) & 0xFFFFFFFF;
    H[1] = (H[1] + B) & 0xFFFFFFFF;
    H[2] = (H[2] + C) & 0xFFFFFFFF;
    H[3] = (H[3] + D) & 0xFFFFFFFF;
    H[4] = (H[4] + E) & 0xFFFFFFFF;

    Message_Block_Index = 0;
}

/*
 *    PadMessage
 *
 *    Description:
 *        According to the standard, the message must be padded to an even
 *        512 bits.  The first padding bit must be a '1'.  The last 64 bits
 *        represent the length of the original message.  All bits in between
 *        should be 0.  This function will pad the message according to those
 *        rules by filling the message_block array accordingly.  It will also
 *        call ProcessMessageBlock() appropriately.  When it returns, it
 *        can be assumed that the message digest has been computed.
 *
 *    Parameters:
 *        None.
 *
 *    Returns:
 *        Nothing.
 *
 *    Comments:
 *
 */
void SHA1::PadMessage()
{
    /*
     *    Check to see if the current message block is too small to hold
     *    the initial padding bits and length.  If so, we will pad the
     *    block, process it, and then continue padding into a second block.
     */
    if (Message_Block_Index > 55)
    {
        Message_Block[Message_Block_Index++] = 0x80;
        while(Message_Block_Index < 64)
        {
            Message_Block[Message_Block_Index++] = 0;
        }

        ProcessMessageBlock();

        while(Message_Block_Index < 56)
        {
            Message_Block[Message_Block_Index++] = 0;
        }
    }
    else
    {
        Message_Block[Message_Block_Index++] = 0x80;
        while(Message_Block_Index < 56)
        {
            Message_Block[Message_Block_Index++] = 0;
        }

    }

    /*
     *    Store the message length as the last 8 octets
     */
    Message_Block[56] = (Length_High >> 24) & 0xFF;
    Message_Block[57] = (Length_High >> 16) & 0xFF;
    Message_Block[58] = (Length_High >> 8) & 0xFF;
    Message_Block[59] = (Length_High) & 0xFF;
    Message_Block[60] = (Length_Low >> 24) & 0xFF;
    Message_Block[61] = (Length_Low >> 16) & 0xFF;
    Message_Block[62] = (Length_Low >> 8) & 0xFF;
    Message_Block[63] = (Length_Low) & 0xFF;

    ProcessMessageBlock();
}

/*
 *    CircularShift
 *
 *    Description:
 *        This member function will perform a circular shifting operation.
 *
 *    Parameters:
 *        bits: [in]
 *            The number of bits to shift (1-31)
 *        word: [in]
 *            The value to shift (assumes a 32-bit integer)
 *
 *    Returns:
 *        The shifted value.
 *
 *    Comments:
 *
 */
unsigned SHA1::CircularShift(int bits, unsigned word)
{
    return ((word << bits) & 0xFFFFFFFF) | ((word & 0xFFFFFFFF) >> (32-bits));
}