text:
class WebDatabase;
class WebDatabaseTable;
class WebDataRequest;
class WebDataRequestManager;

// WebDatabaseBackend handles all database tasks posted by
// WebDatabaseService. It is refcounted to allow asynchronous destruction on the
// DB thread.

class WEBDATA_EXPORT WebDatabaseBackend
    : public base::RefCountedDeleteOnMessageLoop<WebDatabaseBackend> {
 public:
  class Delegate {
   public:
    virtual ~Delegate() {}

    // Invoked when the backend has finished loading the db.
    // |status| is the result of initializing the db.
    // |diagnostics| contains diagnostic information about the db, and it will
    // only be populated when an error occurs.
    virtual void DBLoaded(sql::InitStatus status,
                          const std::string& diagnostics) = 0;
  };

  WebDatabaseBackend(
      const base::FilePath& path,
      Delegate* delegate,
      const scoped_refptr<base::SingleThreadTaskRunner>& db_thread);

  // Must call only before InitDatabaseWithCallback.
  void AddTable(std::unique_ptr<WebDatabaseTable> table);

  // Initializes the database and notifies caller via callback when complete.
  // Callback is called synchronously.
  void InitDatabase();

  // Shuts down the database.
  void ShutdownDatabase();

  // Task wrappers to update requests and and notify |request_manager_|. These
  // are used in cases where the request is being made from the UI thread and an
  // asyncronous callback is required to notify the client of |request|'s
  // completion.
  void DBWriteTaskWrapper(const WebDatabaseService::WriteTask& task,
                          std::unique_ptr<WebDataRequest> request);
  void DBReadTaskWrapper(const WebDatabaseService::ReadTask& task,
                         std::unique_ptr<WebDataRequest> request);

  // Task runners to run database tasks.
  void ExecuteWriteTask(const WebDatabaseService::WriteTask& task);
  std::unique_ptr<WDTypedResult> ExecuteReadTask(
      const WebDatabaseService::ReadTask& task);

  const scoped_refptr<WebDataRequestManager>& request_manager() {
    return request_manager_;
  }

  WebDatabase* database() { return db_.get(); }

 protected:
  friend class base::RefCountedDeleteOnMessageLoop<WebDatabaseBackend>;
  friend class base::DeleteHelper<WebDatabaseBackend>;

  virtual ~WebDatabaseBackend();

 private:
  // Opens the database file from the profile path if an init has not yet been
  // attempted. Separated from the constructor to ease construction/destruction
  // of this object on one thread but database access on the DB thread.
  void LoadDatabaseIfNecessary();

  // Invoked on a db error.
  void DatabaseErrorCallback(int error, sql::Statement* statement);

  // Commit the current transaction.
  void Commit();

  // Path to database file.
  base::FilePath db_path_;

  // The tables that participate in managing the database. These are
  // owned here but other than that this class does nothing with
  // them. Their initialization is in whatever factory creates
  // WebDatabaseService, and lookup by type is provided by the
  // WebDatabase class. The tables need to be owned by this refcounted
  // object, or they themselves would need to be refcounted. Owning
  // them here rather than having WebDatabase own them makes for
  // easier unit testing of WebDatabase.
  ScopedVector<WebDatabaseTable> tables_;

  std::unique_ptr<WebDatabase> db_;

  // Keeps track of all pending requests made to the db.
  scoped_refptr<WebDataRequestManager> request_manager_;

  // State of database initialization. Used to prevent the executing of tasks
  // before the db is ready.
  sql::InitStatus init_status_;

  // True if an attempt has been made to load the database (even if the attempt
  // fails), used to avoid continually trying to reinit if the db init fails.
  bool init_complete_;

  // True if a catastrophic database error occurs and further error callbacks
  // from the database should be ignored.
  bool catastrophic_error_occurred_;

  // If a catastrophic database error has occurred, this contains any available
  // diagnostic information.
  std::string diagnostics_;

  // Delegate. See the class definition above for more information.
  std::unique_ptr<Delegate> delegate_;

  DISALLOW_COPY_AND_ASSIGN(WebDatabaseBackend);
};

#endif  // COMPONENTS_WEBDATA_COMMON_WEB_DATABASE_BACKEND_H_


text:
/* This file contains overrides for the NProgress library's default stylings. */

#nprogress .bar {
	background: #fff;
	height: 1px;
}

#nprogress .peg {
	display: none;
}

#nprogress .spinner-icon {
  border-top-color: #fff;
  border-left-color: #fff;
}

redpajama_set_name: RedPajamaGithub


text:
import ManageObject  from "../base/ManageObject";

export default class View extends ManageObject
{

    init()
    {
        super.init();
        this._subviews = [];
        this.$element = $(`<${this.getElementTag()}/>`);
        if (this.id !== null)
        {
            this.$element.attr("id", this.id);
        }
        this.$container = this.$element;
    }

    getElementTag()
    {
        return "div";
    }

    get subview()
    {
        return this._subviews;
    }

    addStyleClass(...args)
    {
        this.$element.addClass(...args);
    }

    removeStyleClass(...args)
    {
        this.$element.removeClass(...args);
    }

    toggleStyleClass()
    {
        this.$element.toggleClass(...args);
    }

    addSubView(view, $container = this.$container)
    {
        if (view instanceof View)
        {
            if (view._parent)
            {
                view.removeFromParent();
            }
            view._parent = this;
            this._subviews.push(view);
            view.placeAt($container);
        }
    }

    addSubViews(views, $container = this.$container)
    {
        if (Array.isArray(views))
        {
            views.forEach(item => {
                this.addSubView(item, $container);
            });
        }
    }

    removeSubView(view, neverUseAgain = false)
    {
        const index = this._subviews.indexOf(view);
        if (index !== -1)
        {
            view._parent = null;
            this._subviews.splice(index, 1);
            if (neverUseAgain)
            {
                view.$element.remove();
            }
            else
            {
                view.$element.detach();
            }
        }
    }

    removeAllSubViews(neverUseAgain = false)
    {
        while (this._subviews.length > 0)
        {
            this._removeSubView(this._subviews[0], neverUseAgain);
        }
    }

    removeFromParent()
    {
       if (this.parent)
       {
           this.parent.removeSubView(this);
       }
    }

    placeAt(target)
    {
        const $target =  (target instanceof jQuery ? target : $(target));
        $target.append(this.$element);
    }

    $(...args)
    {
        return this.$element.find(...args);
    }

}


text:
'use strict';

/* Directives */

var gamesDirectives = angular.module('gamesDirectives', []);

gamesDirectives.directive('gameResume', function() {
    return {
      restrict: 'E',
      templateUrl: 'partials/game-resume.html',
      scope: {
        game: '=game'
      }
    };
  });


text:
package _lib_language_generator_.structures.bnf.productions.misc.elements;

/**
 * Element or char.
 *
 * @author GlaDos
 * @since 07.07.17
 */
public interface NonterminalOrChar {
	ElemType getType();
}


text:
@interface PodsDummy_Pods_Pinner_Tests : NSObject
@end
@implementation PodsDummy_Pods_Pinner_Tests
@end


text:
(function (app) {
    var dataEvent = app('data-event');
    var collExpense = app('coll-expense');
    var collCategory = app('coll-category');
    var timeLogger = app('time-logger')('ui-list-expenses');
    var logger = app('logger')('ui-list-expenses');
    var helper = app('helper');
    var confirmPlugin = app('confirm');
    var translate = app('translate');
    var dataProcessor = app('data-processor');
    var promise = app('promise');
    var parser = app('input-money-parser');
    var broadcast = app('broadcast');
    var pouchProcEvs = broadcast.events('pouch-processor');

    var MAX_ITEMS = 50;

    function updateItem(item) {
        var map = this._catMap;
        var catId = item.catId;
        var cat = map[catId];
        var parentCat = cat ? map[cat.catId] : null;
        var catTitle = parentCat ? parentCat.title : '';
        item.catSubTitle = cat ? cat.title: '';
        if (parentCat && cat) {
            catTitle += ' / ';
        }
        item.catTitle = catTitle;
    }

    function getData() {
        var self = this;
        var holder = promise();

        holder
            .then(function () {
                return collCategory.getCategoriesWithRemoved();
            })
            .then(function (catList) {
                var map = self._catMap;
                helper.arrayWalk(catList, function (item) {
                    item && item.id && (map[item.id] = item);
                });
                return collExpense.getExpenses({limit: MAX_ITEMS});
            })
            .then(function (expenseList) {
                helper.arrayWalk(expenseList, function (item) {
                    updateItem.call(self, item);
                });

                self.setItems(expenseList);
                bindExpenseChanges.call(self);
                self.checkHaveMore(expenseList.length);
            });

        holder.startThens();
    }

    var UiListClass = app('bb-co')('ui-list-expenses', {
        tpl: 'scripts/ui-controllers/components-custom/ui-controls/lists/expense-list/ui-list-expenses',
        init: function () {
            var self = this;
            UiListClass._parent.init.apply(this, arguments);
            this._catMap = {};

            this.defineScope({
                isEmpty: '',
                haveMore: false,
                items: []
            });

            getData.call(this);

            this._currId = null;
            broadcast.on(pouchProcEvs.onChanged, this._onPouch = function () {
                getData.call(self);
            });

        },
        setItems: function (data) {
            data = helper.clone(data);
            timeLogger.startTimer();
            var items = this.getScope().items;
            items.clear();
            if (items.pushList) {
                items.pushList(data);
            } else {
                helper.arrayWalk(data, function (item) {
                    items.push(item);
                });
            }
            this.checkEmpty();
            timeLogger.stopTimer();
            var timerInfo = timeLogger.getTimeTotal();
            logger.info(this.getName(), '->setItems() len=', data ? data.length : 'null', timerInfo);
        },
        checkHaveMore: function (loadedLen) {
            var scope = this.getScope();
            scope.haveMore = (loadedLen < MAX_ITEMS) ? 'helper-hide' : '';
        },
        checkEmpty: function () {
            var scope = this.getScope();
            scope.isEmpty = (scope.items.length != 0) ? 'helper-hide' : '';
        },
        pushItem: function (item) {
            this.getScope().items.splice(0, 0, item);
            this.checkEmpty();
        },
        processContent: function (content) {
            var self = this;
            content.on('jrclick', function (ev) {
                self.contentCallClick(ev, self);
            });
            UiListClass._parent.processContent.apply(this, arguments);
        },
        callEdit: function (ev) {
            logger.log('edit', this._currId);
            dataProcessor('expense.showEdit').call(this, ev);
        },
        getValue: function () {
            var item = getItemById.call(this, this._currId);
            logger.log(item);
            return {
                id: item && item.id,
                catId: item && item.catId,
                desc: item && item.desc,
                cost: item && item.cost
            };
        },
        callShowMore: function () {
            logger.log('callShowMore');
            var items = this.getScope().items;
            var self = this;
            collExpense.getExpenses({limit: MAX_ITEMS, offset: items.length})
                .then(function (expenseList) {
                    helper.arrayWalk(expenseList, function (item) {
                        updateItem.call(self, item);
                        items.push(item);
                    });
                    self.checkEmpty();
                    self.checkHaveMore(expenseList.length);
                });
        },
        callShowPopup: function () {
            dataProcessor('expense.showPopup').call(this);
        },
        callRemove: function () {
            logger.log('remove', this._currId);
            var item = getItemById.call(this, this._currId);
            doRemove(item);
        },
        callItemClick: function (t) {
            this._currId = dataProcessor('list.editing').call(this, t);
        },
        destroy: function () {
            UiListClass._parent.destroy.apply(this, arguments);
            var blockActions = collExpense.getBlockActions();
            dataEvent.offBlock(blockActions.PUSH, this._dbExpensePush);
            dataEvent.offBlock(blockActions.REMOVE, this._dbExpenseDrop);
            dataEvent.offBlock(blockActions.UPDATE, this._dbExpenseUpdate);
            broadcast.off(pouchProcEvs.onChanged, this._onPouch);
        }

    });

    function getItemById(id) {
        var ret = null;
        if (id) {
            var items = this.getScope().items;
            helper.arrayWalk(items, function (item) {
                if (item.id == id) {
                    ret = item;
                    return false;
                }
            });
        }
        return ret;
    }

    function doRemove(item) {
        if (item) {
            var money = getItemTitle(item);
            var msg = translate('expense.remove', money);
            confirmPlugin.confirm(msg, function () {
                collExpense.removeExpense(item.id);
            });
        }
    }

    function getItemTitle(item) {
        var money = parser.numToMoney(item.cost);
        var ret = item.catTitle + item.catSubTitle + ': ' + money;
        return ret;
    }

    function bindExpenseChanges() {
        // :todo change this
        var self = this;
        var blockActions = collExpense.getBlockActions();
        dataEvent.onBlock(blockActions.REMOVE, this._dbExpenseDrop = function (removedId) {
            logger.log('dataEvent.onBlock(REMOVE)', removedId);
            var items = self.getScope().items;
            for (var i = 0, l = items.length; i < l; i++) {
                var node = items[i];
                if (node.id == removedId) {
                    items.splice(i, 1);
                    l--;
                    i--;
                }
            }
            self.checkEmpty();
        });
        dataEvent.onBlock(blockActions.PUSH, this._dbExpensePush = function (item) {
            item = helper.clone(item);
            logger.log('dataEvent.onBlock(PUSH)', item);
            updateItem.call(self, item);
            self.pushItem(item);
        });
        dataEvent.onBlock(blockActions.UPDATE, this._dbExpenseUpdate = function (data) {
            logger.log('dataEvent.onBlock(UPDATE)', data);
            var item = getItemById.call(self, data.id);
            if (item){
                var newFields = data.newFields;
                for (var key in newFields) {
                    item[key] = newFields[key];
                }
                if (newFields.catId) {
                    updateItem.call(self, item);
                }
            }
        });

    }

})(window.app);


text:
<?php

namespace Opencolour\Migrations\Commands;

use Opencolour\Additions\Config;
use Opencolour\Migrations\FormatCoder;
use Opencolour\Migrations\MigrationCollector;
use Opencolour\Migrations\StructureParser;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Monolog\Logger;

/**
 * Class InitializeCommand
 * @package Opencolour\Migrations\Commands
 *
 * Команда инициализации системы миграций
 */
class GenerateCommand extends Command {

    /** @var Logger $log */
    protected $log = null;

    public function __construct(Logger $log, $name = null)
    {
        $this->log = $log;
        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setName("migrations:generate")
            ->setDescription("Generate new migration file")
            ->setHelp(<<<EOT
Here is description
EOT
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $config = Config::getInstance();
        $formatCoder = new FormatCoder($this->log);
        $structureParser = new StructureParser($this->log, $formatCoder, $output);
        $migrationCollector = new MigrationCollector($this->log, $formatCoder, $output, $structureParser);

        if($migrationCollector->writeMigration()) {
            $structureParser->initializeSchema();
        }

        $style = new OutputFormatterStyle('green', 'white', array('bold'));
        $output->getFormatter()->setStyle('end', $style);
        $output->writeln('<end>Generating complete</end>');
    }
}


text:
<?php  /* Template Name: Sub Page Template */ get_header(); ?>

	<?php if (have_posts()): while (have_posts()) : the_post(); ?>

		<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
			<?php the_content(); ?>
			<?php #comments_template( '', true ); // Remove if you don't want comments ?>

			<?php #edit_post_link(); ?>

	<?php endwhile; ?>
	<?php else: ?>

<?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?>

	<?php endif; ?>

<?php #get_sidebar(); ?>

<?php get_footer(); ?>


text:
module Drafting
  module BaseClassMethods
    ALLOWED_DRAFT_OPTION_KEYS = [ :parent ]

    def has_drafts(options={})
      raise ArgumentError unless options.is_a?(Hash)
      raise ArgumentError unless options.keys.all? { |k| ALLOWED_DRAFT_OPTION_KEYS.include?(k) }

      unless method_defined? :drafts
        class_eval do
          def self.child_drafts
            Draft.where(parent_type: self.base_class.name)
          end
        end
      end

      include Drafting::InstanceMethods
      extend Drafting::ClassMethods

      attr_writer :draft_id
      after_create :clear_draft

      has_many :drafts, as: :parent
    end
  end
end


text:
import Operator from '../Operator';
import Observer from '../Observer';
import Observable from '../Observable';
import Subscriber from '../Subscriber';
import Subscription from '../Subscription';

import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import OuterSubscriber from '../OuterSubscriber';
import subscribeToResult from '../util/subscribeToResult';

export class ExpandOperator<T, R> implements Operator<T, R> {
  constructor(private project: (value: T, index: number) => Observable<any>,
              private concurrent: number = Number.POSITIVE_INFINITY) {
  }

  call(subscriber: Subscriber<R>): Subscriber<T> {
    return new ExpandSubscriber(subscriber, this.project, this.concurrent);
  }
}

export class ExpandSubscriber<T, R> extends OuterSubscriber<T, R> {
  private index: number = 0;
  private active: number = 0;
  private hasCompleted: boolean = false;
  private buffer: any[];

  constructor(destination: Subscriber<R>,
              private project: (value: T, index: number) => Observable<R>,
              private concurrent: number = Number.POSITIVE_INFINITY) {
    super(destination);
    if (concurrent < Number.POSITIVE_INFINITY) {
      this.buffer = [];
    }
  }

  _next(value: any): void {
    const index = this.index++;
    this.destination.next(value);
    if (this.active < this.concurrent) {
      let result = tryCatch(this.project)(value, index);
      if (result === errorObject) {
        this.destination.error(result.e);
      } else {
        if (result._isScalar) {
          this._next(result.value);
        } else {
          this.active++;
          this.add(subscribeToResult<T, R>(this, result, value, index));
        }
      }
    } else {
      this.buffer.push(value);
    }
  }

  _complete(): void {
    this.hasCompleted = true;
    if (this.hasCompleted && this.active === 0) {
      this.destination.complete();
    }
  }

  notifyComplete(innerSub: Subscription<T>): void {
    const buffer = this.buffer;
    this.remove(innerSub);
    this.active--;
    if (buffer && buffer.length > 0) {
      this._next(buffer.shift());
    }
    if (this.hasCompleted && this.active === 0) {
      this.destination.complete();
    }
  }

  notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {
    this._next(innerValue);
  }
}


text:
using namespace std;

class Sphere : public Primitive {
	private:
		static const int NUM_LIGHTPOINTS;
		const vector3_t pos;
		const double radius;
		vector<vector3_t> lightPoints;

		hitresult_t intersect(const ray_t& ray, double& distance, vector3_t& hit, vector3_t& normal);
		void generateLightPoints();
		vector3_t randomPoint();

	public:
		Sphere(const vector3_t& pos, double radius);
		void getLightPoints(forward_list<vector3_t>& lightList) const;
};

#endif


text:
package es.logongas.ix3.service;

/**
 *
 * @author logongas
 */
public interface Service<EntityType> extends es.logongas.ix3.core.EntityType<EntityType> {

}


text:
@interface WSPTableViewCell : UITableViewCell

@property(nonatomic, strong)
    MCOIMAPMessageRenderingOperation *messageRenderingOperation;
@property(strong, nonatomic) IBOutlet UILabel *authorLabel;
@property(strong, nonatomic) IBOutlet UILabel *titleLabel;
@property(strong, nonatomic) IBOutlet UILabel *previewLabel;
@property(strong, nonatomic) IBOutlet UILabel *timestampLabel;

@end


text:
SYNONYM

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

#### Published in
Am. J. Bot. 36: 404 (1949)

#### Original name
Entyloma scirpicola Thirum. & J.G. Dicks., 1949

### Remarks
null


text:
using System;
using NLibuv.Native;

namespace NLibuv
{
	/// <summary>
	/// Represents a pipe connect request (uv_connect_t).
	/// </summary>
	public class UvPipeConnectRequest : UvRequest<UvPipe>
	{
		/// <summary>
		/// Callback type (uv_connect_cb).
		/// </summary>
		/// <param name="request"></param>
		/// <param name="error"></param>
		/// <param name="stateObject"></param>
		public delegate void CallbackDelegate(UvPipeConnectRequest request, Exception error, object stateObject);

		/// <summary>
		/// The name of the pipe to connect to.
		/// </summary>
		/// <remarks>
		/// This field will be cleared before the callback invocation.
		/// </remarks>
		protected string PipeName;

		/// <summary>
		/// The callback to be called after the request finish.
		/// </summary>
		/// <remarks>
		/// This field will be cleared before the callback invocation.
		/// </remarks>
		protected CallbackDelegate Callback;

		/// <summary>
		/// The state object to be passed to the callback.
		/// </summary>
		/// <remarks>
		/// This field will be cleared before the callback invocation.
		/// </remarks>
		protected object State;

		/// <summary>
		/// Initializes a new pipe connection request.
		/// </summary>
		/// <param name="baseHandle"></param>
		/// <param name="pipeName"></param>
		/// <param name="callback"></param>
		/// <param name="state"></param>
		public UvPipeConnectRequest(UvPipe baseHandle, string pipeName, CallbackDelegate callback, object state)
			: base(baseHandle, UvRequestType.Connect)
		{
			this.PipeName = pipeName;
			this.Callback = callback;
			this.State = state;
		}

		/// <summary>
		/// Executes the request on the base handle.
		/// </summary>
		public void Connect()
		{
			Libuv.uv_pipe_connect(this, this.BaseHandle, this.PipeName, _UvConnectCallback);
			this.PipeName = null;
		}

		private static readonly UvConnectCallback _UvConnectCallback = _ConnectCallback;
		private static void _ConnectCallback(IntPtr handle, int status)
		{
			var request = FromIntPtr<UvPipeConnectRequest>(handle);

			var callback = request.Callback;
			request.Callback = null;

			var state = request.State;
			request.State = null;

			Exception error;
			Libuv.CheckStatusCode(status, out error);

			if (callback != null)
			{
				callback.Invoke(request, error, state);
			}

			request.Close();
		}
	}
}


text:
function isTypeof(constructor, suspect) {
  return suspect.constructor == constructor;
}

function isNotTypeof(constructor, suspect) {
  return suspect.constructor != constructor;
}

isEqual = _.isEqual;

isArguments = _.isArguments;

isObject = _.isObject;

isArray = _.isArray;

isString = _.isString;

isNumber = _.isNumber;

isBoolean = _.isBoolean;

isFunction = _.isFunction;

isDate = _.isDate;

isRegExp = _.isRegExp;

isNull = _.isNull;

isElement = _.isElement;

isUndefined = _.isUndefined;

sequence = _.uniqueId;

function uid () {

    function S4() {
       return ( ( ( 1 + Math.random() ) * 0x10000 ) | 0 ).toString(16).substring(1);
    }

    return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();

}

var isDefined = function(suspect) {
    return !_.isUndefined(suspect);
}

if (typeof String.prototype.isEmpty === "undefined") {
    String.prototype.isEmpty = function() {
        return _.isEmpty(this);
    };
}

if (typeof String.prototype.escape === "undefined") {
    String.prototype.escape = function() {
        return _.escape.apply(this, [this].concat(_.toArray(arguments)));
    };
}
(function() {
  var methods = [
    "all",
    "any",
    "collect",
    "compact",
    "contains",
    "countBy",
    "detect",
    "difference",
    "every",
    "filter",
    "find",
    "first",
    "flatten",
    "foldr",
    "groupBy",
    "include",
    "indexOf",
    "initial",
    "inject",
    "intersection",
    "invoke",
    "isEmpty",
    "last",
    "lastIndexOf",
    "map",
    "max",
    "min",
    "pluck",
    "reduce",
    "reduceRight",
    "reject",
    "rest",
    "select",
    "shuffle",
    "size",
    "some",
    "sortBy",
    "sortedIndex",
    "tail",
    "take",
    "toArray",
    "union",
    "uniq",
    "without",
    "zip"
  ];

  _.each(methods, function(method) {
    if (Array.prototype[method]) { return; }
    Object.defineProperty(Array.prototype, method, {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return _[method].apply(_, [this].concat(_.toArray(arguments)));
      }
    });
  });

  if (!Array.prototype.sum) {
    Object.defineProperty(Array.prototype, 'sum', {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return _.reduce(this, function(memo, num) {
          return memo + num;
        }, 0);
      }
    });
  }

  if (!Array.range) {
    Object.defineProperty(Array, 'range', {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return _.range.apply([], arguments);
      }
    });
  }

  var nativeMethods = [{
    func: Array.prototype.forEach,
    alias: 'each'
  }];

  _.each(nativeMethods, function(nativeMethod) {
    if (nativeMethod.func) {
      Object.defineProperty(Array.prototype, nativeMethod.alias, {
        writeable: false,
        configurable: false,
        enumerable: false,
        value: nativeMethod.func
      });
    }
  });

  if (typeof Array.prototype.isEmpty === "undefined") {
    Object.defineProperty(Array.prototype, 'isEmpty', {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: _.isEmpty.call(this, this)
    });
  }

  if (typeof Array.prototype.isNotEmpty === "undefined") {
    Object.defineProperty(Array.prototype, 'isNotEmpty', {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return !_.isEmpty.call(this, this);
      }
    });
  }

})();
(function() {

  var methods = [
    'keys',
    'values',
    'pairs',
    'invert',
    'functions',
    'pick',
    'omit',
    'defaults',
    'tap'
  ];

  _.each(methods, function(method) {
    if (Object.prototype[method]) { return; }
    Object.defineProperty(Object.prototype, method, {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return _[method].apply(this, [this].concat(_.toArray(arguments)));
      }
    });
  });

  var aliases = {
    extend: 'mixin',
    clone: 'dup',
    has: 'defines'
  };

  _.each(aliases, function(alias, method) {
    if (Object.prototype[alias]) { return; }
    Object.defineProperty(Object.prototype, alias, {
      writeable: false,
      configurable: false,
      enumerable: false,
      value: function() {
        return _[method].apply(this, [this].concat(_.toArray(arguments)));
      }
    });
  });

})();
(function() {

  var methods = [
    'bind',
    'compose',
    'debounce',
    'defer',
    'delay',
    'memoize',
    'once',
    'throttle',
    'wrap'
  ];

  _.each(methods, function(method) {
    if (!Function.prototype[method]) {
      Object.defineProperty(Function.prototype, method, {
        writeable: false,
        configurable: false,
        enumerable: false,
        value: function() {
          return _[method].apply(this, [this].concat(_.toArray(arguments)));
        }
      });
    }
  });

})();
var Template = (function() {

  function Template(src) {
    if (src.match(/^#/)) {
      this.src = document.getElementById(src.replace(/^#/, '')).innerHTML;
    }
    else {
      this.src = src;
    }
  }

  Template.prototype.render = function(data, settings) {
    return _.template(this.src, data, settings);
  };

  return Template;
})();


text:
layout: page
title: Hivebot
---

  The MakeTronica Hivebot is a collection of hardware and (predominantely)
  open-source software installed in the beehives in our back yard, with the
  purpose of tracking environmental conditions within and around the hives,
  as well as provide instructional material so that others may possibly
  apply some of what I've done to their own beehive, or beer fridge, or
  whatever maker project they have in mind.

Charts

{% include_relative _charts.html %}

Videos

  I've posted a bunch of videos detailing the process of setting up
  each of the sensors within the beehives on my
  MakeTronica YouTube channel.

Software

  The following is a list of open-source sofware I've written that, as a
  collection, provides all of the hivebot functionality.

  Although the code is open-source, I am currently only working on it
  to serve my own purposes. You are free to download it, modify it,
  and try to get it working on your own beehives and hardware, but I'm not
  likely be be able to provide any support or assistance at this time.

  To get all of the pieces working together, you want to, at a bare minimum,
  consider yourself proficient at reading and running Ruby applications, basic
  networking, electronics assembly and soldering (for the sensors),
  troubleshooting, and self-sufficient problem solving.

hivebot.avr

  hivebot.avr is the
  code for the Arduino in each hive. The Arduino has several sensors and the
  sensor data is sent over a USB serial connection to a Raspberry Pi, also in
  the hive, for transmission back to the house.

  The original plan was to have everything running off of Arduinos, but I ran
  into too many problems consistently transmitting the data back to the house,
  that I eventually moved some stuff to Raspberry Pis. The Ardunio's may
  eventually be retired in favor of attaching all sensors directly to the Pis,
  but that remains to be seen.

hivebot.rb

  hivebot.rb is the
  Ruby code that runs on a Raspberry Pi in each beehive. It reads data over the
  USB serial connection from the Arduino, and then transmits it over our WiFi
  network to hivemom.rb, running on another Raspberry Pi in the house.

  Each Raspberry Pi is running a recent (as of the time I installed it) version
  of Ubuntu Mate.

hivemom.rb

  hivemom.rb is the
  Ruby code running on a Pi back in the house. It's a simple HTTP RACK app
  that receives RESTful posts from each hivebot.rb, stores the data in a
  local database, writes out .csv files for hivedash.csv, and pushes copies
  of the .csv files up to Amazon S3 to enable generating the demo charts on
  this website (www.maketronica.com).

  Each Raspberry Pi is running a recent (as of the time I installed it) version
  of Ubuntu Mate.

hivedash.jkyl

  hivedash.jkyl is
  a static Jekyll website served from
  the same Raspberry Pi that Hivemom runs on to generate graphs of sensor
  data.


text:
using Newtonsoft.Json.Linq;
using System;

namespace TrackPlayer.Logic
{
    public class Track
    {
        public string Id { get; set; }
        public Uri Url { get; set; }
        public string Type { get; set; }
        public double Duration { get; set; }

        public string Title { get; set; }
        public string Artist { get; set; }
        public string Album { get; set; }
        public Uri Artwork { get; set; }

        private JObject _originalObj;

        public Track(JObject data)
        {
            Id = (string)data.GetValue("id");
            Url = Utils.GetUri(data, "url", null);
            Type = Utils.GetValue<string>(data, "type", TrackType.Default);

            SetMetadata(data);

            _originalObj = data;
        }

        public void SetMetadata(JObject data)
        {
            Duration = Utils.GetValue<double>(data, "duration", 0);

            Title = Utils.GetValue<string>(data, "title", null);
            Artist = Utils.GetValue<string>(data, "artist", null);
            Album = Utils.GetValue<string>(data, "album", null);
            Artwork = Utils.GetUri(data, "artwork", null);

            if (_originalObj != null && _originalObj != data)
                _originalObj.Merge(data);
        }

        public JObject ToObject()
        {
            return _originalObj;
        }
    }

    public static class TrackType
    {
        public const string Default = "default";
        public const string Dash = "dash";
        public const string Hls = "hls";
        public const string SmoothStreaming = "smoothstreaming";
    }
}


text:
require 'logroll'
local _ = require 'moses'
local classic = require 'classic'
local cjson = require 'cjson'

local Setup = classic.class('Setup')

-- Performs global setup
function Setup:_init(arg)
  -- Create log10 for Lua 5.2
  if not math.log10 then
    math.log10 = function(x)
      return math.log(x, 10)
    end
  end

  -- Parse command-line options
  self.opt = self:parseOptions(arg)

  -- Create experiment directory
  if not paths.dirp(self.opt.experiments) then
    paths.mkdir(self.opt.experiments)
  end
  paths.mkdir(paths.concat(self.opt.experiments, self.opt._id))
  -- Save options for reference
  local file = torch.DiskFile(paths.concat(self.opt.experiments, self.opt._id, 'opts.json'), 'w')
  file:writeString(cjson.encode(self.opt))
  file:close()

  -- Set up logging
  local flog = logroll.file_logger(paths.concat(self.opt.experiments, self.opt._id, 'log.txt'))
  local plog = logroll.print_logger()
  log = logroll.combine(flog, plog) -- Global logger

  -- Validate command-line options (logging errors)
  self:validateOptions()

  -- Augment environments to meet spec
  self:augmentEnv()

  -- Torch setup
  log.info('Setting up Torch7')
  -- Set number of BLAS threads
  torch.setnumthreads(self.opt.threads)
  -- Set default Tensor type (float is more efficient than double)
  torch.setdefaulttensortype(self.opt.tensorType)
  -- Set manual seed
  torch.manualSeed(self.opt.seed)

  -- Tensor creation function for removing need to cast to CUDA if GPU is enabled
  -- TODO: Replace with local functions across codebase
  self.opt.Tensor = function(...)
    return torch.Tensor(...)
  end

  -- GPU setup
  if self.opt.gpu > 0 then
    log.info('Setting up GPU')
    cutorch.setDevice(self.opt.gpu)
    -- Set manual seeds using random numbers to reduce correlations
    cutorch.manualSeed(torch.random())
    -- Replace tensor creation function
    self.opt.Tensor = function(...)
      return torch.CudaTensor(...)
    end
  end

  classic.strict(self)
end

-- Parses command-line options
function Setup:parseOptions(arg)
  -- Detect and use GPU 1 by default
  local cuda = pcall(require, 'cutorch')

  local cmd = torch.CmdLine()
  -- Base Torch7 options
  cmd:option('-seed', 1, 'Random seed')
  cmd:option('-threads', 4, 'Number of BLAS or async threads')
  cmd:option('-tensorType', 'torch.FloatTensor', 'Default tensor type')
  cmd:option('-gpu', cuda and 1 or 0, 'GPU device ID (0 to disable)')
  cmd:option('-cudnn', 'false', 'Utilise cuDNN (if available)')
  -- Environment options
  cmd:option('-env', 'rlenvs.Catch', 'Environment class (Lua file to be loaded/rlenv)')
  cmd:option('-zoom', 1, 'Display zoom (requires QT)')
  cmd:option('-game', '', 'Name of Atari ROM (stored in "roms" directory)')
  -- Training vs. evaluate mode
  cmd:option('-mode', 'train', 'Train vs. test mode: train|eval')
  -- State preprocessing options (for visual states)
  cmd:option('-height', 0, 'Resized screen height (0 to disable)')
  cmd:option('-width', 0, 'Resize screen width (0 to disable)')
  cmd:option('-colorSpace', '', 'Colour space conversion (screen is RGB): <none>|y|lab|yuv|hsl|hsv|nrgb')
  -- Model options
  cmd:option('-modelBody', 'models.Catch', 'Path to Torch nn model to be used as DQN "body"')
  cmd:option('-hiddenSize', 512, 'Number of units in the hidden fully connected layer')
  cmd:option('-histLen', 4, 'Number of consecutive states processed/used for backpropagation-through-time') -- DQN standard is 4, DRQN is 10
  cmd:option('-duel', 'true', 'Use dueling network architecture (learns advantage function)')
  cmd:option('-bootstraps', 10, 'Number of bootstrap heads (0 to disable)')
  --cmd:option('-bootstrapMask', 1, 'Independent probability of masking a transition for each bootstrap head ~ Ber(bootstrapMask) (1 to disable)')
  cmd:option('-recurrent', 'false', 'Use recurrent connections')
  -- Experience replay options
  cmd:option('-discretiseMem', 'true', 'Discretise states to integers ∈ [0, 255] for storage')
  cmd:option('-memSize', 1e6, 'Experience replay memory size (number of tuples)')
  cmd:option('-memSampleFreq', 4, 'Interval of steps between sampling from memory to learn')
  cmd:option('-memNSamples', 1, 'Number of times to sample per learning step')
  cmd:option('-memPriority', '', 'Type of prioritised experience replay: <none>|rank|proportional') -- TODO: Implement proportional prioritised experience replay
  cmd:option('-alpha', 0.65, 'Prioritised experience replay exponent α') -- Best vals are rank = 0.7, proportional = 0.6
  cmd:option('-betaZero', 0.45, 'Initial value of importance-sampling exponent β') -- Best vals are rank = 0.5, proportional = 0.4
  -- Reinforcement learning parameters
  cmd:option('-gamma', 0.99, 'Discount rate γ')
  cmd:option('-epsilonStart', 1, 'Initial value of greediness ε')
  cmd:option('-epsilonEnd', 0.01, 'Final value of greediness ε') -- Tuned DDQN final greediness (1/10 that of DQN)
  cmd:option('-epsilonSteps', 1e6, 'Number of steps to linearly decay epsilonStart to epsilonEnd') -- Usually same as memory size
  cmd:option('-tau', 30000, 'Steps between target net updates τ') -- Tuned DDQN target net update interval (3x that of DQN)
  cmd:option('-rewardClip', 1, 'Clips reward magnitude at rewardClip (0 to disable)')
  cmd:option('-tdClip', 1, 'Clips TD-error δ magnitude at tdClip (0 to disable)')
  cmd:option('-doubleQ', 'true', 'Use Double Q-learning')
  -- Note from Georg Ostrovski: The advantage operators and Double DQN are not entirely orthogonal as the increased action gap seems to reduce the statistical bias that leads to value over-estimation in a similar way that Double DQN does
  cmd:option('-PALpha', 0.9, 'Persistent advantage learning parameter α (0 to disable)')
  -- Training options
  cmd:option('-optimiser', 'rmspropm', 'Training algorithm') -- RMSProp with momentum as found in "Generating Sequences With Recurrent Neural Networks"
  cmd:option('-eta', 0.0000625, 'Learning rate η') -- Prioritied experience replay learning rate (1/4 that of DQN; does not account for Duel as well)
  cmd:option('-momentum', 0.95, 'Gradient descent momentum')
  cmd:option('-batchSize', 32, 'Minibatch size')
  cmd:option('-steps', 5e7, 'Training iterations (steps)') -- Frame := step in ALE; Time step := consecutive frames treated atomically by the agent
  cmd:option('-learnStart', 50000, 'Number of steps after which learning starts')
  cmd:option('-gradClip', 10, 'Clips L2 norm of gradients at gradClip (0 to disable)')
  -- Evaluation options
  cmd:option('-progFreq', 10000, 'Interval of steps between reporting progress')
  cmd:option('-reportWeights', 'false', 'Report weight and weight gradient statistics')
  cmd:option('-noValidation', 'false', 'Disable asynchronous agent validation thread') -- TODO: Make behaviour consistent across Master/AsyncMaster
  cmd:option('-valFreq', 250000, 'Interval of steps between validating agent') -- valFreq steps is used as an epoch, hence #epochs = steps/valFreq
  cmd:option('-valSteps', 125000, 'Number of steps to use for validation')
  cmd:option('-valSize', 500, 'Number of transitions to use for calculating validation statistics')
  -- Async options
  cmd:option('-async', '', 'Async agent: <none>|Sarsa|OneStepQ|NStepQ|A3C') -- TODO: Change names
  cmd:option('-rmsEpsilon', 0.1, 'Epsilon for sharedRmsProp')
  cmd:option('-entropyBeta', 0.01, 'Policy entropy regularisation β')
  -- ALEWrap options
  cmd:option('-fullActions', 'false', 'Use full set of 18 actions')
  cmd:option('-actRep', 4, 'Times to repeat action') -- Independent of history length
  cmd:option('-randomStarts', 30, 'Max number of no-op actions played before presenting the start of each training episode')
  cmd:option('-poolFrmsType', 'max', 'Type of pooling over previous emulator frames: max|mean')
  cmd:option('-poolFrmsSize', 2, 'Number of emulator frames to pool over')
  cmd:option('-lifeLossTerminal', 'true', 'Use life loss as terminal signal (training only)')
  cmd:option('-flickering', 0, 'Probability of screen flickering (Catch only)')
  -- Experiment options
  cmd:option('-experiments', 'experiments', 'Base directory to store experiments')
  cmd:option('-_id', '', 'ID of experiment (used to store saved results, defaults to game name)')
  cmd:option('-network', '', 'Saved network weights file to load (weights.t7)')
  cmd:option('-checkpoint', 'false', 'Checkpoint network weights (instead of saving just latest weights)')
  cmd:option('-verbose', 'false', 'Log info for every episode (only in train mode)')
  cmd:option('-saliency', '', 'Display saliency maps (requires QT): <none>|normal|guided|deconvnet')
  cmd:option('-record', 'false', 'Record screen (only in eval mode)')
  local opt = cmd:parse(arg)

  -- Process boolean options (Torch fails to accept false on the command line)
  opt.cudnn = opt.cudnn == 'true'
  opt.duel = opt.duel == 'true'
  opt.recurrent = opt.recurrent == 'true'
  opt.discretiseMem = opt.discretiseMem == 'true'
  opt.doubleQ = opt.doubleQ == 'true'
  opt.reportWeights = opt.reportWeights == 'true'
  opt.fullActions = opt.fullActions == 'true'
  opt.lifeLossTerminal = opt.lifeLossTerminal == 'true'
  opt.checkpoint = opt.checkpoint == 'true'
  opt.verbose = opt.verbose == 'true'
  opt.record = opt.record == 'true'
  opt.noValidation = opt.noValidation == 'true'

  -- Process boolean/enum options
  if opt.colorSpace == '' then opt.colorSpace = false end
  if opt.memPriority == '' then opt.memPriority = false end
  if opt.async == '' then opt.async = false end
  if opt.saliency == '' then opt.saliency = false end
  if opt.async then opt.gpu = 0 end -- Asynchronous agents are CPU-only

  -- Set ID as env (plus game name) if not set
  if opt._id == '' then
    local envName = paths.basename(opt.env)
    if opt.game == '' then
      opt._id = envName
    else
      opt._id = envName .. '.' .. opt.game
    end
  end

  -- Create one environment to extract specifications
  local Env = require(opt.env)
  local env = Env(opt)
  opt.stateSpec = env:getStateSpec()
  opt.actionSpec = env:getActionSpec()
  -- Process display if available (can be used for saliency recordings even without QT)
  if env.getDisplay then
    opt.displaySpec = env:getDisplaySpec()
  end

  return opt
end

-- Logs and aborts on error
local function abortIf(err, msg)
  if err then
    log.error(msg)
    error(msg)
  end
end

-- Validates setup options
function Setup:validateOptions()
  -- Check environment state is a single tensor
  abortIf(#self.opt.stateSpec ~= 3 or not _.isArray(self.opt.stateSpec[2]), 'Environment state is not a single tensor')

  -- Check environment has discrete actions
  abortIf(self.opt.actionSpec[1] ~= 'int' or self.opt.actionSpec[2] ~= 1, 'Environment does not have discrete actions')

  -- Change state spec if resizing
  if self.opt.height ~= 0 then
    self.opt.stateSpec[2][2] = self.opt.height
  end
  if self.opt.width ~= 0 then
    self.opt.stateSpec[2][3] = self.opt.width
  end

  -- Check colour conversions
  if self.opt.colorSpace then
    abortIf(not _.contains({'y', 'lab', 'yuv', 'hsl', 'hsv', 'nrgb'}, self.opt.colorSpace), 'Unsupported colour space for conversion')
    abortIf(self.opt.stateSpec[2][1] ~= 3, 'Original colour space must be RGB for conversion')
    -- Change state spec if converting from colour to greyscale
    if self.opt.colorSpace == 'y' then
      self.opt.stateSpec[2][1] = 1
    end
  end

  -- Check start of learning occurs after at least one minibatch of data has been collected
  abortIf(self.opt.learnStart <= self.opt.batchSize, 'learnStart must be greater than batchSize')

  -- Check enough validation transitions will be collected before first validation
  abortIf(self.opt.valFreq <= self.opt.valSize, 'valFreq must be greater than valSize')

  -- Check prioritised experience replay options
  abortIf(self.opt.memPriority and not _.contains({'rank', 'proportional'}, self.opt.memPriority), 'Type of prioritised experience replay unrecognised')
  abortIf(self.opt.memPriority == 'proportional', 'Proportional prioritised experience replay not implemented yet') -- TODO: Implement

  -- Check no prioritized replay is done when bootstrap
  abortIf(self.opt.bootstraps > 0 and _.contains({'rank', 'proportional'}, self.opt.memPriority), 'Prioritized experience replay not possible with bootstrap')

  -- Check start of learning occurs after at least 1/100 of memory has been filled
  abortIf(self.opt.learnStart <= self.opt.memSize/100, 'learnStart must be greater than memSize/100')

  -- Check memory size is multiple of 100 (makes prioritised sampling partitioning simpler)
  abortIf(self.opt.memSize % 100 ~= 0, 'memSize must be a multiple of 100')

  -- Check learning occurs after first progress report
  abortIf(self.opt.learnStart < self.opt.progFreq, 'learnStart must be greater than progFreq')

  -- Check saliency map options
  abortIf(self.opt.saliency and not _.contains({'normal', 'guided', 'deconvnet'}, self.opt.saliency), 'Unrecognised method for visualising saliency maps')

  -- Check saliency is valid
  abortIf(self.opt.saliency and not self.opt.displaySpec, 'Saliency cannot be shown without env:getDisplay()')
  abortIf(self.opt.saliency and #self.opt.stateSpec[2] ~= 3 and (self.opt.stateSpec[2][1] ~= 3 or self.opt.stateSpec[2][1] ~= 1), 'Saliency cannot be shown without visual state')

  -- Check async options
  if self.opt.async then
    abortIf(self.opt.recurrent and self.opt.async ~= 'OneStepQ', 'Recurrent connections only supported for OneStepQ in async for now')
    abortIf(self.opt.PALpha > 0, 'Persistent advantage learning not supported in async modes yet')
    abortIf(self.opt.bootstraps > 0, 'Bootstrap heads not supported in async mode yet')
    abortIf(self.opt.async == 'A3C' and self.opt.duel, 'Dueling networks and A3C are incompatible')
    abortIf(self.opt.async == 'A3C' and self.opt.doubleQ, 'Double Q-learning and A3C are incompatible')
    abortIf(self.opt.saliency, 'Saliency maps not supported in async modes yet')
  end
end

-- Augments environments with extra methods if missing
function Setup:augmentEnv()
  local Env = require(self.opt.env)
  local env = Env(self.opt)

  -- Set up fake training mode (if needed)
  if not env.training then
    Env.training = function() end
  end
  -- Set up fake evaluation mode (if needed)
  if not env.evaluate then
    Env.evaluate = function() end
  end
end

return Setup


text:
<?php

namespace {{ namespace }}\Entity\Pages;

use {{ namespace }}\Form\Pages\{{ entity_class }}OverviewPageAdminType;
use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\NodeSearchBundle\Helper\SearchTypeInterface;
use Kunstmaan\PagePartBundle\Helper\HasPageTemplateInterface;
use Kunstmaan\NodeBundle\Controller\SlugActionInterface;
use Kunstmaan\ArticleBundle\Entity\AbstractArticleOverviewPage;
use Kunstmaan\PagePartBundle\PagePartAdmin\AbstractPagePartAdminConfigurator;

/**
 * @ORM\Entity(repositoryClass="{{ namespace }}\Repository\{{ entity_class }}OverviewPageRepository")
 * @ORM\Table(name="{{ prefix }}{{ entity_class|lower }}_overview_pages")
 */
class {{ entity_class }}OverviewPage extends AbstractArticleOverviewPage implements HasPageTemplateInterface, SearchTypeInterface, SlugActionInterface
{
    public function getPagePartAdminConfigurations(): array
    {
        return ['{% if not isV4 %}{{ bundle.getName() }}:{%endif%}{{ entity_class|lower }}main'];
    }

    public function getPageTemplates(): array
    {
        return ['{% if not isV4 %}{{ bundle.getName() }}:{%endif%}{{ entity_class|lower }}overviewpage'];
    }

    /**
     * @param \Doctrine\ORM\EntityManagerInterface $em
     *
     * @return \Doctrine\Common\Persistence\ObjectRepository
     */
    public function getArticleRepository($em)
    {
        return $em->getRepository('{{ bundle.getName() }}:Pages\{{ entity_class }}Page');
    }

    public function getDefaultView(): string
    {
        return '{% if not isV4 %}{{ bundle.getName() }}:{%endif%}Pages/{{ entity_class }}OverviewPage{% if not isV4 %}:{% else %}/{% endif %}view.html.twig';
    }

    public function getSearchType(): string
    {
        return '{{ entity_class }}';
    }

    public function getDefaultAdminType(): string
    {
        return {{ entity_class }}OverviewPageAdminType::class;
    }

    public function getControllerAction(): string
    {
        {% if isV4 %}
        return 'App\Controller\{{ entity_class }}ArticleController::serviceAction';
        {% else %}
        return '{{ bundle.getName() }}:{{ entity_class }}Article:service';
        {% endif %}
    }
}


text:
package org.apache.jena.geosparql.geof.topological.filter_functions.simple_features;

import org.apache.jena.geosparql.implementation.DimensionInfo;
import org.apache.jena.geosparql.implementation.GeometryWrapper;
import org.apache.jena.geosparql.implementation.datatype.WKTDatatype;
import org.apache.jena.rdf.model.ResourceFactory;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.operation.TransformException;
import org.opengis.util.FactoryException;

/**
 * Contains returns t (TRUE) if the second geometry is completely contained by
 * the first geometry.
 */
public class SfContainsFFTest {

    public SfContainsFFTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testRelate_polygon_point() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((30 40, 30 70, 90 70, 90 40, 30 40))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POINT(60 60)", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = true;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    @Test
    public void testRelate_polygon_linestring() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((30 40, 30 70, 90 70, 90 40, 30 40))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> LINESTRING(40 50, 80 50)", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = true;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    @Test
    public void testRelate_polygon_polygon() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((140 15, 140 45, 200 45, 200 15, 140 15))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((145 30, 145 40, 160 40, 160 30, 145 30))", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = true;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    @Test
    public void testRelate_polygon_point_false() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((30 40, 30 70, 90 70, 90 40, 30 40))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POINT(30 20)", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = false;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    @Test
    public void testRelate_polygon_linestring_false() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((30 40, 30 70, 90 70, 90 40, 30 40))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> LINESTRING(75 60, 145 60)", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = false;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    @Test
    public void testRelate_polygon_polygon_false() throws FactoryException, MismatchedDimensionException, TransformException {

        GeometryWrapper subjectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((30 40, 30 70, 90 70, 90 40, 30 40))", WKTDatatype.INSTANCE));
        GeometryWrapper objectGeometryWrapper = GeometryWrapper.extract(ResourceFactory.createTypedLiteral("<http://www.opengis.net/def/crs/EPSG/0/27700> POLYGON((140 15, 140 45, 200 45, 200 15, 140 15))", WKTDatatype.INSTANCE));

        SfContainsFF instance = new SfContainsFF();

        Boolean expResult = false;
        Boolean result = instance.relate(subjectGeometryWrapper, objectGeometryWrapper);
        assertEquals(expResult, result);
    }

    /**
     * Test of isDisjoint method, of class SfContainsFF.
     */
    @Test
    public void testIsDisjoint() {

        SfContainsFF instance = new SfContainsFF();
        boolean expResult = false;
        boolean result = instance.isDisjoint();
        assertEquals(expResult, result);
    }

    /**
     * Test of isDisconnected method, of class SfContainsFF.
     */
    @Test
    public void testIsDisconnected() {

        SfContainsFF instance = new SfContainsFF();
        boolean expResult = false;
        boolean result = instance.isDisconnected();
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_point_point() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POINT;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POINT;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_point_linestring() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POINT;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_LINESTRING;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_point_polygon() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POINT;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POLYGON;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_linestring_linestring() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_LINESTRING;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_LINESTRING;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_linestring_point() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_LINESTRING;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POINT;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_linestring_polygon() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_LINESTRING;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POLYGON;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_polygon_polygon() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POLYGON;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POLYGON;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_polygon_linestring() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POLYGON;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_LINESTRING;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

    /**
     * Test of permittedTopology method, of class SfContainsFF.
     */
    @Test
    public void testPermittedTopology_polygon_point() {

        DimensionInfo sourceDimensionInfo = DimensionInfo.XY_POLYGON;
        DimensionInfo targetDimensionInfo = DimensionInfo.XY_POINT;
        SfContainsFF instance = new SfContainsFF();
        boolean expResult = true;
        boolean result = instance.permittedTopology(sourceDimensionInfo, targetDimensionInfo);
        assertEquals(expResult, result);
    }

}


text:
module RustExample
  VERSION = "0.2.0"
end


text:
package com.spike.giantdataanalysis.commons.guava.collections;

import org.junit.Assert;
import org.junit.Test;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

/**
 * <pre>
 * {@link BiMap}的单元测试: 双向的Map、保持键和值的唯一性
 * </pre>
 *
 * @author zhoujiagen
 */
public class TestBiMap {

  @Test(expected = IllegalArgumentException.class)
  public void _create() {
    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("1", "foo");
    // 不允许有重复的值
    biMap.put("2", "foo");
  }

  @Test
  public void _forcePut() {
    BiMap<String, String> biMap = HashBiMap.create();
    biMap.put("1", "foo");
    biMap.forcePut("2", "foo");

    Assert.assertTrue(biMap.containsValue("foo"));
    Assert.assertNull(biMap.get("1"));
    Assert.assertNotNull(biMap.get("2"));

    System.out.println(biMap);
  }

  @Test
  public void _inverse() {
    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("1", "foo");
    biMap.put("2", "bar");

    BiMap<String, String> inversedBiMap = biMap.inverse();

    Assert.assertTrue(inversedBiMap.containsKey("foo"));
    Assert.assertTrue(inversedBiMap.containsKey("bar"));

    Assert.assertTrue(inversedBiMap.containsValue("1"));
    Assert.assertTrue(inversedBiMap.containsValue("2"));

    System.out.println(inversedBiMap);
  }

}


text:
using System;

namespace MooGet.Commands {

	///<summary></summary>
	public class FetchCommand {

		[Command(Name = "fetch", Description = "Download a .nupkg to the current directory")]
		public static object Run(string[] args) {
			var package = RemotePackage.FindLatestPackageByName(args[0]);
			if (package == null)
				return string.Format("Package not found: {0}", args[0]);
			else {
				package.Fetch();
				return string.Format("Downloaded {0}", package.Nupkg);
			}
		}
	}
}


text:
class BeaconTile: public Tile {
public:

	static Tile* beacon;

	BeaconTile(int);

	virtual const TextureUVCoordinateSet& getTexture(signed char, int);
	bool isCubeShaped();
	bool isSolidRender();

private:
	TextureUVCoordinateSet secondary_tex;
	TextureUVCoordinateSet terciary_tex;
	//TextureUVCoordinateSet fourth_tex;
	//TextureUVCoordinateSet fifth_tex;
};


text:
using std::cout;
using std::endl;
using std::setw;

using VInt = std::vector<int>;

// hice print histogram
//
std::ostream &operator <<(std::ostream &, const VInt &);

int main(int argc, char *argv[])
{
    // Create generator and distribution
    //
    // (we'll use poisson instead of normal for visual purposes)
    //
    std::default_random_engine g {
        std::chrono::system_clock::now().time_since_epoch().count()};
    std::normal_distribution<double> d {15, 4};

    // bind distribution to generator for short call
    //
    auto rnd = bind(d, g);

    // Create and fill histogram
    VInt hist(30);
    for(int i{0}; 2000 > i; ++i)
    {
        int x {static_cast<int>(rnd())};

        // Put low/high values into under/over-flow bins
        //
        if (x < 0)
            x = 0;
        else if (x > 29)
            x = 29;

        ++hist[x];
    }

    // nice print histogram
    //
    cout << hist << endl;
}

std::ostream &operator <<(std::ostream &os, const VInt &v)
{
    // loop over bins
    //
    for(const auto &x:v)
    {
        // bin ID is calculated on fly: momory and CPU hungry computation
        //
        os << setw(2) << (&x - &v.front()) << "| ";

        // print bin content which is scaled down by x2
        //
        for(int i {0}, counts {x / 2}; counts > i; ++i)
            os << '*';

        // proceed to next bin
        //
        os << endl;
    }

    return os;
}


text:
package org.keycloak.representations.info;

import org.keycloak.common.Profile;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Stian Thorgersen
 */
public class ProfileInfoRepresentation {

    private String name;
    private List<String> disabledFeatures;
    private List<String> previewFeatures;
    private List<String> experimentalFeatures;

    public static ProfileInfoRepresentation create() {
        ProfileInfoRepresentation info = new ProfileInfoRepresentation();

        Profile profile = Profile.getInstance();

        info.name = profile.getName().name().toLowerCase();
        info.disabledFeatures = names(profile.getDisabledFeatures());
        info.previewFeatures = names(profile.getPreviewFeatures());
        info.experimentalFeatures = names(profile.getExperimentalFeatures());

        return info;
    }

    public String getName() {
        return name;
    }

    public List<String> getDisabledFeatures() {
        return disabledFeatures;
    }

    public List<String> getPreviewFeatures() {
        return previewFeatures;
    }

    public List<String> getExperimentalFeatures() {
        return experimentalFeatures;
    }

    private static List<String> names(Set<Profile.Feature> featureSet) {
        List<String> l = new LinkedList();
        for (Profile.Feature f : featureSet) {
            l.add(f.name());
        }
        return l;
    }

}


text:
@interface WKInterfaceImage (Spec)

@property (nonatomic, readonly) UIImage *image;

@end


text:
Edit Issue

        <form class="form-horizontal" role="form">

                Title

                    <input ng-model="issue.Title" type="text" class="form-control" id="inputIssueTitle"
                           placeholder="Issue Title"/>

                Description

                    <textarea ng-model="issue.Description" class="form-control" rows="3" id="inputDescription"></textarea>

                Search

                    <input ng-keyup="loadUsersByFilter()" ng-model="search.user" class="form-control" id="inputSearchAssignee"
                           placeholder="Search for issue assignee, then select the user." type="text">

                Assignee

                    <select ng-model="issue.Assignee.Id" class="form-control" id="issueAssignee">
                        <option value="" disabled selected hidden>Choose project leader.</option>
                        <option ng-repeat="user in users" value="{{user.Id}}">{{user.Username}}</option>
                    </select>

                    <button ng-click="loadAllUsers()" type="button" class="btn btn-primary">Load All Users</button>

                Priority

                    <input disabled ng-model="issue.Priority.Name" class="form-control" id="issuePriority" />

                Due Date

                    <input ng-model="issue.DueDate" class="form-control" id="inputDueDate" type="text">

                Labels

                    <input ng-keyup="searchLabel($event)" ng-model="search.label" type="search" class="form-control" id="inputLabelSearch"
                           placeholder="Press Enter to add."/>

Maybe you mean: {{search.labelSuggestions[0].Name}}

Labels

                    {{label.Name}}

                <button ng-click="editIssue()" type="button" class="btn btn-primary">Submit</button>
                <button type="reset" class="btn btn-default">Clear</button>

        </form>


text:
$seconds = $ARGV[0];
$file = $ARGV[1];
if ((!$seconds) || ($file eq "")) {
        die "Usage: silence seconds newfilename.wav\n";
}

open(OUT, ">/tmp/$$.dat");
print OUT "; SampleRate 8000\n";
$samples = $seconds * 8000;
for ($i = 0; ($i < $samples); $i++) {
        print OUT $i / 8000, "\t0\n";
}
close(OUT);

# Note: I threw away some arguments, which appear in the original
# script, and which did not worked (on OS X at least)
system("sox /tmp/$$.dat -c 2 -r 44100 -e signed-integer $file");
unlink("/tmp/$$.dat");


text:
#import "IJKMediaPlayback.h"
#import "IJKFFOptions.h"

// media meta
#define k_IJKM_KEY_FORMAT         @"format"
#define k_IJKM_KEY_DURATION_US    @"duration_us"
#define k_IJKM_KEY_START_US       @"start_us"
#define k_IJKM_KEY_BITRATE        @"bitrate"

// stream meta
#define k_IJKM_KEY_TYPE           @"type"
#define k_IJKM_VAL_TYPE__VIDEO    @"video"
#define k_IJKM_VAL_TYPE__AUDIO    @"audio"
#define k_IJKM_VAL_TYPE__UNKNOWN  @"unknown"

#define k_IJKM_KEY_CODEC_NAME      @"codec_name"
#define k_IJKM_KEY_CODEC_PROFILE   @"codec_profile"
#define k_IJKM_KEY_CODEC_LONG_NAME @"codec_long_name"

// stream: video
#define k_IJKM_KEY_WIDTH          @"width"
#define k_IJKM_KEY_HEIGHT         @"height"
#define k_IJKM_KEY_FPS_NUM        @"fps_num"
#define k_IJKM_KEY_FPS_DEN        @"fps_den"
#define k_IJKM_KEY_TBR_NUM        @"tbr_num"
#define k_IJKM_KEY_TBR_DEN        @"tbr_den"
#define k_IJKM_KEY_SAR_NUM        @"sar_num"
#define k_IJKM_KEY_SAR_DEN        @"sar_den"
// stream: audio
#define k_IJKM_KEY_SAMPLE_RATE    @"sample_rate"
#define k_IJKM_KEY_CHANNEL_LAYOUT @"channel_layout"

#define kk_IJKM_KEY_STREAMS       @"streams"

typedef enum IJKLogLevel {
    k_IJK_LOG_UNKNOWN = 0,
    k_IJK_LOG_DEFAULT = 1,

    k_IJK_LOG_VERBOSE = 2,
    k_IJK_LOG_DEBUG   = 3,
    k_IJK_LOG_INFO    = 4,
    k_IJK_LOG_WARN    = 5,
    k_IJK_LOG_ERROR   = 6,
    k_IJK_LOG_FATAL   = 7,
    k_IJK_LOG_SILENT  = 8,
} IJKLogLevel;

@interface IJKFFMoviePlayerController : NSObject <IJKMediaPlayback>

- (id)initWithContentURL:(NSURL *)aUrl
             withOptions:(IJKFFOptions *)options;

- (id)initWithContentURLString:(NSString *)aUrlString
                   withOptions:(IJKFFOptions *)options;

- (void)prepareToPlay;
- (void)play;
- (void)pause;
- (void)stop;
- (BOOL)isPlaying;

- (void)setPauseInBackground:(BOOL)pause;
- (BOOL)isVideoToolboxOpen;

+ (void)setLogReport:(BOOL)preferLogReport;
+ (void)setLogLevel:(IJKLogLevel)logLevel;
+ (BOOL)checkIfFFmpegVersionMatch:(BOOL)showAlert;
+ (BOOL)checkIfPlayerVersionMatch:(BOOL)showAlert
                            major:(unsigned int)major
                            minor:(unsigned int)minor
                            micro:(unsigned int)micro;

@property(nonatomic, readonly) CGFloat fpsInMeta;
@property(nonatomic, readonly) CGFloat fpsAtOutput;

- (void)setOptionValue:(NSString *)value
                forKey:(NSString *)key
            ofCategory:(IJKFFOptionCategory)category;

- (void)setOptionIntValue:(int64_t)value
                   forKey:(NSString *)key
               ofCategory:(IJKFFOptionCategory)category;

- (void)setFormatOptionValue:       (NSString *)value forKey:(NSString *)key;
- (void)setCodecOptionValue:        (NSString *)value forKey:(NSString *)key;
- (void)setSwsOptionValue:          (NSString *)value forKey:(NSString *)key;
- (void)setPlayerOptionValue:       (NSString *)value forKey:(NSString *)key;

- (void)setFormatOptionIntValue:    (int64_t)value forKey:(NSString *)key;
- (void)setCodecOptionIntValue:     (int64_t)value forKey:(NSString *)key;
- (void)setSwsOptionIntValue:       (int64_t)value forKey:(NSString *)key;
- (void)setPlayerOptionIntValue:    (int64_t)value forKey:(NSString *)key;

@property (nonatomic, retain) id<IJKMediaUrlOpenDelegate> segmentOpenDelegate;
@property (nonatomic, retain) id<IJKMediaUrlOpenDelegate> tcpOpenDelegate;
@property (nonatomic, retain) id<IJKMediaUrlOpenDelegate> httpOpenDelegate;
@property (nonatomic, retain) id<IJKMediaUrlOpenDelegate> liveOpenDelegate;

@end

#define IJK_FF_IO_TYPE_READ (1)
void IJKFFIOStatDebugCallback(const char *url, int type, int bytes);
void IJKFFIOStatRegister(void (*cb)(const char *url, int type, int bytes));

void IJKFFIOStatCompleteDebugCallback(const char *url,
                                      int64_t read_bytes, int64_t total_size,
                                      int64_t elpased_time, int64_t total_duration);
void IJKFFIOStatCompleteRegister(void (*cb)(const char *url,
                                            int64_t read_bytes, int64_t total_size,
                                            int64_t elpased_time, int64_t total_duration));


text:
/*	$NetBSD: wdc_obio.c,v 1.1 2002/04/27 19:29:09 shiba Exp $ */

/*
 * Copyright (c) 2002 Takeshi Shibagaki  All rights reserved.
 *
 * mac68k OBIO-IDE attachment created by Takeshi Shibagaki
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Charles M. Hannum.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/callout.h>

#include <machine/bus.h>
#include <machine/intr.h>
#include <machine/cpu.h>
#include <machine/viareg.h>

#include <mac68k/obio/obiovar.h>

#include <dev/ata/atavar.h>
#include <dev/ic/wdcvar.h>

#define	WDC_OBIO_REG_NPORTS	(8<<3)
#define	WDC_OBIO_AUXREG_OFFSET	0x38
#define	WDC_OBIO_AUXREG_NPORTS	1
#define	WDC_OBIO_ISR_OFFSET	0x101
#define	WDC_OBIO_ISR_NPORTS	1

static u_long	IDEBase = 0x50f1a000;

/*
 * XXX This code currently doesn't even try to allow 32-bit data port use.
 */

struct wdc_obio_softc {
	struct  wdc_softc sc_wdcdev;
	struct  channel_softc *wdc_chanptr;
	struct  channel_softc wdc_channel;
	void    *sc_ih;
};

int	wdc_obio_match	__P((struct device *, struct cfdata *, void *));
void	wdc_obio_attach	__P((struct device *, struct device *, void *));
void	wdc_obio_intr __P((void *));
void	mac68k_bsh_wdc_set_stride __P((bus_space_tag_t t,
	bus_space_handle_t *h, int stride));
u_int16_t	mac68k_bsr2_wdc_gen __P((bus_space_tag_t t,
		bus_space_handle_t *bsh, bus_size_t offset));

struct cfattach wdc_obio_ca = {
	sizeof(struct wdc_obio_softc), wdc_obio_match, wdc_obio_attach
};

int
wdc_obio_match(parent, match, aux)
	struct device *parent;
	struct cfdata *match;
	void *aux;
{
	struct obio_attach_args *oa = (struct obio_attach_args *) aux;
	struct channel_softc ch;
	static int wdc_matched = 0;
	int result = 0;

	memset(&ch, 0, sizeof(ch));

	switch (current_mac_model->machineid) {
	case MACH_MACPB150:
	case MACH_MACPB190:
	case MACH_MACPB190CS:
	case MACH_MACP580:
	case MACH_MACQ630:
		ch.cmd_iot = ch.ctl_iot = oa->oa_tag;

		if (bus_space_map(ch.cmd_iot, IDEBase, WDC_OBIO_REG_NPORTS,
				  0, &ch.cmd_ioh))
			return 0;

		mac68k_bsh_wdc_set_stride(ch.cmd_iot, &ch.cmd_ioh, 4);

		if (bus_space_subregion(ch.cmd_iot, ch.cmd_ioh,
				        WDC_OBIO_AUXREG_OFFSET,
					WDC_OBIO_AUXREG_NPORTS, &ch.ctl_ioh))
			return 0;

		result = wdcprobe(&ch);

		bus_space_unmap(ch.cmd_iot, ch.cmd_ioh, WDC_OBIO_REG_NPORTS);

		if (result)
			wdc_matched = 1;
		return (result);
	}
	return 0;
}

static bus_space_tag_t		wdc_obio_isr_tag;
static bus_space_handle_t	wdc_obio_isr_hdl;
static struct channel_softc	*ch_sc = NULL;

void
wdc_obio_intr(arg)
	void *arg;
{
	unsigned char status;

	status = bus_space_read_1(wdc_obio_isr_tag,
				  wdc_obio_isr_hdl, 0);
	if (status & 0x20) {
		wdcintr(ch_sc);
		bus_space_write_1(wdc_obio_isr_tag,
				  wdc_obio_isr_hdl, 0, status&~0x20);
	}
}

void
wdc_obio_attach(parent, self, aux)
	struct device *parent;
	struct device *self;
	void *aux;
{
	struct wdc_obio_softc *sc = (void *)self;
	struct obio_attach_args *oa = aux;
	struct channel_softc *chp = &sc->wdc_channel;

	oa->oa_addr = IDEBase;
	sc->wdc_channel.cmd_iot = sc->wdc_channel.ctl_iot = oa->oa_tag;

	if (bus_space_map(sc->wdc_channel.cmd_iot, oa->oa_addr,
			  WDC_OBIO_REG_NPORTS, 0, &sc->wdc_channel.cmd_ioh)) {
		printf("%s: couldn't map registers\n",
			sc->sc_wdcdev.sc_dev.dv_xname);
		return;
	}

	mac68k_bsh_wdc_set_stride(sc->wdc_channel.cmd_iot,
				  &sc->wdc_channel.cmd_ioh, 4);

	if (bus_space_subregion(sc->wdc_channel.cmd_iot,
				sc->wdc_channel.cmd_ioh, WDC_OBIO_AUXREG_OFFSET,
				WDC_OBIO_AUXREG_NPORTS,
				&sc->wdc_channel.ctl_ioh))
		return;

    	wdc_obio_isr_tag = oa->oa_tag;

	if (bus_space_map(wdc_obio_isr_tag,
			  oa->oa_addr+WDC_OBIO_ISR_OFFSET,
			  WDC_OBIO_ISR_NPORTS, 0, &wdc_obio_isr_hdl)) {
		printf("%s: couldn't map intr status register\n",
			sc->sc_wdcdev.sc_dev.dv_xname);
		return;
	}

	switch (current_mac_model->machineid) {
	case MACH_MACP580:
	case MACH_MACQ630:
		/*
		 * Quadra/Performa IDE generates pseudo Nubus intr at slot F
		 */
		printf(" (Quadra/Performa series IDE interface)");

		add_nubus_intr(0xf, (void (*)(void*))wdc_obio_intr, (void *)sc);

		break;
	case MACH_MACPB150:
	case MACH_MACPB190:
	case MACH_MACPB190CS:
		/*
		 * PowerBook IDE generates pseudo NuBus intr at slot C
		 */
		printf(" (PowerBook series IDE interface)");

		add_nubus_intr(0xc, (void (*)(void*))wdc_obio_intr, (void *)sc);

		break;
	}

	ch_sc = chp;
	if (sc->sc_wdcdev.sc_dev.dv_cfdata->cf_flags & WDC_CAPABILITY_NOIRQ)
		sc->sc_wdcdev.cap |= WDC_CAPABILITY_NOIRQ;
	sc->sc_wdcdev.cap |= WDC_CAPABILITY_DATA16;
	sc->sc_wdcdev.PIO_cap = 0;
	sc->wdc_chanptr = chp;
	sc->sc_wdcdev.channels = &sc->wdc_chanptr;
	sc->sc_wdcdev.nchannels = 1;
	chp->channel = 0;
	chp->wdc = &sc->sc_wdcdev;
	chp->ch_queue = malloc(sizeof(struct channel_queue), M_DEVBUF, M_NOWAIT);

	if (chp->ch_queue == NULL) {
		printf("%s: can't allocate memory for command queue",
			sc->sc_wdcdev.sc_dev.dv_xname);
		return;
	}

	printf("\n");

	wdcattach(chp);
}

u_int16_t
mac68k_bsr2_wdc_gen(bus_space_tag_t t, bus_space_handle_t *bsh, bus_size_t offset)
{
	return (*(volatile u_int16_t *) (bsh->base + offset * bsh->stride));
}

void
mac68k_bsh_wdc_set_stride(bus_space_tag_t t, bus_space_handle_t *h, int stride)
{
	h->stride = stride;
	h->bsr1 = mac68k_bsr1_gen;
	h->bsr2 = mac68k_bsr2_wdc_gen;
	h->bsr4 = mac68k_bsr4_gen;
	h->bsrs2 = mac68k_bsrs2_gen;
	h->bsrs4 = mac68k_bsrs4_gen;
	h->bsrm1 = mac68k_bsrm1_gen;
	h->bsrm2 = mac68k_bsrm2_swap;
	h->bsrm4 = mac68k_bsrm4_swap;
	h->bsrms2 = mac68k_bsrm2;
	h->bsrms4 = mac68k_bsrm4;
	h->bsrr1 = mac68k_bsrr1_gen;
	h->bsrr2 = mac68k_bsrr2_gen;
	h->bsrr4 = mac68k_bsrr4_gen;
	h->bsrrs2 = mac68k_bsrrs2_gen;
	h->bsrrs4 = mac68k_bsrrs4_gen;
	h->bsw1 = mac68k_bsw1_gen;
	h->bsw2 = mac68k_bsw2_gen;
	h->bsw4 = mac68k_bsw4_gen;
	h->bsws2 = mac68k_bsws2_gen;
	h->bsws4 = mac68k_bsws4_gen;
	h->bswm2 = mac68k_bswm2_swap;
	h->bswm4 = mac68k_bswm4_swap;
	h->bswms2 = mac68k_bswm2;
	h->bswms4 = mac68k_bswm4;
	h->bswr1 = mac68k_bswr1_gen;
	h->bswr2 = mac68k_bswr2_gen;
	h->bswr4 = mac68k_bswr4_gen;
	h->bswrs2 = mac68k_bswrs2_gen;
	h->bswrs4 = mac68k_bswrs4_gen;
	h->bssm1 = mac68k_bssm1_gen;
	h->bssm2 = mac68k_bssm2_gen;
	h->bssm4 = mac68k_bssm4_gen;
	h->bssr1 = mac68k_bssr1_gen;
	h->bssr2 = mac68k_bssr2_gen;
	h->bssr4 = mac68k_bssr4_gen;
}


text:
import { createLocalVue, mount, Wrapper } from '@vue/test-utils';
import Vue, { VueConstructor } from 'vue';

import { renderComponent } from '../../../tests/helpers/render';
import { MPanel, MPanelSkin } from './panel';

describe('MPanel', () => {
    let localVue: VueConstructor<Vue>;
    beforeEach(() => {
        localVue = createLocalVue();
    });

    it('should render correctly', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            slots: {
                default: 'body'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly when an header is provided', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            slots: {
                default: 'body',
                header: 'header'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly when a footer is provided', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            slots: {
                default: 'body',
                footer: 'footer'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render skink correctly', async () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            slots: {
                default: 'body'
            }
        });

        for (const skin in MPanelSkin) {
            pnl.setProps({ skin: MPanelSkin[skin] });
            expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot(skin);
        }
    });

    it('should render correctly with border', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                border: true
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly with shadow', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                shadow: true
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly with no padding', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                padding: false
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly with no body padding', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                paddingBody: false
            },
            slots: {
                default: 'body'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly with no header padding', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                paddingHeader: false
            },
            slots: {
                header: 'header'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should render correctly with no footer padding', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            propsData: {
                paddingFooter: false
            },
            slots: {
                footer: 'footer'
            }
        });

        return expect(renderComponent(pnl.vm)).resolves.toMatchSnapshot();
    });

    it('should emit click event when panel is clicked on', () => {
        const pnl: Wrapper<MPanel> = mount(MPanel, {
            localVue: localVue,
            slots: {
                default: 'body'
            }
        });

        pnl.find('article').trigger('click');

        expect(pnl.emitted('click'));
    });
});


text:
package com.orientechnologies.orient.server.network.protocol.http.multipart;

import java.io.IOException;

import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest;
import com.orientechnologies.orient.server.network.protocol.http.OHttpUtils;

/**
 * @author luca.molino
 *
 */
public class OHttpMultipartHelper {

	protected static boolean isMultipartPartHeader(StringBuilder header) {
		final String linePart = header.toString().trim();
		return ((linePart.equals(OHttpUtils.MULTIPART_CONTENT_CHARSET)) || (linePart.equals(OHttpUtils.MULTIPART_CONTENT_FILENAME))
				|| (linePart.equals(OHttpUtils.MULTIPART_CONTENT_NAME)) || (linePart.equals(OHttpUtils.MULTIPART_CONTENT_TYPE))
				|| (linePart.equals(OHttpUtils.MULTIPART_CONTENT_DISPOSITION)) || (linePart
				.equals(OHttpUtils.MULTIPART_CONTENT_TRANSFER_ENCODING)));
	}

	public static boolean isEndRequest(final OHttpRequest iRequest) throws IOException {
		int in = iRequest.multipartStream.read();
		if (((char) in) == '-') {
			in = iRequest.multipartStream.read();
			if (((char) in) == '-') {
				in = iRequest.multipartStream.read();
				if (((char) in) == '\r') {
					in = iRequest.multipartStream.read();
					if (((char) in) == '\n') {
						return true;
					} else {
						iRequest.multipartStream.setSkipInput(in);
					}
				} else {
					iRequest.multipartStream.setSkipInput(in);
				}
			} else {
				iRequest.multipartStream.setSkipInput(in);
			}
		} else {
			iRequest.multipartStream.setSkipInput(in);
		}
		return false;
	}

}


text:
/*
 * imu_temp.c
 *
 *  Created on: 3 Jan, 2017
 *      Author: ASUS
 */
#include "ch.h"
#include "hal.h"

#include "mpu6500.h"
#include "imu_temp.h"

extern PWMDriver PWMD12;

#define TEMP_THRESHOLD 62
#define TEMPERATURE_UPDATE_PERIOD_S 1U

TPIDStruct tempPID1;

// These are the definitions of the PWMConfig stuctures
// E.g. the function name means PWM 3 CONFIGURATION
static PWMConfig pwm3cfg = {
        100000,   /* 1MHz PWM clock frequency.   */
        100,      /* Initial PWM period 1ms.       */
        NULL,       /* Periodic call back */
        {
                {PWM_OUTPUT_ACTIVE_HIGH, NULL}, /* {<pwm_initialisation_status>, <callback function of the channel> */
                {PWM_OUTPUT_ACTIVE_HIGH, NULL},
                {PWM_OUTPUT_DISABLED, NULL},
                {PWM_OUTPUT_DISABLED, NULL}
        },
        0,
        0
};

static const TPIDConfigStruct tpid1_conf = {
                                            5600.0f,   //Kp
                                            70.0f,      //Ki
                                            0.0f       //Kd
};

pTPIDStruct TPID_get(void){
  return &tempPID1;
}

void tempPID_Init(pTPIDStruct tempPID, const TPIDConfigStruct* const tpid_conf){
  tempPID->Kp = tpid_conf->Kp;
  tempPID->Ki = tpid_conf->Ki;
  tempPID->Kd = tpid_conf->Kd;
  tempPID->Error_Integral = 0.0f;
  tempPID->Previous_Error = 0.0f;
  tempPID->PID_Value = 0;
}

int tempPID_Update(pTPIDStruct tempPID, PIMUStruct pIMU){
  float Error = TEMP_THRESHOLD - pIMU->temperature;
  tempPID->Error_Integral = tempPID->Error_Integral + Error;
  if(tempPID->Error_Integral > 2200)
    tempPID->Error_Integral = 2200;
  else if(tempPID->Error_Integral < -2200)
    tempPID->Error_Integral = -2200;

  float Error_Derivative = Error - tempPID->Previous_Error;
  tempPID->Previous_Error = Error;

  int PID_Output = (int)((tempPID->Kp * Error) + (tempPID->Ki * tempPID->Error_Integral) + (tempPID->Kd * Error_Derivative));

  if(PID_Output > 10000)
    PID_Output= 10000;
  else if(PID_Output < 0)
    PID_Output = 0;

  tempPID->PID_Value = PID_Output;

  return PID_Output;
}

static THD_WORKING_AREA(Temperature_thread_wa, 4096);
static THD_FUNCTION(Temperature_thread, p)
{
  chRegSetThreadName("IMU Temperature Control");

  (void)p;

  PIMUStruct pIMU = imu_get();
  pTPIDStruct tempPID = TPID_get();
  tempPID_Init(tempPID, &tpid1_conf);
  pwmEnableChannel(&PWMD3, 1, PWM_PERCENTAGE_TO_WIDTH(&PWMD3, 0));
  uint32_t tick = chVTGetSystemTimeX();

  while(true)
  {
    tick += S2ST(TEMPERATURE_UPDATE_PERIOD_S);
    if(chVTGetSystemTimeX() < tick)
      chThdSleepUntil(tick);
    else
    {
      tick = chVTGetSystemTimeX();
      pIMU->errorCode |= IMU_LOSE_FRAME;
    }

    if(pIMU->temperature > 88.0f)
    {
      pIMU->errorCode |= IMU_TEMP_ERROR;
      tempController_kill();
      chThdExit(MSG_OK);
    }

    int PWM_Output = tempPID_Update(tempPID, pIMU);
    pwmEnableChannel(&PWMD3, 1, PWM_PERCENTAGE_TO_WIDTH(&PWMD3, PWM_Output));
  }
}

void tempControllerInit(void){
  pwmStart(&PWMD3, &pwm3cfg);
  pwmEnableChannel(&PWMD3, 0, PWM_PERCENTAGE_TO_WIDTH(&PWMD3, 0));
  chThdCreateStatic(Temperature_thread_wa, sizeof(Temperature_thread_wa),
    NORMALPRIO - 10,
                      Temperature_thread, NULL);
}


text:
<?php
namespace Apps\Modules\Admin\Controllers;

use Cygnite\Mvc\View\Widget;
use Cygnite\Foundation\Application;
use Apps\Modules\Admin\Models\User;
use Cygnite\Mvc\Controller\AbstractBaseController;

class UserController extends AbstractBaseController
{
     /*
     * Your constructor.
     * @access public
     *
     */
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * Default method for your controller. Render widget and return
     * @access public
     *
     */
   public function indexAction($id)
   {
        $users = array();
        //$users = User::all();
        return Widget::make('modules::admin::user', array('msg' => 'Hello! Widget', 'users' => $users));
   }
}//End of your controller


text:
'use strict';

// MAIN //

/**
* Performs a map-reduce operation against each element in an array and returns the accumulated result.
*
* @private
* @param {Object} x - object containing input array data
* @param {ArrayLikeObject} x.data - input array data
* @param {Function} x.getter - callback for accessing input array data elements
* @param {*} initial - initial value
* @param {Function} mapper - mapping function
* @param {Function} reducer - reducing function
* @param {*} thisArg - reducing function execution context
* @returns {*} accumulated result
*
* @example
* function square( value ) {
*     return value * value;
* }
*
* function sum( acc, value ) {
*     return acc + value;
* }
*
* // Define a getter:
* function getter( buf, idx ) {
*     return buf[ idx ];
* }
*
* // Create the input array object:
* var x = {
*     'data': [ 1, 2, 3, 4 ],
*     'getter': getter
* };
*
* // Compute the sum of squared values:
* var out = mapReduce( x, 0, square, sum );
* // returns 30
*/
function mapReduce( x, initial, mapper, reducer, thisArg ) {
	var xbuf;
	var get;
	var acc;
	var i;

	// Cache reference to the input data:
	xbuf = x.data;

	// Cache the element accessor:
	get = x.getter;

	// Iterate over each element...
	acc = initial;
	for ( i = 0; i < xbuf.length; i++ ) {
		acc = reducer.call( thisArg, acc, mapper( get( xbuf, i ), i, xbuf ), i, xbuf ); // eslint-disable-line max-len
	}
	return acc;
}

// EXPORTS //

module.exports = mapReduce;


text:
const path = require("path");
const settings = require("../../../../../../../../settings.local.json");
const isProduction = process.env.NODE_ENV === "production";

module.exports = {
  entry: "./index",
  optimization: {
    minimize: true
  },
  node: {
    fs: "empty"
  },
  output: {
    path:
      isProduction || settings.WebsitePath == ""
        ? path.resolve(
            "../../../../admin/personaBar/Dnn.Sites/scripts/exportables/Sites"
          )
        : settings.WebsitePath +
          "\\DesktopModules\\Admin\\Dnn.PersonaBar\\Modules\\Dnn.Sites\\scripts\\exportables\\Sites\\",
    filename: "SitesListView.js",
    publicPath: isProduction ? "" : "http://localhost:8050/dist/"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        enforce: "pre",
        exclude: /node_modules/,
        loader: "eslint-loader",
        options: { fix: true }
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: "babel-loader",
        options: {
          presets: ["@babel/preset-env", "@babel/preset-react"],
          plugins: [
            "@babel/plugin-transform-react-jsx",
            "@babel/plugin-proposal-object-rest-spread"
          ]
        }
      },
      { test: /\.(less|css)$/, loader: "style-loader!css-loader!less-loader" }
    ]
  },
  externals: require("@dnnsoftware/dnn-react-common/WebpackExternals"),
  resolve: {
    extensions: [".js", ".json", ".jsx"],
    modules: [
      path.resolve(__dirname, "./src"),
      path.resolve(__dirname, "../"),
      path.resolve(__dirname, "node_modules"),
      path.resolve(__dirname, "../../node_modules"),
      path.resolve(__dirname, "../../../../../../../../node_modules")
    ]
  }
};


text:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/*
  Generated class for the Settings page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@IonicPage()

@Component({
  selector: 'page-settings',
  templateUrl: 'settings.html'
})
export class SettingsPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad SettingsPage');
  }

}


text:
module BABYLON {
    export class InterpolateValueAction extends Action {
        private _target: any;
        private _effectiveTarget: any;
        private _property: string;

        constructor(triggerOptions: any, target: any, public propertyPath: string, public value: any, public duration: number = 1000, condition?: Condition, public stopOtherAnimations?: boolean, public onInterpolationDone?: () => void) {
            super(triggerOptions, condition);

            this._target = this._effectiveTarget = target;
        }

        public _prepare(): void {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        }

        public execute(): void {
            var scene = this._actionManager.getScene();
            var keys = [
                {
                    frame: 0,
                    value: this._effectiveTarget[this._property]
                }, {
                    frame: 100,
                    value: this.value
                }
            ];

            var dataType: number;

            if (typeof this.value === "number") {
                dataType = Animation.ANIMATIONTYPE_FLOAT;
            } else if (this.value instanceof Color3) {
                dataType = Animation.ANIMATIONTYPE_COLOR3;
            } else if (this.value instanceof Vector3) {
                dataType = Animation.ANIMATIONTYPE_VECTOR3;
            } else if (this.value instanceof Matrix) {
                dataType = Animation.ANIMATIONTYPE_MATRIX;
            } else if (this.value instanceof Quaternion) {
                dataType = Animation.ANIMATIONTYPE_QUATERNION;
            } else {
                Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
                return;
            }

            var animation = new Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, Animation.ANIMATIONLOOPMODE_CONSTANT);

            animation.setKeys(keys);

            if (this.stopOtherAnimations) {
                scene.stopAnimation(this._effectiveTarget);
            }

            scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
        }

        public serialize(parent: any): any {
            return super._serialize({
                name: "InterpolateValueAction",
                properties: [
                    Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: Action._SerializeValueAsString(this.value) },
                    { name: "duration", value: Action._SerializeValueAsString(this.duration) },
                    { name: "stopOtherAnimations", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false }
                ]
            }, parent);
        }
    }
}


text:
class AddPasswordDigestToUsers < ActiveRecord::Migration
  def up
    add_column :users, :password_digest, :string
  end

  def down
    remove_column :users, :password_digest
  end
end


text:
<form [formGroup]="formGroup" novalidate>
  <sky-input-box>
    <label class="sky-control-label" [for]="autonumericInput.id">
      Donation amount
    </label>
    <input
      class="sky-form-control"
      formControlName="donationAmount"
      skyId
      type="text"
      #autonumericInput="skyId"
      [skyAutonumeric]="autonumericOptions"
    />
  </sky-input-box>
</form>


text:
actions :run

attribute :command_file, :kind_of => String, :required => true

attribute :host, :kind_of => String, :required => true
attribute :port, :kind_of => Integer, :default => 5432
attribute :admin_username, :kind_of => String, :default => nil
attribute :admin_password, :kind_of => String, :default => nil
attribute :dbname, :kind_of => String, :required => true
attribute :match, :kind_of => String, :default => nil

attribute :returns, :kind_of => [Array, Integer], :default => 0

default_action :run