text:
/*
 * This file is auto-generated, do not modify directly.
 */

using System.Collections.Generic;
using Jurassic;

namespace Jurassic.Library
{

	public partial class ReflectObject
	{
		private static List<PropertyNameAndValue> GetDeclarativeProperties(ScriptEngine engine)
		{
			return new List<PropertyNameAndValue>(17)
			{
				new PropertyNameAndValue("apply", new ClrStubFunction(engine, "apply", 3, __STUB__Apply), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("construct", new ClrStubFunction(engine, "construct", 2, __STUB__Construct), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("defineProperty", new ClrStubFunction(engine, "defineProperty", 3, __STUB__DefineProperty), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("deleteProperty", new ClrStubFunction(engine, "deleteProperty", 2, __STUB__DeleteProperty), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("get", new ClrStubFunction(engine, "get", 2, __STUB__Get), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("getOwnPropertyDescriptor", new ClrStubFunction(engine, "getOwnPropertyDescriptor", 2, __STUB__GetOwnPropertyDescriptor), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("getPrototypeOf", new ClrStubFunction(engine, "getPrototypeOf", 1, __STUB__GetPrototypeOf), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("has", new ClrStubFunction(engine, "has", 2, __STUB__Has), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("isExtensible", new ClrStubFunction(engine, "isExtensible", 1, __STUB__IsExtensible), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("ownKeys", new ClrStubFunction(engine, "ownKeys", 1, __STUB__OwnKeys), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("preventExtensions", new ClrStubFunction(engine, "preventExtensions", 1, __STUB__PreventExtensions), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("set", new ClrStubFunction(engine, "set", 3, __STUB__Set), PropertyAttributes.NonEnumerable),
				new PropertyNameAndValue("setPrototypeOf", new ClrStubFunction(engine, "setPrototypeOf", 2, __STUB__SetPrototypeOf), PropertyAttributes.NonEnumerable),
			};
		}

		private static object __STUB__Apply(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object");
				case 1:
					throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object");
				case 2:
					throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object");
				default:
					return Apply(TypeConverter.ToObject<FunctionInstance>(engine, args[0]), args[1], TypeConverter.ToObject(engine, args[2]));
			}
		}

		private static object __STUB__Construct(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object");
				case 1:
					throw new JavaScriptException(ErrorType.TypeError, "undefined cannot be converted to an object");
				case 2:
					return Construct(TypeConverter.ToObject<FunctionInstance>(engine, args[0]), TypeConverter.ToObject(engine, args[1]), null);
				default:
					return Construct(TypeConverter.ToObject<FunctionInstance>(engine, args[0]), TypeConverter.ToObject(engine, args[1]), TypeUtilities.IsUndefined(args[2]) ? null : TypeConverter.ToObject<FunctionInstance>(engine, args[2]));
			}
		}

		private static object __STUB__DefineProperty(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return DefineProperty(Undefined.Value, Undefined.Value, Undefined.Value);
				case 1:
					return DefineProperty(args[0], Undefined.Value, Undefined.Value);
				case 2:
					return DefineProperty(args[0], args[1], Undefined.Value);
				default:
					return DefineProperty(args[0], args[1], args[2]);
			}
		}

		private static object __STUB__DeleteProperty(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return DeleteProperty(Undefined.Value, Undefined.Value);
				case 1:
					return DeleteProperty(args[0], Undefined.Value);
				default:
					return DeleteProperty(args[0], args[1]);
			}
		}

		private static object __STUB__Get(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return Get(Undefined.Value, Undefined.Value, null);
				case 1:
					return Get(args[0], Undefined.Value, null);
				case 2:
					return Get(args[0], args[1], null);
				default:
					return Get(args[0], args[1], TypeUtilities.IsUndefined(args[2]) ? null : args[2]);
			}
		}

		private static object __STUB__GetOwnPropertyDescriptor(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return GetOwnPropertyDescriptor(Undefined.Value, Undefined.Value);
				case 1:
					return GetOwnPropertyDescriptor(args[0], Undefined.Value);
				default:
					return GetOwnPropertyDescriptor(args[0], args[1]);
			}
		}

		private static object __STUB__GetPrototypeOf(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return GetPrototypeOf(Undefined.Value);
				default:
					return GetPrototypeOf(args[0]);
			}
		}

		private static object __STUB__Has(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return Has(Undefined.Value, Undefined.Value);
				case 1:
					return Has(args[0], Undefined.Value);
				default:
					return Has(args[0], args[1]);
			}
		}

		private static object __STUB__IsExtensible(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return IsExtensible(Undefined.Value);
				default:
					return IsExtensible(args[0]);
			}
		}

		private static object __STUB__OwnKeys(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return OwnKeys(Undefined.Value);
				default:
					return OwnKeys(args[0]);
			}
		}

		private static object __STUB__PreventExtensions(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return PreventExtensions(Undefined.Value);
				default:
					return PreventExtensions(args[0]);
			}
		}

		private static object __STUB__Set(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return Set(Undefined.Value, Undefined.Value, Undefined.Value, null);
				case 1:
					return Set(args[0], Undefined.Value, Undefined.Value, null);
				case 2:
					return Set(args[0], args[1], Undefined.Value, null);
				case 3:
					return Set(args[0], args[1], args[2], null);
				default:
					return Set(args[0], args[1], args[2], TypeUtilities.IsUndefined(args[3]) ? null : args[3]);
			}
		}

		private static object __STUB__SetPrototypeOf(ScriptEngine engine, object thisObj, object[] args)
		{
			switch (args.Length)
			{
				case 0:
					return SetPrototypeOf(Undefined.Value, Undefined.Value);
				case 1:
					return SetPrototypeOf(args[0], Undefined.Value);
				default:
					return SetPrototypeOf(args[0], args[1]);
			}
		}
	}

}


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body,               null: false
      t.integer :commentable_id,  null: false
      t.string :commentable_type, null: false
      t.integer :user_id,         null: false
      t.timestamps
    end
    add_index :comments, :user_id
    add_index :comments, [:commentable_id, :commentable_type]

    add_column :stories, :comments_count, :integer, default: 0
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php declare(strict_types=1);

namespace PhpParser\NodeVisitor;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\NodeTraverser;
use PHPUnit\Framework\TestCase;

class FirstFindingVisitorTest extends TestCase
{
    public function testFindFirstVariable() {
        $traverser = new NodeTraverser();
        $visitor = new FirstFindingVisitor(function(Node $node) {
            return $node instanceof Node\Expr\Variable;
        });
        $traverser->addVisitor($visitor);

        $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\Variable('b'));
        $stmts = [new Node\Stmt\Expression($assign)];

        $traverser->traverse($stmts);
        $this->assertSame($assign->var, $visitor->getFoundNode());
    }

    public function testFindNone() {
        $traverser = new NodeTraverser();
        $visitor = new FirstFindingVisitor(function(Node $node) {
            return $node instanceof Node\Expr\BinaryOp;
        });
        $traverser->addVisitor($visitor);

        $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\Variable('b'));
        $stmts = [new Node\Stmt\Expression($assign)];

        $traverser->traverse($stmts);
        $this->assertNull($visitor->getFoundNode());
    }
}


text:
namespace azure { namespace storage {

    queue_request_options cloud_queue_client::get_modified_options(const queue_request_options& options) const
    {
        queue_request_options modified_options(options);
        modified_options.apply_defaults(default_request_options());
        return modified_options;
    }

    queue_result_iterator cloud_queue_client::list_queues(const utility::string_t& prefix, bool get_metadata, utility::size64_t max_results, const queue_request_options& options, operation_context context) const
    {
        auto instance = std::make_shared<cloud_queue_client>(*this);
        return queue_result_iterator(
            [instance, prefix, get_metadata, options, context](const continuation_token& token, size_t max_results_per_segment)
        {
            return instance->list_queues_segmented(prefix, get_metadata, (int)max_results_per_segment, token, options, context);
        },
            max_results, 0);
    }

    pplx::task<queue_result_segment> cloud_queue_client::list_queues_segmented_async(const utility::string_t& prefix, bool get_metadata, int max_results, const continuation_token& token, const queue_request_options& options, operation_context context) const
    {
        queue_request_options modified_options = get_modified_options(options);
        storage_uri uri = protocol::generate_queue_uri(*this, prefix, get_metadata, max_results, token);

        auto instance = std::make_shared<cloud_queue_client>(*this);
        std::shared_ptr<core::storage_command<queue_result_segment>> command = std::make_shared<core::storage_command<queue_result_segment>>(uri);
        command->set_build_request(std::bind(protocol::list_queues, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        command->set_authentication_handler(authentication_handler());
        command->set_location_mode(core::command_location_mode::primary_or_secondary, token.target_location());
        command->set_preprocess_response(std::bind(protocol::preprocess_response<queue_result_segment>, queue_result_segment(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        command->set_postprocess_response([instance, get_metadata] (const web::http::http_response& response, const request_result& result, const core::ostream_descriptor&, operation_context context) -> pplx::task<queue_result_segment>
        {
            UNREFERENCED_PARAMETER(context);
            protocol::list_queues_reader reader(response.body());
            std::vector<protocol::cloud_queue_list_item> queue_items = reader.move_items();

            std::vector<cloud_queue> results;
            results.reserve(queue_items.size());

            for (std::vector<protocol::cloud_queue_list_item>::iterator it = queue_items.begin(); it != queue_items.end(); ++it)
            {
                cloud_queue queue = instance->get_queue_reference(it->move_name());
                if (get_metadata)
                {
                    queue.set_metadata(it->move_metadata());
                }

                results.push_back(std::move(queue));
            }

            utility::string_t next_marker = reader.move_next_marker();
            if (!next_marker.empty())
            {
                next_marker = core::make_query_parameter(protocol::queue_query_next_marker, next_marker);
            }

            azure::storage::continuation_token next_token(std::move(next_marker));
            next_token.set_target_location(result.target_location());

            queue_result_segment result_segment(std::move(results), std::move(next_token));
            return pplx::task_from_result(result_segment);
        });
        return core::executor<queue_result_segment>::execute_async(command, modified_options, context);
    }

    pplx::task<service_properties> cloud_queue_client::download_service_properties_async(const queue_request_options& options, operation_context context) const
    {
        queue_request_options modified_options(options);
        modified_options.apply_defaults(default_request_options());

        return download_service_properties_base_async(modified_options, context);
    }

    pplx::task<void> cloud_queue_client::upload_service_properties_async(const service_properties& properties, const service_properties_includes& includes, const queue_request_options& options, operation_context context) const
    {
        queue_request_options modified_options(options);
        modified_options.apply_defaults(default_request_options());

        return upload_service_properties_base_async(properties, includes, modified_options, context);
    }

    pplx::task<service_stats> cloud_queue_client::download_service_stats_async(const queue_request_options& options, operation_context context) const
    {
        queue_request_options modified_options(options);
        modified_options.apply_defaults(default_request_options());

        return download_service_stats_base_async(modified_options, context);
    }

    cloud_queue cloud_queue_client::get_queue_reference(utility::string_t queue_name) const
    {
        cloud_queue queue(*this, std::move(queue_name));
        return queue;
    }

    void cloud_queue_client::set_authentication_scheme(azure::storage::authentication_scheme value)
    {
        cloud_client::set_authentication_scheme(value);

        storage_credentials creds = credentials();
        if (creds.is_shared_key())
        {
            utility::string_t account_name = creds.account_name();
            switch (authentication_scheme())
            {
            case azure::storage::authentication_scheme::shared_key_lite:
                set_authentication_handler(std::make_shared<protocol::shared_key_authentication_handler>(std::make_shared<protocol::shared_key_lite_blob_queue_canonicalizer>(std::move(account_name)), std::move(creds)));
                break;

            default: // azure::storage::authentication_scheme::shared_key
                set_authentication_handler(std::make_shared<protocol::shared_key_authentication_handler>(std::make_shared<protocol::shared_key_blob_queue_canonicalizer>(std::move(account_name)), std::move(creds)));
                break;
            }
        }
        else if (creds.is_sas())
        {
            set_authentication_handler(std::make_shared<protocol::sas_authentication_handler>(std::move(creds)));
        }
        else
        {
            set_authentication_handler(std::make_shared<protocol::authentication_handler>());
        }
    }

}} // namespace azure::storage


text:
/************************************************/
/* IPB3 Javascript								*/
/* -------------------------------------------- */
/* ips.profile.js - Forum view code				*/
/* (c) IPS, Inc 2008							*/
/* -------------------------------------------- */
/* Author: Rikki Tissier						*/
/************************************************/

var _sharelinks = window.IPBoard;

_sharelinks.prototype.sharelinks = {
	popups: null,
	bname: null,
	url: null,
	title: null,
	maxTwitterLen: 115,

	init: function()
	{
		Debug.write("Initializing ips.sharelinks.js");

		document.observe("dom:loaded", function(){
			ipb.sharelinks.initEvents();
		});
	},

	/* ------------------------------ */
	/**
	 * Initialize events
	*/
	initEvents: function()
	{
		ipb.delegate.register('._slink', ipb.sharelinks.sharePop);
	},

	/* ------------------------------ */
	/**
	 * Twitter pop innit
	 *
	 * @param	{event}		e		The event
	*/
	sharePop: function(e, elem)
	{
		var shareKey = elem.id.replace( /slink_/, '' );
		var ok       = false;
		var callback = null;
		var h        = '190';

		/*if ( shareKey == 'twitter' )
		{
			if ( ipb.vars['member_id'] && ipb.vars['twitter_id'] )
			{
				callback = ipb.sharelinks.twitterPostPop;
				ok       = true;
				h        = '110';
			}
		}*/

		if ( ok === false || DISABLE_AJAX )
		{
			return false;
		}

		/* Still here? */
		Event.stop(e);

		var _url  = ipb.vars['base_url'] + '&app=core&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=sharelinks&do=' + shareKey + 'Form';

		var x = new ipb.Popup( 'shareKeyPop_' + Math.random(), { type: 'modal',
																 ajaxURL: _url,
																 modal: true,
																 stem: false,
																 hideAtStart: false,
																 w: '550px', h: h }, { 'afterAjax': callback, 'beforeAjax': ipb.sharelinks.resetPop } );
	},

	/**
	 * Post process twitter pop-up
	 */
	facebookPostPop: function( e, responseText )
	{
		/* Issue with FB API? */
		if( responseText == 'x' )
		{
			window.location = "http://www.facebook.com/sharer.php?u=" + ipb.sharelinks.url.encodeParam();
			return false;
		}

		$('fContent').update('');
		$('fSubmit').observe('click', ipb.sharelinks.goFacebook);
	},

	/**
	 * Post process twitter pop-up
	 */
	twitterPostPop: function( e, responseText )
	{
		/* Issue with Twitter API? */
		if( responseText == 'x' )
		{
			window.location = "http://twitter.com/intent/tweet?status=" + ipb.sharelinks.title.encodeParam() + '%20-%20' + ipb.sharelinks.url.encodeParam();
			return false;
		}

		/* clean up title */
		ipb.sharelinks.title = ipb.sharelinks.title.replace(/"/g , '"');
		ipb.sharelinks.title = ipb.sharelinks.title.replace(/!/g , "!");
		ipb.sharelinks.title = ipb.sharelinks.title.replace(/'/g, "'");
		ipb.sharelinks.title = ipb.sharelinks.title.replace(/"/g, '"');

		/* Clean up board name */
		ipb.sharelinks.bname = ipb.sharelinks.bname.replace(/"/g , '"');
		ipb.sharelinks.bname = ipb.sharelinks.bname.replace(/!/g , "!");
		ipb.sharelinks.bname = ipb.sharelinks.bname.replace(/'/g , "'");
		ipb.sharelinks.bname = ipb.sharelinks.bname.replace(/"/g, '"');
		Debug.write( ipb.sharelinks.title );
		$('tContent').value = ipb.sharelinks.bname + ': ' + ipb.sharelinks.title;
		$('tContent').observe('keyup', ipb.sharelinks.checkTwitterLength);
		$('tSubmit').observe('click', ipb.sharelinks.goTwitter);

		ipb.sharelinks.checkTwitterLength(e);
	},

	/**
	 * Reset pop-up
	 */
	resetPop: function(e)
	{
		if ( $('tContent') )
		{
			$('tContent').stopObserving();
			$('tContent').remove();
			$('tSubmit').stopObserving();
			$('tWrap').remove();
		}

		if ( $('cLeft') )
		{
			$('cLeft').remove();
		}

		if ( $('fContent') )
		{
			$('fContent').remove();
			$('fSubmit').stopObserving();
			$('fWrap').remove();
		}
	},

	/**
	 * Post a comment to twitter
	 */
	goTwitter: function(e)
	{
		if( DISABLE_AJAX )
		{
			return false;
		}

		Event.stop(e);

		if ( ! $('tContent') || $F('tContent').blank() )
		{
			return;
		}

		new Ajax.Request( ipb.vars['base_url'] + '&app=core&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=sharelinks&do=twitterGo',
						{
							method: 'post',
							parameters: {
								'tweet': $F('tContent').encodeParam(),
								'title': ipb.sharelinks.title.encodeParam(),
								'url': ipb.sharelinks.url.encodeParam()
							},
							onSuccess: function(t)
							{
								/* Check */
								if( t.responseText == 'failwhale' )
								{
									alert( ipb.lang['action_failed'] );
									return;
								}
								else
								{
									$('tWrap').update( t.responseText );
								}
							}
						});
	},

	/**
	 * Post a comment to Facebook
	 * @Deprecated as of 3.3 - now using Facebook standard share button
	 */
	goFacebook: function(e)
	{
		if( DISABLE_AJAX )
		{
			return false;
		}

		Event.stop(e);

		new Ajax.Request( ipb.vars['base_url'] + '&app=core&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=sharelinks&do=facebookGo',
						{
							method: 'post',
							parameters: {
								'comment': $F('fContent').encodeParam(),
								'title': ipb.sharelinks.title.encodeParam(),
								'url': ipb.sharelinks.url.encodeParam()
							},
							onSuccess: function(t)
							{
								/* Check */
								if( t.responseText == 'finchersaysno' )
								{
									alert( ipb.lang['action_failed'] );
									return;
								}
								else
								{
									$('fWrap').update( t.responseText );
								}
							}
						});
	},

	checkTwitterLength: function(e)
	{
		newTotal = parseInt( ipb.sharelinks.maxTwitterLen ) - parseInt( $F('tContent').length );

		if( newTotal < 0 )
		{
			$('tContent').value = $F('tContent').truncate( ipb.sharelinks.maxTwitterLen, '' );
			newTotal = 0;
		}

		$('cLeft').update( newTotal );
	}
};

ipb.sharelinks.init();


text:
from __future__ import print_function
from ..color import Color
from ..effect import Effect
import time

class EffectKnightRider(Effect):

    def run(self, color=Color(0, 0, 0), milliseconds=20, iterations=1):
        print("[EffectKnightRider][info] Knight rider: to NeoPixel pixels with pause '%d' milliseconds and '%d' iterations" % (milliseconds, iterations))

        try:
            while self.ITERATE:
                for j in range(iterations):
                    for i in range(self.controller.LEDS):
                        self.controller.pixel_color(i, Color(255, 0, 0))
                        time.sleep(milliseconds / 1000.0)

                    for i in range(self.controller.LEDS, -1, -1):
                        self.controller.pixel_color(i, Color(0, 0, 0))
                        time.sleep(milliseconds / 1000.0)

                time.sleep(milliseconds / 1000.0)
        except AttributeError:
            print("[EffectKnightRider][error] An error occurred setting knight rider to NeoPixel pixels")


text:
import {
  MachineDictItem,
  machineConfig
} from '@/components/MachineTrans/engine'
import { Language } from '@opentranslate/translator'
import { Subunion } from '@/typings/helpers'

export type GoogleLanguage = Subunion<
  Language,
  'zh-CN' | 'zh-TW' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'ru' | 'nl'
>

export type GoogleConfig = MachineDictItem<
  GoogleLanguage,
  {
    cnfirst: boolean
    concurrent: boolean
  }
>

export default (): GoogleConfig =>
  machineConfig<GoogleConfig>(
    ['zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru', 'nl'],
    {},
    {
      cnfirst: true,
      concurrent: false
    },
    {}
  )


text:
/* eslint max-lines: 0 */
import React, { Component } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import _ from "lodash";
import ItemCheckboxList from "../addons/ItemCheckboxList";
import ItemList from "../addons/ItemList";
import manager from "../middleware/ChannelManager";
import { StaticSearch } from "../addons/StaticSearch";
import InitialLoader from "../addons/InitialLoader";

const helper = require("../middleware/helper");

export default class NativeList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			items: [],
			storedItems: [],
			rawData: {
				hits: {
					hits: []
				}
			},
			queryStart: false,
			defaultSelected: null,
			selectAll: false
		};
		this.sortObj = {
			aggSort: this.props.sortBy
		};
		this.selectAllWhenReady = false;
		this.previousSelectedSensor = {};
		this.channelId = null;
		this.channelListener = null;
		this.urlParams = props.URLParams ? helper.URLParams.get(props.componentId, props.multipleSelect) : null;
		this.handleSelect = this.handleSelect.bind(this);
		this.handleRemove = this.handleRemove.bind(this);
		this.filterBySearch = this.filterBySearch.bind(this);
		this.onSelectAll = this.onSelectAll.bind(this);
		this.type = this.props.multipleSelect && this.props.queryFormat === "or" ? "terms" : "term";
		this.customQuery = this.customQuery.bind(this);
		this.defaultCustomQuery = this.defaultCustomQuery.bind(this);
	}

	// Get the items from Appbase when component is mounted
	componentWillMount() {
		this.setReact(this.props);
		this.size = this.props.size;
		this.setQueryInfo(this.props);
		this.createChannel(true);
		this.defaultValue = this.urlParams !== null ? this.urlParams : this.props.defaultSelected;
		this.previousQuery = null;	// initial value for onQueryChange
		this.changeValues(this.defaultValue);
		this.listenFilter();
	}

	componentWillReceiveProps(nextProps) {
		this.urlParams = nextProps.URLParams ? helper.URLParams.get(nextProps.componentId, nextProps.multipleSelect) : null;

		if (this.props.queryFormat !== nextProps.queryFormat) {
			this.type = nextProps.multipleSelect && nextProps.queryFormat === "or" ? "terms" : "term";
		}

		if (!_.isEqual(this.props.react, nextProps.react) || this.props.size !== nextProps.size) {
			this.setReact(nextProps);
			manager.update(this.channelId, this.react, nextProps.size, 0, false);
		}

		if (this.sortBy !== nextProps.sortBy) {
			this.sortBy = nextProps.sortBy;
			this.handleSortSelect(nextProps);
		}

		if (!_.isEqual(this.props.defaultSelected, nextProps.defaultSelected)) {
			this.defaultValue = nextProps.defaultSelected;
			this.changeValues(this.defaultValue);
		} else if (this.urlParams !== null) {
			this.defaultValue = this.urlParams;
			this.changeValues(this.defaultValue);
		}

		if (this.props.showFilter !== nextProps.showFilter || this.props.filterLabel !== nextProps.filterLabel) {
			this.setQueryInfo(nextProps);
			this.setValue(this.state.defaultSelected, true);
		}
	}

	// build query for this sensor only
	// execute either user defined customQuery or component default query
	// customQuery will receive 2 arguments, selected sensor value and select all.
	customQuery(value) {
		const defaultQuery = this.props.customQuery ? this.props.customQuery : this.defaultCustomQuery;
		const currentQuery = defaultQuery(value);
		if (this.props.onQueryChange && JSON.stringify(this.previousQuery) !== JSON.stringify(currentQuery)) {
			this.props.onQueryChange(this.previousQuery, currentQuery);
			this.previousQuery = currentQuery;
		}
		return currentQuery;
	}

	defaultCustomQuery(value) {
		let query = null;
		if (this.state.selectAll) {
			query = {
				exists: {
					field: [this.props.dataField]
				}
			};
		} else if (value) {
			let listQuery;
			// queryFormat should not affect SingleList
			if (this.props.queryFormat === "and" && this.props.multipleSelect) {
				// adds a sub-query with must as an array of objects for each term/value
				const queryArray = value.map(item => (
					{
						[this.type]: {
							[this.props.dataField]: item
						}
					}
				));
				listQuery = {
					bool: {
						must: queryArray
					}
				};
			} else {
				// for the default queryFormat = "or" and SingleList
				listQuery = {
					[this.type]: {
						[this.props.dataField]: value
					}
				};
			}

			query = this.props.multipleSelect ? (value.length ? listQuery : null) : listQuery;
		}
		return query;
	}

	changeValues(defaultValue) {
		let items = this.state.items;
		if (this.props.selectAllLabel && defaultValue === this.props.selectAllLabel) {
			this.selectAllWhenReady = true;
		} else if (defaultValue !== undefined) {
			items = items.map((item) => {
				item.key = item.key.toString();
				item.status = ((defaultValue && defaultValue.indexOf(item.key) > -1) || (this.selectedValue && this.selectedValue.indexOf(item.key) > -1));
				return item;
			});
			this.setState({
				items,
				storedItems: items
			});
			this.handleSelect(defaultValue);
		}
		if (this.sortBy !== this.props.sortBy) {
			this.sortBy = this.props.sortBy;
			this.handleSortSelect(this.props);
		}
		if (this.size !== this.props.size) {
			this.size = this.props.size;
			this.removeChannel();
			this.createChannel();
		}
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		this.removeChannel();
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if (data === this.props.componentId) {
				this.changeValues(null);
			}
		});
	}

	removeChannel() {
		if (this.channelId) {
			manager.stopStream(this.channelId);
		}
		if (this.channelListener) {
			this.channelListener.remove();
		}
		if (this.loadListener) {
			this.loadListener.remove();
		}
		if (this.filterListener) {
			this.filterListener.remove();
		}
	}

	// set the query type and input data
	setQueryInfo(props) {
		const obj = {
			key: props.componentId,
			value: {
				queryType: this.type,
				inputData: props.dataField,
				customQuery: this.customQuery,
				reactiveId: this.context.reactiveId,
				showFilter: props.showFilter,
				filterLabel: props.filterLabel ? props.filterLabel : props.componentId,
				component: props.component,
				defaultSelected: this.urlParams !== null ? this.urlParams : props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	includeAggQuery() {
		const obj = {
			key: `${this.props.componentId}-sort`,
			value: this.sortObj
		};
		helper.selectedSensor.setSortInfo(obj);
	}

	handleSortSelect(props) {
		this.sortObj = {
			aggSort: props.sortBy
		};
		const obj = {
			key: `${props.componentId}-sort`,
			value: this.sortObj
		};
		helper.selectedSensor.set(obj, true, "sortChange");
	}

	setReact(props) {
		// Set the react - add self aggs query as well with react
		const react = Object.assign({}, props.react);
		react.aggs = {
			key: props.dataField,
			sort: props.sortBy,
			size: props.size,
			sortRef: `${props.componentId}-sort`
		};
		const reactAnd = [`${props.componentId}-sort`, "nativeListChanges"];
		this.react = helper.setupReact(react, reactAnd);
	}

	// Create a channel which passes the react and receive results whenever react changes
	createChannel(executeChannel = false) {
		this.includeAggQuery();
		// create a channel and listen the changes
		const channelObj = manager.create(this.context.appbaseRef, this.context.type, this.react, 100, 0, false, this.props.componentId);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(this.channelId, (res) => {
			if (res.error) {
				this.setState({
					queryStart: false
				});
			}
			if (res.appliedQuery) {
				const data = res.data;
				let rawData;
				if (res.mode === "streaming") {
					rawData = this.state.rawData;
					rawData.hits.hits.push(res.data);
				} else if (res.mode === "historic") {
					rawData = data;
				}
				this.setState({
					queryStart: false,
					rawData
				});
				this.setData(rawData);
			}
		});
		this.listenLoadingChannel(channelObj);
	}

	listenLoadingChannel(channelObj) {
		this.loadListener = channelObj.emitter.addListener(`${channelObj.channelId}-query`, (res) => {
			if (res.appliedQuery) {
				this.setState({
					queryStart: res.queryState
				});
			}
		});
	}

	setData(data) {
		if (data.aggregations && data.aggregations[this.props.dataField] && data.aggregations[this.props.dataField].buckets) {
			this.addItemsToList(data.aggregations[this.props.dataField].buckets);
		}
	}

	addItemsToList(newItems) {
		const items = [];
		newItems.forEach((item) => {
			const key = item.key.toString();
			if (key.trim() !== "") {
				item.key = key;
				item.status = !!((this.selectedValue && this.selectedValue.indexOf(item.key) > -1));
				items.push(item);
			}
		});
		this.setState({
			items,
			storedItems: items
		}, () => {
			if (this.selectAllWhenReady) {
				this.onSelectAll(this.props.selectAllLabel);
			}
		});
	}

	// Handler function when a value is selected
	handleSelect(handleValue) {
		this.setValue(handleValue, true);
	}

	// Handler function when a value is deselected or removed
	handleRemove(value) {
		this.setValue(value, true);
	}

	// set value
	setValue(value, isExecuteQuery = false) {
		const onUpdate = () => {
			const execQuery = () => {
				if (this.props.onValueChange) {
					this.props.onValueChange(value);
				}
				const selectedValue = typeof value === "string" ? (value.trim() ? value : null) : value;
				if (this.props.URLParams) {
					helper.URLParams.update(this.props.componentId, selectedValue, this.props.URLParams);
				}
				helper.selectedSensor.set(obj, isExecuteQuery);
			};

			if (this.props.beforeValueChange) {
				this.props.beforeValueChange(value)
				.then(() => {
					execQuery();
				})
				.catch((e) => {
					console.warn(`${this.props.componentId} - beforeValueChange rejected the promise with`, e);
				});
			} else {
				execQuery();
			}
		};

		const obj = {
			key: this.props.componentId,
			value
		};

		this.selectedValue = value;
		if (this.props.multipleSelect) {
			const items = this.state.items.map((item) => {
				if (value && value.indexOf(item.key) > -1) {
					item.status = true;
				} else {
					item.status = false;
				}
				return item;
			});

			value = value && value.length ? value : null;
			obj.value = value;
			const isSelectAll = !!(this.selectedValue && this.selectedValue.indexOf(this.props.selectAllLabel) >= 0);

			this.setState({
				items,
				defaultSelected: isSelectAll ? [this.props.selectAllLabel] : this.selectedValue,
				selectAll: isSelectAll
			}, () => {
				onUpdate();
			});
		} else {
			this.setState({
				defaultSelected: this.selectedValue,
				selectAll: this.selectedValue && this.selectedValue === this.props.selectAllLabel
			}, () => {
				onUpdate();
			});
		}
	}

	onSelectAll(selectedValue) {
		const items = this.state.items.map((item) => {
			item.status = true;
			return item;
		});
		this.selectedValue = selectedValue;
		this.setState({
			items,
			storedItems: items,
			selectAll: true
		}, () => {
			this.setValue(selectedValue, true);
		});
	}

	// filter
	filterBySearch(value) {
		if (value) {
			const items = this.state.storedItems.map((item) => {
				item.visible = !!(item.key && item.key.toLowerCase().indexOf(value.toLowerCase()) > -1);
				return item;
			});
			this.setState({
				items
			});
		} else {
			const items = this.state.storedItems.map((item) => {
				item.visible = true;
				return item;
			});
			this.setState({
				items
			});
		}
	}

	render() {
		// Checking if component is single select or multiple select
		let listComponent,
			searchComponent = null,
			title = null;

		if (this.state.items.length === 0) {
			return null;
		}

		if (this.props.multipleSelect) {
			listComponent = (<ItemCheckboxList
				items={this.state.items}
				onSelect={this.handleSelect}
				onRemove={this.handleRemove}
				showCount={this.props.showCount}
				showCheckbox={this.props.showCheckbox}
				defaultSelected={this.state.defaultSelected}
				selectAllLabel={this.props.selectAllLabel}
				selectAll={this.state.selectAll}
				onSelectAll={this.onSelectAll}
			/>);
		} else {
			listComponent = (<ItemList
				items={this.state.items}
				onSelect={this.handleSelect}
				onRemove={this.handleRemove}
				showCount={this.props.showCount}
				showRadio={this.props.showRadio}
				defaultSelected={this.state.defaultSelected}
				selectAllLabel={this.props.selectAllLabel}
				selectAll={this.state.selectAll}
				onSelectAll={this.onSelectAll}
			/>);
		}

		// set static search
		if (this.props.showSearch) {
			searchComponent = (<StaticSearch
				placeholder={this.props.placeholder}
				changeCallback={this.filterBySearch}
			/>);
		}

		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-search-active": this.props.showSearch,
			"rbc-search-inactive": !this.props.showSearch,
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-placeholder-active": this.props.placeholder,
			"rbc-placeholder-inactive": !this.props.placeholder,
			"rbc-singlelist": !this.props.multipleSelect,
			"rbc-multilist": this.props.multipleSelect,
			"rbc-initialloader-active": this.props.initialLoader,
			"rbc-initialloader-inactive": !this.props.initialLoader
		}, this.props.className);

		return (
			<div className={`rbc col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.style}>
				{title}
				{searchComponent}
				{listComponent}
				{this.props.initialLoader && this.state.queryStart ? (<InitialLoader defaultText={this.props.initialLoader} />) : null}

		);
	}
}

NativeList.propTypes = {
	dataField: PropTypes.string.isRequired,
	componentId: PropTypes.string.isRequired,
	title: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.element
	]),
	size: helper.sizeValidation,
	showCount: PropTypes.bool,
	multipleSelect: PropTypes.bool,
	sortBy: PropTypes.oneOf(["asc", "desc", "count"]),
	showSearch: PropTypes.bool,
	placeholder: PropTypes.string,
	selectAllLabel: PropTypes.string,
	customQuery: PropTypes.func,
	initialLoader: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.element
	]),
	defaultSelected: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.number,
		PropTypes.array
	]),
	react: PropTypes.object,
	beforeValueChange: PropTypes.func,
	onValueChange: PropTypes.func,
	onQueryChange: PropTypes.func,
	style: PropTypes.object,
	showRadio: PropTypes.bool,
	showCheckbox: PropTypes.bool,
	URLParams: PropTypes.bool,
	showFilter: PropTypes.bool,
	filterLabel: PropTypes.string,
	queryFormat: PropTypes.oneOf(["and", "or"]),
	className: PropTypes.string
};

// Default props value
NativeList.defaultProps = {
	showCount: true,
	multipleSelect: true,
	sortBy: "count",
	size: 100,
	showSearch: false,
	title: null,
	placeholder: "Search",
	selectAllLabel: null,
	style: {},
	showRadio: true,
	showCheckbox: true,
	URLParams: false,
	showFilter: true,
	queryFormat: "or"
};

// context type
NativeList.contextTypes = {
	appbaseRef: PropTypes.any.isRequired,
	type: PropTypes.any.isRequired,
	reactiveId: PropTypes.number
};


text:
package com.hqme.cm.core.policyParser;

import com.hqme.cm.core.RuleCollection;
import com.hqme.cm.core.WorkOrder;

import java.util.HashMap;

public class PolicyExpression extends Expression {
    // each expression that would make up the <Download> or <Cache>
    // corresponds to:
    // a) a Rule element to be evaluated and the RuleCollection that corresponds to it
    // (for which we may call evaluateRuleSet)
    // b) true() or false() which are xPath reps of true/false
	private String name;
	private boolean value;
	protected RuleCollection mRules;
	public String getName() {
        return name;
    }

	public PolicyExpression(String name,HashMap<String, RuleCollection> ruleMap) {
	    this.name = name;
	    if (ruleMap.get(name) != null)
	        this.mRules = ruleMap.get(name);

	    if ("true()".compareTo(name) == 0)
	        value = true;
	}

	public String toString() {
		return name;
	}

	public boolean evaluate(WorkOrder workOrder) {
	    if (this.mRules != null) {
	        if (workOrder!= null)
	            return mRules.evaluateRuleSet(workOrder);
	    }

	    return value;
	}

}


text:
package net.kahowell.xsd.fuzzer.generator.builtin;

import java.sql.Date;
import java.text.SimpleDateFormat;

import net.kahowell.xsd.fuzzer.generator.AbstractXsdTypeValueGenerator;
import net.kahowell.xsd.fuzzer.generator.GeneratesType;

import org.apache.xmlbeans.SchemaType;

import com.google.inject.Singleton;

@Singleton
@GeneratesType(namespace = "http://www.w3.org/2001/XMLSchema", localname = "time")
public class TimeGenerator extends AbstractXsdTypeValueGenerator {

	@Override
	protected String generateExampleValue(SchemaType rootType) {
		return "12:14:00";
	}

	@Override
	protected String generateRandomValue(SchemaType rootType) {
		return new SimpleDateFormat("HH:mm:ss").format(new Date(random.nextLong()));
	}
}


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.WindowsAzure;

namespace Microsoft.Azure.Management.WebSites.Models
{
    /// <summary>
    /// The information gathered about a backup storaged in a storage account.
    /// </summary>
    public partial class WebSiteRestoreDiscoverResponse : OperationResponse
    {
        private WebSiteRestoreDiscover _envelope;

        /// <summary>
        /// Optional. OperationId for the restore operation.
        /// </summary>
        public WebSiteRestoreDiscover Envelope
        {
            get { return this._envelope; }
            set { this._envelope = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebSiteRestoreDiscoverResponse
        /// class.
        /// </summary>
        public WebSiteRestoreDiscoverResponse()
        {
        }
    }
}


text:
using namespace boost::placeholders;

static const int64_t nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), numBlocksAtStartup(-1), pollTimer(0)
{
    qRegisterMetaType<CNodeShortStats>("CNodeShortStats");

    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

CNodeShortStats ClientModel::getConnections() const
{
    CNodeShortStats vStats;
    {
        LOCK(cs_vNodes);
        for(const CNode* pNode : vNodes) {
            CNodeShortStat nodeStat = {
                pNode->addrName,
                pNode->nVersion,
                pNode->strSubVer,
                pNode->nStartingHeight
            };
            vStats.push_back(nodeStat);
        }
    }
    return vStats;
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    LOCK(cs_main);
    return nBestHeight;
}

int ClientModel::getPegSupplyIndex() const
{
    LOCK(cs_main);
    CBlockIndex* pblockindex = pindexBest;
    return pblockindex->nPegSupplyIndex;
}

int ClientModel::getPegNextSupplyIndex() const
{
    LOCK(cs_main);
    CBlockIndex* pblockindex = pindexBest;
    return pblockindex->GetNextIntervalPegSupplyIndex();
}

int ClientModel::getPegNextNextSupplyIndex() const
{
    LOCK(cs_main);
    CBlockIndex* pblockindex = pindexBest;
    return pblockindex->GetNextNextIntervalPegSupplyIndex();
}

int ClientModel::getPegStartBlockNum() const
{
    LOCK(cs_main);
    return nPegStartHeight;
}

boost::tuple<int,int,int> ClientModel::getPegVotes() const
{
    LOCK(cs_main);
    CBlockIndex* pblockindex = pindexBest;
    return boost::make_tuple(pblockindex->nPegVotesInflate,
                             pblockindex->nPegVotesDeflate,
                             pblockindex->nPegVotesNochange);
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

quint64 ClientModel::getTotalBytesRecv() const
{
    return CNode::GetTotalBytesRecv();
}

quint64 ClientModel::getTotalBytesSent() const
{
    return CNode::GetTotalBytesSent();
}

QDateTime ClientModel::getLastBlockDate() const
{
    LOCK(cs_main);
    if (pindexBest)
        return QDateTime::fromTime_t(pindexBest->GetBlockTime());
    else
        return QDateTime::fromTime_t(Params().GenesisBlock().nTime); // Genesis block's time of current network
}

void ClientModel::updateTimer()
{
    // Get required lock upfront. This avoids the GUI from getting stuck on
    // periodical polls if the core is holding the locks for a longer time -
    // for example, during a wallet rescan.
    TRY_LOCK(cs_main, lockMain);
    if(!lockMain)
        return;
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();

    if(cachedNumBlocks != newNumBlocks)
    {
        cachedNumBlocks = newNumBlocks;

        emit numBlocksChanged(newNumBlocks);
    }

    emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateConnections(const CNodeShortStats & stats)
{
    emit connectionsChanged(stats);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false, CClientUIInterface::ICON_ERROR);
        }
    }

    emit alertsChanged(getStatusBarWarnings());
}

bool ClientModel::isTestNet() const
{
    return TestNet();
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

bool ClientModel::isImporting() const
{
    return fImporting;
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyConnectionsChanged(ClientModel *clientmodel, const CNodeShortStats & stats)
{
    // Too noisy: qDebug() << "NotifyConnectionsChanged : " + QString::number(stats.size());
    CNodeShortStats stats_copy = stats;
    QMetaObject::invokeMethod(clientmodel, "updateConnections", Qt::QueuedConnection,
                              Q_ARG(CNodeShortStats, stats_copy));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyConnectionsChanged.connect(boost::bind(NotifyConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyConnectionsChanged.disconnect(boost::bind(NotifyConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}


text:
@implementation JVFloatLabeledTextField

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    _floatingLabel = [UILabel new];
    _floatingLabel.alpha = 0.0f;
    [self addSubview:_floatingLabel];

    // some basic default fonts/colors
    _floatingLabelFont = [UIFont boldSystemFontOfSize:12.0f];
    _floatingLabel.font = _floatingLabelFont;
    _floatingLabelTextColor = [UIColor grayColor];
    _floatingLabel.textColor = _floatingLabelTextColor;
    _animateEvenIfNotFirstResponder = 0;
    _floatingLabelShowAnimationDuration = kFloatingLabelShowAnimationDuration;
    _floatingLabelHideAnimationDuration = kFloatingLabelHideAnimationDuration;
    [self setPlaceholder:self.placeholder];

    _adjustsClearButtonRect = 1;
}

#pragma mark -

- (UIColor *)labelActiveColor
{
    if (_floatingLabelActiveTextColor) {
        return _floatingLabelActiveTextColor;
    }
    else if ([self respondsToSelector:@selector(tintColor)]) {
        return [self performSelector:@selector(tintColor)];
    }
    return [UIColor blueColor];
}

- (void)setFloatingLabelFont:(UIFont *)floatingLabelFont
{
    _floatingLabelFont = floatingLabelFont;
    _floatingLabel.font = (_floatingLabelFont ? _floatingLabelFont : [UIFont boldSystemFontOfSize:12.0f]);
    [self setFloatingLabelText:self.placeholder];
    [self invalidateIntrinsicContentSize];
}

- (void)showFloatingLabel:(BOOL)animated
{
    void (^showBlock)() = ^{
        _floatingLabel.alpha = 1.0f;
        _floatingLabel.frame = CGRectMake(_floatingLabel.frame.origin.x,
                                          _floatingLabelYPadding,
                                          _floatingLabel.frame.size.width,
                                          _floatingLabel.frame.size.height);
    };

    if (animated || 0 != _animateEvenIfNotFirstResponder) {
        [UIView animateWithDuration:_floatingLabelShowAnimationDuration
                              delay:0.0f
                            options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut
                         animations:showBlock
                         completion:nil];
    }
    else {
        showBlock();
    }
}

- (void)hideFloatingLabel:(BOOL)animated
{
    void (^hideBlock)() = ^{
        _floatingLabel.alpha = 0.0f;
        _floatingLabel.frame = CGRectMake(_floatingLabel.frame.origin.x,
                                          _floatingLabel.font.lineHeight + _placeholderYPadding,
                                          _floatingLabel.frame.size.width,
                                          _floatingLabel.frame.size.height);

    };

    if (animated || 0 != _animateEvenIfNotFirstResponder) {
        [UIView animateWithDuration:_floatingLabelHideAnimationDuration
                              delay:0.0f
                            options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseIn
                         animations:hideBlock
                         completion:nil];
    }
    else {
        hideBlock();
    }
}

- (void)setLabelOriginForTextAlignment
{
    CGRect textRect = [self textRectForBounds:self.bounds];

    CGFloat originX = textRect.origin.x;

    if (self.textAlignment == NSTextAlignmentCenter) {
        originX = textRect.origin.x + (textRect.size.width/2) - (_floatingLabel.frame.size.width/2);
    }
    else if (self.textAlignment == NSTextAlignmentRight) {
        originX = textRect.origin.x + textRect.size.width - _floatingLabel.frame.size.width;
    }
    else if (self.textAlignment == NSTextAlignmentNatural) {
        JVTextDirection baseDirection = [_floatingLabel.text getBaseDirection];
        if (baseDirection == JVTextDirectionRightToLeft) {
            originX = textRect.origin.x + textRect.size.width - _floatingLabel.frame.size.width;
        }
    }

    _floatingLabel.frame = CGRectMake(originX, _floatingLabel.frame.origin.y,
                                      _floatingLabel.frame.size.width, _floatingLabel.frame.size.height);
}

- (void)setFloatingLabelText:(NSString *)text
{
    _floatingLabel.text = text;
    [self setNeedsLayout];
}

- (void)setPlaceholderTextColor:(UIColor *)placeholderTextColor
{
    _placeholderTextColor = placeholderTextColor;
    [self setPlaceholder:self.placeholder];
}

#pragma mark - UITextField

- (CGSize)intrinsicContentSize
{
    CGSize textFieldIntrinsicContentSize = [super intrinsicContentSize];
    return CGSizeMake(textFieldIntrinsicContentSize.width,
                      textFieldIntrinsicContentSize.height + _floatingLabelYPadding + _floatingLabel.font.lineHeight);
}

- (void)setPlaceholder:(NSString *)placeholder
{
    if (self.placeholderTextColor) {
        NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSForegroundColorAttributeName : self.placeholderTextColor}];
        [super setAttributedPlaceholder:attributedPlaceholder];
    } else {
        [super setPlaceholder:placeholder];
    }
    [self setFloatingLabelText:placeholder];
}

- (void)setAttributedPlaceholder:(NSAttributedString *)attributedPlaceholder
{
    [super setAttributedPlaceholder:attributedPlaceholder];
    [self setFloatingLabelText:attributedPlaceholder.string];
}

- (void)setPlaceholder:(NSString *)placeholder floatingTitle:(NSString *)floatingTitle
{
    [self setPlaceholder:placeholder];
    [self setFloatingLabelText:floatingTitle];
}

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect rect = [super textRectForBounds:bounds];
    if ([self.text length]) {
        CGFloat topInset = ceilf(_floatingLabel.font.lineHeight + _placeholderYPadding);
        topInset = MIN(topInset, [self maxTopInset]);
        rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(topInset, 0.0f, 0.0f, 0.0f));
    }
    return CGRectIntegral(rect);
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect rect = [super editingRectForBounds:bounds];
    if ([self.text length]) {
        CGFloat topInset = ceilf(_floatingLabel.font.lineHeight + _placeholderYPadding);
        topInset = MIN(topInset, [self maxTopInset]);
        rect = UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(topInset, 0.0f, 0.0f, 0.0f));
    }
    return CGRectIntegral(rect);
}

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    CGRect rect = [super clearButtonRectForBounds:bounds];
    if (0 != self.adjustsClearButtonRect) {
        if ([self.text length]) {
            CGFloat topInset = ceilf(_floatingLabel.font.lineHeight + _placeholderYPadding);
            topInset = MIN(topInset, [self maxTopInset]);
            rect = CGRectMake(rect.origin.x, rect.origin.y + topInset / 2.0f, rect.size.width, rect.size.height);
        }
    }
    return CGRectIntegral(rect);
}

- (CGFloat)maxTopInset
{
    return MAX(0, floorf(self.bounds.size.height - self.font.lineHeight - 4.0f));
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
    [super setTextAlignment:textAlignment];
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.floatingLabelFont) {
        _floatingLabel.font = self.floatingLabelFont;
    }

    [_floatingLabel sizeToFit];

    [self setLabelOriginForTextAlignment];

    BOOL firstResponder = self.isFirstResponder;
    _floatingLabel.textColor = (firstResponder && self.text && self.text.length > 0 ?
                                self.labelActiveColor : self.floatingLabelTextColor);
    if (!self.text || 0 == [self.text length]) {
        [self hideFloatingLabel:firstResponder];
    }
    else {
        [self showFloatingLabel:firstResponder];
    }
}

@end


text:
goog.provide('lf.proc.QueryTask');

goog.require('goog.Promise');
goog.require('lf.TransactionStats');
goog.require('lf.TransactionType');
goog.require('lf.cache.Journal');
goog.require('lf.proc.PhysicalQueryPlan');
goog.require('lf.proc.Task');
goog.require('lf.query.SelectContext');
goog.require('lf.service');
goog.require('lf.structs.set');

/**
 * A QueryTask represents a collection of queries that should be executed as
 * part of a single transaction.
 * @implements {lf.proc.Task}
 * @constructor
 * @struct
 *
 * @param {!lf.Global} global
 * @param {!Array<!lf.proc.TaskItem>} items
 */
lf.proc.QueryTask = function(global, items) {
  /** @protected {!lf.Global} */
  this.global = global;

  /** @private {!lf.BackStore} */
  this.backStore_ = global.getService(lf.service.BACK_STORE);

  /** @protected {!Array<!lf.query.Context>} */
  this.queries = items.map(function(item) {
    return item.context;
  });

  /** @private {!Array<!lf.proc.PhysicalQueryPlan>} */
  this.plans_ = items.map(function(item) {
    return item.plan;
  });

  /** @private {!lf.structs.Set<!lf.schema.Table>} */
  this.combinedScope_ = lf.proc.PhysicalQueryPlan.getCombinedScope(this.plans_);

  /** @private {!lf.TransactionType} */
  this.txType_ = this.detectType_();

  /** @private {!goog.promise.Resolver.<!Array<!lf.proc.Relation>>} */
  this.resolver_ = goog.Promise.withResolver();

  /** @private {!lf.backstore.Tx} */
  this.tx_;
};

/**
 * @return {!lf.TransactionType}
 * @private
 */
lf.proc.QueryTask.prototype.detectType_ = function() {
  var txType = this.queries.some(
      function(query) {
        return !(query instanceof lf.query.SelectContext);
      }) ? lf.TransactionType.READ_WRITE : lf.TransactionType.READ_ONLY;
  return txType;
};

/** @override */
lf.proc.QueryTask.prototype.exec = function() {
  var journal = this.txType_ == lf.TransactionType.READ_ONLY ?
      undefined : new lf.cache.Journal(this.global, this.combinedScope_);
  var results = [];

  var remainingPlans = this.plans_.slice();
  var queries = this.queries;

  /** @return {!IThenable} */
  var sequentiallyExec = function() {
    var plan = remainingPlans.shift();
    if (plan) {
      var queryContext = queries[results.length];
      return plan.getRoot().exec(journal, queryContext).then(
          function(relations) {
            results.push(relations[0]);
            return sequentiallyExec();
          });
    }
    return goog.Promise.resolve();
  };

  return sequentiallyExec().then(function() {
    this.tx_ = this.backStore_.createTx(
        this.txType_, lf.structs.set.values(this.combinedScope_), journal);
    return this.tx_.commit();
  }.bind(this)).then(function() {
    this.onSuccess(results);
    return results;
  }.bind(this), function(e) {
    if (goog.isDefAndNotNull(journal)) {
      journal.rollback();
    }
    throw e;
  });
};

/** @override */
lf.proc.QueryTask.prototype.getType = function() {
  return this.txType_;
};

/** @override */
lf.proc.QueryTask.prototype.getScope = function() {
  return this.combinedScope_;
};

/** @override */
lf.proc.QueryTask.prototype.getResolver = function() {
  return this.resolver_;
};

/** @override */
lf.proc.QueryTask.prototype.getId = function() {
  return goog.getUid(this);
};

/** @override */
lf.proc.QueryTask.prototype.getPriority = goog.abstractMethod;

/**
 * Executes after all queries have finished successfully. Default implementation
 * is a no-op. Subclasses should override this method as necessary.
 * @param {!Array<!lf.proc.Relation>} results The results of all queries run by
 *     this task.
 * @protected
 */
lf.proc.QueryTask.prototype.onSuccess = function(results) {
  // Default implementation is a no-op.
};

/**
 * Returns stats for the task. Used in transaction.exec([queries]).
 * @return {!lf.TransactionStats}
 */
lf.proc.QueryTask.prototype.stats = function() {
  var results = null;
  if (goog.isDefAndNotNull(this.tx_)) {
    results = this.tx_.stats();
  }
  return goog.isNull(results) ? lf.TransactionStats.getDefault() : results;
};


text:
require 'synapse/service_watcher/multi/resolver/base'
require 'synapse/log'
require 'synapse/statsd'
require 'synapse/atomic'

require 'aws-sdk'
require 'timeout'
require 'thread'
require 'yaml'

class Synapse::ServiceWatcher::Resolver
  class S3ToggleResolver < BaseResolver
    include Synapse::Logging
    include Synapse::StatsD

    # The S3 file schema, which is validated in validate_s3_file_schema, is YAML
    # of the form:
    #
    # ---
    # primary: weight
    # watcher_name: weight
    # ...
    #
    # The keys refer to the watchers as defined in the Synapse configuration.
    # `primary` is the default watcher, defined by the `discovery` section.
    # All other watchers are defined under `discovery_multi.watchers`.
    # The weight is a non-negative integer value which determines how likely it
    # is for the watcher to get chosen.
    DEFAULT_WATCHER = 'primary'.freeze

    @@s3_watcher = nil

    def initialize(opts, watchers, notification_callback)
      super(opts, watchers, notification_callback)

      @watcher_setting = Synapse::AtomicValue.new(DEFAULT_WATCHER)
      @last_watcher_weights_hash = nil

      @polling_interval = @opts['s3_polling_interval_seconds']

      s3_parts = parse_s3_url(@opts['s3_url'])
      @s3_bucket = s3_parts['bucket']
      @s3_path = s3_parts['path']

      @@s3_watcher ||= BackgroundS3Poller.new
    end

    def start
      log.info "synapse: s3 toggle resolver: starting"
      @@s3_watcher.add_path(@s3_bucket, @s3_path, @polling_interval,
                            ->(path) { set_watcher(path) })
    end

    def stop
      log.warn "synapse: s3 toggle resolver: stopping"
      @@s3_watcher.stop
    end

    def merged_backends
      return current_watcher.backends
    end

    def merged_config_for_generator
      return current_watcher.config_for_generator
    end

    def healthy?
      return current_watcher.ping?
    end

    def validate_opts
      %w(method s3_url s3_polling_interval_seconds).each do |opt|
        raise ArgumentError, "s3 toggle resolver expects option #{opt}" unless @opts.has_key?(opt)
      end

      raise ArgumentError, "s3 toggle resolver expects method to be s3_toggle" unless @opts['method'] == 's3_toggle'
      raise ArgumentError, "s3 url should be of form s3://{bucket}/{name}" unless @opts['s3_url'].start_with?('s3://')
      raise ArgumentError, "s3 toggle resolver expects numeric s3_polling_interval_seconds > 0" unless @opts['s3_polling_interval_seconds'].is_a?(Numeric) && @opts['s3_polling_interval_seconds'] > 0
      raise ArgumentError, "s3 toggle resolver expects at least 1 watcher" unless @watchers.length > 0
    end

    private

    def set_watcher(w)
      unless @watchers.keys.include?(w)
        log.warn "synapse: s3 toggle resolver: tried to set unknown watcher #{w}"
        statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:fail', 'reason:unknown_watcher'])
        return
      end

      current = @watcher_setting.get

      unless current == w
        @watcher_setting.set(w)
        send_notification
      end
    end

    def current_watcher
      watcher_name = @watcher_setting.get
      return @watchers[watcher_name]
    end

    # url = s3://{bucket}/{path}
    def parse_s3_url(url)
      parts = url.partition('s3://')
      raise ArgumentError, "expected url to begin with 's3://' prefix: #{url}" unless parts.length == 3

      bucket, path = parts[2].split('/', 2)
      raise ArgumentError, "expected url to be of format s3://{bucket}/{key}" unless (
          !bucket.nil? &&
          !path.nil? &&
          bucket.length > 0 &&
          path.length > 0)

      return {'bucket' => bucket, 'path' => path}
    end

    # Polls multiple S3 files with different polling intervals.
    # Calls a callback with the file contents after each read.
    class BackgroundS3Poller
      include Synapse::Logging
      include Synapse::StatsD

      @@s3_client = AWS::S3::Client.new

      def initialize()
        @mu = Mutex.new
        @thread = nil
        @paths = {}
      end

      def add_path(bucket, key, polling_interval, callback)
        path_key = "#{bucket}/#{key}:#{polling_interval}s"

        @mu.synchronize {
          path_config = @paths[path_key]

          if path_config.nil?
            path_config = {:bucket => bucket,
                           :key => key,
                           :polling_interval => polling_interval,
                           :last_run => Time.now - rand(polling_interval),
                           :picked_watcher => nil,
                           :last_content_hash => nil,
                           :callbacks => []}
          end

          path_config[:callbacks] << callback
          @paths[path_key] = path_config
        }
        start
      end

      def start
        return unless @thread.nil?

        @should_exit = false
        @thread = Thread.new {
          log.info "synapse: s3 toggle resolver: background thread starting"

          while true
            should_exit = nil
            @mu.synchronize {
              should_exit = @should_exit
              update_s3_picks
            }

            break if should_exit
            sleep 1
          end

          log.info "synapse: s3 toggle resolver: background thread exiting normally"
        }
      end

      def stop
        @mu.synchronize { @should_exit = true }
      end

      private

      def update_s3_picks
        @paths.each_value do |path_data|
          if Time.now - path_data[:last_run] >= path_data[:polling_interval]
            path_data_from_s3 = read_s3_file(path_data[:bucket], path_data[:key])
            set_watcher(path_data, path_data_from_s3)
          end
        end
      end

      # pick and set a new watcher, but only if the hash has changed
      def set_watcher(path_data, watcher_weights)
        path_data[:last_run] = Time.now

        if watcher_weights.hash == path_data[:last_content_hash]
          log.info "synapse: s3 toggle resolver: watcher weights hash does not change; ignoring update"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:skip'])

          return path_data[:picked_watcher]
        end

        picked_watcher = pick_watcher(watcher_weights)
        if picked_watcher.nil?
          return path_data[:picked_watcher]
        end

        path_data[:picked_watcher] = picked_watcher
        path_data[:last_content_hash] = watcher_weights.hash

        path_data[:callbacks].each do |cb|
          cb.call(picked_watcher)
        end

        return picked_watcher
      end

      # randomly pick a watcher based on the provided weights.
      # if it returns nil, it means it could not pick.
      def pick_watcher(watcher_weights)
        if watcher_weights.nil?
          log.warn "synapse: s3 toggle resolver: received nil watcher weights, not picking"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:fail', 'reason:nil_weights'])

          return nil
        end

        watcher_name = nil
        total_weight = watcher_weights.values.inject(0, :+)

        if total_weight == 0
          log.warn "synapse: s3 toggle resolver: sum of all weights equal 0, not picking"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:fail', 'reason:zero_sum'])
        elsif watcher_weights.length == 0
          log.warn "synapse: s3 toggle resolver: no watchers read, failed to pick a watcher"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:fail', 'reason:watchers_missing'])
        else
          pick = rand(total_weight)

          watcher_weights.each do |key, value|
            if pick < value
              watcher_name  = key
              break
            else
              pick -= value
            end
          end
        end

        if watcher_name.nil?
          log.warn "synapse: s3 toggle resolver: failed to pick a watcher"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:fail', 'reason:no_choice'])
        else
          log.info "synapse: s3 toggle resolver: chose watcher #{watcher_name}"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.switch', ['result:success', "watcher:#{watcher_name}"])
        end

        return watcher_name
      end

      def read_s3_file(bucket, key)
        data =
          begin
            resp = @@s3_client.get_object(bucket_name: bucket, key: key)
            parsed = YAML.load(resp.data[:data])

            log.info "synapse: s3 toggle resolver: read s3 file: #{parsed}"
            parsed
          rescue Psych::SyntaxError, TypeError => e
            log.warn "synapse: s3 toggle resolver: failed to parse s3 file: #{e}"
            statsd_increment('synapse.watcher.multi.resolver.s3_toggle.fetch_failure', ["reason:parse_error"])
            nil
          rescue AWS::Errors::Base => e
            log.warn "synapse: s3 toggle resolver: failed to fetch s3 file: #{e}"
            statsd_increment('synapse.watcher.multi.resolver.s3_toggle.fetch_failure', ["reason:s3_error"])
            nil
          end

        if validate_s3_file_schema(data)
          return data
        else
          log.warn "synapse: s3 toggle resolver: s3 file has invalid schema"
          statsd_increment('synapse.watcher.multi.resolver.s3_toggle.fetch_failure', ["reason:invalid_schema"])

          return nil
        end
      end

      # expected schema is {'watcher_name' => Integer, ...}
      def validate_s3_file_schema(contents)
        return false if (
            contents.nil? ||
            !contents.is_a?(Hash)
          )

        contents.each do |key, value|
          return false unless key.is_a?(String) && value.is_a?(Integer) && value >= 0
        end

        return true
      end
    end
  end
end


text:
namespace VertexAsylum
{
    // FS: Decided to make these two singletons as I can't think of a use where they wouldn't be at the moment. If need
    // arises, one option is to split vaDebugCanvas2DBase into ICanvas2D interface and then inherit vaCanvas2DSingleton from it.

    class vaDebugCanvas2DBase : public vaSingletonBase < vaDebugCanvas2DBase >
    {
    protected:
        virtual ~vaDebugCanvas2DBase( ) {}
        //
    public:
        // would've used DrawText but thats #defined somewhere in windows.h or related headers :/
        virtual void        DrawString( int x, int y, const wchar_t * text, ... ) = 0;
        virtual void        DrawString( int x, int y, unsigned int penColor, const wchar_t * text, ... ) = 0;
        virtual void        DrawString( int x, int y, unsigned int penColor, unsigned int shadowColor, const wchar_t * text, ... ) = 0;
        virtual void        DrawString( int x, int y, const char * text, ... ) = 0;
        virtual void        DrawString( int x, int y, unsigned int penColor, const char * text, ... ) = 0;
        virtual void        DrawString( int x, int y, unsigned int penColor, unsigned int shadowColor, const char * text, ... ) = 0;
        //virtual void        GetTextWidth( const char * text );
        //virtual void        GetTextWidth( const wchar_t * text );
        virtual void        DrawLine( float x0, float y0, float x1, float y1, unsigned int penColor ) = 0;
        virtual void        DrawLineArrowhead( float x0, float y0, float x1, float y1, float arrowHeadSize, unsigned int penColor );
        virtual void        DrawRectangle( float x0, float y0, float width, float height, unsigned int penColor ) = 0;
        virtual void        DrawCircle( float x, float y, float radius, unsigned int penColor, float tess = 0.6f ) = 0;
        virtual void        FillRectangle( float x0, float y0, float width, float height, unsigned int brushColor ) = 0;
        //
        virtual int         GetWidth( ) = 0;
        virtual int         GetHeight( ) = 0;
        //
        inline void         DrawLine( const vaVector2 & a, vaVector2 & b, unsigned int penColor )                                                   { DrawLine( a.x, a.y, b.x, b.y, penColor ); }
        inline void         DrawLineArrowhead( const vaVector2 & a, vaVector2 & b, float arrowHeadSize, unsigned int penColor )                     { DrawLineArrowhead( a.x, a.y, b.x, b.y, arrowHeadSize, penColor ); }
    };

    class vaDebugCanvas3DBase : public vaSingletonBase < vaDebugCanvas3DBase >
    {
    protected:
        virtual ~vaDebugCanvas3DBase( ) {}
        //
    public:
        //
        virtual void        DrawLine( const vaVector3 & v0, const vaVector3 & v1, unsigned int penColor ) = 0;
        virtual void        DrawAxis( const vaVector3 & v0, float size, const vaMatrix4x4 * transform = NULL, float alpha = 0.5f ) = 0;

        virtual void        DrawBox( const vaVector3 & v0, const vaVector3 & v1, unsigned int penColor, unsigned int brushColor = 0x000000, const vaMatrix4x4 * transform = NULL ) = 0;
        virtual void        DrawTriangle( const vaVector3 & v0, const vaVector3 & v1, const vaVector3 & v2, unsigned int penColor, unsigned int brushColor = 0x000000, const vaMatrix4x4 * transform = NULL ) = 0;
        virtual void        DrawQuad( const vaVector3 & v0, const vaVector3 & v1, const vaVector3 & v2, const vaVector3 & v3, unsigned int penColor, unsigned int brushColor = 0x000000, const vaMatrix4x4 * transform = NULL ) = 0;
        virtual void        DrawSphere( const vaVector3 & center, float radius, unsigned int penColor, unsigned int brushColor = 0x000000 ) = 0;
        //
        void                DrawBox( const vaBoundingBox & aabb, unsigned int penColor, unsigned int brushColor = 0x000000, const vaMatrix4x4 * transform = NULL  );
        void                DrawBox( const vaOrientedBoundingBox & obb, unsigned int penColor, unsigned int brushColor = 0x000000 );
        void                DrawSphere( const vaBoundingSphere & bs, unsigned int penColor, unsigned int brushColor = 0x000000 );
    };

    //////////////////////////////////////////////////////////////////////////
    // Inline
    //////////////////////////////////////////////////////////////////////////

    inline void vaDebugCanvas2DBase::DrawLineArrowhead( float x0, float y0, float x1, float y1, float arrowHeadSize, unsigned int penColor )
    {
        vaVector2 lineDir = vaVector2( x1 - x0, y1 - y0 );
        float lengthSq = lineDir.LengthSq();
        if( lengthSq < VA_EPSf )
            return;

        lineDir /= vaMath::Sqrt( lengthSq );
        vaVector2 lineDirOrt = vaVector2( lineDir.y, -lineDir.x );

        vaVector2 ptFrom = vaVector2( x1, y1 );
        vaVector2 ptA   = ptFrom - lineDir * arrowHeadSize + lineDirOrt * arrowHeadSize;
        vaVector2 ptB   = ptFrom - lineDir * arrowHeadSize - lineDirOrt * arrowHeadSize;

        ptFrom += lineDir * 1.5f;

        DrawLine( ptFrom, ptA, penColor );
        DrawLine( ptFrom, ptB, penColor );
    }

    inline void vaDebugCanvas3DBase::DrawSphere( const vaBoundingSphere & bs, unsigned int penColor, unsigned int brushColor )
    {
        DrawSphere( bs.Center, bs.Radius, penColor, brushColor );
    }

    inline void vaDebugCanvas3DBase::DrawBox( const vaBoundingBox & aabb, unsigned int penColor, unsigned int brushColor, const vaMatrix4x4 * transform )
    {
        DrawBox( aabb.Min, aabb.Max(), penColor, brushColor, transform );
    }

    inline void vaDebugCanvas3DBase::DrawBox( const vaOrientedBoundingBox & obb, unsigned int penColor, unsigned int brushColor )
    {
        vaBoundingBox bb;
        vaMatrix4x4 transform;
        obb.ToAABBAndTransform( bb, transform );
        DrawBox( bb.Min, bb.Max( ), penColor, brushColor, &transform );
    }

}


text:
void testApp::setup() {
	dome.setScreenDivision(3, 1);
	dome.setCoordinateSystemCube(1024);
	dome.setup();

	dome.loadMeshCompositionString(ofBufferFromFile("mesh.txt").getText());

	images[ofxDome::CUBE_TEXTURE_TOP] = ofImage("cube_top.jpg");
	images[ofxDome::CUBE_TEXTURE_FRONT] = ofImage("cube_front.jpg");
	images[ofxDome::CUBE_TEXTURE_LEFT] = ofImage("cube_left.jpg");
	images[ofxDome::CUBE_TEXTURE_RIGHT] = ofImage("cube_right.jpg");
	images[ofxDome::CUBE_TEXTURE_BACK] = ofImage("cube_back.jpg");
}

//--------------------------------------------------------------
void testApp::update() {

}

//--------------------------------------------------------------
void testApp::draw() {
	for (int i = 0; i < ofxDome::CUBE_TEXTURES_NUM; i++) {
		dome.beginFbo(i);
		images[i].draw(0, 0, 1024, 1024);
		dome.endFbo(i);
	}
}

//--------------------------------------------------------------
void testApp::keyPressed( int key ) {
	switch (key) {
	case 'l':
		dome.setMeshVisiblity(!dome.getMeshVisiblity());
		break;
	case 'f':
		ofToggleFullscreen();
		break;
	}
}

void testApp::mouseReleased(int x, int y, int button) {
	ofBuffer buffer(dome.getMeshCompositionString());
	ofBufferToFile("mesh.txt", buffer);
}


text:
using System;
using AlienInvasion.Fleets;

namespace AlienInvasion
{
    namespace Ships
    {
        class DestroyerShip : AlienShipBase
        {
            public DestroyerShip(int shipIndex, int internalFleetIndex, int health, string pilotName, ShipType type, AlienFleet fleet)
                : base(shipIndex, internalFleetIndex, health, pilotName, type, fleet)
            {

            }
        }
    }
}


text:
package com.heaven7.android.component.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import com.heaven7.core.util.ViewHelper;

/**
 * Created by heaven7 on 2016/5/24.
 */
public final class FragmentCallbackContext {

    private FragmentMediator mMediator;

    /*public*/ void setFragmentMediator(FragmentMediator mediator){
        this.mMediator = mediator;
    }
    public FragmentMediator getFragmentMediator(){
        return mMediator;
    }

    public Fragment getFragment(){
        return  mMediator.getFragment();
    }
    public ViewHelper getViewHelper(){
        return mMediator.getViewHelper();
    }
    public Bundle getSaveBundle(){
        return mMediator.getSaveBundle();
    }
}


text:
namespace {

// We are backed by an Pbuffer offscreen surface through which ANGLE provides
// a handle to the corresponding render target texture through an extension.
class PbufferImageTransportSurface
    : public gfx::GLSurfaceAdapter,
      public ImageTransportSurface,
      public base::SupportsWeakPtr<PbufferImageTransportSurface> {
 public:
  PbufferImageTransportSurface(GpuChannelManager* manager,
                               GpuCommandBufferStub* stub);

  // gfx::GLSurface implementation
  virtual bool Initialize() OVERRIDE;
  virtual void Destroy() OVERRIDE;
  virtual bool IsOffscreen() OVERRIDE;
  virtual bool SwapBuffers() OVERRIDE;
  virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE;
  virtual std::string GetExtensions() OVERRIDE;
  virtual void SetVisible(bool visible) OVERRIDE;

 protected:
  // ImageTransportSurface implementation
  virtual void OnNewSurfaceACK(uint64 surface_handle,
                               TransportDIB::Handle shm_handle) OVERRIDE;
  virtual void OnBuffersSwappedACK() OVERRIDE;
  virtual void OnPostSubBufferACK() OVERRIDE;
  virtual void OnResizeViewACK() OVERRIDE;
  virtual void OnResize(gfx::Size size) OVERRIDE;

 private:
  virtual ~PbufferImageTransportSurface();
  void SendBuffersSwapped();

  // Whether the surface is currently visible.
  bool is_visible_;

  // Size to resize to when the surface becomes visible.
  gfx::Size visible_size_;

  scoped_ptr<ImageTransportHelper> helper_;

  DISALLOW_COPY_AND_ASSIGN(PbufferImageTransportSurface);
};

PbufferImageTransportSurface::PbufferImageTransportSurface(
    GpuChannelManager* manager,
    GpuCommandBufferStub* stub)
    : GLSurfaceAdapter(new gfx::PbufferGLSurfaceEGL(false, gfx::Size(1, 1))),
      is_visible_(true) {
  helper_.reset(new ImageTransportHelper(this,
                                         manager,
                                         stub,
                                         gfx::kNullPluginWindow));
}

PbufferImageTransportSurface::~PbufferImageTransportSurface() {
  Destroy();
}

bool PbufferImageTransportSurface::Initialize() {
  // Only support this path if the GL implementation is ANGLE.
  // IO surfaces will not work with, for example, OSMesa software renderer
  // GL contexts.
  if (gfx::GetGLImplementation() != gfx::kGLImplementationEGLGLES2)
    return false;

  if (!helper_->Initialize())
    return false;

  return GLSurfaceAdapter::Initialize();
}

void PbufferImageTransportSurface::Destroy() {
  helper_->Destroy();
  GLSurfaceAdapter::Destroy();
}

bool PbufferImageTransportSurface::IsOffscreen() {
  return false;
}

bool PbufferImageTransportSurface::SwapBuffers() {
  HANDLE surface_handle = GetShareHandle();
  if (!surface_handle)
    return false;

  helper_->DeferToFence(base::Bind(
      &PbufferImageTransportSurface::SendBuffersSwapped,
      AsWeakPtr()));

  return true;
}

bool PbufferImageTransportSurface::PostSubBuffer(
    int x, int y, int width, int height) {
  NOTREACHED();
  return false;
}

void PbufferImageTransportSurface::SetVisible(bool visible) {
  if (visible == is_visible_)
    return;

  is_visible_ = visible;

  if (visible)
    Resize(visible_size_);
  else
    Resize(gfx::Size(1, 1));
}

std::string PbufferImageTransportSurface::GetExtensions() {
  std::string extensions = gfx::GLSurface::GetExtensions();
  extensions += extensions.empty() ? "" : " ";
  extensions += "GL_CHROMIUM_front_buffer_cached";
  return extensions;
}

void PbufferImageTransportSurface::SendBuffersSwapped() {
  GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
  params.surface_handle = reinterpret_cast<int64>(GetShareHandle());
  params.size = GetSize();
  helper_->SendAcceleratedSurfaceBuffersSwapped(params);

  helper_->SetScheduled(false);
}

void PbufferImageTransportSurface::OnBuffersSwappedACK() {
  helper_->SetScheduled(true);
}

void PbufferImageTransportSurface::OnPostSubBufferACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnNewSurfaceACK(
    uint64 surface_handle,
    TransportDIB::Handle shm_handle) {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResizeViewACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResize(gfx::Size size) {
  if (is_visible_)
    Resize(size);

  visible_size_ = size;
}

}  // namespace anonymous

// static
scoped_refptr<gfx::GLSurface> ImageTransportSurface::CreateSurface(
    GpuChannelManager* manager,
    GpuCommandBufferStub* stub,
    gfx::PluginWindowHandle handle) {
  scoped_refptr<gfx::GLSurface> surface;

  if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2 &&
      !CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableImageTransportSurface)) {
    const char* extensions = eglQueryString(eglGetDisplay(EGL_DEFAULT_DISPLAY),
                                            EGL_EXTENSIONS);
    if (strstr(extensions, "EGL_ANGLE_query_surface_pointer") &&
        strstr(extensions, "EGL_ANGLE_surface_d3d_texture_2d_share_handle")) {
      surface = new PbufferImageTransportSurface(manager, stub);
    }
  }

  if (!surface.get()) {
    surface = gfx::GLSurface::CreateViewGLSurface(false, handle);
    if (!surface.get())
      return NULL;

    surface = new PassThroughImageTransportSurface(manager,
                                                   stub,
                                                   surface.get());
  }

  if (surface->Initialize())
    return surface;
  else
    return NULL;
}

#endif  // ENABLE_GPU


text:
import React, { Component } from 'react';

//const SOURCE_FOLDER = 'src/components/';
const SOURCE_FOLDER = 'https://github.com/dkozar/react-liberator/tree/master/src/components/';

export default class SourceLink extends Component {
    render() {
        return (
            Click here for the source
        );
    }
}


text:
const char kPushMessagingEndpoint[] = "https://android.googleapis.com/gcm/send";

const char kPushMessagingForcedNotificationTag[] =
    "user_visible_auto_notification";


text:
using System;
using Foundation;
using UIKit;
using Agencies.Shared;

namespace Agencies.iOS
{
	public partial class GroupsViewController : BaseViewController
	{
		class Segues
		{
			public const string Embed = "Embed";
			public const string Detail = "GroupDetail";
		}

		GroupsTableViewController GroupsTableController => ChildViewControllers [0] as GroupsTableViewController;

		public GroupsViewController (IntPtr handle) : base (handle)
		{
		}

		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			GroupsTableController.GroupSelectionChanged += OnGroupSelectionChanged;
		}

		public override void ViewWillDisappear (bool animated)
		{
			GroupsTableController.GroupSelectionChanged -= OnGroupSelectionChanged;

			base.ViewWillDisappear (animated);
		}

		void OnGroupSelectionChanged (object sender, PersonGroup selection)
		{
			FaceState.Current.CurrentGroup = selection;

			PerformSegue (Segues.Detail, this);
		}

		public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
		{
			base.PrepareForSegue (segue, sender);

			if (segue.Identifier == Segues.Embed && segue.DestinationViewController is GroupsTableViewController groupsTVC)
			{
				groupsTVC.AllowDelete = true;
			}
		}
	}
}


text:
package org.apache.http.client.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Static helpers for dealing with {@link HttpResponse}s and {@link HttpClient}s.
 *
 * @since 4.2
 */
public class HttpClientUtils {

    private HttpClientUtils() {
    }

    /**
     * Unconditionally close a response.
     *

     * Example Code:
     *
     *

     * HttpResponse httpResponse = null;
     * try {
     *     httpResponse = httpClient.execute(httpGet);
     * } catch (Exception e) {
     *     // error handling
     * } finally {
     *     HttpClientUtils.closeQuietly(httpResponse);
     * }
     *

     *
     * @param response
     *            the HttpResponse to release resources, may be null or already
     *            closed.
     *
     * @since 4.2
     */
    public static void closeQuietly(final HttpResponse response) {
        if (response != null) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                try {
                    EntityUtils.consume(entity);
                } catch (final IOException ex) {
                }
            }
        }
    }

    /**
     * Unconditionally close a httpClient. Shuts down the underlying connection
     * manager and releases the resources.
     *

     * Example Code:
     *
     *

     * HttpClient httpClient = null;
     * try {
     *   httpClient = new DefaultHttpClient(...);
     * } catch (Exception e) {
     *   // error handling
     * } finally {
     *   HttpClientUtils.closeQuietly(httpClient);
     * }
     *

     *
     * @param httpClient
     *            the HttpClient to close, may be null or already closed.
     * @since 4.2
     */
    public static void closeQuietly(final HttpClient httpClient) {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }

}


text:
import camelcase = require( './index' );

// TESTS //

// The function returns a string...
{
	camelcase( 'Hello World!' ); // $ExpectType string
}

// The compiler throws an error if the function is provided a value other than a string...
{
	camelcase( true ); // $ExpectError
	camelcase( false ); // $ExpectError
	camelcase( null ); // $ExpectError
	camelcase( undefined ); // $ExpectError
	camelcase( 5 ); // $ExpectError
	camelcase( [] ); // $ExpectError
	camelcase( {} ); // $ExpectError
	camelcase( ( x: number ): number => x ); // $ExpectError
}

// The compiler throws an error if the function is provided insufficient arguments...
{
	camelcase(); // $ExpectError
}


text:
module VCloudCloud
  module Steps
    class InsertCatalogMedia < Step
      def perform(name, &block)
        media, _ = client.media name
        params = VCloudSdk::Xml::WrapperFactory.create_instance 'MediaInsertOrEjectParams'
        params.media_href = media.href
        vm = state[:vm]
        @logger.debug "INSERTMEDIA #{media.name} into VM #{vm.name}"
        client.timed_loop do
          media = client.reload media
          vm = client.reload vm
          if media.running_tasks.empty? && media.prerunning_tasks.empty?
            client.invoke_and_wait :post, vm.insert_media_link,
                    :payload => params,
                    :headers => { :content_type => VCloudSdk::Xml::MEDIA_TYPE[:MEDIA_INSERT_EJECT_PARAMS] }
            break
          else
            media = client.wait_entity media
          end
        end
        state[:vm] = client.reload vm
      end

      def rollback
        vm = state[:vm]
        name = vm.name

        catalog_media = client.catalog_item :media, name, VCloudSdk::Xml::MEDIA_TYPE[:MEDIA]
        # return if doesn't exist
        return unless catalog_media
        media = client.resolve_link catalog_media.entity
        params = VCloudSdk::Xml::WrapperFactory.create_instance 'MediaInsertOrEjectParams'
        params.media_href = media.href
        vm = state[:vm]
        client.timed_loop do
          media = client.reload media
          vm = client.reload vm
          if media.running_tasks.empty?
            client.invoke_and_wait :post, vm.eject_media_link,
                                   :payload => params,
                                   :headers => { :content_type => VCloudSdk::Xml::MEDIA_TYPE[:MEDIA_INSERT_EJECT_PARAMS] }
            break
          else
            media = client.wait_entity media
          end
        end
      end
    end
  end
end


text:
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName		= "Wire Flash EEPROM"
ENT.WireDebugName 	= "WireHDD"

if CLIENT then return end -- No more client

function ENT:OnRemove()
	for k,v in pairs(self.CacheUpdated) do
		file.Write(self:GetStructName(k),self:MakeFloatTable(self.Cache[k]))
	end
end

function ENT:Initialize()
	self:PhysicsInit(SOLID_VPHYSICS)
	self:SetMoveType(MOVETYPE_VPHYSICS)
	self:SetSolid(SOLID_VPHYSICS)
	self:SetUseType(SIMPLE_USE)

	self.Outputs = Wire_CreateOutputs(self, { "Data" })
	self.Inputs = Wire_CreateInputs(self, { "Clk", "AddrRead", "AddrWrite", "Data" })

	self.Clk = 0
	self.AWrite = 0
	self.ARead = 0
	self.Data = 0
	self.Out = 0

	-- Flash type
	--   0: compatibility 16 values per block mode
	--   1: 128 values per block mode
	self.FlashType = 0
	self.BlockSize = 16

	-- Hard drive id/folder id:
	self.DriveID = 0
	self.PrevDriveID = nil

	-- Hard drive capicacity (loaded from hdd)
	self.DriveCap = 0
	self.MaxAddress = 0

	-- Current cache (array of blocks)
	self.Cache = {}
	self.CacheUpdated = {}

	-- Owners STEAMID
	self.Owner_SteamID = "SINGLEPLAYER"
	self:NextThink(CurTime()+1.0)
end

function ENT:Setup(DriveID, DriveCap)
	self.DriveID = DriveID
	self.DriveCap = DriveCap
	self:UpdateCap()
end

function ENT:GetStructName(name)
	return "WireFlash/"..(self.Owner_SteamID or "UNKNOWN").."/HDD"..self.DriveID.."/"..name..".txt"
end

function ENT:GetCap()
	-- If hard drive exists
	if file.Exists(self:GetStructName("drive"),"DATA") then
		-- Read format data
		local formatData = file.Read(self:GetStructName("drive"),"DATA")

		if tonumber(formatData) then
			self.DriveCap = tonumber(formatData)
			self.FlashType = 0
			self.BlockSize = 16
			self.MaxAddress = self.DriveCap * 1024
		else
			local formatInfo = string.Explode("\n",formatData)
			if (formatInfo[1] == "FLASH1") then
				self.DriveCap = tonumber(formatInfo[2]) or 0
				self.MaxAddress = tonumber(formatInfo[3]) or (self.DriveCap * 1024)
				self.FlashType = 1
				self.BlockSize = 32
			else
				file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
			end
		end
	else
		file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
		self.FlashType = 1
		self.BlockSize = 32
		self.MaxAddress = 0
	end

	--Can't have cap bigger than 256 in MP
	if (not game.SinglePlayer()) and (self.DriveCap > 256) then
		self.DriveCap = 256
	end
end

function ENT:UpdateCap()
	--Can't have cap bigger than 256 in MP
	if (not game.SinglePlayer()) and (self.DriveCap > 256) then
		self.DriveCap = 256
	end
	if self.FlashType == 0 then
		file.Write(self:GetStructName("drive"),self.DriveCap)
	else
		file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
	end

	self:GetCap()
end

function ENT:GetFloatTable(Text)
	local text = Text
	local tbl = {}
	local ptr = 0
	while (string.len(text) > 0) do
		local value = string.sub(text, 1, 24)
		text = string.sub(text, 25)
		tbl[ptr] = tonumber(value)
		ptr = ptr + 1
	end
	return tbl
end

function ENT:MakeFloatTable(Table)
	local text = ""
	for i=0,#Table-1 do
		--Clamp size to 24 chars
		local floatstr = string.sub(tostring(Table[i]),1,24)
		--Make a string, and append missing spaces
		floatstr = floatstr .. string.rep(" ",24-string.len(floatstr))

		text = text..floatstr
	end

	return text
end

function ENT:ReadCell(Address)
	--DriveID should be > 0, and less than  4 in MP
	if ((self.DriveID < 0) || (!game.SinglePlayer() && (self.DriveID >= 4))) then
		return nil
	end

	local player = self:GetPlayer()
	if player:IsValid() then
		local steamid = player:SteamID()
		steamid = string.gsub(steamid, ":", "_")
		if (steamid ~= "UNKNOWN") then
			self.Owner_SteamID = steamid
		else
			self.Owner_SteamID = "SINGLEPLAYER"
		end

		-- If drive has changed, change cap
		if self.DriveID ~= self.PrevDriveID then
			self:GetCap()
			self.PrevDriveID = self.DriveID
		end

		-- Check if address is valid
		if (Address < self.DriveCap * 1024) and (Address >= 0) then
			-- Compute address
			local block = math.floor(Address / self.BlockSize)
			local blockaddress = math.floor(Address) % self.BlockSize

			-- Check if this address is cached for read
			if self.Cache[block] then
				return self.Cache[block][blockaddress] or 0
			end

			-- If sector isn't created yet, return 0
			if not file.Exists(self:GetStructName(block),"DATA") then
				self.Cache[block] = {}
				self.CacheUpdated[block] = true
				for i=0,self.BlockSize-1 do
					self.Cache[block][i] = 0
				end
				return 0
			end

			-- Read the block
			local blockdata = self:GetFloatTable(file.Read(self:GetStructName(block)))
			self.Cache[block] = {}
			for i=0,self.BlockSize-1 do
				self.Cache[block][i] = blockdata[i] or 0
			end
			return self.Cache[block][blockaddress]
		else
			return nil
		end
	else
		return nil
	end
end

function ENT:WriteCell(Address, value)
	--DriveID should be > 0, and less than  4 in MP
	if ((self.DriveID < 0) || (!game.SinglePlayer() && (self.DriveID >= 4))) then
		return false
	end

	local player = self:GetPlayer()
	if (player:IsValid()) then
		local steamid = player:SteamID()
		steamid = string.gsub(steamid, ":", "_")
		if (steamid ~= "UNKNOWN") then
			self.Owner_SteamID = steamid
		else
			self.Owner_SteamID = "SINGLEPLAYER"
		end

		-- If drive has changed, change cap
		if self.DriveID ~= self.PrevDriveID then
			self:GetCap()
			self.PrevDriveID = self.DriveID
		end

		-- Check if address is valid
		if (Address < self.DriveCap * 1024) and (Address >= 0) then
			-- Compute address
			local block = math.floor(Address / self.BlockSize)
			local blockaddress = math.floor(Address) % self.BlockSize

			-- Check if this address is cached
			if self.Cache[block] then
				self.CacheUpdated[block] = true
				self.Cache[block][blockaddress] = value
				if Address > self.MaxAddress then
					self.MaxAddress = Address
				end
				return true
			end

			-- If sector isn't created yet, cache it
			if not file.Exists(self:GetStructName(block),"DATA") then
				self.Cache[block] = {}
				self.CacheUpdated[block] = true
				for i=0,self.BlockSize-1 do
					self.Cache[block][i] = 0
				end
				self.Cache[block][blockaddress] = value
				if Address > self.MaxAddress then
					self.MaxAddress = Address
				end
				return true
			end

			-- Read the block
			local blockdata = self:GetFloatTable(file.Read(self:GetStructName(block)))
			self.Cache[block] = {}
			for i=0,self.BlockSize-1 do
				self.Cache[block][i] = blockdata[i] or 0
			end
			self.CacheUpdated[block] = true
			self.Cache[block][blockaddress] = value
			if Address > self.MaxAddress then
				self.MaxAddress = Address
			end
			return true
		else
			return false
		end
	else
		return false
	end
end

function ENT:Think()
	local cachedBlockIndex = next(self.CacheUpdated)
	if cachedBlockIndex then
		self.CacheUpdated[cachedBlockIndex] = nil
		file.CreateDir(string.GetPathFromFilename(self:GetStructName(cachedBlockIndex)))
		file.Write(self:GetStructName(cachedBlockIndex),self:MakeFloatTable(self.Cache[cachedBlockIndex]))
		self:UpdateCap()
	end
	self:NextThink(CurTime()+0.25)
	return true
end

function ENT:TriggerInput(iname, value)
	if (iname == "Clk") then
		self.Clk = value
		if (self.Clk >= 1) then
			self:WriteCell(self.AWrite, self.Data)
			if (self.ARead == self.AWrite) then
				local val = self:ReadCell(self.ARead)
				if (val) then
					Wire_TriggerOutput(self, "Data", val)
					self.Out = val
				end
			end
		end
	elseif (iname == "AddrRead") then
		self.ARead = value
		local val = self:ReadCell(value)
		if (val) then
			Wire_TriggerOutput(self, "Data", val)
			self.Out = val
		end
	elseif (iname == "AddrWrite") then
		self.AWrite = value
		if (self.Clk >= 1) then
			self:WriteCell(self.AWrite, self.Data)
		end
	elseif (iname == "Data") then
		self.Data = value
		if (self.Clk >= 1) then
			self:WriteCell(self.AWrite, self.Data)
			if (self.ARead == self.AWrite) then
				local val = self:ReadCell(self.ARead)
				if (val) then
					Wire_TriggerOutput(self, "Data", val)
					self.Out = val
				end
			end
		end
	end

	self:SetOverlayText(self.DriveCap.."kb".."\nWriteAddr:"..self.AWrite.."  Data:"..self.Data.."  Clock:"..self.Clk.."\nReadAddr:"..self.ARead.." = ".. self.Out)
end

duplicator.RegisterEntityClass("gmod_wire_hdd", WireLib.MakeWireEnt, "Data", "DriveID", "DriveCap")