text:
package mabernardo.cadastroapi.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;

import mabernardo.cadastroapi.domain.enums.TipoTelefone;

/**
 * Entidade de telefones de pessoas.
 * @author Marcio Bernardo
 */
@ApiModel(description = "Entidade de telefones de pessoas. @author Marcio Bernardo")
@Entity
@Table(name = "telefone")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Telefone implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(max = 3)
    @Column(name = "ddd", length = 3, nullable = false)
    private String ddd;

    @NotNull
    @Size(max = 10)
    @Column(name = "numero", length = 10, nullable = false)
    private String numero;

    @Enumerated(EnumType.STRING)
    @Column(name = "tipo")
    private TipoTelefone tipo;
/*
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pessoa_id")
    @JsonIgnore
    private Pessoa pessoa;
*/
    public Long getId() {
        return id;
    }

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

    public String getDdd() {
        return ddd;
    }

    public Telefone ddd(String ddd) {
        this.ddd = ddd;
        return this;
    }

    public void setDdd(String ddd) {
        this.ddd = ddd;
    }

    public String getNumero() {
        return numero;
    }

    public Telefone numero(String numero) {
        this.numero = numero;
        return this;
    }

    public void setNumero(String numero) {
        this.numero = numero;
    }

    public TipoTelefone getTipo() {
        return tipo;
    }

    public Telefone tipo(TipoTelefone tipo) {
        this.tipo = tipo;
        return this;
    }

    public void setTipo(TipoTelefone tipo) {
        this.tipo = tipo;
    }
/*
    public Pessoa getPessoa() {
        return pessoa;
    }

    public Telefone pessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
        return this;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }
*/
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Telefone telefone = (Telefone) o;
        if (telefone.getId() == null || getId() == null) {
            return false;
        }
        return Objects.equals(getId(), telefone.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getId());
    }

    @Override
    public String toString() {
        return "Telefone{" +
            "id=" + getId() +
            ", ddd='" + getDdd() + "'" +
            ", numero='" + getNumero() + "'" +
            ", tipo='" + getTipo() + "'" +
            "}";
    }
}


text:
// Type definitions for braintree-web-drop-in 1.22
// Project: https://github.com/braintree/braintree-web-dropin
// Definitions by: Saoud Rizwan <https://github.com/saoudrizwan>
//                 Ricard Solé Casas <https://github.com/iamricard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.3

/// <reference types="googlepay" />
/// <reference types="applepayjs" />

/*
USAGE:
import * as dropin from "braintree-web-drop-in"

NOTE:
Some objects, such as as the payload returned from Dropin.requestPaymentMethod, can have various shapes. Review Braintree's documentation for more information about any types not covered in this file:
https://braintree.github.io/braintree-web-drop-in/docs/current/module-braintree-web-drop-in.html
*/

import { ApplePayPaymentRequest } from 'braintree-web/modules/apple-pay';
import { HostedFieldsField } from 'braintree-web/modules/hosted-fields';
import { ThreeDSecureVerifyPayload } from 'braintree-web/modules/three-d-secure';
import { ButtonStyle } from 'paypal-checkout-components';

// Options

export interface Options {
    authorization: string;
    container: string | HTMLElement;
    locale?: string | undefined;
    translations?: object | undefined;
    paymentOptionPriority?: string[] | undefined;
    card?: boolean | cardCreateOptions | undefined;
    paypal?: paypalCreateOptions | undefined;
    paypalCredit?: paypalCreateOptions | undefined;
    venmo?: venmoCreateOptions | boolean | undefined;
    applePay?: applePayCreateOptions | undefined;
    googlePay?: googlePayCreateOptions | undefined;
    dataCollector?: dataCollectorOptions | boolean | undefined;
    threeDSecure?: boolean | threeDSecureOptions | undefined;
    vaultManager?: boolean | undefined;
    preselectVaultedPaymentMethod?: boolean | undefined;
}

export interface applePayCreateOptions {
    buttonStyle?: 'black' | 'white' | 'white-outline' | undefined;
    displayName: string;
    applePaySessionVersion?: number | undefined;
    paymentRequest: ApplePayPaymentRequest;
}

export interface cardCreateOptions {
    cardholderName?:
        | boolean
        | {
              required?: boolean | undefined;
          } | undefined;
    overrides?: {
        fields?: {
            number?: HostedFieldsField | undefined;
            cvv?: HostedFieldsField | undefined;
            expirationDate?: HostedFieldsField | undefined;
            postalCode?: HostedFieldsField | undefined;
        } | undefined;
        styles?: object | undefined;
    } | undefined;
    clearFieldsAfterTokenization?: boolean | undefined;
    vault?: {
        allowVaultCardOverride?: boolean | undefined;
        vaultCard?: boolean | undefined;
    } | undefined;
}

export interface dataCollectorOptions {
    kount?: boolean | undefined;
}

export interface googlePayCreateOptions {
    merchantId: string;
    googlePayVersion?: string | undefined;
    transactionInfo: google.payments.api.TransactionInfo;
    button?: google.payments.api.ButtonOptions | undefined;
}

export interface paypalCreateOptions {
    flow: 'checkout' | 'vault';
    amount?: string | number | undefined;
    currency?: string | undefined;
    buttonStyle?: Partial<ButtonStyle> | undefined;
    commit?: boolean | undefined;
}

/**
 * @deprecated
 */
export interface threeDSecureOptions {
    amount: string;
}

export interface venmoCreateOptions {
    allowNewBrowserTab?: boolean | undefined;
}

// Dropin

export interface PaymentMethodRequestablePayload {
    type: 'CreditCard' | 'PayPalAccount';
    paymentMethodIsSelected: boolean;
}

export interface PaymentOptionSelectedPayload {
    paymentOption: 'card' | 'paypal' | 'paypalCredit';
}

export interface Dropin {
    clearSelectedPaymentMethod(): void;
    isPaymentMethodRequestable(): boolean;
    on(event: 'noPaymentMethodRequestable', handler: () => void): void;
    on(event: 'paymentMethodRequestable', handler: (payload: PaymentMethodRequestablePayload) => void): void;
    on(event: 'paymentOptionSelected', handler: (payload: PaymentOptionSelectedPayload) => void): void;
    off(event: 'noPaymentMethodRequestable', handler: () => void): void;
    off(event: 'paymentMethodRequestable', handler: (payload: PaymentMethodRequestablePayload) => void): void;
    off(event: 'paymentOptionSelected', handler: (payload: PaymentOptionSelectedPayload) => void): void;
    requestPaymentMethod(options: PaymentMethodOptions, callback: RequestPaymentMethodCallback): void;
    requestPaymentMethod(callback: RequestPaymentMethodCallback): void;
    requestPaymentMethod(options?: PaymentMethodOptions): Promise<PaymentMethodPayload>;
    teardown(callback: (error: object | null | undefined) => void): void;
    teardown(): Promise<void>;
}

export interface PaymentMethodOptions {
    threeDSecure: {
        amount: string;
        challengeRequested?: boolean | undefined;
        exemptionRequested?: boolean | undefined;
        email?: string | undefined;
        mobilePhoneNumber?: string | undefined;
        billingAddress?: object | undefined;
        additionalInformation?: object | undefined;
    };
}

export type RequestPaymentMethodCallback = (error: object | null, payload: PaymentMethodPayload) => void;

export type PaymentMethodPayload =
    | applePayPaymentMethodPayload
    | cardPaymentMethodPayload
    | googlePayPaymentMethodPayload
    | paypalPaymentMethodPayload
    | venmoPaymentMethodPayload;

export interface binData {
    commercial: string;
    countryOfIssuance: string;
    debit: 'Yes' | 'No' | 'Unknown';
    durbinRegulated: 'Yes' | 'No' | 'Unknown';
    healthcare: 'Yes' | 'No' | 'Unknown';
    issuingBank: string;
    payroll: 'Yes' | 'No' | 'Unknown';
    prepaid: 'Yes' | 'No' | 'Unknown';
    productId: string;
}

export interface applePayPaymentMethodPayload {
    nonce: string;
    vaulted?: boolean | undefined;
    details: {
        cardType: string;
        cardHolderName: string;
        dpanLastTwo: string;
        rawPaymentData: ApplePayJS.ApplePayPayment;
    };
    description: string;
    type: 'ApplePayCard';
    binData: binData;
    deviceData?: string | undefined;
}

export interface cardPaymentMethodPayload {
    nonce: string;
    details: {
        bin: string;
        cardType: string;
        expirationMonth: string;
        expirationYear: string;
        cardholderName: string;
        lastFour: string;
        lastTwo: string;
    };
    type: 'CreditCard';
    binData: binData;
    vaulted?: boolean | undefined;
    deviceData?: string | undefined;
    liabilityShifted?: boolean | undefined;
    liabilityShiftPossible?: boolean | undefined;
    threeDSecureInfo?: ThreeDSecureVerifyPayload | undefined;
}

export interface googlePayPaymentMethodPayload {
    nonce: string;
    details: {
        cardType: string;
        lastFour: string;
        lastTwo: string;
        isNetworkTokenized: boolean;
        bin: string;
        rawPaymentData: google.payments.api.PaymentData;
    };
    type: 'AndroidPayCard';
    binData: binData;
    deviceData?: string | undefined;
}

export interface Address {
    recipientName: string;
    line1: string;
    line2: string;
    city: string;
    state: string;
    postalCode: string;
    countryCode: string;
}

export interface paypalPaymentMethodPayload {
    nonce: string;
    vaulted?: boolean | undefined;
    details: {
        email: string;
        payerId: string;
        firstName: string;
        lastName: string;
        countryCode?: string | undefined;
        phone?: string | undefined;
        shippingAddress?: Address | undefined;
        billingAddress?: Address | undefined;
    };
    type: 'PayPalAccount';
    deviceData?: string | undefined;
}

export interface venmoPaymentMethodPayload {
    nonce: string;
    vaulted?: boolean | undefined;
    details: {
        username: string;
    };
    type: 'VenmoAccount';
    deviceData?: string | undefined;
}

// Methods

export function create(options: Options, callback: (error: object | null, dropin: Dropin | undefined) => void): void;
export function create(options: Options): Promise<Dropin>;

// Global

declare global {
    const braintree: {
        dropin: {
            create(options: Options, callback: (error: object | null, dropin: Dropin | undefined) => void): void;
            create(options: Options): Promise<Dropin>;
        };
    };
}

redpajama_set_name: RedPajamaGithub


text:
// -----------------------------------------------------------------------
//   <copyright file="Cluster.cs" company="Asynkron HB">
//       Copyright (C) 2015-2017 Asynkron HB All rights reserved
//   </copyright>
// -----------------------------------------------------------------------

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Proto.Remote;

namespace Proto.Cluster
{
    public static class Cluster
    {
        private static readonly ILogger Logger = Log.CreateLogger(typeof(Cluster).FullName);

        internal static ClusterConfig cfg;

        public static void Start(string clusterName, string address, int port, IClusterProvider cp) => StartWithConfig(new ClusterConfig(clusterName, address, port, cp));

        public static void StartWithConfig(ClusterConfig config)
        {
            cfg = config;

            Remote.Remote.Start(cfg.Address, cfg.Port, cfg.RemoteConfig);

            Serialization.RegisterFileDescriptor(ProtosReflection.Descriptor);
            Logger.LogInformation("Starting Proto.Actor cluster");
            var (h, p) = ParseAddress(ProcessRegistry.Instance.Address);
            var kinds = Remote.Remote.GetKnownKinds();
            Partition.Setup(kinds);
            PidCache.Setup();
            MemberList.Setup();
            cfg.ClusterProvider.RegisterMemberAsync(cfg.Name, h, p, kinds, config.InitialMemberStatusValue, config.MemberStatusValueSerializer).Wait();
            cfg.ClusterProvider.MonitorMemberStatusChanges();

            Logger.LogInformation("Started Cluster");
        }

        public static void Shutdown(bool gracefull = true)
        {
            if (gracefull)
            {
                cfg.ClusterProvider.Shutdown();
                //This is to wait ownership transfering complete.
                Task.Delay(2000).Wait();
                MemberList.Stop();
                PidCache.Stop();
                Partition.Stop();
            }

            Remote.Remote.Shutdown(gracefull);

            Logger.LogInformation("Stopped Cluster");
        }

        private static (string host, int port) ParseAddress(string address)
        {
            //TODO: use correct parsing
            var parts = address.Split(':');
            var host = parts[0];
            var port = int.Parse(parts[1]);
            return (host, port);
        }

        public static Task<(PID, ResponseStatusCode)> GetAsync(string name, string kind) => GetAsync(name, kind, CancellationToken.None);

        public static async Task<(PID, ResponseStatusCode)> GetAsync(string name, string kind, CancellationToken ct)
        {
            //Check Cache
            if (PidCache.TryGetCache(name, out var pid))
                return (pid, ResponseStatusCode.OK);

            //Get Pid
            var address = MemberList.GetPartition(name, kind);

            if (string.IsNullOrEmpty(address))
            {
                return (null, ResponseStatusCode.Unavailable);
            }

            var remotePid = Partition.PartitionForKind(address, kind);
            var req = new ActorPidRequest
            {
                Kind = kind,
                Name = name
            };

            try
            {
                var resp = ct == null || ct == CancellationToken.None
                           ? await remotePid.RequestAsync<ActorPidResponse>(req, cfg.TimeoutTimespan)
                           : await remotePid.RequestAsync<ActorPidResponse>(req, ct);
                var status = (ResponseStatusCode) resp.StatusCode;
                switch (status)
                {
                    case ResponseStatusCode.OK:
                        PidCache.TryAddCache(name, resp.Pid);
                        return (resp.Pid, status);
                    default:
                        return (resp.Pid, status);
                }
            }
            catch(TimeoutException)
            {
                return (null, ResponseStatusCode.Timeout);
            }
            catch
            {
                return (null, ResponseStatusCode.Error);
            }
        }

        public static void RemoveCache(string name) => PidCache.RemoveCacheByName(name);
    }
}


text:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Logger } from '../../providers/logger/logger';

// providers
import { AppIdentityProvider } from '../app-identity/app-identity';

import * as bitauthService from 'bitauth';

@Injectable()
export class BitPayProvider {
  private NETWORK: string;
  private BITPAY_API_URL: string;
  constructor(
    private http: HttpClient,
    private appIdentityProvider: AppIdentityProvider,
    private logger: Logger
  ) {
    this.logger.info('BitPayProvider initialized.');
    this.NETWORK = 'livenet';
    this.BITPAY_API_URL = this.NETWORK == 'livenet' ? 'https://bitpay.com' : 'https://test.bitpay.com';
  }

  public getEnvironment() {
    return {
      network: this.NETWORK
    };
  }

  public get(endpoint, successCallback, errorCallback) {
    let url = this.BITPAY_API_URL + endpoint;
    let headers: any = {
      'Content-Type': 'application/json'
    };
    this.http.get(url, { headers }).subscribe((data) => {
      successCallback(data);
    }, (data) => {
      errorCallback(data);
    });
  };

  public post(endpoint, json, successCallback, errorCallback) {

    this.appIdentityProvider.getIdentity(this.getEnvironment().network, (err, appIdentity: any) => {
      if (err) {
        return errorCallback(err);
      }

      let dataToSign = this.BITPAY_API_URL + endpoint + JSON.stringify(json);
      let signedData = bitauthService.sign(dataToSign, appIdentity.priv);
      let url = this.BITPAY_API_URL + endpoint;

      let headers: any = new HttpHeaders().set('content-type', 'application/json');
      headers = headers.append('x-identity', appIdentity.pub);
      headers = headers.append('x-signature', signedData);

      this.http.post(url, json, { headers }).subscribe((data) => {
        successCallback(data);
      }, (data) => {
        errorCallback(data);
      });
    });
  }

  public postAuth(json, successCallback, errorCallback) {
    this.appIdentityProvider.getIdentity(this.getEnvironment().network, (err, appIdentity) => {
      if (err) {
        return errorCallback(err);
      }

      json['params'].signature = bitauthService.sign(JSON.stringify(json.params), appIdentity.priv);
      json['params'].pubkey = appIdentity.pub;
      json['params'] = JSON.stringify(json.params);
      let url = this.BITPAY_API_URL + '/api/v2/';
      let headers: any = {
        'Content-Type': 'application/json'
      };
      this.logger.debug('post auth:' + JSON.stringify(json));
      this.http.post(url, json, { headers }).subscribe((data: any) => {
        data.appIdentity = appIdentity;
        successCallback(data);
      }, (data) => {
        errorCallback(data);
      });
    });
  };

}


text:
package org.usfirst.frc.team2471.robot.commands;

import org.usfirst.frc.team2471.robot.Robot;
import org.usfirst.frc.team2471.robot.RobotMap;

import edu.wpi.first.wpilibj.command.Command;

public class SpitUpReverse extends Command{

	boolean stateOrbital = false;

	@Override
	protected void initialize() {
		// TODO Auto-generated method stub
		stateOrbital = !RobotMap.ltop.get();
		Robot.sucker.setOrbUpState(false);
		Robot.sucker.topExtension(false);
	}

	@Override
	protected void execute() {
		// TODO Auto-generated method stub
		if(stateOrbital){
			Robot.sucker.orbitalUp();
		}
		else{
			Robot.sucker.suckup(0.5, 0.5);
		}
	}

	@Override
	protected boolean isFinished() {
		// TODO Auto-generated method stub
		if(stateOrbital){
			return RobotMap.ltop.get();
		}
		else{
			return !Robot.oi.sMid.get();
		}
	}

	@Override
	protected void end() {
		// TODO Auto-generated method stub
		Robot.sucker.orbitalOff();
		Robot.sucker.setOrbUpState(true);
		Robot.sucker.suckup(0.0, 0.0);
	}

	@Override
	protected void interrupted() {
		// TODO Auto-generated method stub
		end();
	}

}


text:
package com.at.junit5.exams.intf2;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

import org.junit.jupiter.api.Test;

public interface EqualsContract<T> extends Testable<T> {

    T createNotEqualValue();

    @Test
    default void valueEqualsItself() {
        T value = createValue();
        assertEquals(value, value);
    }

    @Test
    default void valueDoesNotEqualNull() {
        T value = createValue();
        assertFalse(value.equals(null));
    }

    @Test
    default void valueDoesNotEqualDifferentValue() {
        T value = createValue();
        T differentValue = createNotEqualValue();
        assertNotEquals(value, differentValue);
        assertNotEquals(differentValue, value);
    }

}


text:
using System.Threading.Tasks;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.InteractiveWindow;

namespace Microsoft.PythonTools.Repl {
    /// <summary>
    /// The Python repl evaluator.  An instance of this can be acquired by creating a REPL window
    /// via PythonToolsPackage.CreatePythonRepl and getting the Evaluator from the resulting
    /// window.
    ///
    /// This interface provides additional functionality for interacting with the Python REPL
    /// above and beyond the standard IReplEvaluator interface.
    /// </summary>
    interface IPythonInteractiveEvaluator {
        /// <summary>
        /// Executes the specified file in the REPL window.
        ///
        /// Does not reset the process, and the process will remain after the file is executed.
        /// </summary>
        Task<bool> ExecuteFileAsync(string filename, string extraArgs);

        /// <summary>
        /// Returns true if the REPL window process has exited.
        /// </summary>
        bool IsDisconnected { get; }

        /// <summary>
        /// Returns true if the REPL window is currently executing user code.
        /// </summary>
        bool IsExecuting { get; }

        /// <summary>
        /// User friendly name of the evaluator.
        /// </summary>
        string DisplayName { get; }
    }
}


text:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace SteamToolkit
{
    /// <summary>
    /// Various extension methods used in the library.
    /// </summary>
    public static class ExtensionMethods
    {
        /// <summary>
        /// Converts the bool variable to its integer representation of 0 for false and 1 for true.
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static int IntValue(this bool b)
        {
            return b ? 1 : 0;
        }

        public static string SerializeToXml<T>(this T value)
        {
            if (value == null) return string.Empty;

            try
            {
                var xmlserializer = new XmlSerializer(typeof(T));
                var stringWriter = new StringWriter();

                var settings = new XmlWriterSettings
                {
                    Indent = true,
                    IndentChars = "  ",
                    NewLineChars = "\r\n",
                    NewLineHandling = NewLineHandling.Replace
                };

                using (var writer = XmlWriter.Create(stringWriter, settings))
                {
                    xmlserializer.Serialize(writer, value);
                    return stringWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }

        public static string SerializeToJson<TSerializable>(this TSerializable serializable)
        {
            try
            {
                return JsonConvert.SerializeObject(serializable);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred", ex);
            }
        }
    }
}


text:
<?php use Symfony\Component\Finder\Tests\FakeAdapter\DummyAdapter;
defined('BX_DOL') or die('hack attempt');

require_once(BX_DIRECTORY_PATH_PLUGINS . 'stripe/init.php');

define('STRP_MODE_LIVE', 1);
define('STRP_MODE_TEST', 2);

class BxPaymentProviderStripe extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
{
	protected $_aIncludeJs;
	protected $_aIncludeCss;

    protected $_sFormCard;
	protected $_sFormDisplayCardAdd;

	protected $_iMode;
	protected $_bCheckAmount;

	protected $_oCustomer;

    function __construct($aConfig)
    {
    	$this->MODULE = 'bx_payment';

        parent::__construct($aConfig);

        $this->_sFormCard = 'bx_payment_form_strp_card';
        $this->_sFormDisplayCardAdd = 'bx_payment_form_strp_card_add';

        $this->_bRedirectOnResult = false;
        $this->_iMode = (int)$this->getOption('mode');
        $this->_bCheckAmount = $this->getOption('check_amount') == 'on';
        $this->_bUseSsl = $this->getOption('ssl') == 'on';
        $this->_sLogFile = BX_DIRECTORY_PATH_LOGS . 'bx_pp_' . $this->_sName . '.log';

        $this->_aIncludeJs = array(
        	'https://checkout.stripe.com/checkout.js',
        	'main.js',
        	'stripe.js'
        );
        $this->_aIncludeCss = array(
        	'stripe.css'
        );

        $this->_oCustomer = null;

        \Stripe\Stripe::setApiKey($this->_getSecretKey());
    }

	public function addJsCss()
    {
    	if(!$this->isActive())
    		return;

		$this->_oModule->_oTemplate->addJs($this->_aIncludeJs);
		$this->_oModule->_oTemplate->addCss($this->_aIncludeCss);
    }

    public function initializeCheckout($iPendingId, $aCartInfo)
    {
    	$sToken = bx_process_input(bx_get('token'));

    	if(empty($aCartInfo['items']) || !is_array($aCartInfo['items']))
    		return $this->_sLangsPrefix . 'err_empty_items';

		$aClient = $this->_oModule->getProfileInfo();
		$aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);

		$aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
		if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
            return $this->_sLangsPrefix . 'err_already_processed';

		switch($aPending['type']) {
			case BX_PAYMENT_TYPE_SINGLE:
				$aCartInfo['items_title'] = '';
				foreach($aCartInfo['items'] as $aItem)
		            $aCartInfo['items_title'] .= ' ' . $aItem['title'] . ',';
				$aCartInfo['items_title'] = trim($aCartInfo['items_title'], ', ');

				$mixedResult = $this->_createCharge($sToken, $iPendingId, $aClient, $aCartInfo);
				if($mixedResult === false)
					return $this->_sLangsPrefix . 'err_cannot_perform';

				header("Location: " . $this->getReturnDataUrl($aVendor['id'], array(
					'order_id' => $mixedResult['order'],
					'customer_id' => $mixedResult['customer'],
					'pending_id' => $aPending['id']
				)));
				exit;

			case BX_PAYMENT_TYPE_RECURRING:
				$mixedResult = $this->_createSubscription($sToken, $iPendingId, $aClient, $aCartInfo);
				if($mixedResult === false)
					return $this->_sLangsPrefix . 'err_cannot_perform';

				return array(
					'code' => 0,
					'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onSubscribeSubmit(oData);',
					'redirect' => $this->getReturnDataUrl($aVendor['id'], array(
						'order_id' => $mixedResult['order'],
						'customer_id' => $mixedResult['customer'],
						'pending_id' => $aPending['id']
					))
				);
		}
    }

    public function finalizeCheckout(&$aData)
    {
    	$sOrderId = bx_process_input($aData['order_id']);
    	$sCustomerId = bx_process_input($aData['customer_id']);
		$iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
        if(empty($iPendingId))
        	return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_wrong_data');

		$aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
        if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
            return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');

		$aResult = array(
			'code' => BX_PAYMENT_RESULT_SUCCESS,
        	'message' => '',
			'pending_id' => $iPendingId,
		    'customer_id' => '',
		    'subscription_id' => '',
			'client_name' => '',
			'client_email' => '',
			'paid' => false
		);

		switch($aPending['type']) {
			case BX_PAYMENT_TYPE_SINGLE:
				$aCustomer = $this->_retrieveCustomer($sCustomerId)->jsonSerialize();
				$aCharge = $this->_retrieveCharge($sOrderId)->jsonSerialize();
				if(empty($aCustomer) || !is_array($aCustomer) || empty($aCharge) || !is_array($aCharge))
					return array('code' => 4, 'message' => $this->_sLangsPrefix . 'err_cannot_perform');

				$aResult = array_merge($aResult, array(
					'message' => $this->_sLangsPrefix . 'strp_msg_charged',
					'client_email' => $aCustomer['email'],
					'paid' => (bool)$aCharge['paid']
				));
				break;

			case BX_PAYMENT_TYPE_RECURRING:
				$aCustomer = $this->_retrieveCustomer($sCustomerId)->jsonSerialize();
				$aSubscription = $this->_retrieveSubscription($sCustomerId, $sOrderId)->jsonSerialize();
				if(empty($aCustomer) || !is_array($aCustomer) || empty($aSubscription) || !is_array($aSubscription))
					return array('code' => 4, 'message' => $this->_sLangsPrefix . 'err_cannot_perform');

				$aResult = array_merge($aResult, array(
					'message' => $this->_sLangsPrefix . 'strp_msg_subscribed',
                    'customer_id' => $sCustomerId,
				    'subscription_id' => $sOrderId,
					'client_email' => $aCustomer['email']
				));
				break;
		}

        //--- Update pending transaction ---//
        $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
            'order' => $sOrderId,
            'error_code' => $aResult['code'],
            'error_msg' => _t($aResult['message'])
        ));

        return $aResult;
    }

    public function notify()
    {
		$iResult = $this->_processEvent();
		http_response_code($iResult);
    }

    public function getButtonSingle($iClientId, $iVendorId, $aParams = array())
    {
    	$aItems = array();
    	$aCartInfo = $this->_oModule->getObjectCart()->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, (int)$iVendorId, $aItems);

    	return $this->_getButton(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId, array_merge($aParams, array(
			'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aCartInfo['vendor_name']),
			'sVendorCurrency' => $aCartInfo['vendor_currency_code'],
			'sVendorIcon' => $aCartInfo['vendor_icon'],
    	)));
    }

    public function getButtonRecurring($iClientId, $iVendorId, $aParams = array())
    {
    	$aVendor = $this->_oModule->getVendorInfo((int)$iVendorId);

		return $this->_getButton(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iVendorId, array_merge($aParams, array(
			'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aVendor['name']),
			'sVendorCurrency' => $aVendor['currency_code'],
			'sVendorIcon' => $aVendor['icon'],
		)));
    }

    public function getMenuItemsActionsRecurring($iClientId, $iVendorId, $aParams = array())
    {
        if(empty($aParams['order']))
            return array();

        $sJsObject = $this->_oModule->_oConfig->getJsObject(BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION);

        $sPrefix = 'bx-payment-strp-';
        return array(
            array('id' => $sPrefix . 'details', 'name' => $sPrefix . 'details', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".getDetails(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_details')),
            array('id' => $sPrefix . 'billing', 'name' => $sPrefix . 'billing', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".getBilling(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_billing')),
            array('id' => $sPrefix . 'change', 'name' => $sPrefix . 'change', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".changeBilling(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_billing_change')),
        );
    }

    public function getDetailsRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
    {
        $aSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId)->jsonSerialize();
        if(empty($aSubscription) || !is_array($aSubscription))
            return '';

        $sNone = _t('_bx_payment_txt_none');
        return $this->_oModule->_oTemplate->parseHtmlByName('strp_details_recurring.html', array(
            'plan' => $aSubscription['plan']['name'],
            'cost' => _t('_bx_payment_strp_txt_cost_mask', (int)$aSubscription['plan']['amount'] / 100, $aSubscription['plan']['currency'], $aSubscription['plan']['interval']),
            'status' => $aSubscription['status'],
        	'created' => bx_time_js($aSubscription['created']),
        	'started' => !empty($aSubscription['start']) ? bx_time_js($aSubscription['start']) : $sNone,
        	'trial_start' => !empty($aSubscription['trial_start']) ? bx_time_js($aSubscription['trial_start']) : $sNone,
        	'trial_end' => !empty($aSubscription['trial_end']) ? bx_time_js($aSubscription['trial_end']) : $sNone,
            'cperiod_start' => !empty($aSubscription['current_period_start']) ? bx_time_js($aSubscription['current_period_start']) : $sNone,
        	'cperiod_end' => !empty($aSubscription['current_period_end']) ? bx_time_js($aSubscription['current_period_end']) : $sNone,
        ));
    }

    public function getBillingRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
    {
        $aCard = $this->_retrieveCard($sCustomerId)->jsonSerialize();

        return $this->_oModule->_oTemplate->parseHtmlByName('strp_billing_recurring.html', array(
            'brand' => $aCard['brand'],
        	'origin' => $aCard['country'],
            'type' => $aCard['funding'],
            'number' => _t('_bx_payment_strp_txt_card_number_mask', $aCard['last4']),
            'expires' => _t('_bx_payment_strp_txt_card_expires_mask', $aCard['exp_month'], $aCard['exp_year']),
            'cvc' => _t(strcmp($aCard['cvc_check'], 'pass') === 0 ? '_bx_payment_strp_txt_card_cvc_passed' : '_bx_payment_txt_none'),
        ));
    }

    public function changeBillingRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
    {
        $oForm = BxDolForm::getObjectInstance($this->_sFormCard, $this->_sFormDisplayCardAdd, $this->_oModule->_oTemplate);
        $oForm->aFormAttrs['id'] = $this->_oModule->_oConfig->getHtmlIds('subscription', 'form_subscription_change_billing');
        $oForm->aFormAttrs['action'] = BX_DOL_URL_ROOT . $this->_oModule->_oConfig->getBaseUri() . 'subscription_change_billing/' . $iPendingId;

        $oForm->initChecker();
        if($oForm->isSubmittedAndValid()) {
            list($iMonth, $iYear) = explode(' ', $oForm->getCleanValue('card_expire'));

        	$aToken = $this->_createToken(array(
                'number' => $oForm->getCleanValue('card_number'),
                'exp_month' => $iMonth,
                'exp_year' => $iYear,
                'cvc' => $oForm->getCleanValue('card_cvv')
            ));
            if(empty($aToken) || !is_array($aToken))
                return array('code' => 1, 'message' => _t('_bx_payment_strp_err_billing_changed'));

            $aCard = $this->_createCard($sCustomerId, $aToken['id']);
            if(empty($aCard) || !is_array($aCard))
                return array('code' => 1, 'message' => _t('_bx_payment_strp_err_billing_changed'));

            $oCustomer = $this->_retrieveCustomer($sCustomerId);
            $oCustomer->default_source = $aCard['id'];
            $oCustomer->save();

            return array('code' => 0, 'message' => _t('_bx_payment_strp_msg_billing_changed'));
        }

        return $this->_oModule->_oTemplate->parseHtmlByName('strp_card_recuring.html', array(
        	'object' => $this->_oModule->_oConfig->getJsObject('subscription'),
            'form' => $oForm->getCode(),
            'form_id' => $oForm->aFormAttrs['id'],
        ));
    }

    public function getCheckoutParamsSingle($aParams, &$oGrid)
    {
    	if(bx_get('token') !== false)
    		$aParams['token'] = bx_process_input(bx_get('token'));

    	return $aParams;
    }

	protected function _getPublicKey()
	{
		return $this->_iMode == STRP_MODE_LIVE ? $this->getOption('live_pub_key') : $this->getOption('test_pub_key');
	}

	protected function _getSecretKey()
	{
		return $this->_iMode == STRP_MODE_LIVE ? $this->getOption('live_sec_key') : $this->getOption('test_sec_key');
	}

    protected function _createToken($aCard)
    {
		try {
			$oToken = Stripe\Token::create(array('card' => $aCard));
		}
		catch (Stripe\Error\Base $oException) {
			return $this->_processException('Create Token Error: ', $oException);
		}

		return $oToken->jsonSerialize();
	}

	protected function _createCustomer($sToken, $aClient)
	{
		try {
			$aClientParams = array(
				'card'  => $sToken,
				'email' => !empty($aClient['email']) ? $aClient['email'] : ''
			);

			$this->_oCustomer = \Stripe\Customer::create($aClientParams);
		}
		catch (Stripe\Error\Base $oException) {
			return $this->_processException('Create Customer Error: ', $oException);
		}

		return $this->_oCustomer->jsonSerialize();
	}

	protected function _retrieveCustomer($sId) {
		try {
			$oCustomer = \Stripe\Customer::retrieve($sId);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Customer Error: ', $oException);
		}

		return $oCustomer;
	}

	protected function _createCharge($sToken, $iPendingId, &$aClient, &$aCartInfo) {
		if(empty($this->_oCustomer))
			$this->_createCustomer($sToken, $aClient);

		if(empty($this->_oCustomer))
			return false;

		$fAmount = 100 * (float)$aCartInfo['items_price'];

		try {
			$oCharge = \Stripe\Charge::create(array(
				'customer' => $this->_oCustomer->id,
				'amount' => $fAmount,
				'currency' => $aCartInfo['vendor_currency_code'],
				'description' => $aCartInfo['items_title'],
				'metadata' => array(
					'vendor' => $aCartInfo['vendor_id'],
					'client' => $aClient['id'],
					'product' => $iPendingId,
					'verification' => $this->_getVerificationCodeCharge($aCartInfo['vendor_id'], $aClient['id'], $fAmount, $aCartInfo['vendor_currency_code'])
				)
			));
		}
		catch (Exception $oException) {
			return $this->_processException('Create Charge Error: ', $oException);
		}

		$aResult = $oCharge->jsonSerialize();
		if(empty($aResult) || !is_array($aResult) || empty($aResult['paid']))
			return false;

		$aMetadata = $aResult['metadata'];
		if(empty($aMetadata['verification']) || $aMetadata['verification'] != $this->_getVerificationCodeCharge($aCartInfo['vendor_id'], $aClient['id'], $aResult['amount'], $aResult['currency']))
			return false;

		return array(
			'pending' => $iPendingId,
			'amount' =>(float)$aResult['amount'] / 100,
			'customer' => $this->_oCustomer->id,
			'order' => $aResult['id']
		);
	}

	protected function _retrieveCharge($sId) {
		try {
			$oCharge = \Stripe\Charge::retrieve($sId);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Charge Error: ', $oException);
		}

		return $oCharge;
	}

	protected function _createSubscription($sToken, $iPendingId, &$aClient, &$aCartInfo)
	{
		$bTrial = false;

		if(empty($this->_oCustomer))
			$this->_createCustomer($sToken, $aClient);

		if(empty($this->_oCustomer))
			return false;

		try {
			$aItem = array_shift($aCartInfo['items']);
			if(empty($aItem) || !is_array($aItem))
				return false;

			//TODO: "Trial" wasn't finaly relized. It's just a draft.
			if(isset($aItem['trial']) && $aItem['trial'] === true)
				$bTrial = true;

			$oSubscription = $this->_oCustomer->subscriptions->create(array(
				'plan' => $aItem['name'],
				'metadata' => array(
					'vendor' => $aCartInfo['vendor_id'],
					'client' => $aClient['id'],
					'product' => $iPendingId,
					'verification' => $this->_getVerificationCodeSubscription($aCartInfo['vendor_id'], $aClient['id'], $aItem['name'], $aCartInfo['vendor_currency_code'])
				)
			));
		}
		catch (Exception $oException) {
			return $this->_processException('Create Subscription Error: ', $oException);
		}

		$aResult = $oSubscription->jsonSerialize();
		if(empty($aResult) || !is_array($aResult) || (!$bTrial && $aResult['status'] != 'active') || ($bTrial && !in_array($aResult['status'], array('active', 'trialing'))))
			return false;

		$aMetadata = $aResult['metadata'];
		if(empty($aMetadata['verification']) || $aMetadata['verification'] != $this->_getVerificationCodeSubscription($aCartInfo['vendor_id'], $aClient['id'], $aResult['plan']['id'], $aResult['plan']['currency']))
			return false;

		return array(
			'pending' => $iPendingId,
			'amount' =>(float)$aCartInfo['items_price'],
			'customer' => $this->_oCustomer->id,
			'order' => $aResult['id'],
			'trial' => $bTrial
		);
	}

	protected function _retrieveSubscription($sCustomerId, $sSubscriptionId) {
		try {
			$oCustomer = \Stripe\Customer::retrieve($sCustomerId);
			$oSubscription = $oCustomer->subscriptions->retrieve($sSubscriptionId);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Subscription Error: ', $oException);
		}

		return $oSubscription;
	}

    protected function _createCard($sCustomerId, $sToken)
	{
		try {
			$oCard = $this->_retrieveCustomer($sCustomerId)->sources->create(array(
            	'source' => $sToken
            ));
		}
		catch (Stripe\Error\Base $oException) {
			return $this->_processException('Create Card Error: ', $oException);
		}

		return $oCard->jsonSerialize();
	}

    protected function _retrieveCard($sCustomerId, $sCardId = '') {
		try {
			$oCustomer = \Stripe\Customer::retrieve($sCustomerId);
			$oCard = $oCustomer->sources->retrieve(!empty($sCardId) ? $sCardId : $oCustomer->default_source);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Card Error: ', $oException);
		}

		return $oCard;
	}

	protected function _retrieveCoupon($sId) {
		try {
			$oCoupon = \Stripe\Coupon::retrieve($sId);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Coupon Error: ', $oException);
		}

		return $oCoupon;
	}

	protected function _retrieveEvent($sId) {
		try {
			$oEvent = \Stripe\Event::retrieve($sId);
		}
		catch (Exception $oException) {
			return $this->_processException('Retrieve Event Error: ', $oException);
		}

		return $oEvent;
	}

	protected function _processEvent()
	{
    	$sInput = @file_get_contents("php://input");
		$aEvent = json_decode($sInput, true);
		if(empty($aEvent) || !is_array($aEvent))
			return 404;

		$sType = $aEvent['type'];
		if(!in_array($sType, array('invoice.payment_succeeded', 'charge.refunded', 'customer.subscription.deleted')))
			return 200;

		$this->log('Webhooks: ' . (!empty($sType) ? $sType : ''));
		$this->log($aEvent);

		$sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
    	if(!method_exists($this, $sMethod))
    		return 200;

    	return $this->$sMethod($aEvent) ? 200 : 403;
    }

	protected function _processEventInvoicePaymentSucceeded(&$aEvent)
	{
		$mixedResult = $this->_getData($aEvent);
		if($mixedResult === false)
			return false;

		list($aPending, $oCharge) = $mixedResult;
		if(empty($aPending) || !is_array($aPending) || empty($oCharge))
			return false;

		$fChargeAmount = (float)$oCharge->amount / 100;
		$sChargeCurrency = strtoupper($oCharge->currency);
		if($this->_bCheckAmount && ((float)$aPending['amount'] != $fChargeAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sChargeCurrency) !== 0))
			return false;

		return $this->_oModule->registerPayment($aPending);
	}

	protected function _processEventChargeRefunded(&$aEvent)
	{
		$mixedResult = $this->_getData($aEvent);
		if($mixedResult === false)
			return false;

		list($aPending) = $mixedResult;
		if(empty($aPending) || !is_array($aPending))
			return false;

		return $this->_oModule->refundPayment($aPending);
	}

	protected function _processEventCustomerSubscriptionDeleted(&$aEvent)
	{
		$mixedResult = $this->_getData($aEvent);
		if($mixedResult === false)
			return false;

		list($aPending) = $mixedResult;
		if(empty($aPending) || !is_array($aPending))
			return true;

		return $this->_oModule->cancelSubscription($aPending);
	}

	protected function _processException($sMessage, &$oException)
	{
		$aError = $oException->getJsonBody();

		$sMessage = $aError['error']['message'];
		if(empty($sMessage))
			$sMessage = $oException->getMessage();

		$this->log($sMessage . $aError['error']['message']);
		$this->log($aError);

		return false;
	}

	protected function _getData(&$aEvent, $bRetrieve = true)
	{
		if($bRetrieve)
			$oEvent = $this->_retrieveEvent($aEvent['id']);
		else
			$oEvent = \Stripe\Util\Util::convertToStripeObject($aEvent, array());

		if(empty($oEvent))
			return false;

		$aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $oEvent->data->object->subscription));
		$oCharge = $this->_retrieveCharge($oEvent->data->object->charge);

		return array($aPending, $oCharge);
	}

	protected function _getVerificationCodeCharge($iVendorId, $iCustomerId, $fAmount, $sCurrency) {
		return md5(implode('#-#', array(
			(int)$iVendorId,
			(int)$iCustomerId,
			(float)$fAmount,
			strtoupper($sCurrency)
		)));
	}

	protected function _getVerificationCodeSubscription($iVendorId, $iCustomerId, $sSubscription, $sCurrency) {
		return md5(implode('#-#', array(
			(int)$iVendorId,
			(int)$iCustomerId,
			strtoupper($sSubscription),
			strtoupper($sCurrency)
		)));
	}

    protected function _getButton($sType, $iClientId, $iVendorId, $aParams = array())
    {
    	$sClientEmail = '';
    	if(!empty($iClientId)) {
    		$oClient = BxDolProfile::getInstance($iClientId);
    		if($oClient)
    			$sClientEmail = $oClient->getAccountObject()->getEmail();
    	}

    	return $this->_oModule->_oTemplate->parseHtmlByName('strp_button_' . $sType . '.html', array(
    		'type' => $sType,
    		'caption' => _t($this->_sLangsPrefix . 'strp_txt_checkout_with_' . $sType, $this->_sCaption),
    		'js_object' => $this->_oModule->_oConfig->getJsObject($this->_sName),
    		'js_code' => $this->_oModule->_oTemplate->getJsCode($this->_sName, array_merge(array(
	    		'sProvider' => $this->_sName,
	    		'sPublicKey' => $this->_getPublicKey(),
	    		'sVendorName' => '',
	    		'sVendorCurrency' => '',
	    		'sVendorIcon' => '',
	    		'sClientEmail' => $sClientEmail,
	    	), $aParams))
    	));
    }
}

/** @} */


text:
ActiveRecord::Schema.define(:version => 1) do
  create_table :simple_oauths, :force => true do |t|
    t.string   "token_a", "token_b", :limit => 999
    t.string   "service", "type", :null => false
    t.string   "owner_type"
    t.integer  "owner_id"
    t.datetime "created_at", "updated_at", :null => false
  end
  create_table :users, :force => true do |t|
    t.string 'login', 'password'
  end
end


text:
var update = (function() {

//Width and height
var width = '300',
    height = '300',
    radius = Math.min(width, height) / 2,
    color = d3.scale.category20(),
    cpus,
    mems,
    arc,
    svg,
    g,
    lastData,
    shouldUpdate = true,
    path,
    vizPieCPU = d3.layout.pie()
                .sort(null)
                .value(function(d) { return d; });
    vizPieMem = d3.layout.pie()
                .sort(null)
                .value(function(d) { return d; });

var svgCPU,
    svgMem,
    arcCPU,
    arcMem,
    gCPU,
    pathCPU,
    pathMem,
    gMem;

/**
 * Initial setup for d3 elements
 */
function setup(jsonData) {
    var jsonData = BrowserUtils.getProcesses();
    cpus = [];
    mems = [];
    for (item in jsonData) {
        if(jsonData.hasOwnProperty(item)) {
            cpus.push(jsonData[item].cpu);
            mems.push(jsonData[item].memory);
        }
    }

    //Create SVG element
    svgCPU = d3.select("#cpuContainer").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    svgMem = d3.select("#memContainer").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

    arcCPU = d3.svg.arc()
        .innerRadius(radius - 50)
        .outerRadius(radius);

    arcMem = d3.svg.arc()
        .innerRadius(radius - 50)
        .outerRadius(radius);

    pathMem = svgMem.selectAll("path")
                .data(vizPieMem(mems))
                .enter()
                .append("path")
                .attr("fill", function(d, i) { return color(i); });

    pathCPU = svgCPU.selectAll("path")
                .data(vizPieCPU(cpus))
                .enter()
                .append("path")
                .attr("fill", function(d, i) { return color(i); });

    pathCPU.transition()
        .duration(1000)
        .attr("d", arcCPU)
        .each(function(d) { this._current = d; });

    pathMem.transition()
        .duration(1000)
        .attr("d", arcMem)
        .each(function(d) { this._current = d; });    // gCPU = svgCPU.selectAll(".arc")
    //     .data(vizPieCPU(cpus))
    //     .enter().append("path");
    //     // .attr("class", "arc");

    // gMem = svgMem.selectAll(".arc")
    //     .data(vizPieMem(mems))
    //     .enter().append("path")
    //     .attr("class", "arc");

    // // Add loading text.
    // gCPU.append("text")
    //     .style("text-anchor", "middle")
    //     .style("font-size","24px")
    //     .text("Loading...");

}

/**
 * Creates and returns a handler to close a tab
 * @param id    the tabId
 * @return      handler to close the relevant tab
 */
function closeTab(id) {
    return function(evt) {
        chrome.tabs.remove(id || someTabIds.pop());
    }
}

/**
 * Returns the first element in an array matching the
 * input property/value pair
 * @param array      the array in question
 * @param prop       the property name
 * @param val        the value of the property to match
 */
function getArrayEltByProp(array, prop, val) {
    var i;
    for(i=0;i<array.length;i++) {
        if(array[i][prop] === val) {
            return array[i];
        }
    }
    return null;
}

/**
 * Creates and returns a click handler that creates
 * a menu with additional information about the selected
 * process
 * @param id             the id of the selected process
 * @param processList    the list of all processes
 * @return               hover handler
 */
function createProcessMenu(id, processList, container) {
    return function(evt) {
        shouldUpdate = false;
        evt.stopPropagation();
        $('#procMenu').remove();
        $('#lettuceWrap').on('click', function() {
            $('#procMenu').remove();
            shouldUpdate = true;
        });
        var left = evt.clientX,
            top = evt.clientY,
            menu = $(document.createElement('div')),
            nameDiv = $(document.createElement('div')),
            memDiv = $(document.createElement('div')),
            cpuDiv = $(document.createElement('div')),
            removeTabButton,
            process,
            name,
            mem,
            cpu;
        container = container || $('#lettuceWrap');
        menu.attr('id', 'procMenu');
        menu.css({
            position: 'absolute',
            left: left,
            top: top,
            background: 'rgba(255,100,0,0.5)'
        })
        container.append(menu);
        process = getArrayEltByProp(processList, 'id', id);
        mem = process.memory;
        cpu = process.cpu;
        if(process && process.info && process.info.type === 'tab') {
            removeTabButton = $(document.createElement('button'));
            removeTabButton.attr({
                type: 'button'
            });
            removeTabButton.text('close tab');
            removeTabButton.on('click', function(evt) {
                shouldUpdate = true;
                closeTab(process.info.tabid)(evt);
            });
            menu.append(removeTabButton);
            name = process.info.title;
        } else {
            name = process.info.type;
        }
        nameDiv.text(name);
        memDiv.text(mem);
        cpuDiv.text(cpu);
        menu.append(nameDiv);
        menu.append(memDiv);
        menu.append(cpuDiv);

    }
}

/**
 * Filters list of processes to reflect current filter settings
 * @param jsonData     the list of processes to filter
 * @return             the filtered list
 */
function filterProcesses(jsonData) {
    var filter = $('#filterSelect').val().toLowerCase().replace(/ /g,''),
        ret = [],
        type,
        i;
    for(i=0;i<jsonData.length;i++) {
        // debugger;
        type = jsonData[i].info.type;
        if(filter === 'all' || (type === 'tab' &&  filter==='tabsonly') || (type !== 'tab' && filter==='notabs')){
            ret.push(jsonData[i]);
        }
    }
    return ret;
}

/**
 * Update the d3 elements
 * @param jsonData    an array of processes
 */
function displayData(jsonData) {

    if(!shouldUpdate) {
        return;
    }
    // $('#cpuContainer').empty(); // Clear
    $('#memContainer').empty(); // Clear

    jsonData = filterProcesses(jsonData);
    cpus = [];
    mems = [];
    for (item in jsonData) {
        if(jsonData.hasOwnProperty(item)) {
            cpus.push(jsonData[item].cpu);
            mems.push(jsonData[item].memory);
        }
    }

    var totalCPU = 0;
    var totalMem = 0;

    for(var i=0, len=cpus.length; i<len; i++){
        totalCPU += cpus[i];  //Iterate over your first array and then grab the second element add the values up
    }
    if (totalCPU === 0) {
        return;
    }
    for(var i=0, len=mems.length; i<len; i++){
        totalMem += mems[i];  //Iterate over your first array and then grab the second element add the values up
    }
    if (totalMem === 0) {
        return;
    }

    $('#loading').empty(); // Clear

    // For finding maxes
    var dummyCPUS = cpus.slice(0);
    var dummyMems = mems.slice(0);
    maxCPUVals = [];
    maxMemVals = [];

    for(var i=0;i<4;i++) {
        var maxCPUVal = Math.max.apply(Math, dummyCPUS);
        maxCPUVals.push(maxCPUVal);

        var maxMemVal = Math.max.apply(Math, dummyMems);
        maxMemVals.push(maxMemVal);

        var indexCPU = dummyCPUS.indexOf(maxCPUVal);
        var indexMem = dummyMems.indexOf(maxMemVal);

        if (indexCPU > -1) {
            dummyCPUS.splice(indexCPU, 1);
        }
        if (indexMem > -1) {
            dummyMems.splice(indexMem, 1);
        }
    }

    names = []
    for (item in jsonData) {
        if(jsonData.hasOwnProperty(item)) {
            // Determine title to display

            if (maxCPUVals.indexOf(jsonData[item].cpu) === -1) {
                // Not one of the bigger processes, so set its title to a blank string
                // console.log("one: " + jsonData[item].cpu);
                names.push("");
            } else {
                // one of max vals, get real name
                if (jsonData[item].info.type == "tab") {

                    if (jsonData[item].info.title.length >= 10) {
                        var url = jsonData[item].info.url
                        title = url.match(/[^w]\w+\.{1}/g)

                        if (title == null) {
                            names.push(jsonData[item].info.title.slice(1,10))
                        }
                        else {
                            var matchNum = 0;
                            if (title[matchNum].match(/www/g)) {
                                matchNum += 1
                            }
                            if (title[matchNum][0].match(/\w/g)){
                                // first char is alpha, so slice from there
                                finalTitle = title[matchNum].slice(0,-1);
                                names.push(finalTitle);
                            }
                            else {
                                finalTitle = title[matchNum].slice(1,-1);
                                names.push(finalTitle);
                            }

                        }

                    }
                    else {
                        names.push(jsonData[item].info.title);
                    }
                }
                else {
                    names.push(jsonData[item].info.type);
                }
            }
        }
    }
    console.log("---B---")

    pathCPU.data(vizPieCPU(cpus));
    pathCPU.transition().duration(1000).attrTween("d", arcCPUTween);

    pathMem.data(vizPieMem(mems));
    pathMem.transition().duration(1000).attrTween("d", arcMemTween);

    // Define svg canvas
    // svgCPU = d3.select("#cpuContainer").append("svg")
    //     .attr("width", width)
    //     .attr("height", height)
    //     .append("g")
    //     .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

    // Define svg canvas
    // svgMem = d3.select("#memContainer").append("svg")
    //     .attr("width", width)
    //     .attr("height", height)
    //     .append("g")
    //     .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

    // arcCPU = d3.svg.arc()
    //     .innerRadius(radius - 50)
    //     .outerRadius(radius);

    // arcMem = d3.svg.arc()
    //     .innerRadius(radius - 50)
    //     .outerRadius(radius);

    // pathCPU = svgCPU.datum(cpus).selectAll("path")
    //                       .data(vizPieCPU)
    //                       .attr("d", arc)
    // pathCPU = svgCPU.selectAll("path")
    //             .data(vizPieCPU(cpus))
    //             .enter()
    //             .append("path")
    //             .attr("d", arc);

    // pathMem = svgMem.datum(mems).selectAll("path")
    //                       .data(vizPieMem)
    //                       .attr("d", arc)

    // Defines arcs
    // gCPU = svgCPU.selectAll(".arc")
    //     .data(vizPieCPU(cpus))
    //     .enter().append("g")
    //     .attr("class", "arc")
    //     .style("stroke-width", 3);

    // gMem = svgMem.selectAll(".arc")
    //     .data(vizPieMem(mems))
    //     .enter().append("g")
    //     .attr("class", "arc")
    //     .style("stroke-width", 3);

    // // Draws and colors
    // gCPU.append("path")
    //   .attr("d", arcCPU)
    //   .style("fill", function(d, i) { return color(i); });

    // // Draws and colors
    // gMem.append("path")
    //   .attr("d", arcMem)
    //   .style("fill", function(d, i) { return color(i); });

    // // svgCPU.selectAll('path').each(function(d, i) {
    // //     $(this).attr('id', jsonData[i].id)
    // //     $(this).on('click', createProcessMenu(parseInt($(this).attr('id'), 10), jsonData));
    // // });

    // // svgMem.selectAll('path').each(function(d, i) {
    // //     // debugger;
    // //     $(this).attr('id', jsonData[i].id)
    // //     $(this).on('click', createProcessMenu(parseInt($(this).attr('id'), 10), jsonData));
    // // });

    // // gCPU.append("text")
    // //   .attr("transform", function(d) { return "translate(" + arcCPU.centroid(d) + ")"; })
    // //   .attr("dy", ".35em")
    // //   .style("text-anchor", "middle")
    // //   .style("font-size","8px")
    // //   .data(names)
    // //   .text(function(d, i) {return d; });

    // gMem.append("text")
    //   .attr("transform", function(d) { return "translate(" + arcMem.centroid(d) + ")"; })
    //   .attr("dy", ".35em")
    //   .style("text-anchor", "middle")
    //   .style("font-size","8px")
    //   .data(names)
    //   .text(function(d, i) {return d; });

    // // gCPU.append("text")
    // //     .style("text-anchor", "middle")
    // //     .style("font-size","24px")
    // //     .text("CPU Usage");

    // gMem.append("text")
    //     .style("text-anchor", "middle")
    //     .style("font-size","24px")
    //     .text("Memory Usage");

   }

   function arcCPUTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arcCPU(i(t));
  };
}

   function arcMemTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arcMem(i(t));
  };
}

return {
    displayData: displayData,
    setup:  setup
};

})();


text:
/* GStreamer mplex (mjpegtools) wrapper
 * (c) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
 *
 * gstmplexjob.hh: gstreamer/mplex multiplex-job wrapper
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstmplexjob.hh"

enum
{
  ARG_0,
  ARG_FORMAT,
  ARG_MUX_BITRATE,
  ARG_VBR,
  ARG_SYSTEM_HEADERS,
  ARG_SPLIT_SEQUENCE,
  ARG_SEGMENT_SIZE,
  ARG_PACKETS_PER_PACK,
  ARG_SECTOR_SIZE,
  ARG_BUFSIZE
      /* FILL ME */
};

#define DEFAULT_FORMAT MPEG_FORMAT_DVD
/*
 * Property enumeration types.
 */

#define GST_TYPE_MPLEX_FORMAT \
  (gst_mplex_format_get_type ())

static GType
gst_mplex_format_get_type (void)
{
  static GType mplex_format_type = 0;

  if (!mplex_format_type) {
    static const GEnumValue mplex_formats[] = {
      {MPEG_FORMAT_MPEG1, "Generic MPEG-1", "mpeg-1"},
      {MPEG_FORMAT_VCD, "Standard VCD", "vcd"},
      {MPEG_FORMAT_VCD_NSR, "User VCD", "vcd-nsr"},
      {MPEG_FORMAT_MPEG2, "Generic MPEG-2", "mpeg-2"},
      {MPEG_FORMAT_SVCD, "Standard SVCD", "svcd"},
      {MPEG_FORMAT_SVCD_NSR, "User SVCD", "svcd-nsr"},
      {MPEG_FORMAT_VCD_STILL, "VCD Stills sequences", "vcd-still"},
      {MPEG_FORMAT_SVCD_STILL, "SVCD Stills sequences", "svcd-still"},
      {MPEG_FORMAT_DVD_NAV, "DVD MPEG-2 for dvdauthor", "dvd-nav"},
      {MPEG_FORMAT_DVD, "DVD MPEG-2", "dvd"},
      {MPEG_FORMAT_ATSC480i, "ATSC 480i", "atsc-480i"},
      {MPEG_FORMAT_ATSC480p, "ATSC 480p", "atsc-480p"},
      {MPEG_FORMAT_ATSC720p, "ATSC 720p", "atsc-720p"},
      {MPEG_FORMAT_ATSC1080i, "ATSC 1080i", "atsc-1080i"},
      {0, NULL, NULL},
    };

    mplex_format_type =
        g_enum_register_static ("GstMplexFormat", mplex_formats);
  }

  return mplex_format_type;
}

/*
 * Class init functions.
 */

GstMplexJob::GstMplexJob (void):
MultiplexJob ()
{
  /* blabla */
  bufsize = 0;
}

/*
 * GObject properties.
 */

void
GstMplexJob::initProperties (GObjectClass * klass)
{
  /* encoding profile */
  g_object_class_install_property (klass, ARG_FORMAT,
      g_param_spec_enum ("format", "Format", "Encoding profile format",
          GST_TYPE_MPLEX_FORMAT, DEFAULT_FORMAT,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));

  /* total stream datarate. Normally, this shouldn't be needed, but
   * some DVD/VCD/SVCD players really need strict values to handle
   * the created files correctly. */
  g_object_class_install_property (klass, ARG_MUX_BITRATE,
      g_param_spec_int ("mux-bitrate", "Mux. bitrate",
          "Bitrate of output stream in kbps (0 = autodetect)",
          0, 15 * 1024, 0,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));

  /* override decode buffer size otherwise determined by format */
  g_object_class_install_property (klass, ARG_BUFSIZE,
      g_param_spec_int ("bufsize", "Decoder buf. size",
          "Target decoders video buffer size (kB) "
          "[default determined by format if not explicitly set]",
          20, 4000, 46,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));

  /* some boolean stuff for headers */
  g_object_class_install_property (klass, ARG_VBR,
      g_param_spec_boolean ("vbr", "VBR",
          "Whether the input video stream is variable bitrate",
          FALSE,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
  g_object_class_install_property (klass, ARG_SYSTEM_HEADERS,
      g_param_spec_boolean ("system-headers", "System headers",
          "Create system header in every pack for generic formats",
          FALSE,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
#if 0                           /* not supported */
  g_object_class_install_property (klass, ARG_SPLIT_SEQUENCE,
      g_param_spec_boolean ("split-sequence", "Split sequence",
          "Simply split a sequence across files "
          "(rather than building run-out/run-in)",
          FALSE,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));

  /* size of a segment */
  g_object_class_install_property (klass, ARG_SEGMENT_SIZE,
      g_param_spec_int ("max-segment-size", "Max. segment size",
          "Max. size per segment/file in MB (0 = unlimited)",
          0, 10 * 1024, 0,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
#endif

  /* packets per pack (generic formats) */
  g_object_class_install_property (klass, ARG_PACKETS_PER_PACK,
      g_param_spec_int ("packets-per-pack", "Packets per pack",
          "Number of packets per pack for generic formats",
          1, 100, 1,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));

  /* size of one sector */
  g_object_class_install_property (klass, ARG_SECTOR_SIZE,
      g_param_spec_int ("sector-size", "Sector size",
          "Specify sector size in bytes for generic formats",
          256, 16384, 2048,
          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
}

/*
 * set/get gobject properties.
 */

void
GstMplexJob::getProperty (guint prop_id, GValue * value)
{
  switch (prop_id) {
    case ARG_FORMAT:
      g_value_set_enum (value, mux_format);
      break;
    case ARG_MUX_BITRATE:
      /* convert from bytes back to bits */
      g_value_set_int (value, (data_rate * 8) / 1000);
      break;
    case ARG_VBR:
      g_value_set_boolean (value, VBR);
      break;
    case ARG_SYSTEM_HEADERS:
      g_value_set_boolean (value, always_system_headers);
      break;
    case ARG_SPLIT_SEQUENCE:
      g_value_set_boolean (value, multifile_segment);
      break;
    case ARG_SEGMENT_SIZE:
      g_value_set_int (value, max_segment_size);
      break;
    case ARG_PACKETS_PER_PACK:
      g_value_set_int (value, packets_per_pack);
      break;
    case ARG_SECTOR_SIZE:
      g_value_set_int (value, sector_size);
      break;
    case ARG_BUFSIZE:
      g_value_set_int (value, bufsize);
      break;
    default:
      break;
  }
}

void
GstMplexJob::setProperty (guint prop_id, const GValue * value)
{
  switch (prop_id) {
    case ARG_FORMAT:
      mux_format = g_value_get_enum (value);
      break;
    case ARG_MUX_BITRATE:
      /* data_rate expects bytes (don't ask me why the property itself is
       * in bits, I'm just staying compatible to mjpegtools options), and
       * rounded up to 50-bytes. */
      data_rate = ((g_value_get_int (value) * 1000 / 8 + 49) / 50) * 50;
      break;
    case ARG_VBR:
      VBR = g_value_get_boolean (value);
      break;
    case ARG_SYSTEM_HEADERS:
      always_system_headers = g_value_get_boolean (value);
      break;
    case ARG_SPLIT_SEQUENCE:
      multifile_segment = g_value_get_boolean (value);
      break;
    case ARG_SEGMENT_SIZE:
      max_segment_size = g_value_get_int (value);
      break;
    case ARG_PACKETS_PER_PACK:
      packets_per_pack = g_value_get_int (value);
      break;
    case ARG_SECTOR_SIZE:
      sector_size = g_value_get_int (value);
      break;
    case ARG_BUFSIZE:
      bufsize = g_value_get_int (value);
      break;
    default:
      break;
  }
}


text:
package main

// Imports and register the gRPC tabletmanager client

import (
	_ "vitess.io/vitess/go/vt/vttablet/grpctmclient"
)


text:
#include <LeMoteur/Components/DeferredCamera.hpp>
#include <memory>

namespace LeMoteur {

class ReflectionProbe : public DeferredCamera, public enable_shared_from_this<ReflectionProbe> {
public:
	ReflectionProbe();
	~ReflectionProbe();
};

}


text:
<?php

namespace Laracasts\Matryoshka;

use Cache;

class FlushViews
{
    /**
     * Handle the request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     */
    public function handle($request, $next)
    {
        Cache::tags('views')->flush();

        return $next($request);
    }
}


text:
require_relative "./event"

module SuperTues
  module Board
    module Events

      # Business (day) events comprise the "meat" of player turns.  Players
      #  can play picks, play card, discard, move on the spectrum or poll on
      #  business days.
      #
      # Business days are:
      #   notice_mode: :all_at_once -- Tell everyone it's time to take actions
      #   interaction_mode: :take_turns -- Get actions from one player at a time.
      #   update_mode: :take_turns -- Update after each players action(s)
      #
      class Business < Event

        def initialize(params)
          super(params)
          @notice_mode = :all_at_once
          @interaction_node = :take_turns
          @update_mode = :take_turns
        end

        # Define the state machine for Business day event.
        #
        #  Notify-P1 => Interact-P1 => Update-P1 =>
        #  Notify-P2 => Interact-P2 => ....
        #  ...
        #
        # workflow do
          # state :new do
          # end
          # state :notify do
          # end
          # state :interact do
          # end
          # state :update do
          # end
        # end

        # Build the notification and pass to super to yield to players
        def notify(players)
          super(players, Notices::BusinessNotice.new)
        end

        def to_s
          'Business'
        end

      end

    end
  end
end


text:
package com.yuchengtech.tail4solr.core.index;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.MoreLikeThisParams;
import org.apache.solr.common.util.SimpleOrderedMap;

import com.yuchengtech.tail4solr.core.config.SolrConfig;
import com.yuchengtech.tail4solr.core.config.SolrConfigContainer;
import com.yuchengtech.tail4solr.entry.Content;

public class SolrOper {
	private static Logger logger = Logger.getLogger(SolrOper.class);

	public SolrOper(SolrConfig conf) {
		super();
		solrConf=conf;
		if(solrConf.isCluster()){
			server=createNewCloudSolrServer();
		}else{
			server = createNewSolrServer();
		}

	}

	private SolrConfig solrConf;
	private SolrServer server;

	public SolrServer getSolrServer() {
		{
			if (server == null) {
				if(solrConf.isCluster()){
					server=createNewCloudSolrServer();
				}else{
					server = createNewSolrServer();
				}

			}
			return server;
		}
	}

	private SolrServer createNewSolrServer() {
		try {

			HttpSolrServer s = new HttpSolrServer(solrConf.getUrl());
			s.setConnectionTimeout(solrConf.getConnectionTimeOut());
			s.setDefaultMaxConnectionsPerHost(solrConf
					.getMaxConnectionsPerHost());
			s.setMaxTotalConnections(solrConf.getMaxTotalConnections());

			if(!solrConf.getUser().trim().equals(""))
				HttpClientUtil.setBasicAuth((DefaultHttpClient)s.getHttpClient(), solrConf.getUser(),solrConf.getPasswd());
			return s;
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	private CloudSolrServer createNewCloudSolrServer() {
		try {

			CloudSolrServer s = new CloudSolrServer(solrConf.getUrl());
			s.setDefaultCollection(solrConf.getDefaultCollection());
			s.setZkClientTimeout(solrConf.getZkClientTimeout());
			s.setZkConnectTimeout(solrConf.getZkConnectTimeout());
//			if(!solrConf.getUser().trim().equals(""))
//				HttpClientUtil.setBasicAuth((DefaultHttpClient)s.getLbServer().getHttpClient(), solrConf.getUser(),solrConf.getPasswd());

			s.connect();
			System.out.println("ClusterState:"+s.getZkStateReader().getClusterState());

			return s;
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	/*
	 * 将content添加到索引
	 */

	public void addDoc(Content content) {

		try {
			UpdateResponse rep=server.addBean(content);
			logger.debug("status:"+rep.getStatus());
			server.commit();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SolrServerException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		/*****************另一种写法:

		SolrInputDocument doc = new SolrInputDocument();
		doc.setField("id", content.getId());
		doc.setField("host", content.getHost());
		doc.setField("path", content.getPath());
		doc.setField("time", content.getTime());
		doc.setField("lineNum", content.getLineNum());
		doc.setField("content", content.getContent());

		UpdateRequest req = new UpdateRequest();
		req.setAction(ACTION.COMMIT, true, true);
		req.add(doc);
		try {
			UpdateResponse rep = req.process(server);
			logger.debug(rep.getStatus());
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		********************/
	}

	/*
	 * 将列表中的contents添加到索引
	 */

	public void addDocs(List<Content> contents) {

		try {
			UpdateResponse rep=server.addBeans(contents);
			logger.debug(rep.getStatus());
			server.commit();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SolrServerException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/*
	 * 删除关键字相关的DOC
	 */

	public void removeById(String id){
		try {
			server.deleteById(id);
			server.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*
	 * 删除关键字列表中的DOC
	 */

	public void removeByIds(List<String> ids){
		try {
			server.deleteById(ids);
			server.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * 删除查询结果
	 */

	public void removeByQuery(String keyWord){
		try {
			server.deleteByQuery(keyWord);
			server.commit();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/*
	 * 删除查询结果并优化索引
	 */
	public void removeByQueryAndOptimize(String keyWord){
		try {
			server.deleteByQuery(keyWord);
			server.commit();
			server.optimize();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*
	 * 不分页查询
	 * @param  String  keyWord 包括:contentKey,idKey,hostKey,timeKey,pathKey,lineNumKey
	 * @return List<Content>
	 */
	public List<Content> query(String keyWord){
		List<Content> contentList=new ArrayList<Content>();
		SolrQuery query =new SolrQuery(keyWord);
	    try {
			QueryResponse response = server.query( query );
			SolrDocumentList docList=response.getResults();
			contentList=server.getBinder().getBeans(Content.class, docList);
			Iterator<Content> it=contentList.iterator();
			while(it.hasNext()){
				Content content=it.next();
//				String content=doc.getFieldValue("content").toString();
				logger.debug(content);
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return contentList;
	}

	/*
	 * 查询相似信息——more like this
	 * 与quereyMoreLikeThisByHandler的区别是:无需必须配置  <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" />
	 *
	 *keyWord mast is "id:****"
	 *@param keyWord 推荐用ID查询,例如:"id:****" ;合并每个查询结果(每个ID)的MORELIKETHIS,
	 *@param mltfields 属性termVectors必须为TRUE,例如:time,host,content,多个FIELDS以逗号分隔。
	 *@param mltDocCount  若mltDocCount<0返回全部
	 *@return List<Content>
	 *@see http://localhost:8080/solr/core0/select?q=id:20131271&mlt=true&mlt.fl=time,host&mlt.mindf=1&mlt.mintf=1&mlt.interestingTerms=details
	 */

	public List<Content> quereyMoreLikeThis(String keyWord, String mltfields,int mltDocCount) {
		List<Content> contentList = new ArrayList<Content>();
		SolrQuery query = new SolrQuery(keyWord);
		query.set(MoreLikeThisParams.MLT, true);
		query.set(MoreLikeThisParams.SIMILARITY_FIELDS, mltfields);
		if(mltDocCount>0)query.set("rows", mltDocCount);
		query.set(MoreLikeThisParams.MIN_TERM_FREQ, 1);// 关联字在单一文档中的出现频率
		query.set(MoreLikeThisParams.MIN_DOC_FREQ, 1);// 关联字的文档频率
		// query.set(MoreLikeThisParams.INTERESTING_TERMS,"details");//显示关联字

		try {
			QueryResponse response = server.query(query);
			SimpleOrderedMap more = (SimpleOrderedMap) response.getResponse().get("moreLikeThis");

			for (int i = 0; i < more.size(); i++) {
				Object o = more.getVal(i);
				if (o instanceof SolrDocumentList) {
					SolrDocumentList solrList = (SolrDocumentList) o;
					List<Content> tmpList = server.getBinder().getBeans(Content.class, solrList);
					contentList.addAll(tmpList);
				}
			}

		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug(contentList);
		return contentList;
	}

	/*
	 * 查询相似信息——more like this
	 * 必须配置  <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" />
	 *
	 * @param keyWord 推荐用ID查询,例如:"id:****" ;合并每个查询结果(每个ID)的MORELIKETHIS,
	 * @param mltfields 属性termVectors必须为TRUE,例如:time,host,content,多个FIELDS以逗号分隔。
	 * @param mltDocCount  若mltDocCount<0返回全部
	 * @return List<Content>
	 *
	 * @see http://localhost:8080/solr/core0/mlt?q=id:20131271&mlt.fl=host,time&mlt.mindf=1&mlt.mintf=1
	 * @see http://localhost:8080/solr/core0/select?q=id:20131271&mlt=true&mlt.fl=host,time&mlt.mindf=1&mlt.mintf=1
	 * @see http://localhost:8080/solr/core0/mlt?q=id:20131271&mlt.fl=time,host&mlt.mindf=1&mlt.mintf=1&mlt.interestingTerms=details
	 *
	 */

	public List<Content>  quereyMoreLikeThisByHandler(String keyWord,String mltfields,int mltDocCount){
		List<Content> contentList=new ArrayList<Content>();
		SolrQuery query =new SolrQuery(keyWord);
		query.setRequestHandler("/mlt");
		query.set(MoreLikeThisParams.MLT,true);
		query.set(MoreLikeThisParams.SIMILARITY_FIELDS,mltfields);
		if(mltDocCount>0)query.set(MoreLikeThisParams.DOC_COUNT,mltDocCount);
		query.set(MoreLikeThisParams.MIN_TERM_FREQ, solrConf.getMLTMinTermFreq());//关联字在单一文档中的出现频率
		query.set(MoreLikeThisParams.MIN_DOC_FREQ, solrConf.getMLTMinDocFreq());//关联字的文档频率
//		query.set(MoreLikeThisParams.INTERESTING_TERMS,"details");//显示关联字
		   try {
				QueryResponse response = server.query( query );
				SolrDocumentList docList=response.getResults();

				contentList=server.getBinder().getBeans(Content.class, docList);
				logger.debug(contentList);
			} catch (SolrServerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return contentList;
	}

	/*
	 * 自动补全——Suggestion
	 * 在solrconfig中必须配置:
	 * <requestHandler name="/suggest" class="org.apache.solr.handler.component.SearchHandler">
	 * <searchComponent name="suggest" class="solr.SpellCheckComponent">
	 * solr cloud 不支持Suggestion,但对<requestHandler name="/suggest"/>配置<bool name="distrib">false</bool>后,可以随机从某一个SHARD中,取数据。
	 * @param  keyWord field必须在<searchComponent/>中配置。此处只能是content。
	 * @return  list<String>
	 * @see http://localhost:8080/solr/core0/suggest?q=content:ban    若查询整个单词返回空。
	 *
	 */

	public List<String> querySuggestion(String keyWord){
		List<String> suggestList=new ArrayList<String>();
		SolrQuery query =new SolrQuery(keyWord);
		query.setRequestHandler("/suggest");
//不需要下列参数
//		  query.set("qt", "/suggest");
//		  query.set("spellcheck", "on");
//        query.set("spellcheck.build", "true");
//        query.set("spellcheck.onlyMorePopular", "true");
//
//        query.set("spellcheck.count", "100");
//        query.set("spellcheck.alternativeTermCount", "4");
//        query.set("spellcheck.onlyMorePopular", "true");
//
//        query.set("spellcheck.extendedResults", "true");
//        query.set("spellcheck.maxResultsForSuggest", "5");
//
//        query.set("spellcheck.collate", "true");
//        query.set("spellcheck.collateExtendedResults", "true");
//        query.set("spellcheck.maxCollationTries", "5");
//        query.set("spellcheck.maxCollations", "3");

	    try {
			QueryResponse response = server.query( query );
			SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
	        if (spellCheckResponse != null) {
	            List<Suggestion> suggestionList = spellCheckResponse.getSuggestions();
	            for (Suggestion suggestion : suggestionList) {
	                logger.debug("Suggestions NumFound: " + suggestion.getNumFound());
	                logger.debug("Token: " + suggestion.getToken());
	                List<String> suggestedWordList = suggestion.getAlternatives();
	                suggestList.addAll(suggestedWordList);
	            }

	        }else{
	        	logger.debug("suggestion is null");
	        }

		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug("suggestList is:"+suggestList);
		return suggestList;

	}

	/*
	 *查询关键字的时间分别情况
	 *
	 *@param	gap:包括:+1HOUR,+1DAY,+1MONTH,+1YEAR
 	 *@param   datefield 必须是DATE(time zone)类型。会合并每个查询结果(每个datefield)的facet
	 *@param   factDocCount 返回的factDoc数目
	 *@return   List<Count>
	 *@see      http://localhost:8080/solr/core0/select?q=content:apple&facet=on&facet.field=time&facet.date=time&facet.date.start=2013-01-03T01:04:01.001Z&facet.date.end=2013-12-31T01:01:01.001Z&facet.date.gap=%2B1MONTH
	 *
	 *
	 */

	public List<Count> queryFacet(String keyWord,String dateField,Date startTm,Date endTm,String gap,int factDocCount){
		List<Count> countList=new ArrayList<Count>();
		SolrQuery query =new SolrQuery(keyWord);
		query.addFacetField(dateField);
		query.setFacet(true);
		query.setFacetMissing(false);
		query.setFacetSort(dateField);
		query.set(FacetParams.FACET_DATE_GAP,gap);
		query.set(FacetParams.FACET_DATE, dateField);
		query.set(FacetParams.FACET_DATE_START,new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(startTm).toString()+"Z");
		query.set(FacetParams.FACET_DATE_END,new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(endTm).toString()+"Z");
		query.set(FacetParams.FACET_DATE_HARD_END,true);
		query.set(FacetParams.FACET_LIMIT,factDocCount);//FACET DOC 数目

//		query.addDateRangeFacet(field, startTm, endTm, gap);//此方法不行。

		try {
			QueryResponse response = server.query( query );

			List<FacetField> fieldFacets = response.getFacetDates();
			if (fieldFacets != null && !fieldFacets.isEmpty()) {

				for (FacetField fieldFacet : fieldFacets) {
					List<Count> tmpList=fieldFacet.getValues();
					countList.addAll(tmpList);
				}
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug(countList);
		return countList;
	}

	public Map<String,List<Count>>  queryFacet(String keyWord,int factDocCount,String ... facetFields){
		Map<String,List<Count>> facetMap=new HashMap<String, List<Count>>();

		SolrQuery query =new SolrQuery(keyWord);
		query.setFacet(true);
		query.setFacetMissing(false);
		query.set(FacetParams.FACET_LIMIT,factDocCount);//FACET DOC 数目
		query.addFacetField(facetFields);

		try {
			QueryResponse response = server.query( query );
			List<FacetField> fieldFacets = response.getFacetFields();
			if (fieldFacets != null && !fieldFacets.isEmpty()) {
				for (FacetField fieldFacet : fieldFacets) {
					String facetNm =fieldFacet.getName();
					List<Count> facetList=fieldFacet.getValues();
					facetMap.put(facetNm, facetList);
				}
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug(facetMap);
		return facetMap;
	}

	/*
	 * 分页查询并高亮显示
	 * @param startNum  起始位
	 * @param pageSize  返回的数目
	 * @param  String   keyWord 包括:contentKey
	 * @param  String...   filterString 包括:idKey,hostKey,timeKey,pathKey,lineNumKey,用于多条件查询。
	 * eg:
	 * lineNumKey:
	 * lineNum:[1 TO 10]  1<=lineNum<=10
	 * lineNum:{1 TO 10}  1<lineNum<10
	 * lineNum:[1 TO *]   lineNum>=1
	 * lineNum:[* TO 10]  lineNum<=10
	 * contentKey:
	 * content:apple banana NOT contet:orange
	 * content:apple banana NOT contet:orange AND lineNum:[* TO 10]    AND可以addFilterQuery替代
	 *
	 * @see http://localhost:8080/solr/core0/select?q=id:20131271
	 */

	public List<Content> query(int startNum,int pageSize,String keyWord,String ... filterString){
		List<Content> contentList=new ArrayList<Content>();
		SolrQuery query =new SolrQuery(keyWord);
		query.addFilterQuery(filterString);

		query.setHighlight(true);
		query.setHighlightFragsize(solrConf.getHighlightFragsize());//摘要长度
		query.setHighlightSnippets(solrConf.getHighlightSnippets());//摘要段数
		query.addHighlightField("content");
		query.setHighlightSimplePre(solrConf.getHighlightSimplePre());
		query.setHighlightSimplePost(solrConf.getHighlightSimplePost());

		query.setStart(startNum);
		query.setRows(pageSize);

		try {
			QueryResponse response = server.query( query );

			SolrDocumentList docList=response.getResults();
			contentList=server.getBinder().getBeans(Content.class, docList);

			Map<String,Map<String,List<String>>> hlMap=response.getHighlighting();
			logger.debug(hlMap.toString());

			Iterator<Content> it=contentList.iterator();
			while(it.hasNext()){
				Content content=it.next();
				logger.debug(content);
				Iterator<String> hlIter=hlMap.get(content.getId()).get("content").iterator();
				StringBuffer hlStr= new StringBuffer("");
				int i=0;
				while(hlIter.hasNext()){
					if(i++>0)hlStr.append("<br>");
					hlStr.append(hlIter.next());
				}
				content.setHighlightContent(hlStr.toString());
				logger.debug(content);
			}

			long totalCount=docList.getNumFound();
			logger.debug("totalCount is:"+totalCount);

		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return contentList;

	}

	public Long getCount(String keyWord,String ... filterString){
		Long count =0l;

		SolrQuery query =new SolrQuery(keyWord);
		query.addFilterQuery(filterString);

	    try {
			QueryResponse response = server.query( query );
			SolrDocumentList docList=response.getResults();
			count =  docList.getNumFound();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return count;
	}

}


text:
<?php

namespace Discord\View;

interface Viewable
{

    /**
     * Render template into viewable
     *
     * @param string $template
     * @param array $data
     *
     * @return mixed
     */
    public function render($template, array $data = []);

}


text:
package com.facebook.buck.cxx;

import static org.junit.Assert.assertNotEquals;

import com.facebook.buck.cli.BuildTargetNodeToBuildRuleTransformer;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.FakeBuildRuleParamsBuilder;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.HashedFileTool;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.keys.DefaultRuleKeyBuilderFactory;
import com.facebook.buck.testutil.FakeFileHashCache;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import org.junit.Test;

import java.nio.file.Path;
import java.nio.file.Paths;

public class ArchiveTest {

  private static final Path AR = Paths.get("ar");
  private static final Archiver DEFAULT_ARCHIVER = new GnuArchiver(new HashedFileTool(AR));
  private static final Path RANLIB = Paths.get("ranlib");
  private static final Tool DEFAULT_RANLIB = new HashedFileTool(RANLIB);
  private static final Path DEFAULT_OUTPUT = Paths.get("foo/libblah.a");
  private static final ImmutableList<SourcePath> DEFAULT_INPUTS =
      ImmutableList.<SourcePath>of(
          new FakeSourcePath("a.o"),
          new FakeSourcePath("b.o"),
          new FakeSourcePath("c.o"));

  @Test
  public void testThatInputChangesCauseRuleKeyChanges() {
    SourcePathResolver pathResolver =
        new SourcePathResolver(
            new BuildRuleResolver(TargetGraph.EMPTY, new BuildTargetNodeToBuildRuleTransformer()));
    BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
    BuildRuleParams params = new FakeBuildRuleParamsBuilder(target).build();
    FakeFileHashCache hashCache = FakeFileHashCache.createFromStrings(
        ImmutableMap.<String, String>builder()
            .put(AR.toString(), Strings.repeat("0", 40))
            .put(RANLIB.toString(), Strings.repeat("1", 40))
            .put("a.o", Strings.repeat("a", 40))
            .put("b.o", Strings.repeat("b", 40))
            .put("c.o", Strings.repeat("c", 40))
            .put(Paths.get("different").toString(), Strings.repeat("d", 40))
            .build()
    );

    // Generate a rule key for the defaults.
    RuleKey defaultRuleKey = new DefaultRuleKeyBuilderFactory(hashCache, pathResolver).build(
        new Archive(
            params,
            pathResolver,
            DEFAULT_ARCHIVER,
            DEFAULT_RANLIB,
            DEFAULT_OUTPUT,
            DEFAULT_INPUTS));

    // Verify that changing the archiver causes a rulekey change.
    RuleKey archiverChange = new DefaultRuleKeyBuilderFactory(hashCache, pathResolver).build(
        new Archive(
            params,
            pathResolver,
            new GnuArchiver(new HashedFileTool(Paths.get("different"))),
            DEFAULT_RANLIB,
            DEFAULT_OUTPUT,
            DEFAULT_INPUTS));
    assertNotEquals(defaultRuleKey, archiverChange);

    // Verify that changing the output path causes a rulekey change.
    RuleKey outputChange = new DefaultRuleKeyBuilderFactory(hashCache, pathResolver).build(
        new Archive(
            params,
            pathResolver,
            DEFAULT_ARCHIVER,
            DEFAULT_RANLIB,
            Paths.get("different"),
            DEFAULT_INPUTS));
    assertNotEquals(defaultRuleKey, outputChange);

    // Verify that changing the inputs causes a rulekey change.
    RuleKey inputChange = new DefaultRuleKeyBuilderFactory(hashCache, pathResolver).build(
        new Archive(
            params,
            pathResolver,
            DEFAULT_ARCHIVER,
            DEFAULT_RANLIB,
            DEFAULT_OUTPUT,
            ImmutableList.<SourcePath>of(new FakeSourcePath("different"))));
    assertNotEquals(defaultRuleKey, inputChange);

    // Verify that changing the type of archiver causes a rulekey change.
    RuleKey archiverTypeChange = new DefaultRuleKeyBuilderFactory(hashCache, pathResolver).build(
        new Archive(
            params,
            pathResolver,
            new BsdArchiver(new HashedFileTool(AR)),
            DEFAULT_RANLIB,
            DEFAULT_OUTPUT,
            DEFAULT_INPUTS));
    assertNotEquals(defaultRuleKey, archiverTypeChange);
  }

}


text:
function printMessage(msg, eol , funName, typeMsg)

if nargin<2
    eol = 1;
end

if nargin<4 || isempty(typeMsg)
    beginText = '';
elseif strcmp(typeMsg,'e')
    beginText = '[ERROR] ';
    eol = 1;
elseif strcmp(typeMsg,'w')
    beginText = '[WARNING] ';
elseif strcmp(typeMsg,'m')
    beginText = '[MESSAGE] ';
end

if nargin<3 || isempty(funName)
    middleText = '';
else
    middleText = sprintf('%s.m : ',funName);
end

fprintf('%s%s%s', beginText, middleText, msg)

if eol == 1
    fprintf('\n');
end


text:
The Deluxe Demo Bundle shows off the fancy technology that Keylime is capable of.  It is intended to be installed on a throwaway demo machine!

It includes the following demos:
* IMA Demo
* Webserver Demo (using nginx)
* TrustedGRUB Demo

The bundle contains the following files:
* **demo_setup.sh**: This sets up and installs the demos (on top of an existing Keylime installation)
* **ima-policy**: IMA policy file (less burdensome than the IMA TCB policy)
* **ima-policies/**: Additional IMA policy file examples, including the default TCB policy
* **keyfile.txt**: Keyfile that decrypts the payload.enc and payload.txt files
* **autorun.sh**: This file is sent to the cloud agent, which will decrypt and mount the payload.enc
    * *__NOTE:__ Your keylime.conf file's ```cloud_agent.payload_script``` should be set to autorun.sh*
* **payload.enc**: The target of the mount.sh script (LUKS encrypted payload), containing the "protected" website
* **payload.txt**: A simple encrypted payload to demonstrate the "Keyfile" payload type
* **payload/**: Directory containing the "unprotected" website

Also, see the **demo/agent_monitor** directory for an agent "phone-home" demo!

## Usage

The demo_setup.sh script can be executed with the following options:
```
Usage: ./demo_setup.sh [option...]
Options:
-p PATH         Use PATH as Keylime path
-i              Install IMA-related demo
-w              Install webserver-related demo
-t              Install TrustedGRUB2 (i386-pc w/ TPM) to /dev/sda
-T PATH         Install TrustedGRUB2 (i386-pc w/ TPM) to PATH
-n              No-password sudo for current user
-N USER         No-password sudo for user USER
-f              Full install (same as -niwt)
-y              No confirmations (feeling lucky)
-h              This help info
```

## Important Notes

### Webserver Demo

Both the keyfile.txt and autorun.sh files should be sent to the agent (via "CA Dir" mode provisioning).

`keylime_tenant -t 192.168.0.100 -u my_agent_id --cert default --include agent_files_dir`

The payload.enc file should be in the web server HTML directory (demo_setup.sh will put it there).

### TrustedGRUB

Defaults to using https://github.com/Rohde-Schwarz-Cybersecurity/TrustedGRUB2

Caveats: This requires a physical TPM, otherwise your system will be *unbootable*.
It also does not support UEFI mode booting, so make sure you are using legacy boot in your BIOS settings.
It will be built for the i386-pc platform.

### No-password sudo

Obviously a bad idea unless done on a scrappable, demo-only system!

## License

Copyright (c) 2015 Massachusetts Institute of Technology.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

DISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited.

This material is based upon work supported by the Assistant Secretary of Defense for
Research and Engineering under Air Force Contract No. FA8721-05-C-0002 and/or
FA8702-15-D-0001. Any opinions, findings, conclusions or recommendations expressed in this
material are those of the author(s) and do not necessarily reflect the views of the
Assistant Secretary of Defense for Research and Engineering.

Delivered to the US Government with Unlimited Rights, as defined in DFARS Part
252.227-7013 or 7014 (Feb 2014). Notwithstanding any copyright notice, U.S. Government
rights in this work are defined by DFARS 252.227-7013 or DFARS 252.227-7014 as detailed
above. Use of this work other than as specifically authorized by the U.S. Government may
violate any copyrights that exist in this work.


text:
package com.springboot.spark.starter.runner.official.profile;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Profile;

/**
 * Run with spring.profiles.active=PageRank
 */
@Target({
    ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Profile("PageRank")
public @interface PageRankProfile {

}


text:
<?php

namespace Acquia\Blt\Tests\BltProject;

use Acquia\Blt\Tests\BltProjectTestBase;

/**
 * Class BehatTest.
 *
 * Verifies that behat configuration is as expected.
 */
class BehatTest extends BltProjectTestBase {

  /**
   * Tests Phing setup:behat target.
   *
   * @group blt-project
   */
  public function testSetupBehat() {

    // Assert that a local.yml file was created in the new project.
    $this->assertFileExists($this->projectDirectory . '/tests/behat/local.yml');
    $this->assertNotContains(
          '${local_url}',
          file_get_contents("{$this->projectDirectory}/tests/behat/local.yml")
      );
  }

}