text:
JSValue::JSValue(JSContext ^ context, JSValueRef value)
: _context(context), _value(value)
{
    // TODO: is this necessary (probably...)?
    JSValueProtect(_context->context(), _value);
}

JSValue::~JSValue()
{
    // TODO: would probably be nicer to implement IDisposable instead
    // erm......
    if (_context != nullptr && _context->context() != NULL)
        JSValueUnprotect(_context->context(), _value);
}

String ^ JSValue::ToString()
{
    JSStringRef jsStr = JSValueToStringCopy(_context->context(), _value, NULL);
    String ^ str = JSCoreMarshal::JSStringToString(jsStr);
    JSStringRelease(jsStr);
    return str;
}

bool JSValue::IsBoolean::get()
{
    return JSValueIsBoolean(_context->context(), _value);
}

bool JSValue::IsNull::get()
{
    return JSValueIsNull(_context->context(), _value);
}

bool JSValue::IsNumber::get()
{
    return JSValueIsNumber(_context->context(), _value);
}

bool JSValue::IsObject::get()
{
    return JSValueIsObject(_context->context(), _value);
}

bool JSValue::IsString::get()
{
    return JSValueIsString(_context->context(), _value);
}

bool JSValue::IsUndefined::get()
{
    return JSValueIsUndefined(_context->context(), _value);
}

String ^ JSValue::ToJSONString()
{
    return "";
}

bool JSValue::ToBoolean()
{
    return JSValueToBoolean(_context->context(), _value);
}

double JSValue::ToNumber()
{
    return JSValueToNumber(_context->context(), _value, NULL);
}

JSObject ^ JSValue::ToObject()
{
    return gcnew JSObject(_context, (JSObjectRef)_value);
}

void JSValue::Protect()
{
}

void JSValue::Unprotect()
{
}

#ifdef DOTNET4
bool JSValue::TryConvert(System::Dynamic::ConvertBinder^ binder, [OutAttribute] Object ^% result)
{
    if(binder->Type == double::typeid)
    {
        if(IsNumber)
        {
            result = ToNumber();
            return true;
        }
        return false;
    }
    if(binder->Type == bool::typeid)
    {
        if(IsBoolean)
        {
            result = ToBoolean();
            return true;
        }
        return false;
    }
    if(binder->Type == String::typeid)
    {
        if(IsString)
        {
            result = ToString();
            return true;
        }
        return false;
    }
    return false;
}

bool JSValue::TryGetMember(System::Dynamic::GetMemberBinder ^ binder, Object ^% result)
{
    if(!IsObject) return false;
    JSObject ^ obj = ToObject();
    if(!obj->HasProperty(binder->Name)) return false;

    JSValue ^ value = obj->GetProperty(binder->Name);
    if(value->IsNumber)
    {
        result = value->ToNumber();
        return true;
    }
    if(value->IsBoolean)
    {
        result = value->ToBoolean();
        return true;
    }
    if(value->IsString)
    {
        result = value->ToString();
        return true;
    }
    if(value->IsObject)
    {
        result = value->ToObject();
        return true;
    }
    return false;
}

bool JSValue::TrySetMember(System::Dynamic::SetMemberBinder ^ binder, Object ^ value)
{
    if(!IsObject) return false;

    JSObject ^ obj = ToObject();

    Type ^ type = value->GetType();
    if(type == double::typeid)
    {
        obj->SetProperty(binder->Name, (double)value);
        return true;
    }
    if(type == bool::typeid)
    {
        obj->SetProperty(binder->Name, (bool)value);
        return true;
    }
    if(type == String::typeid)
    {
        obj->SetProperty(binder->Name, (String ^)value);
        return true;
    }
    obj->SetProperty(binder->Name, value);
    return true;
}

bool JSValue::TryInvokeMember(System::Dynamic::InvokeMemberBinder ^ binder, array<Object ^> ^ args, Object ^% result)
{
    if(!IsObject) return false;
    JSObject ^ obj = ToObject();
    result = obj->CallFunction(binder->Name, args);
    return true;
}
#endif


text:
package kafka.javaapi

import java.util

import kafka.common.TopicAndPartition
import kafka.api.{PartitionFetchInfo, Request}

import scala.collection.JavaConverters._

object FetchRequest {
  private def seqToLinkedHashMap[K, V](s: Seq[(K, V)]): util.LinkedHashMap[K, V] = {
    val map = new util.LinkedHashMap[K, V]
    s.foreach { case (k, v) => map.put(k, v) }
    map
  }
}

class FetchRequest(correlationId: Int,
                   clientId: String,
                   maxWait: Int,
                   minBytes: Int,
                   requestInfo: util.LinkedHashMap[TopicAndPartition, PartitionFetchInfo]) {

  @deprecated("The order of partitions in `requestInfo` is relevant, so this constructor is deprecated in favour of the " +
    "one that takes a LinkedHashMap", since = "0.10.1.0")
  def this(correlationId: Int, clientId: String, maxWait: Int, minBytes: Int,
    requestInfo: java.util.Map[TopicAndPartition, PartitionFetchInfo]) {
    this(correlationId, clientId, maxWait, minBytes,
      FetchRequest.seqToLinkedHashMap(kafka.api.FetchRequest.shuffle(requestInfo.asScala.toSeq)))
  }

  val underlying = kafka.api.FetchRequest(
    correlationId = correlationId,
    clientId = clientId,
    replicaId = Request.OrdinaryConsumerId,
    maxWait = maxWait,
    minBytes = minBytes,
    requestInfo = requestInfo.asScala.toBuffer
  )

  override def toString = underlying.toString

  override def equals(other: Any) = canEqual(other) && {
    val otherFetchRequest = other.asInstanceOf[kafka.javaapi.FetchRequest]
    this.underlying.equals(otherFetchRequest.underlying)
  }

  def canEqual(other: Any) = other.isInstanceOf[kafka.javaapi.FetchRequest]

  override def hashCode = underlying.hashCode

}

redpajama_set_name: RedPajamaGithub


text:
pub static global: int = 3;

#[inline(never)]
static global0: int = 4;

#[inline(never)]
pub static global2: &'static int = &global0;

pub fn verify_same(a: &'static int) {
    let a = a as *const int as uint;
    let b = &global as *const int as uint;
    assert_eq!(a, b);
}

pub fn verify_same2(a: &'static int) {
    let a = a as *const int as uint;
    let b = global2 as *const int as uint;
    assert_eq!(a, b);
}


text:
/* eslint no-unused-vars: 0 */
var SerialTransaction = require("./serialtransaction").SerialTransaction,
  getLog = require("./../logging").getLog,
  arraify = require("./../util").arraify,
  zip = require("./../util").zip,
  util = require("./../util"),
  scheduler = require("./../scheduler"),
  memops = require("./memops"),
  Stk500v2CodecSocket = require("./../io/stk500v2codec.js").Stk500v2CodecSocket,
  ioutil = require("./../io/util.js"),
  status = require("./../status.js"),
  errno = require("./../errno")

function STK500v2Transaction() {
  SerialTransaction.apply(this, arraify(arguments))
  this.log = getLog("STK500v2")
  this.cmdSeq = 1
  this.codecsocketClass = Stk500v2CodecSocket
}
STK500v2Transaction.prototype = Object.create(SerialTransaction.prototype)
STK500v2Transaction.prototype.STK2 = {
  CMD_SIGN_ON: 1,
  CMD_SET_PARAMETER: 2,
  CMD_GET_PARAMETER: 3,
  CMD_SET_DEVICE_PARAMETERS: 4,
  CMD_OSCCAL: 5,
  CMD_LOAD_ADDRESS: 6,
  CMD_FIRMWARE_UPGRADE: 7,
  CMD_CHECK_TARGET_CONNECTION: 13,
  CMD_LOAD_RC_ID_TABLE: 14,
  CMD_LOAD_EC_ID_TABLE: 15,
  CMD_ENTER_PROGMODE_ISP: 16,
  CMD_LEAVE_PROGMODE_ISP: 17,
  CMD_CHIP_ERASE_ISP: 18,
  CMD_PROGRAM_FLASH_ISP: 19,
  CMD_READ_FLASH_ISP: 20,
  CMD_PROGRAM_EEPROM_ISP: 21,
  CMD_READ_EEPROM_ISP: 22,
  CMD_PROGRAM_FUSE_ISP: 23,
  CMD_READ_FUSE_ISP: 24,
  CMD_PROGRAM_LOCK_ISP: 25,
  CMD_READ_LOCK_ISP: 26,
  CMD_READ_SIGNATURE_ISP: 27,
  CMD_READ_OSCCAL_ISP: 28,
  CMD_SPI_MULTI: 29,
  CMD_XPROG: 80,
  CMD_XPROG_SETMODE: 81,
  STATUS_CMD_OK: 0,
  STATUS_CMD_TOUT: 128,
  STATUS_RDY_BSY_TOUT: 129,
  STATUS_SET_PARAM_MISSING: 130,
  STATUS_CMD_FAILED: 192,
  STATUS_CKSUM_ERROR: 193,
  STATUS_CMD_UNKNOWN: 201,
  MESSAGE_START: 27,
  TOKEN: 14
}
STK500v2Transaction.prototype.cmd = function(cmd, cb) {
  if (cmd.length != 4) {
    this.errCb(errno.COMMAND_SIZE_FAIL, {
      receivedCmd: cmd
    })
    return
  }
  var buf = [this.STK2.CMD_SPI_MULTI, 4, 4, 0].concat(cmd)
  this.writeThenRead(buf, function(resp) {
    cb(resp.slice(2, 6))
  })
}
STK500v2Transaction.prototype.flash = function(deviceName, sketchData) {
  this.refreshTimeout()
  this.sketchData = sketchData
  this.deviceName = deviceName
  var self = this
  var smartOpen = {
    state: "smartOpenDevice",
    retries: 3,
    retryInterval: 1e3
  }
  this.setStatus(status.CONNECTING, {
    device: deviceName
  })
  this.transition(smartOpen, deviceName, this.config.speed, {
    request: [this.STK2.CMD_SIGN_ON],
    response: [self.STK2.CMD_SIGN_ON, self.STK2.STATUS_CMD_OK]
  }, this.transitionCb({
    state: "signedOn",
    retries: 10,
    waitBefore: 200,
    retryInterval: 0
  }))
}
STK500v2Transaction.prototype.signedOn = function() {
  var timeout = 200,
    stabDelay = 100,
    cmdExecDelay = 25,
    syncHLoops = 32,
    byteDelay = 0,
    pollValue = 83,
    pollIndex = 3,
    pgmEnable = [172, 83, 0, 0],
    nextStep = this.transitionCb("postSignOn")
  this.writeThenRead([this.STK2.CMD_ENTER_PROGMODE_ISP, timeout, stabDelay, cmdExecDelay, syncHLoops, byteDelay, pollValue, pollIndex].concat(pgmEnable), nextStep)
}
STK500v2Transaction.prototype.postSignOn = function(cb) {
  var self = this,
    programFlash = this.transitionCb("programFlash", this.config.avrdude.memory.flash.page_size)

  function eraseCmd(cmd, cb) {
    var buf = [self.STK2.CMD_CHIP_ERASE_ISP, self.config.avrdude.chipEraseDelay / 1e3, 0].concat(cmd)
    self.writeThenRead(buf, cb)
  }
  this.transition("maybeCheckSignature", this.transitionCb("maybeChipErase", programFlash, eraseCmd))
}
STK500v2Transaction.prototype.preProgramHack = function(offset, pgSize) {
  this.cmdChain([
    [48, 0, 0, 0],
    [48, 0, 1, 0],
    [48, 0, 2, 0],
    [160, 15, 252, 0],
    [160, 15, 253, 0],
    [160, 15, 254, 0],
    [160, 15, 255, 0]
  ], this.transitionCb("programFlash", pgSize || 256))
}
STK500v2Transaction.prototype.programFlash = function(pageSize) {
  this.sketchData.tile(this.transitionCb("writePage"), pageSize, this.transitionCb("checkPages", pageSize), this.sketchData.min())
}
STK500v2Transaction.prototype.checkPages = function(pageSize) {
  var self = this

  function writeAndRecheck(retryCb, offset, payload, done) {
    self.writePage(offset, payload, retryCb)
  }
  this.sketchData.tile(this.transitionCb({
    state: "checkPage",
    fallbackCb: writeAndRecheck,
    retries: 10
  }), pageSize, this.transitionCb("maybeCleanupBits"), this.sketchData.min())
}
STK500v2Transaction.prototype.maybeCleanupBits = function(pageSize) {
  this.setupSpecialBits(this.config.cleanControlBits, this.transitionCb("doneProgramming"))
}
STK500v2Transaction.prototype.doneProgramming = function() {
  var self = this
  self.writeThenRead([17, 1, 1], function(data) {
    self.setStatus(status.CLEANING_UP)
    self.transition("disconnect", function() {
      self.cleanup(function() {
        scheduler.setTimeout(self.finishCallback, 1e3)
      })
    })
  })
}
STK500v2Transaction.prototype.writePage = function(offset, payload, done) {
  var self = this
  this.writeThenRead(this.addressMsg(offset), function(reponse) {
    self.writeThenRead(self.writeMsg(payload), function(response) {
      if (response[0] != 19 || response[1] != 0) {
        self.errCb(errno.PAGE_WRITE_RESPONSE, {
          deviceResponse: response,
          expectedResponse: [19, 0]
        })
        return
      }
      done()
    })
  })
}
STK500v2Transaction.prototype.checkPage = function(offset, payload, done) {
  var self = this,
    index = 0
  this.writeThenRead(this.addressMsg(offset), function(reponse) {
    self.writeThenRead(self.readMsg(payload.length), function(response) {
      response = response.slice(2)
      response.pop()
      if (response.length != payload.length || response.some(function(v, i) {
        index = i
        return v != payload[i]
      })) {
        self.errCb(errno.PAGE_CHECK, {
          devPage: response,
          hostPage: payload,
          pageOffset: offset
        })
        return
      }
      done()
    }, {
      minPureData: 2 + payload.length + 1
    })
  })
}
STK500v2Transaction.prototype.readMsg = function(size) {
  var readCmds = memops.opToBin(this.config.avrdude.memory.flash.memops.READ_LO),
    sizeBytes = ioutil.storeAsTwoBytes(size)
  return [this.STK2.CMD_READ_FLASH_ISP, sizeBytes[0], sizeBytes[1], readCmds[0]]
}
STK500v2Transaction.prototype.addressMsg = function(address) {
  var addressBytes = ioutil.storeAsFourBytes(address / 2)
  if (this.config.avrdude.memory.flash.memops.LOAD_EXT_ADDR) addressBytes[0] |= 128
  return [this.STK2.CMD_LOAD_ADDRESS].concat(addressBytes)
}
STK500v2Transaction.prototype.writeMsg = function(payload) {
  var sizeBytes = ioutil.storeAsTwoBytes(payload.length),
    memMode = 193,
    delay = 10,
    loadpageLoCmd = 64,
    writepageCmd = 76,
    avrOpReadLo = 32
  return [this.STK2.CMD_PROGRAM_FLASH_ISP, sizeBytes[0], sizeBytes[1], memMode, delay, loadpageLoCmd, writepageCmd, avrOpReadLo, 0, 0].concat(payload)
}
module.exports.STK500v2Transaction = STK500v2Transaction


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: grpc/service_config/service_config.proto

namespace Grpc\Service_config;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * A ServiceConfig represents information about a service but is not specific to
 * any name resolver.
 *
 * Generated from protobuf message grpc.service_config.ServiceConfig
 */
class ServiceConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.LoadBalancingPolicy load_balancing_policy = 1 [deprecated = true];
     */
    protected $load_balancing_policy = 0;
    /**
     * Multiple LB policies can be specified; clients will iterate through
     * the list in order and stop at the first policy that they support. If none
     * are supported, the service config is considered invalid.
     *
     * Generated from protobuf field repeated .grpc.service_config.LoadBalancingConfig load_balancing_config = 4;
     */
    private $load_balancing_config;
    /**
     * Per-method configuration.
     *
     * Generated from protobuf field repeated .grpc.service_config.MethodConfig method_config = 2;
     */
    private $method_config;
    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.RetryThrottlingPolicy retry_throttling = 3;
     */
    protected $retry_throttling = null;
    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.HealthCheckConfig health_check_config = 5;
     */
    protected $health_check_config = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int $load_balancing_policy
     *     @type \Grpc\Service_config\LoadBalancingConfig[]|\Google\Protobuf\Internal\RepeatedField $load_balancing_config
     *           Multiple LB policies can be specified; clients will iterate through
     *           the list in order and stop at the first policy that they support. If none
     *           are supported, the service config is considered invalid.
     *     @type \Grpc\Service_config\MethodConfig[]|\Google\Protobuf\Internal\RepeatedField $method_config
     *           Per-method configuration.
     *     @type \Grpc\Service_config\ServiceConfig\RetryThrottlingPolicy $retry_throttling
     *     @type \Grpc\Service_config\ServiceConfig\HealthCheckConfig $health_check_config
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Grpc\ServiceConfig\ServiceConfig::initOnce();
        parent::__construct($data);
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.LoadBalancingPolicy load_balancing_policy = 1 [deprecated = true];
     * @return int
     */
    public function getLoadBalancingPolicy()
    {
        return $this->load_balancing_policy;
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.LoadBalancingPolicy load_balancing_policy = 1 [deprecated = true];
     * @param int $var
     * @return $this
     */
    public function setLoadBalancingPolicy($var)
    {
        GPBUtil::checkEnum($var, \Grpc\Service_config\ServiceConfig\LoadBalancingPolicy::class);
        $this->load_balancing_policy = $var;

        return $this;
    }

    /**
     * Multiple LB policies can be specified; clients will iterate through
     * the list in order and stop at the first policy that they support. If none
     * are supported, the service config is considered invalid.
     *
     * Generated from protobuf field repeated .grpc.service_config.LoadBalancingConfig load_balancing_config = 4;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getLoadBalancingConfig()
    {
        return $this->load_balancing_config;
    }

    /**
     * Multiple LB policies can be specified; clients will iterate through
     * the list in order and stop at the first policy that they support. If none
     * are supported, the service config is considered invalid.
     *
     * Generated from protobuf field repeated .grpc.service_config.LoadBalancingConfig load_balancing_config = 4;
     * @param \Grpc\Service_config\LoadBalancingConfig[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setLoadBalancingConfig($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Grpc\Service_config\LoadBalancingConfig::class);
        $this->load_balancing_config = $arr;

        return $this;
    }

    /**
     * Per-method configuration.
     *
     * Generated from protobuf field repeated .grpc.service_config.MethodConfig method_config = 2;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getMethodConfig()
    {
        return $this->method_config;
    }

    /**
     * Per-method configuration.
     *
     * Generated from protobuf field repeated .grpc.service_config.MethodConfig method_config = 2;
     * @param \Grpc\Service_config\MethodConfig[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setMethodConfig($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Grpc\Service_config\MethodConfig::class);
        $this->method_config = $arr;

        return $this;
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.RetryThrottlingPolicy retry_throttling = 3;
     * @return \Grpc\Service_config\ServiceConfig\RetryThrottlingPolicy
     */
    public function getRetryThrottling()
    {
        return isset($this->retry_throttling) ? $this->retry_throttling : null;
    }

    public function hasRetryThrottling()
    {
        return isset($this->retry_throttling);
    }

    public function clearRetryThrottling()
    {
        unset($this->retry_throttling);
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.RetryThrottlingPolicy retry_throttling = 3;
     * @param \Grpc\Service_config\ServiceConfig\RetryThrottlingPolicy $var
     * @return $this
     */
    public function setRetryThrottling($var)
    {
        GPBUtil::checkMessage($var, \Grpc\Service_config\ServiceConfig\RetryThrottlingPolicy::class);
        $this->retry_throttling = $var;

        return $this;
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.HealthCheckConfig health_check_config = 5;
     * @return \Grpc\Service_config\ServiceConfig\HealthCheckConfig
     */
    public function getHealthCheckConfig()
    {
        return isset($this->health_check_config) ? $this->health_check_config : null;
    }

    public function hasHealthCheckConfig()
    {
        return isset($this->health_check_config);
    }

    public function clearHealthCheckConfig()
    {
        unset($this->health_check_config);
    }

    /**
     * Generated from protobuf field .grpc.service_config.ServiceConfig.HealthCheckConfig health_check_config = 5;
     * @param \Grpc\Service_config\ServiceConfig\HealthCheckConfig $var
     * @return $this
     */
    public function setHealthCheckConfig($var)
    {
        GPBUtil::checkMessage($var, \Grpc\Service_config\ServiceConfig\HealthCheckConfig::class);
        $this->health_check_config = $var;

        return $this;
    }

}


text:
package com.amazonaws.services.cloudfront.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 * The request to get a distribution configuration.
 */
public class GetDistributionConfigRequest extends AmazonWebServiceRequest
        implements Serializable, Cloneable {

    /** The distribution's id. */
    private String id;

    /**
     * Default constructor for GetDistributionConfigRequest object. Callers
     * should use the setter or fluent setter (with...) methods to initialize
     * the object after creating it.
     */
    public GetDistributionConfigRequest() {
    }

    /**
     * Constructs a new GetDistributionConfigRequest object. Callers should use
     * the setter or fluent setter (with...) methods to initialize any
     * additional object members.
     *
     * @param id
     *        The distribution's id.
     */
    public GetDistributionConfigRequest(String id) {
        setId(id);
    }

    /**
     * The distribution's id.
     *
     * @param id
     *        The distribution's id.
     */

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

    /**
     * The distribution's id.
     *
     * @return The distribution's id.
     */

    public String getId() {
        return this.id;
    }

    /**
     * The distribution's id.
     *
     * @param id
     *        The distribution's id.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public GetDistributionConfigRequest withId(String id) {
        setId(id);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: " + getId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetDistributionConfigRequest == false)
            return false;
        GetDistributionConfigRequest other = (GetDistributionConfigRequest) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null
                && other.getId().equals(this.getId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getId() == null) ? 0 : getId().hashCode());
        return hashCode;
    }

    @Override
    public GetDistributionConfigRequest clone() {
        return (GetDistributionConfigRequest) super.clone();
    }
}


text:
package com.joypeg.scamandrill.client

import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll
import scala.concurrent.Await
import com.joypeg.scamandrill.models._
import scala.util.{Failure, Success}
import com.joypeg.scamandrill.utils._
import com.joypeg.scamandrill.MandrillTestUtils._
import com.joypeg.scamandrill.models.MSenderDataResponse
import com.joypeg.scamandrill.models.MInfoResponse
import scala.util.Success
import com.joypeg.scamandrill.models.MKey
import com.joypeg.scamandrill.models.MPingResponse
import scala.util.Failure

class UserCallsTest extends FlatSpec with Matchers with SimpleLogger{

  "Ping" should "work getting a valid MPingResponse (async client)" in {
    val res = Await.result(mandrillAsyncClient.usersPing(MKey()), DefaultConfig.defaultTimeout)
    res shouldBe MPingResponse("\"PONG!\"")
  }
  it should "work getting a valid MPingResponse (blocking client)" in {
    mandrillBlockingClient.usersPing(MKey()) match {
      case Success(res) => res shouldBe MPingResponse("\"PONG!\"")
      case Failure(ex) => fail(ex)
    }
  }
  it should "fail if the key passed is invalid, with an 'Invalid_Key' code" in {
    checkFailedBecauseOfInvalidKey(mandrillBlockingClient.usersPing(MKey("invalidkeytest")))
  }

  "Ping (version 2)" should "work getting a valid MPingResponse" in {
    val res1 = Await.result(mandrillAsyncClient.usersPing2(MKey()), DefaultConfig.defaultTimeout)
    res1 shouldBe MPingResponse("PONG!")
  }
  it should "work getting a valid MPingResponse (blocking client)" in {
    mandrillBlockingClient.usersPing2(MKey()) match {
      case Success(res) => res shouldBe MPingResponse("PONG!")
      case Failure(ex) => fail(ex)
    }
  }
  it should "fail if the key passed is invalid, with an 'Invalid_Key' code" in {
    checkFailedBecauseOfInvalidKey(mandrillBlockingClient.usersPing2(MKey("invalidkeytest")))
  }

  "Sender" should "work getting a valid List[MSenderDataResponse] (async client)" in {
    val res = Await.result(mandrillAsyncClient.usersSenders(MKey()), DefaultConfig.defaultTimeout)
    res.head.getClass shouldBe classOf[MSenderDataResponse]
    res.exists(_.address == "scamandrill@test.com") shouldBe true
  }
  it should "work getting a valid List[MSenderDataResponse] (blocking client)" in {
    mandrillBlockingClient.usersSenders(MKey()) match {
      case Success(res) => res.head.getClass shouldBe classOf[MSenderDataResponse]
      case Failure(ex) => fail(ex)
    }
  }
  it should "fail if the key passed is invalid, with an 'Invalid_Key' code" in {
    checkFailedBecauseOfInvalidKey(mandrillBlockingClient.usersSenders(MKey("invalidkeytest")))
  }

  "Info" should "work getting a valid MInfoResponse (async client)" in {
    val res = Await.result(mandrillAsyncClient.usersInfo(MKey()), DefaultConfig.defaultTimeout)
    res.getClass shouldBe classOf[MInfoResponse]
    res.username shouldBe "scamandrill@gmail.com"
    res.created_at shouldBe "2014-05-21 21:04:21.73604"
    res.hourly_quota shouldBe 250
    res.public_id shouldBe "Y5eZitt8VBjItiKUgkNhjg"
  }
  it should "work getting a valid MInfoResponse (blocking client)" in {
    mandrillBlockingClient.usersInfo(MKey()) match {
      case Success(res: MInfoResponse) =>
        res.getClass shouldBe classOf[MInfoResponse]
        res.username shouldBe "scamandrill@gmail.com"
        res.created_at shouldBe "2014-05-21 21:04:21.73604"
        res.hourly_quota shouldBe 250
        res.public_id shouldBe "Y5eZitt8VBjItiKUgkNhjg"
      case Success(res) => fail("Excpecting a MInfoResponse object")
      case Failure(ex) => fail(ex)
    }
  }
  it should "fail if the key passed is invalid, with an 'Invalid_Key' code" in {
    checkFailedBecauseOfInvalidKey(mandrillBlockingClient.usersInfo(MKey("invalidkeytest")))
  }
}


text:
require 'spec_helper'

describe 'collectd::plugin::network::server', type: :define do
  on_supported_os(baseline_os_hash).each do |os, facts|
    context "on #{os}" do
      let :facts do
        facts
      end

      options = os_specific_options(facts)
      context ':ensure => present, create one complex server' do
        let(:title) { 'node1' }
        let :params do
          {
            port: 1234,
            interface: 'eth0',
            securitylevel: 'Encrypt',
            username: 'foo',
            password: 'bar'
          }
        end

        it "Will create #{options[:plugin_conf_dir]}/network-server-node1.conf for collectd >= 4.7" do
          is_expected.to contain_file("#{options[:plugin_conf_dir]}/network-server-node1.conf").with(
            ensure: 'present',
            path: "#{options[:plugin_conf_dir]}/network-server-node1.conf",
            content: "<Plugin network>\n  <Server \"node1\" \"1234\">\n    SecurityLevel \"Encrypt\"\n    Username \"foo\"\n    Password \"bar\"\n    Interface \"eth0\"\n\n  </Server>\n</Plugin>\n"
          )
        end
      end

      context ':ensure => absent' do
        let(:title) { 'node1' }
        let :params do
          {
            ensure: 'absent'
          }
        end

        it "Will not create #{options[:plugin_conf_dir]}/network-server-node1.conf" do
          is_expected.to contain_file("#{options[:plugin_conf_dir]}/network-server-node1.conf").with(ensure: 'absent')
        end
      end
    end
  end
end


text:
{% extends 'base.html' %}
{% load i18n sizeformat %}
{% block title %}{% trans "Project Usage Overview" %}{% endblock %}

{% block page_header %}

{% trans "Project Usage" %}

{% endblock %}

{% block main %}
  {% include "horizon/common/_usage_summary.html" %}
  {{ table.render }}
{% endblock %}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Refresh extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}


text:
package org.audit4j.integration.cdi;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

import org.audit4j.core.IAuditManager;
import org.audit4j.core.annotation.Audit;

/**
 * The Audit Interceptor for CDI spec implementations.
 *
 * For Jboss Weld:
 *
 *

 * {@code
 * <beans
 *    ...
 *    <interceptors>
 *       <class>org.audit4j.intregration.cdi.AuditInterceptor</class>
 *    </interceptors>
 * </beans>
 * }
 *

 *
 * @author Janith Bandara
 * @author Jamie Johnson
 *
 * @since core 2.3.1
 * @since audit4j-cdi 1.0.0
 */
@Audit
@Interceptor
public class AuditInterceptor {

    protected IAuditManager auditManager;

    @Inject
    public AuditInterceptor(IAuditManager auditManager) {
        this.auditManager = auditManager;
    }

    /**
     * Before method invocation.
     *
     * @param joinPoint
     *            the join point
     * @return the object
     * @throws Throwable
     *             the throwable
     */
    @AroundInvoke
    public Object before(InvocationContext joinPoint) throws Exception {
        auditManager.audit(joinPoint.getTarget().getClass(), joinPoint.getMethod(),
                joinPoint.getParameters());
        return joinPoint.proceed();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>

   <extension point="org.eclipse.ui.newWizards">
      <category
            id="com.huawei.networkos.ops.python.PythonCategory"
            name="OpsDev"/>
   </extension>

   <extension
         point="org.eclipse.ui.views">
      <category
            id="com.huawei.networkos.opsdev"
            name="OpsDev"/>
      <view
            category="com.huawei.networkos.opsdev"
            class="com.huawei.networkos.ops.views.DeviceView"
            icon="icons/device_node.png"
            id="com.huawei.networkos.ops.views.DeviceView"
            name="OPS Devices">
      </view>
      <view
            category="com.huawei.networkos.opsdev"
            class="com.huawei.networkos.ops.views.NetworkMonitorView"
            icon="icons/network-idle.png"
            id="com.huawei.networkos.ops.views.NetworkMonitorView"
            name="OPS NetworkMonitor">
      </view>
   </extension>
   <extension
         point="org.eclipse.ui.perspectiveExtensions">
      <perspectiveExtension
            targetID="org.eclipse.jdt.ui.JavaPerspective">
      </perspectiveExtension>
   </extension>

  <extension
        point="org.eclipse.ui.console.consoleFactories">
     <consoleFactory
           class="com.huawei.networkos.opsdev.core.utils.ConsoleFactory"
           id="com.huawei.networkos.opsdev.core.utils.ConsoleFactory"
           label="console">
     </consoleFactory>
  </extension>

  <extension
         point="org.eclipse.ui.propertyPages">
      <page
            class="com.huawei.networkos.ops.properties.SchemaFilePropertyPage"
            id="com.huawei.networkos.ops.java.properties.SchemaFilePropertyPage"
            name="OpsDev - SchemaFile"
            >
      </page>
    </extension>
 	<extension
         point="org.eclipse.ui.propertyPages">
      <page
            class="com.huawei.networkos.ops.properties.OpsPathPropertyPage"
            id="com.huawei.networkos.ops.java.properties.OpsPathPropertyPage"
            name="OpsDev - Path"
            >
      </page>
   </extension>

<extension point="org.eclipse.ui.actionSets">
  <actionSet
        label="OpsDev Navigate"
        visible="false"
        id="com.huawei.networkos.opsdev.navigate.actionSet">
     <menu
           label="Ops&dev"
           id="pyGeneralMenu">
        <separator name="opsNavigateGroup"/>
     </menu>

          <action
           label="&About OpsDev"
           icon="icons/opentype.gif"
           class="com.huawei.networkos.ops.views.AboutOpsdevWorkbench"
           tooltip="OpsDev: About OpsDev"
           menubarPath="opsGeneralMenu/opsNavigateGroup"
           toolbarPath="opsNavigateGroup"
           id="com.huawei.networkos.ops.views.AboutOpsdevWorkbench"
           definitionId="com.huawei.networkos.opsdev.aboutOpsdevWorkbench"
           >
     </action>
  </actionSet>
</extension>

<extension point="org.eclipse.ui.commands">

  <category
            id="com.huawei.networkos.opsdev.Category"
            name="OpsDev"/>
            <command
            name="About OpsDev (Global)"
            description="About OpsDev (Global)"
            categoryId="com.huawei.networkos.opsdev.Category"
            id="com.huawei.networkos.opsdev.aboutOpsdevWorkbench">
      </command>
</extension>

  <extension
         point="org.eclipse.ui.actionSets">
      <actionSet
            label="OpsDev"
            visible="true"
            id="opsdev.actionSet">
         <menu
               label="Ops&dev"
               id="opsSampleMenu">
            <separator
                  name="pyNavigateGroup">
            </separator>
         </menu>
         <action
               label="&About OpsDev"
               icon="icons/opentype.gif"
               class="com.huawei.networkos.ops.views.AboutOpsdevWorkbench"
               tooltip="OpsDev: About OpsDev"
               menubarPath="opsSampleMenu/opsNavigateGroup"
               toolbarPath="opsNavigateGroup"
               id="com.huawei.networkos.ops.views.AboutOpsdevWorkbench">
         </action>
      </actionSet>
   </extension>

</plugin>


text: Attempting to make a micro version of lambda


text:
#ifndef rtkPhaseGatingImageFilter_h
#define rtkPhaseGatingImageFilter_h

#include "rtkSubSelectImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkPhaseReader.h"

namespace rtk
{
/** \class PhaseGatingImageFilter
 *
 * \author Cyril Mory
 *
 * \ingroup RTK
 */
template <typename ProjectionStackType>
class ITK_TEMPLATE_EXPORT PhaseGatingImageFilter : public SubSelectImageFilter<ProjectionStackType>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(PhaseGatingImageFilter);

  /** Standard class type alias. */
  using Self = PhaseGatingImageFilter;
  using Superclass = SubSelectImageFilter<ProjectionStackType>;
  using Pointer = itk::SmartPointer<Self>;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(PhaseGatingImageFilter, SubSelectImageFilter);

  itkSetMacro(PhasesFileName, std::string);
  itkGetMacro(PhasesFileName, std::string);

  itkSetMacro(GatingWindowWidth, float);
  itkGetMacro(GatingWindowWidth, float);

  itkSetMacro(GatingWindowCenter, float);
  itkGetMacro(GatingWindowCenter, float);

  itkSetMacro(GatingWindowShape, int);
  itkGetMacro(GatingWindowShape, int);

  std::vector<float>
  GetGatingWeights();
  std::vector<float>
  GetGatingWeightsOnSelectedProjections();

protected:
  PhaseGatingImageFilter();
  ~PhaseGatingImageFilter() override = default;

  void
  GenerateOutputInformation() override;

  void
  SelectProjections();

  void
  ComputeWeights();

  void
  SetPhases(std::vector<float> phases);

  /** Member pointers to the filters used internally (for convenience)*/
  rtk::PhaseReader::Pointer m_PhaseReader;

  /** Member variables */
  std::vector<float> m_GatingWeights;
  std::vector<float> m_GatingWeightsOnSelectedProjections;
  std::vector<float> m_Phases;
  float              m_GatingWindowWidth;
  float              m_GatingWindowCenter;
  int                m_GatingWindowShape;
  std::string        m_PhasesFileName;
};
} // namespace rtk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "rtkPhaseGatingImageFilter.hxx"
#endif

#endif


text:
@(title: String, javascript: Html = Html(""), login: Boolean = false)(content: Html)
<!DOCTYPE html>

    <title>@title</title>
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("css/main.min.css")">
    <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("img/favicon.png")">

    <link href="@routes.Assets.at("css/bootstrap.min.css")" rel="stylesheet" media="screen">
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">

            <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

            </button>
          @if(login) {
            Italian Startup Directory
          } else {
            Italian Startup Directory
          }

Home

Esplora

            @if(login) {
              Logout
            } else {
              Login
            }

    @content

        About

        Contattaci

        Privacy

  @helper.requireJs(core = routes.Assets.at("js/require.js").url, module = routes.Assets.at("js/app.min").url)

  @javascript


text:
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;

namespace CodeEditor.Text.UI.Unity.Engine.Implementation
{
	public static class MissingEngineAPI
	{
		public static GUIContent GUIContent_Temp(string content)
		{
			return _GUIContent_Temp(content);
		}

		private static readonly GUIContent_Temp_T _GUIContent_Temp = (GUIContent_Temp_T)DelegateForStaticMethodOf<GUIContent, GUIContent_Temp_T>("Temp");

		private delegate GUIContent GUIContent_Temp_T(string content);

		private static Delegate DelegateForStaticMethodOf<T, TDelegate>(string name)
		{
			return DelegateForStaticMethodOf(typeof(T), name, typeof(TDelegate));
		}

		private static Delegate DelegateForStaticMethodOf(Type type, string name, Type delegateType)
		{
			return Delegate.CreateDelegate(delegateType, StaticMethodOf(type, name, DelegateSignature(delegateType)));
		}

		private static Type[] DelegateSignature(Type delegateType)
		{
			return delegateType.GetMethod("Invoke").GetParameters().Select(_ => _.ParameterType).ToArray();
		}

		private static MethodInfo StaticMethodOf(Type type, string name, params Type[] signature)
		{
			var result = type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, signature, null);
			if (result == null)
				throw new ArgumentException(string.Format("Can't find method {0}.{1}({2})", type.Name, name, string.Join(", ", signature.Select(_ => _.FullName).ToArray())));
			return result;
		}
	}
}


text:
import React, { Component, PropTypes } from 'react';
import { formatCurrency } from './utils';
import styles from 'components/map/SelectedHex.module.scss';
import PopInventory from './pop_inventory';

export default class PopTable extends Component {
  static propTypes = {
    pops: PropTypes.array.isRequired
  };

  render () {
    const { pops } = this.props;
    return (

            Job
            Size
            +/-
            Money
            Profit
            # Trades
            Trade Success
            # B
            Inventory

          {_.orderBy(pops, 'id').map((pop, id) => {
            const total_trades = pop.successful_trades + pop.failed_trades;
            return (

                {pop.pop_job.title}
                {pop.population.toLocaleString()}
                {(pop.population - pop.population_yesterday).toLocaleString()}
                {formatCurrency(pop.money)}
                {formatCurrency(pop.money - pop.money_yesterday)}
                {total_trades.toLocaleString()}
                {_.round(pop.successful_trades / total_trades * 100, 2).toLocaleString()}%
                {pop.bankrupt_times.toLocaleString()}
                <PopInventory inventory={pop.inventory} />

            )
          })}

    )
  }
}


text:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SimpleChange, SimpleChanges, NO_ERRORS_SCHEMA } from '@angular/core';

import { NavItemComponent } from './nav-item.component';
import { NavigationNode } from 'app/navigation/navigation.model';

describe('NavItemComponent', () => {

  // Testing the component class behaviors, independent of its template
  // No dependencies. Just new it and test :)
  // Let e2e tests verify how it displays.
  describe('(class-only)', () => {

    let component: NavItemComponent;

    let selectedNodes: NavigationNode[];
    let setClassesSpy: jasmine.Spy;

    function initialize(nd: NavigationNode) {
      component.node = nd;
      onChanges(); // Angular calls when initializing the component
    }

    // Enough to triggers component's ngOnChange method
    function onChanges() {
      component.ngOnChanges();
    }

    beforeEach(() => {

      component = new NavItemComponent();
      setClassesSpy = spyOn(component, 'setClasses').and.callThrough();

      // Selected nodes is the selected node and its header ancestors
      selectedNodes = [
        { title: 'a' },           // selected node: an item or a header
        { title: 'parent' },      // selected node's header parent
        { title: 'grandparent' }, // selected node's header grandparent
      ];
      component.selectedNodes = selectedNodes;
    });

    describe('should have expected classes when initialized', () => {
      it('with selected node', () => {
        initialize(selectedNodes[0]);
        expect(component.classes).toEqual(
          // selected node should be expanded even if is a header.
          { 'level-1': true, collapsed: false, expanded: true, selected: true }
        );
      });

      it('with selected node ancestor', () => {
        initialize(selectedNodes[1]);
        expect(component.classes).toEqual(
          // ancestor is a header and should be expanded
          { 'level-1': true, collapsed: false, expanded: true, selected: true }
        );
      });

      it('with other than a selected node or ancestor', () => {
        initialize({ title: 'x' });
        expect(component.classes).toEqual(
          { 'level-1': true, collapsed: true, expanded: false, selected: false }
        );
      });
    });

    describe('when becomes a non-selected node', () => {

      // this node won't be the selected node when ngOnChanges() called
      beforeEach(() => component.node = { title: 'x' });

      it('should de-select if previously selected', () => {
        component.isSelected = true;
        onChanges();
        expect(component.isSelected).toBe(false, 'becomes de-selected');
      });

      it('should collapse if previously expanded in narrow mode', () => {
        component.isWide = false;
        component.isExpanded = true;
        onChanges();
        expect(component.isExpanded).toBe(false, 'becomes collapsed');
      });

      it('should remain expanded in wide mode', () => {
        component.isWide = true;
        component.isExpanded = true;
        onChanges();
        expect(component.isExpanded).toBe(true, 'remains expanded');
      });
    });

    describe('when becomes a selected node', () => {

      // this node will be the selected node when ngOnChanges() called
      beforeEach(() => component.node = selectedNodes[0]);

      it('should select when previously not selected', () => {
        component.isSelected = false;
        onChanges();
        expect(component.isSelected).toBe(true, 'becomes selected');
      });

      it('should expand the current node or keep it expanded', () => {
        component.isExpanded = false;
        onChanges();
        expect(component.isExpanded).toBe(true, 'becomes true');

        component.isExpanded = true;
        onChanges();
        expect(component.isExpanded).toBe(true, 'remains true');
      });
    });

    describe('when becomes a selected ancestor node', () => {

      // this node will be a selected node ancestor header when ngOnChanges() called
      beforeEach(() => component.node = selectedNodes[2]);

      it('should select when previously not selected', () => {
        component.isSelected = false;
        onChanges();
        expect(component.isSelected).toBe(true, 'becomes selected');
      });

      it('should always expand this header', () => {
        component.isExpanded = false;
        onChanges();
        expect(component.isExpanded).toBe(true, 'becomes expanded');

        component.isExpanded = false;
        onChanges();
        expect(component.isExpanded).toBe(true, 'stays expanded');
      });
    });

    describe('when headerClicked()', () => {
      // current node doesn't matter in these tests.

      it('should expand when headerClicked() and previously collapsed', () => {
        component.isExpanded = false;
        component.headerClicked();
        expect(component.isExpanded).toBe(true, 'should be expanded');
      });

      it('should collapse when headerClicked() and previously expanded', () => {
        component.isExpanded = true;
        component.headerClicked();
        expect(component.isExpanded).toBe(false, 'should be collapsed');
      });

      it('should not change isSelected when headerClicked()', () => {
        component.isSelected = true;
        component.headerClicked();
        expect(component.isSelected).toBe(true, 'remains selected');

        component.isSelected = false;
        component.headerClicked();
        expect(component.isSelected).toBe(false, 'remains not selected');
      });

      it('should set classes', () => {
        component.headerClicked();
        expect(setClassesSpy).toHaveBeenCalled();
      });
    });
  });

  describe('(via TestBed)', () => {
    let component: NavItemComponent;
    let fixture: ComponentFixture<NavItemComponent>;

    beforeEach(() => {
      TestBed.configureTestingModule({
        declarations: [NavItemComponent],
        schemas: [NO_ERRORS_SCHEMA]
      });
      fixture = TestBed.createComponent(NavItemComponent);
      component = fixture.componentInstance;
      component.node = {
        title: 'x',
        children: [
          { title: 'a' },
          { title: 'b', hidden: true},
          { title: 'c' }
        ]
      };
    });

    it('should not show the hidden child nav-item', () => {
      component.ngOnChanges(); // assume component.ngOnChanges ignores arguments
      fixture.detectChanges();
      const children = fixture.debugElement.queryAll(By.directive(NavItemComponent));
      expect(children.length).toEqual(2);
    });

    it('should pass the `isWide` property to all displayed child nav-items', () => {
      component.isWide = true;
      component.ngOnChanges(); // assume component.ngOnChanges ignores arguments
      fixture.detectChanges();
      let children = fixture.debugElement.queryAll(By.directive(NavItemComponent));
      expect(children.length).toEqual(2, 'when IsWide is true');
      children.forEach(child => expect(child.componentInstance.isWide).toBe(true));

      component.isWide = false;
      component.ngOnChanges();
      fixture.detectChanges();
      children = fixture.debugElement.queryAll(By.directive(NavItemComponent));
      expect(children.length).toEqual(2, 'when IsWide is false');
      children.forEach(child => expect(child.componentInstance.isWide).toBe(false));
    });
  });
});


text:
class Server {
public:
    Server(int sock) : m_sock(sock) { }

    ~Server() { }

    typedef msgpack::unique_ptr<msgpack::zone> unique_zone;

    void socket_readable()
    {
        m_pac.reserve_buffer(1024);

        ssize_t count =
            read(m_sock, m_pac.buffer(), m_pac.buffer_capacity());

        if(count <= 0) {
            if(count == 0) {
                throw std::runtime_error("connection closed");
            }
            if(errno == EAGAIN || errno == EINTR) {
                return;
            }
            throw std::runtime_error(strerror(errno));
        }

        m_pac.buffer_consumed(count);

        msgpack::unpacked result;
        while (m_pac.next(&result)) {
            msgpack::object msg = result.get();
            unique_zone& life = result.zone();
            process_message(msg, life);
        }

        if(m_pac.message_size() > 10*1024*1024) {
            throw std::runtime_error("message is too large");
        }
    }

private:
    void process_message(msgpack::object msg, unique_zone&)
    {
        std::cout << "message reached: " << msg << std::endl;
    }

private:
    int m_sock;
    msgpack::unpacker m_pac;
};

static void* run_server(void* arg)
{
    try {
        Server* srv = reinterpret_cast<Server*>(arg);

        while(true) {
            srv->socket_readable();
        }
        return NULL;

    } catch (std::exception& e) {
        std::cerr << "error while processing client packet: "
                  << e.what() << std::endl;
        return NULL;

    } catch (...) {
        std::cerr << "error while processing client packet: "
                  << "unknown error" << std::endl;
        return NULL;
    }
}

struct fwriter {
    fwriter(int fd) : m_fp( fdopen(fd, "w") ) { }

    void write(const char* buf, size_t buflen)
    {
        size_t count = fwrite(buf, buflen, 1, m_fp);
        if(count < 1) {
            std::cout << buflen << std::endl;
            std::cout << count << std::endl;
            throw std::runtime_error(strerror(errno));
        }
    }

    void flush() { fflush(m_fp); }

    void close() { fclose(m_fp); }

private:
    FILE* m_fp;
};

int main(void)
{
    int pair[2];
    if (pipe(pair) != 0) return -1;

    // run server thread
    Server srv(pair[0]);
    pthread_t thread;
    pthread_create(&thread, NULL,
            run_server, reinterpret_cast<void*>(&srv));

    // client thread:
    fwriter writer(pair[1]);
    msgpack::packer<fwriter> pk(writer);

    typedef msgpack::type::tuple<std::string, std::string, std::string> put_t;
    typedef msgpack::type::tuple<std::string, std::string> get_t;

    put_t req1("put", "apple", "red");
    put_t req2("put", "lemon", "yellow");
    get_t req3("get", "apple");
    pk.pack(req1);
    pk.pack(req2);
    pk.pack(req3);
    writer.flush();
    writer.close();

    pthread_join(thread, NULL);
}


text:
This package contains tools to run [MIST](http://mist-deid.sourceforge.net) on
Google Cloud. The example commands use the [bazel build system](http://bazel.build/versions/master/docs/install.html), but can also be
run directly (i.e.`python mist/xxx.py`) if $PYTHONPATH includes this
package.

## How to run

### BigQuery -> GCS

bigquery_to_gcs.py runs a query on BigQuery and writes the data to the given
path in Google Cloud Storage.

```shell
bazel run mist:bigquery_to_gcs -- \
--input_query "select patient_id, note from [${PROJECT?}:${DATASET?}.deid]" \
--output_path gs://${BUCKET?}/deid/mist/bq-output \
--project ${PROJECT?}
```

### Run MIST

run_deid.py runs Physionet De-ID via the Pipelines API on a sharded file in GCS.
The PhysioNet code and configuration has been packaged into a Docker container
at gcr.io/genomics-api-test/physionet. Running it requires having the Google
Python API client and Google Cloud Storage client installed:

```shell
pip install --upgrade apache_beam
pip install --upgrade google-api-python-client
pip install --upgrade google-cloud-storage
```

Example usage (run with `--help` for more about the arguments):

```shell
bazel run mist:run_mist -- \
  --model_filename gs://${BUCKET}/deid/mist/model \
  --project ${PROJECT?} \
  --log_directory gs://${BUCKET?}/deid/mist/logs \
  --input_pattern gs://${BUCKET?}/deid/mist/input/notes* \
  --output_directory gs://${BUCKET?}/deid/mist/output
```

### GCS -> BigQuery

gcs_to_bigquery.py grabs data from a given Google Cloud Storage path and puts
it into BigQuery.

Example usage:

```shell
bazel run mist:gcs_to_bigquery -- \
--input_pattern gs://${BUCKET?}/deid/mist/bq-output* \
--output_table "${PROJECT?}:${DATASET?}.deid_output"
```


text:
<?php

/**
 * Phinx configuration
 *
 *   Please, don't move this file inside `default` folder
 *   It should be placed here for avoid `Config` call in recursion
 *
 * @link https://github.com/robmorgan/phinx/blob/master/docs/configuration.rst
 * @return array
 */

return [
    'paths' => [
        'migrations' => PATH_DATA . '/migrations',
        'seeds' => PATH_DATA . '/seeds'
    ],
    'environments' => [
        'default_migration_table' => 'migrations',
        'default' => (function () {
            $data = \Bluz\Proxy\Config::get('db', 'connect');
            $data['adapter'] = $data['type'];
            $data['charset'] = 'utf8';
            return $data;
        })()
    ]
];


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import unittest

from pants.util.contextutil import temporary_file
from pants.util.fileutil import atomic_copy

class FileutilTest(unittest.TestCase):
  def test_atomic_copy(self):
    with temporary_file() as src:
      src.write(src.name)
      src.flush()
      with temporary_file() as dst:
        atomic_copy(src.name, dst.name)
        dst.close()
        with open(dst.name) as new_dst:
          self.assertEquals(src.name, new_dst.read())


text:
"""Add hashtags to events

Revision ID: 84d8ce8453f3
Revises: 0c5ae11e7666
Create Date: 2022-09-17 08:04:21.745061

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '84d8ce8453f3'
down_revision = '0c5ae11e7666'
branch_labels = None
depends_on = None

def upgrade():
    op.add_column('events', sa.Column('hashtags', sa.String(length=255), nullable=True))
    op.drop_column('users', 'carddata') # clear card data column
    op.add_column('users', sa.Column('carddata', sa.String(length=255), nullable=True))
    # use socialize command to rebuild image index

def downgrade():
    op.drop_column('events', 'hashtags')


text:
using System;
using System.Collections.Generic;

namespace MonoDevelop.Database.Sql
{
	public class UserAlterSchema : AbstractAlterSchema<UserSchema>
	{
		public UserAlterSchema (UserSchema oldSchema, UserSchema newSchema)
			: base (oldSchema, newSchema)
		{
		}

		protected override void DetermineDifferences (UserSchema oldSchema, UserSchema newSchema)
		{
			base.DetermineDifferences (oldSchema, newSchema);

			//TODO:
		}
	}
}


text:
#pragma once
#include <aws/proton/Proton_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/proton/model/EnvironmentTemplateSummary.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Proton
{
namespace Model
{
  class AWS_PROTON_API ListEnvironmentTemplatesResult
  {
  public:
    ListEnvironmentTemplatesResult();
    ListEnvironmentTemplatesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListEnvironmentTemplatesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline ListEnvironmentTemplatesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline ListEnvironmentTemplatesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
A token that indicates the location of the next environment template in the
     * array of environment templates, after the current requested list of environment
     * templates.

     */
    inline ListEnvironmentTemplatesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
An array of environment templates with detail data.

     */
    inline const Aws::Vector<EnvironmentTemplateSummary>& GetTemplates() const{ return m_templates; }

    /**
     *
An array of environment templates with detail data.

     */
    inline void SetTemplates(const Aws::Vector<EnvironmentTemplateSummary>& value) { m_templates = value; }

    /**
     *
An array of environment templates with detail data.

     */
    inline void SetTemplates(Aws::Vector<EnvironmentTemplateSummary>&& value) { m_templates = std::move(value); }

    /**
     *
An array of environment templates with detail data.

     */
    inline ListEnvironmentTemplatesResult& WithTemplates(const Aws::Vector<EnvironmentTemplateSummary>& value) { SetTemplates(value); return *this;}

    /**
     *
An array of environment templates with detail data.

     */
    inline ListEnvironmentTemplatesResult& WithTemplates(Aws::Vector<EnvironmentTemplateSummary>&& value) { SetTemplates(std::move(value)); return *this;}

    /**
     *
An array of environment templates with detail data.

     */
    inline ListEnvironmentTemplatesResult& AddTemplates(const EnvironmentTemplateSummary& value) { m_templates.push_back(value); return *this; }

    /**
     *
An array of environment templates with detail data.

     */
    inline ListEnvironmentTemplatesResult& AddTemplates(EnvironmentTemplateSummary&& value) { m_templates.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_nextToken;

    Aws::Vector<EnvironmentTemplateSummary> m_templates;
  };

} // namespace Model
} // namespace Proton
} // namespace Aws


text:
package azkaban.jobtype;

import azkaban.jobExecutor.JavaProcessJob;
import azkaban.utils.Props;
import org.apache.log4j.Logger;

public class FakeJavaJob extends JavaProcessJob {

  public FakeJavaJob(final String jobid, final Props sysProps, final Props jobProps,
      final Logger log) {
    super(jobid, sysProps, jobProps, log);
  }
}


text:
xlib = {}

function xlib.makecheckbox( t )
	local pnl = vgui.Create( "DCheckBoxLabel", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetText( t.label or "" )
	pnl:SizeToContents()
	pnl:SetValue( t.value or 0 )
	if t.convar then pnl:SetConVar( t.convar ) end

	if t.textcolor then
		pnl:SetTextColor( t.textcolor )
	else
		pnl:SetTextColor( SKIN.text_dark )
	end

	if not t.tooltipwidth then t.tooltipwidth = 250 end
	if t.tooltip then
		if t.tooltipwidth ~= 0 then
			t.tooltip = xlib.wordWrap( t.tooltip, t.tooltipwidth, "Default" )
		end
		pnl:SetToolTip( t.tooltip )
	end

	function pnl:SetDisabled( val )
		pnl.disabled = val
		pnl:SetMouseInputEnabled( not val )
		pnl:SetAlpha( val and 128 or 255 )
	end
	if t.disabled then pnl:SetDisabled( t.disabled ) end

	--Work around for bug where changing the parent of a disabled textbox reenables mouse input.
	local tempfunc = pnl.SetParent
	pnl.SetParent = function( self, parent )
		local ret = tempfunc( self, parent )
		self:SetDisabled( self.disabled )
		return ret
	end

	--Replicated Convar Updating
	if t.repconvar then
		xlib.checkRepCvarCreated( t.repconvar )
		pnl:SetValue( GetConVar( t.repconvar ):GetBool() )
		function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
			if cl_cvar == t.repconvar:lower() then
				pnl:SetValue( new_val )
			end
		end
		hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
		function pnl:OnChange( bVal )
			RunConsoleCommand( t.repconvar, tostring( bVal and 1 or 0 ) )
		end
		pnl.Think = function() end --Override think functions to remove Garry's convar check to (hopefully) speed things up
		pnl.ConVarNumberThink = function() end
		pnl.ConVarStringThink = function() end
		pnl.ConVarChanged = function() end
	end
	return pnl
end

function xlib.makelabel( t )
	local pnl = vgui.Create( "DLabel", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetText( t.label or "" )
	if not t.tooltipwidth then t.tooltipwidth = 250 end
	if t.tooltip then
		if t.tooltipwidth ~= 0 then
			t.tooltip = xlib.wordWrap( t.tooltip, t.tooltipwidth, "Default" )
		end
		pnl:SetToolTip( t.tooltip )
		pnl:SetMouseInputEnabled( true )
	end

	if t.font then pnl:SetFont( t.font ) end
	if t.w and t.wordwrap then
		pnl:SetText( xlib.wordWrap( t.label, t.w, t.font or "Default" ) )
	end
	pnl:SizeToContents()
	if t.w then pnl:SetWidth( t.w ) end
	if t.h then pnl:SetHeight( t.h ) end
	if t.textcolor then
		pnl:SetTextColor( t.textcolor )
	else
		pnl:SetTextColor( SKIN.text_dark )
	end

	return pnl
end

function xlib.makelistlayout( t )
	local pnl = vgui.Create( "DListLayout" )
	pnl.scroll = vgui.Create( "DScrollPanel", t.parent )

	pnl.scroll:SetPos( t.x, t.y )
	pnl.scroll:SetSize( t.w, t.h )
	pnl:SetSize( t.w, t.h )
	pnl.scroll:AddItem( pnl )

	function pnl:PerformLayout()
		self:SizeToChildren( false, true )
		self:SetWide( self.scroll:GetWide() - ( self.scroll.VBar.Enabled and 16 or 0 ) )
	end
	return pnl
end

function xlib.makebutton( t )
	local pnl = vgui.Create( "DButton", t.parent )
	pnl:SetSize( t.w or 20, t.h or 20 )
	pnl:SetPos( t.x, t.y )
	pnl:SetText( t.label or "" )
	pnl:SetDisabled( t.disabled )
	if t.icon then pnl:SetIcon( t.icon ) end
	if t.btype and t.btype == "close" then
		pnl.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "WindowCloseButton", panel, w, h ) end
	end
	if t.centericon then	--Place the image in the cetner of the button instead of the default layout.
		function pnl:PerformLayout()
			if ( IsValid( self.m_Image ) ) then
				self.m_Image:SetPos( (self:GetWide() - self.m_Image:GetWide()) * 0.5, (self:GetTall() - self.m_Image:GetTall()) * 0.5 )
				self:SetTextInset( self.m_Image:GetWide() + 16, 0 )
			end
			DLabel.PerformLayout( self )
		end
	end
	return pnl
end

function xlib.makeframe( t )
	local pnl = vgui.Create( "DFrame", t.parent )
	pnl:SetSize( t.w, t.h )
	if t.nopopup ~= true then pnl:MakePopup() end
	pnl:SetPos( t.x or ScrW()/2-t.w/2, t.y or ScrH()/2-t.h/2 )
	pnl:SetTitle( t.label or "" )
	if t.draggable ~= nil then pnl:SetDraggable( t.draggable ) end
	if t.showclose ~= nil then pnl:ShowCloseButton( t.showclose ) end
	if t.skin then pnl:SetSkin( t.skin ) end
	if t.visible ~= nil then pnl:SetVisible( t.visible ) end
	return pnl
end

function xlib.makepropertysheet( t )
	local pnl = vgui.Create( "DPropertySheet", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )
	--Clears all of the tabs in the base.
	function pnl:Clear()
		for _, Sheet in ipairs( self.Items ) do
			Sheet.Panel:SetParent( t.offloadparent )
			Sheet.Tab:Remove()
		end
		self.m_pActiveTab = nil
		self:SetActiveTab( nil )
		self.tabScroller.Panels = {}
		self.Items = {}
	end
	return pnl
end

function xlib.maketextbox( t )
	local pnl = vgui.Create( "DTextEntry", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetWide( t.w )
	pnl:SetTall( t.h or 20 )
	pnl:SetEnterAllowed( true )
	if t.convar then pnl:SetConVar( t.convar ) end
	if t.text then pnl:SetText( t.text ) end
	if t.enableinput then pnl:SetEnabled( t.enableinput ) end
	pnl.selectAll = t.selectall
	if not t.tooltipwidth then t.tooltipwidth = 250 end
	if t.tooltip then
		if t.tooltipwidth ~= 0 then
			t.tooltip = xlib.wordWrap( t.tooltip, t.tooltipwidth, "Default" )
		end
		pnl:SetToolTip( t.tooltip )
	end

	function pnl:SetDisabled( val ) --Simulate enabling/disabling of a textbox
		pnl:SetEnabled( not val )
		pnl:SetMouseInputEnabled( not val )
		pnl:SetAlpha( val and 128 or 255 )
	end
	if t.disabled then pnl:SetDisabled( t.disabled ) end

	--Replicated Convar Updating
	if t.repconvar then
		xlib.checkRepCvarCreated( t.repconvar )
		pnl:SetValue( GetConVar( t.repconvar ):GetString() )
		function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
			if cl_cvar == t.repconvar:lower() then
				pnl:SetValue( new_val )
			end
		end
		hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
		function pnl:UpdateConvarValue()
			RunConsoleCommand( t.repconvar, self:GetValue() )
		end
		function pnl:OnEnter()
			RunConsoleCommand( t.repconvar, self:GetValue() )
		end
		pnl.Think = function() end --Override think functions to remove Garry's convar check to (hopefully) speed things up
		pnl.ConVarNumberThink = function() end
		pnl.ConVarStringThink = function() end
		pnl.ConVarChanged = function() end
	end
	return pnl
end

function xlib.makelistview( t )
	local pnl = vgui.Create( "DListView", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )
	pnl:SetMultiSelect( t.multiselect )
	pnl:SetHeaderHeight( t.headerheight or 20 )
	return pnl
end

function xlib.makecat( t )
	local pnl = vgui.Create( "DCollapsibleCategory", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )
	pnl:SetLabel( t.label or "" )
	pnl:SetContents( t.contents )
	t.contents:Dock( TOP )

	if t.expanded ~= nil then pnl:SetExpanded( t.expanded ) end
	if t.checkbox then
		pnl.checkBox = vgui.Create( "DCheckBox", pnl.Header )
		pnl.checkBox:SetValue( t.expanded )
		function pnl.checkBox:DoClick()
			self:Toggle()
			pnl:Toggle()
		end
		function pnl.Header:OnMousePressed( mcode )
			if ( mcode == MOUSE_LEFT ) then
				self:GetParent():Toggle()
				self:GetParent().checkBox:Toggle()
				return
			end
			return self:GetParent():OnMousePressed( mcode )
		end
		local tempfunc = pnl.PerformLayout
		pnl.PerformLayout = function( self )
			tempfunc( self )
			self.checkBox:SetPos( self:GetWide()-18, 2 )
		end
	end

	function pnl:SetOpen( bVal )
		if not self:GetExpanded() and bVal then
			pnl.Header:OnMousePressed( MOUSE_LEFT ) --Call the mouse function so it properly toggles the checkbox state (if it exists)
		elseif self:GetExpanded() and not bVal then
			pnl.Header:OnMousePressed( MOUSE_LEFT )
		end
	end

	return pnl
end

function xlib.makepanel( t )
	local pnl = vgui.Create( "DPanel", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )
	if t.visible ~= nil then pnl:SetVisible( t.visible ) end
	return pnl
end

function xlib.makeXpanel( t )
	pnl = vgui.Create( "xlib_Panel", t.parent )
	pnl:MakePopup()
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )
	if t.visible ~= nil then pnl:SetVisible( t.visible ) end
	return pnl
end

function xlib.makenumberwang( t )
	local pnl = vgui.Create( "DNumberWang", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetDecimals( t.decimal or 0 )
	pnl:SetMinMax( t.min or 0, t.max or 255 )
	pnl:SizeToContents()
	pnl:SetValue( t.value )
	if t.w then pnl:SetWide( t.w ) end
	if t.h then pnl:SetTall( t.h ) end
	return pnl
end

function xlib.makecombobox( t )
	local pnl = vgui.Create( "DComboBox", t.parent )
	t.w = t.w or 100
	t.h = t.h or 20
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )

	--Create a textbox to use in place of the button
	if ( t.enableinput == true ) then
		pnl.TextEntry = vgui.Create( "DTextEntry", pnl )
		pnl.TextEntry.selectAll = t.selectall
		pnl.TextEntry:SetEditable( true )

		pnl.TextEntry.OnGetFocus = function( self ) --Close the menu when the textbox is clicked, IF the menu was open.
			hook.Run( "OnTextEntryGetFocus", self )
			if ( pnl.Menu ) then
				pnl.Menu:Remove()
				pnl.Menu = nil
			end
		end

		--Override GetValue/SetValue to get/set the text from the TextEntry instead of itself.
		pnl.GetValue = function( self ) return self.TextEntry:GetValue() end
		pnl.SetText = function( self, val ) self.TextEntry:SetValue( val ) end

		pnl.ChooseOption = function( self, value, index ) --Update the text of the TextEntry when an option is selected.
			if ( self.Menu ) then
				self.Menu:Remove()
				self.Menu = nil
			end
			self.TextEntry:SetText( value )
			self:OnSelect( index, value, self.Data[index] )
		end

		pnl.PerformLayout = function( self ) --Update the size of the textbox when the combobox's PerformLayout is called.
			self.DropButton:SetSize( 15, 15 )
			self.DropButton:AlignRight( 4 )
			self.DropButton:CenterVertical()
			self.TextEntry:SetSize( self:GetWide()-20, self:GetTall() )
		end
	end

	pnl:SetText( t.text or "" )

	if not t.tooltipwidth then t.tooltipwidth = 250 end
	if t.tooltip then
		if t.tooltipwidth ~= 0 then
			t.tooltip = xlib.wordWrap( t.tooltip, t.tooltipwidth, "Default" )
		end
		pnl:SetToolTip( t.tooltip )
	end

	if t.choices then
		for i, v in ipairs( t.choices ) do
			pnl:AddChoice( v )
		end
	end

	function pnl:SetDisabled( val ) --enabling/disabling of a textbox
		self:SetMouseInputEnabled( not val )
		self:SetAlpha( val and 128 or 255 )
	end
	if t.disabled then pnl:SetDisabled( t.disabled ) end

	--Garrys function with no comments, just adding support for Spacers
	function pnl:OpenMenu()
		if ( #self.Choices == 0 ) then return end
		if ( IsValid( self.Menu ) ) then
			self.Menu:Remove()
			self.Menu = nil
		end
		self.Menu = DermaMenu()
			for k, v in pairs( self.Choices ) do
				if v == "--*" then --This is the string to determine where to add the spacer
					self.Menu:AddSpacer()
				else
					self.Menu:AddOption( v, function() self:ChooseOption( v, k ) end )
				end
			end
			local x, y = self:LocalToScreen( 0, self:GetTall() )
			self.Menu:SetMinimumWidth( self:GetWide() )
			self.Menu:Open( x, y, false, self )
	end

	--Replicated Convar Updating
	if t.repconvar then
		xlib.checkRepCvarCreated( t.repconvar )
		if t.isNumberConvar then --This is for convar settings stored via numbers (like ulx_rslotsMode)
			if t.numOffset == nil then t.numOffset = 1 end
			local cvar = GetConVar( t.repconvar ):GetInt()
			if tonumber( cvar ) and cvar + t.numOffset <= #pnl.Choices and cvar + t.numOffset > 0 then
				pnl:ChooseOptionID( cvar + t.numOffset )
			else
				pnl:SetText( "Invalid Convar Value" )
			end
			function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
				if cl_cvar == t.repconvar:lower() then
					if tonumber( new_val ) and new_val + t.numOffset <= #pnl.Choices and new_val + t.numOffset > 0 then
						pnl:ChooseOptionID( new_val + t.numOffset )
					else
						pnl:SetText( "Invalid Convar Value" )
					end
				end
			end
			hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
			function pnl:OnSelect( index )
				RunConsoleCommand( t.repconvar, tostring( index - t.numOffset ) )
			end
		else  --Otherwise, use each choice as a string for the convar
			pnl:SetText( GetConVar( t.repconvar ):GetString() )
			function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
				if cl_cvar == t.repconvar:lower() then
					pnl:SetText( new_val )
				end
			end
			hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
			function pnl:OnSelect( index, value )
				RunConsoleCommand( t.repconvar, value )
			end
		end
	end

	return pnl
end

function xlib.maketree( t )
	local pnl = vgui.Create( "DTree", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w, t.h )

	function pnl:Clear() --Clears the DTree.
		if self.RootNode.ChildNodes then
			for _, node in ipairs( self.RootNode.ChildNodes:GetChildren() ) do
				node:Remove()
			end
			self.m_pSelectedItem = nil
			self:InvalidateLayout()
		end
	end
	return pnl
end

function xlib.makecolorpicker( t )
	local pnl = vgui.Create( "xlibColorPanel", t.parent )
	pnl:SetPos( t.x, t.y )
	if t.noalphamodetwo then pnl:NoAlphaModeTwo() end --Provide an alternate layout with no alpha bar.
	if t.addalpha then
		pnl:AddAlphaBar()
		if t.alphamodetwo then pnl:AlphaModeTwo() end
	end
	if t.color then pnl:SetColor( t.color ) end
	if t.repconvar then
		xlib.checkRepCvarCreated( t.repconvar )
		local col = GetConVar( t.repconvar ):GetString()
		if col == "0" then col = "0 0 0" end
		col = string.Split( col, " " )
		pnl:SetColor( Color( col[1], col[2], col[3] ) )
		function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
			if cl_cvar == t.repconvar:lower() then
				local col = string.Split( new_val, " " )
				pnl:SetColor( Color( col[1], col[2], col[3] ) )
			end
		end
		hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
		function pnl:OnChange( color )
			RunConsoleCommand( t.repconvar, color.r .. " " .. color.g .. " " .. color.b )
		end
	end
	return pnl
end

--Thanks to Megiddo for this code! :D
function xlib.wordWrap( text, width, font )
	surface.SetFont( font )
	if not surface.GetTextSize( "" ) then
		surface.SetFont( "default" ) --Set font to default if specified font does not return a size properly.
	end
	text = text:Trim()
	local output = ""
	local pos_start, pos_end = 1, 1
	while true do
		local begin, stop = text:find( "%s+", pos_end + 1 )

		if (surface.GetTextSize( text:sub( pos_start, begin or -1 ):Trim() ) > width and pos_end - pos_start > 0) then -- If it's not going to fit, split into a newline
			output = output .. text:sub( pos_start, pos_end ):Trim() .. "\n"
			pos_start = pos_end + 1
			pos_end = pos_end + 1
		else
			pos_end = stop
		end

		if not stop then -- We've hit our last word
			output = output .. text:sub( pos_start ):Trim()
			break
		end
	end
	return output
end

function xlib.makeprogressbar( t )
	pnl = vgui.Create( "DProgress", t.parent )
	pnl.Label = xlib.makelabel{ x=5, y=3, w=(t.w or 100), textcolor=SKIN.text_dark, parent=pnl }
	pnl:SetPos( t.x, t.y )
	pnl:SetSize( t.w or 100, t.h or 20 )
	pnl:SetFraction( t.value or 0 )
	if t.visible ~= nil then pnl:SetVisible( t.visible ) end
	return pnl
end

function xlib.checkRepCvarCreated( cvar )
	if GetConVar( cvar ) == nil then
		CreateClientConVar( cvar:lower(), 0, false, false ) --Replicated cvar hasn't been created via ULib. Create a temporary one to prevent errors
	end
end

function xlib.makeslider( t )
	local pnl = vgui.Create( "DNumSlider", t.parent )
	pnl:SetPos( t.x, t.y )
	pnl:SetWide( t.w or 100 )
	pnl:SetTall( t.h or 20 )
	pnl:SetText( t.label or "" )
	pnl:SetMinMax( t.min or 0, t.max or 100 )
	pnl:SetDecimals( t.decimal or 0 )
	pnl.TextArea:SetDrawBackground( true )
	pnl.TextArea.selectAll = t.selectall
	pnl.Label:SizeToContents()

	if t.textcolor then
		pnl.Label:SetTextColor( t.textcolor )
	else
		pnl.Label:SetTextColor( SKIN.text_dark )
	end

	if t.fixclip then pnl.Slider.Knob:NoClipping( false ) end --Fixes clipping on the knob, an example is the sandbox limit sliders.

	if t.convar then pnl:SetConVar( t.convar ) end
	if not t.tooltipwidth then t.tooltipwidth = 250 end
	if t.tooltip then
		if t.tooltipwidth ~= 0 then
			t.tooltip = xlib.wordWrap( t.tooltip, t.tooltipwidth, "Default" )
		end
		pnl:SetToolTip( t.tooltip )
	end

	--Support for enabling/disabling slider
	pnl.SetDisabled = function( self, val )
		pnl:SetAlpha( val and 128 or 255 )
		pnl:SetEnabled( not val )
		pnl.TextArea:SetEnabled( not val )
		pnl.TextArea:SetMouseInputEnabled( not val )
		pnl.Scratch:SetMouseInputEnabled( not val )
		pnl.Slider:SetMouseInputEnabled( not val )
	end
	if t.disabled then pnl:SetDisabled( t.disabled ) end

	pnl:SizeToContents()

	--
	--The following code bits are basically copies of Garry's code with changes to prevent the slider from sending updates so often
	pnl.GetValue = function( self ) return tonumber( self.TextArea:GetValue() ) end
	function pnl.SetValue( self, val )
		if ( val == nil ) then return end
		if t.clampmin then val = math.max( tonumber( val ) or 0, self:GetMin() ) end
		if t.clampmax then val = math.min( tonumber( val ) or 0, self:GetMax() ) end
		self.Scratch:SetValue( val )
		self.ValueUpdated( val )
		self:ValueChanged( val )
	end
	function pnl.ValueChanged( self, val )
		if t.clampmin then val = math.max( tonumber( val ) or 0, self:GetMin() ) end
		if t.clampmax then val = math.min( tonumber( val ) or 0, self:GetMax() ) end
		self.Slider:SetSlideX( self.Scratch:GetFraction( val ) )
		if ( self.TextArea != vgui.GetKeyboardFocus() ) then
			self.TextArea:SetValue( self.Scratch:GetTextValue() )
		end
		self:OnValueChanged( val )
	end

	--Textbox
	function pnl.ValueUpdated( value )
		pnl.TextArea:SetText( string.format("%." .. ( pnl.Scratch:GetDecimals() ) .. "f", tonumber( value ) or 0) )
	end
	pnl.TextArea.OnTextChanged = function() end
	function pnl.TextArea:OnEnter()
		pnl.TextArea:SetText( string.format("%." .. ( pnl.Scratch:GetDecimals() ) .. "f", tonumber( pnl.TextArea:GetText() ) or 0) )
		if pnl.OnEnter then pnl:OnEnter() end
	end
	function pnl.TextArea:OnLoseFocus()
		pnl:SetValue( pnl.TextArea:GetText() )
		hook.Call( "OnTextEntryLoseFocus", nil, self )
	end

	--Slider
	local pnl_val
	function pnl:TranslateSliderValues( x, y )
		pnl_val = self.Scratch:GetMin() + (x * self.Scratch:GetRange()) --Store the value and update the textbox to the new value
		pnl.ValueUpdated( pnl_val )
		self.Scratch:SetFraction( x )

		return self.Scratch:GetFraction(), y
	end
	local tmpfunc = pnl.Slider.Knob.OnMouseReleased
	pnl.Slider.Knob.OnMouseReleased = function( self, mcode )
		tmpfunc( self, mcode )
		pnl.Slider:OnMouseReleased( mcode )
	end
	local tmpfunc = pnl.Slider.SetDragging
	pnl.Slider.SetDragging = function( self, bval )
		tmpfunc( self, bval )
		if ( !bval ) then pnl:SetValue( pnl.TextArea:GetText() ) end
	end
	pnl.Slider.OnMouseReleased = function( self, mcode )
		self:SetDragging( false )
		self:MouseCapture( false )
	end

	--Scratch
	function pnl.Scratch:OnCursorMoved( x, y )
		if ( !self:GetActive() ) then return end

		x = x - math.floor( self:GetWide() * 0.5 )
		y = y - math.floor( self:GetTall() * 0.5 )

		local zoom = self:GetZoom()
		local ControlScale = 100 / zoom;
		local maxzoom = 20
		if ( self:GetDecimals() ) then
			maxzoom = 10000
		end
		zoom = math.Clamp( zoom + ((y * -0.6) / ControlScale), 0.01, maxzoom );
		self:SetZoom( zoom )

		local value = self:GetFloatValue()
		value = math.Clamp( value + (x * ControlScale * 0.002), self:GetMin(), self:GetMax() );
		self:SetFloatValue( value )
		pnl_val = value --Store value for later
		pnl.ValueUpdated( pnl_val )

		self:LockCursor()
	end
	pnl.Scratch.OnMouseReleased = function( self, mousecode )
		g_Active = nil

		self:SetActive( false )
		self:MouseCapture( false )
		self:SetCursor( "sizewe" )

		pnl:SetValue( pnl.TextArea:GetText() )
	end
	--End code changes
	--

	if t.value then pnl:SetValue( t.value ) end

	--Replicated Convar Updating
	if t.repconvar then
		xlib.checkRepCvarCreated( t.repconvar )
		pnl:SetValue( GetConVar( t.repconvar ):GetFloat() )
		function pnl.ConVarUpdated( sv_cvar, cl_cvar, ply, old_val, new_val )
			if cl_cvar == t.repconvar:lower() then
				if ( IsValid( pnl ) ) then	--Prevents random errors when joining.
					pnl:SetValue( new_val )
				end
			end
		end
		hook.Add( "ULibReplicatedCvarChanged", "XLIB_" .. t.repconvar, pnl.ConVarUpdated )
		function pnl:OnValueChanged( val )
			RunConsoleCommand( t.repconvar, tostring( val ) )
		end
		--Override think functions to remove Garry's convar check to (hopefully) speed things up
		pnl.ConVarNumberThink = function() end
		pnl.ConVarStringThink = function() end
		pnl.ConVarChanged = function() end
	end

	return pnl
end

-----------------------------------------
--A stripped-down customized DPanel allowing for textbox input!
-----------------------------------------
local PANEL = {}
AccessorFunc( PANEL, "m_bPaintBackground", "PaintBackground" )
Derma_Hook( PANEL, "Paint", "Paint", "Panel" )
Derma_Hook( PANEL, "ApplySchemeSettings", "Scheme", "Panel" )

function PANEL:Init()
	self:SetPaintBackground( true )
end

derma.DefineControl( "xlib_Panel", "", PANEL, "EditablePanel" )

-----------------------------------------
--A copy of Garry's ColorCtrl used in the sandbox spawnmenu, with the following changes:
-- -Doesn't use convars whatsoever
-- -Is a fixed size, but you can have it with/without the alphabar, and there's two layout styles without the alpha bar.
-- -Has two functions: OnChange and OnChangeImmediate for greater control of handling changes.
-----------------------------------------
local PANEL = {}
function PANEL:Init()
	self.showAlpha=false

	self:SetSize( 130, 135 )

	self.RGBBar = vgui.Create( "DRGBPicker", self )
	self.RGBBar.OnChange = function( ctrl, color )
		if ( self.showAlpha ) then
			color.a = self.txtA:GetValue()
		end
		self:SetBaseColor( color )
	end
	self.RGBBar:SetSize( 15, 100 )
	self.RGBBar:SetPos( 5,5 )
	self.RGBBar.OnMouseReleased = function( self, mcode )
		self:MouseCapture( false )
		self:OnCursorMoved( self:CursorPos() )
		self:GetParent():OnChange( self:GetParent():GetColor() )
	end
	function self.RGBBar:SetColor( color )
		local h, s, v = ColorToHSV( color )
		self.LastY = ( 1 - h / 360 ) * self:GetTall()
	end

	self.ColorCube = vgui.Create( "DColorCube", self )
	self.ColorCube.OnUserChanged = function( ctrl ) self:ColorCubeChanged( ctrl ) end
	self.ColorCube:SetSize( 100, 100 )
	self.ColorCube:SetPos( 25,5 )
	self.ColorCube.OnMouseReleased = function( self, mcode )
		self:SetDragging( false )
		self:MouseCapture( false )
		self:GetParent():OnChange( self:GetParent():GetColor() )
	end

	self.txtR = xlib.makenumberwang{ x=7, y=110, w=35, value=255, parent=self }
	self.txtR.OnValueChanged = function( self, val )
		local p = self:GetParent()
		p:SetColor( Color( val, p.txtG:GetValue(), p.txtB:GetValue(), p.showAlpha and p.txtA:GetValue() ) )
	end
	self.txtR.OnEnter = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		self:OnValueChanged( val )
	end
	self.txtR.OnTextChanged = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		if val ~= math.Clamp( val, 0, 255 ) then self:SetValue( math.Clamp( val, 0, 255 ) ) end
		self:GetParent():UpdateColorText()
	end
	self.txtR.OnLoseFocus = function( self )
		if not tonumber( self:GetValue() ) then self:SetValue( "0" ) end
		local p = self:GetParent()
		p:OnChange( p:GetColor() )
		hook.Call( "OnTextEntryLoseFocus", nil, self )
	end
	function self.txtR.OnMouseReleased( self, mousecode )
		if ( self.Dragging ) then
			self:GetParent():OnChange( self:GetParent():GetColor() )
			self:EndWang()
		return end
	end
	self.txtG = xlib.makenumberwang{ x=47, y=110, w=35, value=100, parent=self }
	self.txtG.OnValueChanged = function( self, val )
		local p = self:GetParent()
		p:SetColor( Color( p.txtR:GetValue(), val, p.txtB:GetValue(), p.showAlpha and p.txtA:GetValue() ) )
	end
	self.txtG.OnEnter = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		self:OnValueChanged( val )
	end
	self.txtG.OnTextChanged = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		if val ~= math.Clamp( val, 0, 255 ) then self:SetValue( math.Clamp( val, 0, 255 ) ) end
		self:GetParent():UpdateColorText()
	end
	self.txtG.OnLoseFocus = function( self )
		if not tonumber( self:GetValue() ) then self:SetValue( "0" ) end
		local p = self:GetParent()
		p:OnChange( p:GetColor() )
		hook.Call( "OnTextEntryLoseFocus", nil, self )
	end
	function self.txtG.OnMouseReleased( self, mousecode )
		if ( self.Dragging ) then
			self:GetParent():OnChange( self:GetParent():GetColor() )
			self:EndWang()
		return end
	end
	self.txtB = xlib.makenumberwang{ x=87, y=110, w=35, value=100, parent=self }
	self.txtB.OnValueChanged = function( self, val )
		local p = self:GetParent()
		p:SetColor( Color( p.txtR:GetValue(), p.txtG:GetValue(), val, p.showAlpha and p.txtA:GetValue() ) )
	end
	self.txtB.OnEnter = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		self:OnValueChanged( val )
	end
	self.txtB.OnTextChanged = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		if val ~= math.Clamp( val, 0, 255 ) then self:SetValue( math.Clamp( val, 0, 255 ) ) end
		self:GetParent():UpdateColorText()
	end
	self.txtB.OnLoseFocus = function( self )
		if not tonumber( self:GetValue() ) then self:SetValue( "0" ) end
		local p = self:GetParent()
		p:OnChange( p:GetColor() )
		hook.Call( "OnTextEntryLoseFocus", nil, self )
	end
	function self.txtB.OnMouseReleased( self, mousecode )
		if ( self.Dragging ) then
			self:GetParent():OnChange( self:GetParent():GetColor() )
			self:EndWang()
		return end
	end

	self:SetColor( Color( 255, 0, 0, 255 ) )
end

function PANEL:AddAlphaBar()
	self.showAlpha = true
	self.txtA = xlib.makenumberwang{ x=150, y=82, w=35, value=255, parent=self }
	self.txtA.OnValueChanged = function( self, val )
		local p = self:GetParent()
		p:SetColor( Color( p.txtR:GetValue(), p.txtG:GetValue(), p.txtB:GetValue(), val ) )
	end
	self.txtA.OnEnter = function( self )
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		self:OnValueChanged( val )
	end
	self.txtA.OnTextChanged = function( self )
		local p = self:GetParent()
		local val = tonumber( self:GetValue() )
		if not val then val = 0 end
		if val ~= math.Clamp( val, 0, 255 ) then self:SetValue( math.Clamp( val, 0, 255 ) ) end
		p.AlphaBar:SetValue( 1 - ( val / 255) )
		p:OnChangeImmediate( p:GetColor() )
	end
	self.txtA.OnLoseFocus = function( self )
		if not tonumber( self:GetValue() ) then self:SetValue( "0" ) end
		local p = self:GetParent()
		p:OnChange( p:GetColor() )
		hook.Call( "OnTextEntryLoseFocus", nil, self )
	end
	function self.txtA.OnMouseReleased( self, mousecode )
		if ( self.Dragging ) then
			self:GetParent():OnChange( self:GetParent():GetColor() )
			self:EndWang()
		return end
	end

	self.AlphaBar = vgui.Create( "DAlphaBar", self )
	self.AlphaBar.OnChange = function( ctrl, alpha ) self:SetColorAlpha( alpha*255 ) end
	self.AlphaBar:SetPos( 25,5 )
	self.AlphaBar:SetSize( 15, 100 )
	self.AlphaBar:SetValue( 1 )
	self.AlphaBar.OnMouseReleased = function( self, mcode )
		self:MouseCapture( false )
		self:OnCursorMoved( self:CursorPos() )
		self:GetParent():OnChange( self:GetParent():GetColor() )
	end

	self.ColorCube:SetPos( 45,5 )
	self:SetSize( 190, 110 )
	self.txtR:SetPos( 150, 7 )
	self.txtG:SetPos( 150, 32 )
	self.txtB:SetPos( 150, 57 )
end

function PANEL:AlphaModeTwo()
	self:SetSize( 156, 135 )
	self.AlphaBar:SetPos( 28,5 )
	self.ColorCube:SetPos( 51,5 )
	self.txtR:SetPos( 5, 110 )
	self.txtG:SetPos( 42, 110 )
	self.txtB:SetPos( 79, 110 )
	self.txtA:SetPos( 116, 110 )
end

function PANEL:NoAlphaModeTwo()
	self:SetSize( 170, 110 )
	self.txtR:SetPos( 130, 7 )
	self.txtG:SetPos( 130, 32 )
	self.txtB:SetPos( 130, 57 )
end

function PANEL:UpdateColorText()
	self.RGBBar:SetColor( Color( self.txtR:GetValue(), self.txtG:GetValue(), self.txtB:GetValue(), self.showAlpha and self.txtA:GetValue() ) )
	self.ColorCube:SetColor( Color( self.txtR:GetValue(), self.txtG:GetValue(), self.txtB:GetValue(), self.showAlpha and self.txtA:GetValue() ) )
	if ( self.showAlpha ) then self.AlphaBar:SetBarColor( Color( self.txtR:GetValue(), self.txtG:GetValue(), self.txtB:GetValue(), 255 ) ) end
	self:OnChangeImmediate( self:GetColor() )
end

function PANEL:SetColor( color )
	self.RGBBar:SetColor( color )
	self.ColorCube:SetColor( color )

	if tonumber( self.txtR:GetValue() ) ~= color.r then self.txtR:SetText( color.r or 255 ) end
	if tonumber( self.txtG:GetValue() ) ~= color.g then self.txtG:SetText( color.g or 0 ) end
	if tonumber( self.txtB:GetValue() ) ~= color.b then self.txtB:SetText( color.b or 0 ) end

	if ( self.showAlpha ) then
		self.txtA:SetText( color.a or 0 )
		self.AlphaBar:SetBarColor( Color( color.r, color.g, color.b ) )
		self.AlphaBar:SetValue( ( ( color.a or 0 ) / 255) )
	end

	self:OnChangeImmediate( color )
end

function PANEL:SetBaseColor( color )
	self.ColorCube:SetBaseRGB( color )

	self.txtR:SetText(self.ColorCube.m_OutRGB.r)
	self.txtG:SetText(self.ColorCube.m_OutRGB.g)
	self.txtB:SetText(self.ColorCube.m_OutRGB.b)

	if ( self.showAlpha ) then
		self.AlphaBar:SetBarColor( Color( self:GetColor().r, self:GetColor().g, self:GetColor().b ) )
	end
	self:OnChangeImmediate( self:GetColor() )
end

function PANEL:SetColorAlpha( alpha )
	if ( self.showAlpha ) then
		alpha = alpha or 0
		self.txtA:SetValue(alpha)
	end
end

function PANEL:ColorCubeChanged( cube )
	self.txtR:SetText(cube.m_OutRGB.r)
	self.txtG:SetText(cube.m_OutRGB.g)
	self.txtB:SetText(cube.m_OutRGB.b)
	if ( self.showAlpha ) then
		self.AlphaBar:SetBarColor( Color( self:GetColor().r, self:GetColor().g, self:GetColor().b ) )
	end
	self:OnChangeImmediate( self:GetColor() )
end

function PANEL:GetColor()
	local color = Color( self.txtR:GetValue(), self.txtG:GetValue(), self.txtB:GetValue() )
	if ( self.showAlpha ) then
		color.a = self.txtA:GetValue()
	else
		color.a = 255
	end
	return color
end

function PANEL:PerformLayout()
	self:SetColor( Color( self.txtR:GetValue(), self.txtG:GetValue(), self.txtB:GetValue(), self.showAlpha and self.txtA:GetValue() ) )
end

function PANEL:OnChangeImmediate( color )
	--For override
end

function PANEL:OnChange( color )
	--For override
end

vgui.Register( "xlibColorPanel", PANEL, "DPanel" )

-------------------------
--Custom Animation System
-------------------------
--This is a heavily edited version of Garry's derma animation stuff with the following differences:
	--Allows for animation chains (one animation to begin right after the other)
	--Can call functions anywhere during the animation cycle.
	--Reliably calls a start/end function for each animation so the animations always shows/ends properly.
	--Animations can be completely disabled by setting 0 for the animation time.
local xlibAnimation = {}
xlibAnimation.__index = xlibAnimation

function xlib.anim( runFunc, startFunc, endFunc )
	local anim = {}
	anim.runFunc = runFunc
	anim.startFunc = startFunc
	anim.endFunc = endFunc
	setmetatable( anim, xlibAnimation )
	return anim
end

xlib.animTypes = {}
xlib.registerAnimType = function( name, runFunc, startFunc, endFunc )
	xlib.animTypes[name] = xlib.anim( runFunc, startFunc, endFunc )
end

function xlibAnimation:Start( Length, Data )
	self.startFunc( Data )
	if ( Length == 0 ) then
		self.endFunc( Data )
		xlib.animQueue_call()
	else
		self.Length = Length
		self.StartTime = SysTime()
		self.EndTime = SysTime() + Length
		self.Data = Data
		table.insert( xlib.activeAnims, self )
	end
end

function xlibAnimation:Stop()
	self.runFunc( 1, self.Data )
	self.endFunc( self.Data )
	for i, v in ipairs( xlib.activeAnims ) do
		if v == self then table.remove( xlib.activeAnims, i ) break end
	end
	xlib.animQueue_call()
end

function xlibAnimation:Run()
	local CurTime = SysTime()
	local delta = (CurTime - self.StartTime) / self.Length
	if ( CurTime > self.EndTime ) then
		self:Stop()
	else
		self.runFunc( delta, self.Data )
	end
end

--Animation Ticker
xlib.activeAnims = {}
xlib.animRun = function()
	for _, v in ipairs( xlib.activeAnims ) do
		v.Run( v )
	end
end
hook.Add( "XLIBDoAnimation", "xlib_runAnims", xlib.animRun )

-------------------------
--Animation chain manager
-------------------------
xlib.animQueue = {}
xlib.animBackupQueue = {}

--This will allow us to make animations run faster when linked together
--Makes sure the entire animation length = animationTime (~0.2 sec by default)
xlib.animStep = 0

--Call this to begin the animation chain
xlib.animQueue_start = function()
	if xlib.animRunning then --If a new animation is starting while one is running, then we should instantly stop the old one.
		xlib.animQueue_forceStop()
		return --The old animation should be finished now, and the new one should be starting
	end
	xlib.curAnimStep = xlib.animStep
	xlib.animStep = 0
	xlib.animQueue_call()
end

xlib.animQueue_forceStop = function()
	--This will trigger the currently chained animations to run at 0 seconds.
	xlib.curAnimStep = -1
	if type( xlib.animRunning ) == "table" then xlib.animRunning:Stop() end
end

xlib.animQueue_call = function()
	if #xlib.animQueue > 0 then
		local func = xlib.animQueue[1]
		table.remove( xlib.animQueue, 1 )
		func()
	else
		xlib.animRunning = nil
		--Check for queues in the backup that haven't been started.
		if #xlib.animBackupQueue > 0 then
			xlib.animQueue = table.Copy( xlib.animBackupQueue )
			xlib.animBackupQueue = {}
			xlib.animQueue_start()
		end
	end
end

xlib.addToAnimQueue = function( obj, ... )
	local arg = { ... }
	--If there is an animation running, then we need to store the new animation stuff somewhere else temporarily.
	--Also, if ignoreRunning is true, then we'll add the anim to the regular queue regardless of running status.
	local outTable = xlib.animRunning and xlib.animBackupQueue or xlib.animQueue

	if type( obj ) == "function" then
		table.insert( outTable, function() xlib.animRunning = true  obj( unpack( arg ) )  xlib.animQueue_call() end )
	elseif type( obj ) == "string" and xlib.animTypes[obj] then
		--arg[1] should be data table, arg[2] should be length
		length = arg[2] or xgui.settings.animTime or 1
		xlib.animStep = xlib.animStep + 1
		table.insert( outTable, function() xlib.animRunning = xlib.animTypes[obj]  xlib.animRunning:Start( ( xlib.curAnimStep ~= -1 and ( length/xlib.curAnimStep ) or 0 ), arg[1] ) end )
	else
		Msg( "Error: XLIB recieved an invalid animation call! TYPE:" .. type( obj ) .. " VALUE:" .. tostring( obj ) .. "\n" )
	end
end

-------------------------
--Default Animation Types
-------------------------
--Slide animation
local function slideAnim_run( delta, data )
	--data.panel, data.startx, data.starty, data.endx, data.endy, data.setvisible
	data.panel:SetPos( data.startx+((data.endx-data.startx)*delta), data.starty+((data.endy-data.starty)*delta) )
end

local function slideAnim_start( data )
	data.panel:SetPos( data.startx, data.starty )
	if data.setvisible == true then
		ULib.queueFunctionCall( data.panel.SetVisible, data.panel, true )
	end
end

local function slideAnim_end( data )
	data.panel:SetPos( data.endx, data.endy )
	if data.setvisible == false then
		data.panel:SetVisible( false )
	end
end
xlib.registerAnimType( "pnlSlide", slideAnim_run, slideAnim_start, slideAnim_end )

--Fade animation
local function fadeAnim_run( delta, data )
	if data.panelOut then data.panelOut:SetAlpha( 255-(delta*255) ) data.panelOut:SetVisible( true ) end
	if data.panelIn then data.panelIn:SetAlpha( 255 * delta ) data.panelIn:SetVisible( true ) end
end

local function fadeAnim_start( data )
	if data.panelOut then data.panelOut:SetAlpha( 255 ) data.panelOut:SetVisible( true ) end
	if data.panelIn then data.panelIn:SetAlpha( 0 ) data.panelIn:SetVisible( true ) end
end

local function fadeAnim_end( data )
	if data.panelOut then data.panelOut:SetVisible( false ) end
	if data.panelIn then data.panelIn:SetAlpha( 255 ) end
end
xlib.registerAnimType( "pnlFade", fadeAnim_run, fadeAnim_start, fadeAnim_end )