<commit_before>define(['text!./result-view-options.html', 'app', 'lodash', 'ngDialog'], function (template, app, _) {
    'use strict';

    app.directive('resultViewOptions', ['$location', 'ngDialog', 'locale', function ($location, ngDialog, locale) {
        return {
            restrict: 'EA',
            template: template,
            scope: {
                viewType        : '=' ,
                sortFields      : '=' ,
                groupByFields   : '=' ,
                onSortByChange  : '&?',
                onViewTypeChange: '&?'
            },
            link: function ($scope, $element, $attr) {

            //    if(!$scope.viewType)
            //         $scope.viewType = 'list';

                $scope.actionSetPage = function (n) {
                    if(n<1 || n>$scope.pageCount)
                        return;
                    $scope.onPageChange({
                        page: n
                    });
                }

                $scope.showSortDialog = function(){
                    var selectedFields = $scope.sortFields
                    ngDialog.open({
                        template : 'sortByDialog',
                        controller: ['$scope', function($scope){
                            $scope.sortByFields = [
                                {field:'relevance'                            , title: 'Relevance'       ,direction: 'asc'},
                                {field:'updatedDate_dt'                       , title: 'Last Updated On' ,direction: 'asc'},
                                {field:'schema_EN_s'.replace('EN', locale.toUpperCase())    , title: 'Record Type'     ,direction: 'asc'},
                                {field:'government_EN_s'.replace('EN', locale.toUpperCase()), title: 'Country'         ,direction: 'asc'}
                            ]

                            _.each(selectedFields, function(field){
                                var splitField = field.split(' ')
                                var existing = _.find($scope.sortByFields, {field: splitField[0]})
                                if(existing){
                                    existing.selected = true;
                                    existing.direction = splitField[1];
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                    $scope.selectedFields.push(existing)
                                }
                            });

                            $scope.selectField = function(field,direction){
                                if(!direction)
                                    field.selected=!field.selected;

                                if(field.field == 'relevance'){
                                    $scope.selectedFields = [];
                                    _.each($scope.sortByFields, function(f){f.selected=f.field == 'relevance'});
                                }
                                else{
                                    var relevance = _.find($scope.selectedFields, {field: 'relevance'})
                                    var index = _.indexOf($scope.selectedFields, relevance);
                                    if(index>=0){
                                        relevance.selected = false;
                                        $scope.selectedFields.splice(index, 1);
                                    }
                                }

                                field.direction=direction||'asc';
                                if(field.selected){
                                    var existing = _.find($scope.selectedFields, {field: field.field})
                                    if(existing)
                                        existing.direction = field.direction
                                    else
                                        $scope.selectedFields.push(field)
                                }
                                else{
                                    var index = _.indexOf($scope.selectedFields, _.find($scope.selectedFields, {field: field.field}));
                                    $scope.selectedFields.splice(index, 1);
                                }
                            }
                            $scope.closeDialog = function(){
                                ngDialog.close();
                            }
                            $scope.apply = function(){
                                onSortByChange($scope.selectedFields)
                                ngDialog.close();
                            }

                        }]
                    })
                }

                $scope.viewTypeChange = function(type){
                    if(type == 'list'){
                        $scope.onViewTypeChange({options:{viewType:type}})
                    }
                    if(type == 'group'){
                        showGroupByDialog()
                    }
                    else{

                    }
                }

                function showGroupByDialog(){
                    var selectedFields = $scope.groupByFields
                    ngDialog.open({
                        template : 'groupByDialog',
                        controller: ['$scope', function($scope){
                            $scope.groupByFields = [
                                {field:'government_EN_s'.replace('EN', locale.toUpperCase())     , title: 'Government'         },
                                {field:'schema_EN_s'.replace('EN', locale.toUpperCase())         , title: 'Type of record'     }
                            ]
                            // ,{field:'submissionYear_s' , title: 'Year of submission' }

                            _.each(selectedFields, function(field){
                                var existing = _.find($scope.groupByFields, {field: field})
                                if(existing){
                                    existing.selected = true;
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                        $scope.selectedFields.push(existing)
                                }
                            });

                            $scope.selectField = function(field){

                                field.selected=!field.selected;
                                if(field.selected){
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                    $scope.selectedFields.push(field)
                                }
                                else{
                                    var index = _.indexOf($scope.selectedFields, _.find($scope.selectedFields, {field: field.field}));
                                    $scope.selectedFields.splice(index, 1);
                                }
                            }
                            $scope.closeDialog = function(){
                                if(($scope.selectedFields||[]).length == 0)
                                    onGroupByChange([{field:'government_s'}, {field:'schema_s'}]) //default to this grouping when nothing is selected
                                ngDialog.close();
                            }
                            $scope.apply = function(){
                                onGroupByChange($scope.selectedFields)
                                ngDialog.close();
                            }

                        }]
                    })
                }

                function onSortByChange(selectedFields){
                    $scope.sortFields = _.map(selectedFields, function(field){return field.field + ' ' + field.direction });
                    $scope.onSortByChange({fields:$scope.sortFields})
                }
                function onGroupByChange(selectedFields){
                    $scope.groupByFields = _.map(selectedFields, function(field){return field.field});
                    $scope.onViewTypeChange({options:{ viewType:'group', fields:$scope.groupByFields}})
                }
            }
        }
    }])

});
<commit_msg>update groupby fields and handle sort<commit_after>define(['text!./result-view-options.html', 'app', 'lodash', 'ngDialog'], function (template, app, _) {
    'use strict';

    app.directive('resultViewOptions', ['$location', 'ngDialog', 'locale', function ($location, ngDialog, locale) {
        return {
            restrict: 'EA',
            template: template,
            scope: {
                viewType        : '=' ,
                sortFields      : '=' ,
                groupByFields   : '=' ,
                onSortByChange  : '&?',
                onViewTypeChange: '&?'
            },
            link: function ($scope, $element, $attr) {

            //    if(!$scope.viewType)
            //         $scope.viewType = 'list';

                $scope.actionSetPage = function (n) {
                    if(n<1 || n>$scope.pageCount)
                        return;
                    $scope.onPageChange({
                        page: n
                    });
                }

                $scope.showSortDialog = function(){
                    var selectedFields = $scope.sortFields
                    ngDialog.open({
                        template : 'sortByDialog',
                        controller: ['$scope', function($scope){
                            $scope.sortByFields = [
                                {field:'relevance'                            , title: 'Relevance'       ,direction: 'asc'},
                                {field:'updatedDate_dt'                       , title: 'Last Updated On' ,direction: 'asc'},
                                {field:'schema_EN_s'.replace('EN', locale.toUpperCase())    , title: 'Record Type'     ,direction: 'asc'},
                                {field:'government_EN_s'.replace('EN', locale.toUpperCase()), title: 'Country'         ,direction: 'asc'}
                            ]

                            _.each(selectedFields, function(field){
                                var splitField = field.split(' ')
                                var existing = _.find($scope.sortByFields, {field: splitField[0]})
                                if(existing){
                                    existing.selected = true;
                                    existing.direction = splitField[1];
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                    $scope.selectedFields.push(existing)
                                }
                            });

                            $scope.selectField = function(field,direction){
                                if(!direction)
                                    field.selected=!field.selected;

                                if(field.field == 'relevance'){
                                    $scope.selectedFields = [];
                                    _.each($scope.sortByFields, function(f){f.selected=f.field == 'relevance'});
                                }
                                else{
                                    var relevance = _.find($scope.selectedFields, {field: 'relevance'})
                                    var index = _.indexOf($scope.selectedFields, relevance);
                                    if(index>=0){
                                        relevance.selected = false;
                                        $scope.selectedFields.splice(index, 1);
                                    }
                                }

                                field.direction=direction||'asc';
                                if(field.selected){
                                    var existing = _.find($scope.selectedFields, {field: field.field})
                                    if(existing)
                                        existing.direction = field.direction
                                    else
                                        $scope.selectedFields.push(field)
                                }
                                else{
                                    var index = _.indexOf($scope.selectedFields, _.find($scope.selectedFields, {field: field.field}));
                                    $scope.selectedFields.splice(index, 1);
                                }
                            }
                            $scope.closeDialog = function(){
                                ngDialog.close();
                            }
                            $scope.apply = function(){
                                onSortByChange($scope.selectedFields)
                                ngDialog.close();
                            }

                        }]
                    })
                }

                $scope.viewTypeChange = function(type){
                    if(type == 'list'){
                        $scope.onViewTypeChange({options:{viewType:type}})
                    }
                    if(type == 'group'){
                        showGroupByDialog()
                    }
                    else{

                    }
                }

                function showGroupByDialog(){
                    var selectedFields = $scope.groupByFields
                    ngDialog.open({
                        template : 'groupByDialog',
                        controller: ['$scope', function($scope){
                            $scope.groupByFields = [
                                {field:'government_s'.replace('EN', locale.toUpperCase())     , title: 'Government'         },
                                {field:'schema_s'.replace('EN', locale.toUpperCase())         , title: 'Type of record'     }
                            ]
                            // ,{field:'submissionYear_s' , title: 'Year of submission' }

                            _.each(selectedFields, function(field){
                                var existing = _.find($scope.groupByFields, {field: field})
                                if(existing){
                                    existing.selected = true;
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                        $scope.selectedFields.push(existing)
                                }
                            });

                            $scope.selectField = function(field){

                                field.selected=!field.selected;
                                if(field.selected){
                                    if(!$scope.selectedFields) $scope.selectedFields = [];
                                    $scope.selectedFields.push(field)
                                }
                                else{
                                    var index = _.indexOf($scope.selectedFields, _.find($scope.selectedFields, {field: field.field}));
                                    $scope.selectedFields.splice(index, 1);
                                }
                            }
                            $scope.closeDialog = function(){
                                if(($scope.selectedFields||[]).length == 0)
                                    onGroupByChange([{field:'government_s'}, {field:'schema_s'}]) //default to this grouping when nothing is selected
                                ngDialog.close();
                            }
                            $scope.apply = function(){
                                onGroupByChange($scope.selectedFields)
                                ngDialog.close();
                            }

                        }]
                    })
                }

                function onSortByChange(selectedFields){
                    $scope.sortFields = _.map(selectedFields, function(field){return field.field + ' ' + field.direction });
                    $scope.onSortByChange({fields:$scope.sortFields})
                }
                function onGroupByChange(selectedFields){
                    $scope.groupByFields = _.map(selectedFields, function(field){return field.field});
                    $scope.onViewTypeChange({options:{ viewType:'group', fields:$scope.groupByFields}})
                }
            }
        }
    }])

});
<|endoftext|>


<commit_before>// A freelook camera script. Upon run, creates necessary components if they don't exist yet, and hooks to the InputMapper's
// input context to process camera movement (WASD + mouse)

var rotate_sensitivity = 0.3
var move_sensitivity = 30.0
var motion_z = 0;
var motion_y = 0;
var motion_x = 0;

if (!me.HasComponent("EC_OgreCamera"))
{
    // Create components & setup default position/lookat for the camera, mimicing RexLogicModule::CreateOpenSimViewerCamera()
    var camera = me.GetOrCreateComponentRaw("EC_OgreCamera");
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    var placeable = me.GetOrCreateComponentRaw("EC_Placeable");
    var soundlistener = me.GetOrCreateComponentRaw("EC_SoundListener");

    camera.AutoSetPlaceable();
    camera.SetActive();

    var transform = placeable.transform;
    transform.rot.x = 90;
    placeable.transform = transform;

    // Hook to update tick
    frame.Updated.connect(Update);
    // Register press & release action mappings to the inputmapper, use higher priority than RexMovementInput to be sure
    inputmapper.contextPriority = 101;
    inputmapper.takeMouseEventsOverQt = true;
    inputmapper.modifiersEnabled = false;
    inputmapper.RegisterMapping("W", "Move(forward)", 1);
    inputmapper.RegisterMapping("S", "Move(back)", 1);
    inputmapper.RegisterMapping("A", "Move(left)", 1);
    inputmapper.RegisterMapping("D", "Move(right)", 1);
    inputmapper.RegisterMapping("Space", "Move(up)", 1);
    inputmapper.RegisterMapping("C", "Move(down)", 1);
    inputmapper.RegisterMapping("W", "Stop(forward)", 3);
    inputmapper.RegisterMapping("S", "Stop(back)", 3);
    inputmapper.RegisterMapping("A", "Stop(left)", 3);
    inputmapper.RegisterMapping("D", "Stop(right)", 3);
    inputmapper.RegisterMapping("Space", "Stop(up)", 3);
    inputmapper.RegisterMapping("C", "Stop(down)", 3);
    inputmapper.RegisterMapping("Up", "Move(forward)", 1);
    inputmapper.RegisterMapping("Down", "Move(back)", 1);
    inputmapper.RegisterMapping("Left", "Move(left)", 1);
    inputmapper.RegisterMapping("Right", "Move(right)", 1);
    inputmapper.RegisterMapping("Up", "Stop(forward)", 3);
    inputmapper.RegisterMapping("Down", "Stop(back)", 3);
    inputmapper.RegisterMapping("Left", "Stop(left)", 3);
    inputmapper.RegisterMapping("Right", "Stop(right)", 3);
    // Connect actions
    me.Action("Move").Triggered.connect(HandleMove);
    me.Action("Stop").Triggered.connect(HandleStop);
    me.Action("MouseLookX").Triggered.connect(HandleMouseLookX);
    me.Action("MouseLookY").Triggered.connect(HandleMouseLookY);
}

function Update(frametime)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
    {
        motion_x = 0;
        motion_y = 0;
        motion_z = 0;
        return;
    }

    var placeable = me.GetComponentRaw("EC_Placeable");
    if (motion_z != 0)
    {
        var motionvec = new Vector3df();
        motionvec.z = -motion_z * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
    if (motion_x != 0)
    {
        var motionvec = new Vector3df();
        motionvec.x = motion_x * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
    if (motion_y != 0)
    {
        var motionvec = new Vector3df();
        motionvec.y = motion_y * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
}

function HandleMove(param)
{
    if (param == "forward")
        motion_z = 1;
    if (param == "back")
        motion_z = -1;
    if (param == "right")
        motion_x = 1;
    if (param == "left")
        motion_x = -1;
    if (param == "up")
        motion_y = 1;
    if (param == "down")
        motion_y = -1;
}

function HandleStop(param)
{
    if ((param == "forward") && (motion_z == 1))
        motion_z = 0;
    if ((param == "back") && (motion_z == -1))
        motion_z = 0;
    if ((param == "right") && (motion_x == 1))
        motion_x = 0;
    if ((param == "left") && (motion_x == -1))
        motion_x = 0;
    if ((param == "up") && (motion_y == 1))
        motion_y = 0;
    if ((param == "down") && (motion_y == -1))
        motion_y = 0;
}

function HandleMouseLookX(param)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
        return;

    var move = parseInt(param);
    var placeable = me.GetComponentRaw("EC_Placeable");
    var newtransform = placeable.transform;
    newtransform.rot.z -= rotate_sensitivity * move;
    placeable.transform = newtransform;
}

function HandleMouseLookY(param)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
        return;

    var move = parseInt(param);
    var placeable = me.GetComponentRaw("EC_Placeable");
    var newtransform = placeable.transform;
    newtransform.rot.x -= rotate_sensitivity * move;
    placeable.transform = newtransform;
}
<commit_msg>Fix freelookcamera to co-operate with the avatar camera and not always activate itself upon creation (due to new asset system it is possible that freelookcamera script is run after avatar script)<commit_after>// A freelook camera script. Upon run, creates necessary components if they don't exist yet, and hooks to the InputMapper's
// input context to process camera movement (WASD + mouse)

var rotate_sensitivity = 0.3
var move_sensitivity = 30.0
var motion_z = 0;
var motion_y = 0;
var motion_x = 0;

if (!me.HasComponent("EC_OgreCamera"))
{
    // Create components & setup default position/lookat for the camera, mimicing RexLogicModule::CreateOpenSimViewerCamera()
    var camera = me.GetOrCreateComponentRaw("EC_OgreCamera");
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    var placeable = me.GetOrCreateComponentRaw("EC_Placeable");
    var soundlistener = me.GetOrCreateComponentRaw("EC_SoundListener");

    camera.AutoSetPlaceable();

    // Co-operate with the AvatarApplication: if AvatarCamera already exists, do not activate the freelookcamera right now
    var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
    if (!avatarcameraentity)
        camera.SetActive();

    var transform = placeable.transform;
    transform.rot.x = 90;
    placeable.transform = transform;

    // Hook to update tick
    frame.Updated.connect(Update);
    // Register press & release action mappings to the inputmapper, use higher priority than RexMovementInput to be sure
    inputmapper.contextPriority = 101;
    inputmapper.takeMouseEventsOverQt = true;
    inputmapper.modifiersEnabled = false;
    inputmapper.RegisterMapping("W", "Move(forward)", 1);
    inputmapper.RegisterMapping("S", "Move(back)", 1);
    inputmapper.RegisterMapping("A", "Move(left)", 1);
    inputmapper.RegisterMapping("D", "Move(right)", 1);
    inputmapper.RegisterMapping("Space", "Move(up)", 1);
    inputmapper.RegisterMapping("C", "Move(down)", 1);
    inputmapper.RegisterMapping("W", "Stop(forward)", 3);
    inputmapper.RegisterMapping("S", "Stop(back)", 3);
    inputmapper.RegisterMapping("A", "Stop(left)", 3);
    inputmapper.RegisterMapping("D", "Stop(right)", 3);
    inputmapper.RegisterMapping("Space", "Stop(up)", 3);
    inputmapper.RegisterMapping("C", "Stop(down)", 3);
    inputmapper.RegisterMapping("Up", "Move(forward)", 1);
    inputmapper.RegisterMapping("Down", "Move(back)", 1);
    inputmapper.RegisterMapping("Left", "Move(left)", 1);
    inputmapper.RegisterMapping("Right", "Move(right)", 1);
    inputmapper.RegisterMapping("Up", "Stop(forward)", 3);
    inputmapper.RegisterMapping("Down", "Stop(back)", 3);
    inputmapper.RegisterMapping("Left", "Stop(left)", 3);
    inputmapper.RegisterMapping("Right", "Stop(right)", 3);
    // Connect actions
    me.Action("Move").Triggered.connect(HandleMove);
    me.Action("Stop").Triggered.connect(HandleStop);
    me.Action("MouseLookX").Triggered.connect(HandleMouseLookX);
    me.Action("MouseLookY").Triggered.connect(HandleMouseLookY);
}

function Update(frametime)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
    {
        motion_x = 0;
        motion_y = 0;
        motion_z = 0;
        return;
    }

    var placeable = me.GetComponentRaw("EC_Placeable");
    if (motion_z != 0)
    {
        var motionvec = new Vector3df();
        motionvec.z = -motion_z * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
    if (motion_x != 0)
    {
        var motionvec = new Vector3df();
        motionvec.x = motion_x * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
    if (motion_y != 0)
    {
        var motionvec = new Vector3df();
        motionvec.y = motion_y * move_sensitivity * frametime;
        placeable.TranslateRelative(motionvec);
    }
}

function HandleMove(param)
{
    if (param == "forward")
        motion_z = 1;
    if (param == "back")
        motion_z = -1;
    if (param == "right")
        motion_x = 1;
    if (param == "left")
        motion_x = -1;
    if (param == "up")
        motion_y = 1;
    if (param == "down")
        motion_y = -1;
}

function HandleStop(param)
{
    if ((param == "forward") && (motion_z == 1))
        motion_z = 0;
    if ((param == "back") && (motion_z == -1))
        motion_z = 0;
    if ((param == "right") && (motion_x == 1))
        motion_x = 0;
    if ((param == "left") && (motion_x == -1))
        motion_x = 0;
    if ((param == "up") && (motion_y == 1))
        motion_y = 0;
    if ((param == "down") && (motion_y == -1))
        motion_y = 0;
}

function HandleMouseLookX(param)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
        return;

    var move = parseInt(param);
    var placeable = me.GetComponentRaw("EC_Placeable");
    var newtransform = placeable.transform;
    newtransform.rot.z -= rotate_sensitivity * move;
    placeable.transform = newtransform;
}

function HandleMouseLookY(param)
{
    var camera = me.GetComponentRaw("EC_OgreCamera");
    if (camera.IsActive() == false)
        return;

    var move = parseInt(param);
    var placeable = me.GetComponentRaw("EC_Placeable");
    var newtransform = placeable.transform;
    newtransform.rot.x -= rotate_sensitivity * move;
    placeable.transform = newtransform;
}
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/instrument/Instrument", "Tone/core/Buffers", "Tone/source/BufferSource"],
	function (Tone) {

	/**
	 * @class Automatically interpolates between a set of pitched samples. Pass in an object which maps the note's pitch or midi value to the url, then you can trigger the attack and release of that note like other instruments. By automatically repitching the samples, it is possible to play pitches which were not explicitly included which can save loading time.
	 *        For sample or buffer playback where repitching is not necessary, use [Tone.Player](https://tonejs.github.io/docs/Player).
	 * @param {Object} samples An object of samples mapping either Midi
	 *                         Note Numbers or Scientific Pitch Notation
	 *                         to the url of that sample.
	 * @example
	 * var sampler = new Tone.Sampler({
	 * 	"C3" : "path/to/C3.mp3",
	 * 	"D#3" : "path/to/Dsharp3.mp3",
	 * 	"F#3" : "path/to/Fsharp3.mp3",
	 * 	"A3" : "path/to/A3.mp3",
	 * }, function(){
	 * 	//sampler will repitch the closest sample
	 * 	sampler.triggerAttack("D3")
	 * })
	 * @extends {Tone.Instrument}
	 */
	Tone.Sampler = function(urls){

		// shift arguments over one. Those are the remainder of the options
		var args = Array.prototype.slice.call(arguments);
		args.shift();
		var options = Tone.defaults(args, ["onload", "baseUrl"], Tone.Sampler);
		Tone.Instrument.call(this, options);

		var urlMap = {};
		for (var note in urls){
			if (Tone.isNote(note)){
				//convert the note name to MIDI
				var mid = Tone.Frequency(note).toMidi();
				urlMap[mid] = urls[note];
			} else if (!isNaN(parseFloat(note))){
				//otherwise if it's numbers assume it's midi
				urlMap[note] = urls[note];
			} else {
				throw new Error("Tone.Sampler: url keys must be the note's pitch");
			}
		}

		/**
		 * The stored and loaded buffers
		 * @type {Tone.Buffers}
		 * @private
		 */
		this._buffers = new Tone.Buffers(urlMap, options.onload, options.baseUrl);

		/**
		 * The object of all currently playing BufferSources
		 * @type {Object}
		 * @private
		 */
		this._activeSources = {};

		/**
		 * The envelope applied to the beginning of the sample.
		 * @type {Time}
		 */
		this.attack = options.attack;

		/**
		 * The envelope applied to the end of the envelope.
		 * @type {Time}
		 */
		this.release = options.release;
	};

	Tone.extend(Tone.Sampler, Tone.Instrument);

	/**
	 * The defaults
	 * @const
	 * @type {Object}
	 */
	Tone.Sampler.defaults = {
		attack : 0,
		release : 0.1,
		onload : Tone.noOp,
		baseUrl : ""
	};

	/**
	 * Returns the difference in steps between the given midi note at the closets sample.
	 * @param  {Midi} midi
	 * @return {Interval}
	 * @private
	 */
	Tone.Sampler.prototype._findClosest = function(midi){
		var MAX_INTERVAL = 24;
		var interval = 0;
		while(interval < MAX_INTERVAL){
			// check above and below
			if (this._buffers.has(midi + interval)){
				return -interval;
			} else if (this._buffers.has(midi - interval)){
				return interval;
			}
			interval++;
		}
		return null;
	};

	/**
	 * @param  {Frequency} note     The note to play
	 * @param  {Time=} time     When to play the note
	 * @param  {NormalRange=} velocity The velocity to play the sample back.
	 * @return {Tone.Sampler}          this
	 */
	Tone.Sampler.prototype.triggerAttack = function(note, time, velocity){
		var midi = Tone.Frequency(note).toMidi();
		// find the closest note pitch
		var difference = this._findClosest(midi);
		if (difference !== null){
			var closestNote = midi - difference;
			var buffer = this._buffers.get(closestNote);
			// play that note
			var source = new Tone.BufferSource({
				"buffer" : buffer,
				"playbackRate" : Tone.intervalToFrequencyRatio(difference),
				"fadeIn" : this.attack,
				"fadeOut" : this.release,
				"curve" : "exponential",
			}).connect(this.output);
			source.start(time, 0, buffer.duration, velocity);
			// add it to the active sources
			if (!Tone.isArray(this._activeSources[midi])){
				this._activeSources[midi] = [];
			}
			this._activeSources[midi].push({
				note : midi,
				source : source
			});
		}
		return this;
	};

	/**
	 * @param  {Frequency} note     The note to release.
	 * @param  {Time=} time     	When to release the note.
	 * @return {Tone.Sampler}	this
	 */
	Tone.Sampler.prototype.triggerRelease = function(note, time){
		var midi = Tone.Frequency(note).toMidi();
		// find the note
		if (this._activeSources[midi] && this._activeSources[midi].length){
			var source = this._activeSources[midi].shift().source;
			time = this.toSeconds(time);
			source.stop(time + this.release, this.release);
		}
	};

	/**
	 * Invoke the attack phase, then after the duration, invoke the release.
	 * @param  {Frequency} note     The note to play
	 * @param  {Time} duration The time the note should be held
	 * @param  {Time=} time     When to start the attack
	 * @param  {NormalRange} [velocity=1] The velocity of the attack
	 * @return {Tone.Sampler}          this
	 */
	Tone.Sampler.prototype.triggerAttackRelease = function(note, duration, time, velocity){
		time = this.toSeconds(time);
		duration = this.toSeconds(duration);
		this.triggerAttack(note, time, velocity);
		this.triggerRelease(note, time + duration);
		return this;
	};

	/**
	 *  Add a note to the sampler.
	 *  @param  {Note|Midi}   note      The buffer's pitch.
	 *  @param  {String|Tone.Buffer|Audiobuffer}  url  Either the url of the bufer,
	 *                                                 or a buffer which will be added
	 *                                                 with the given name.
	 *  @param  {Function=}  callback  The callback to invoke
	 *                                 when the url is loaded.
	 */
	Tone.Sampler.prototype.add = function(note, url, callback){
		if (Tone.isNote(note)){
			//convert the note name to MIDI
			var mid = Tone.Frequency(note).toMidi();
			this._buffers.add(mid, url, callback);
		} else if (!isNaN(parseFloat(note))){
			//otherwise if it's numbers assume it's midi
			this._buffers.add(note, url, callback);
		} else {
			throw new Error("Tone.Sampler: note must be the note's pitch. Instead got "+note);
		}
	};

	/**
	 * If the buffers are loaded or not
	 * @memberOf Tone.Sampler#
	 * @type {Boolean}
	 * @name loaded
	 * @readOnly
	 */
	Object.defineProperty(Tone.Sampler.prototype, "loaded", {
		get : function(){
			return this._buffers.loaded;
		}
	});

	/**
	 * Clean up
	 * @return {Tone.Sampler} this
	 */
	Tone.Sampler.prototype.dispose = function(){
		Tone.Instrument.prototype.dispose.call(this);
		this._buffers.dispose();
		this._buffers = null;
		for (var midi in this._activeSources){
			this._activeSources[midi].forEach(function(event){
				event.source.dispose();
			});
		}
		this._activeSources = null;
		return this;
	};

	return Tone.Sampler;
});
<commit_msg>jsdocing constructor params<commit_after>define(["Tone/core/Tone", "Tone/instrument/Instrument", "Tone/core/Buffers", "Tone/source/BufferSource"],
	function (Tone) {

	/**
	 * @class Automatically interpolates between a set of pitched samples. Pass in an object which maps the note's pitch or midi value to the url, then you can trigger the attack and release of that note like other instruments. By automatically repitching the samples, it is possible to play pitches which were not explicitly included which can save loading time.
	 *        For sample or buffer playback where repitching is not necessary, use [Tone.Player](https://tonejs.github.io/docs/Player).
	 * @param {Object} samples An object of samples mapping either Midi
	 *                         Note Numbers or Scientific Pitch Notation
	 *                         to the url of that sample.
	 * @param {Function=} onload The callback to invoke when all of the samples are loaded.
	 * @param {String=} baseUrl The root URL of all of the samples, which is prepended to all the URLs.
	 * @example
	 * var sampler = new Tone.Sampler({
	 * 	"C3" : "path/to/C3.mp3",
	 * 	"D#3" : "path/to/Dsharp3.mp3",
	 * 	"F#3" : "path/to/Fsharp3.mp3",
	 * 	"A3" : "path/to/A3.mp3",
	 * }, function(){
	 * 	//sampler will repitch the closest sample
	 * 	sampler.triggerAttack("D3")
	 * })
	 * @extends {Tone.Instrument}
	 */
	Tone.Sampler = function(urls){

		// shift arguments over one. Those are the remainder of the options
		var args = Array.prototype.slice.call(arguments);
		args.shift();
		var options = Tone.defaults(args, ["onload", "baseUrl"], Tone.Sampler);
		Tone.Instrument.call(this, options);

		var urlMap = {};
		for (var note in urls){
			if (Tone.isNote(note)){
				//convert the note name to MIDI
				var mid = Tone.Frequency(note).toMidi();
				urlMap[mid] = urls[note];
			} else if (!isNaN(parseFloat(note))){
				//otherwise if it's numbers assume it's midi
				urlMap[note] = urls[note];
			} else {
				throw new Error("Tone.Sampler: url keys must be the note's pitch");
			}
		}

		/**
		 * The stored and loaded buffers
		 * @type {Tone.Buffers}
		 * @private
		 */
		this._buffers = new Tone.Buffers(urlMap, options.onload, options.baseUrl);

		/**
		 * The object of all currently playing BufferSources
		 * @type {Object}
		 * @private
		 */
		this._activeSources = {};

		/**
		 * The envelope applied to the beginning of the sample.
		 * @type {Time}
		 */
		this.attack = options.attack;

		/**
		 * The envelope applied to the end of the envelope.
		 * @type {Time}
		 */
		this.release = options.release;
	};

	Tone.extend(Tone.Sampler, Tone.Instrument);

	/**
	 * The defaults
	 * @const
	 * @type {Object}
	 */
	Tone.Sampler.defaults = {
		attack : 0,
		release : 0.1,
		onload : Tone.noOp,
		baseUrl : ""
	};

	/**
	 * Returns the difference in steps between the given midi note at the closets sample.
	 * @param  {Midi} midi
	 * @return {Interval}
	 * @private
	 */
	Tone.Sampler.prototype._findClosest = function(midi){
		var MAX_INTERVAL = 24;
		var interval = 0;
		while(interval < MAX_INTERVAL){
			// check above and below
			if (this._buffers.has(midi + interval)){
				return -interval;
			} else if (this._buffers.has(midi - interval)){
				return interval;
			}
			interval++;
		}
		return null;
	};

	/**
	 * @param  {Frequency} note     The note to play
	 * @param  {Time=} time     When to play the note
	 * @param  {NormalRange=} velocity The velocity to play the sample back.
	 * @return {Tone.Sampler}          this
	 */
	Tone.Sampler.prototype.triggerAttack = function(note, time, velocity){
		var midi = Tone.Frequency(note).toMidi();
		// find the closest note pitch
		var difference = this._findClosest(midi);
		if (difference !== null){
			var closestNote = midi - difference;
			var buffer = this._buffers.get(closestNote);
			// play that note
			var source = new Tone.BufferSource({
				"buffer" : buffer,
				"playbackRate" : Tone.intervalToFrequencyRatio(difference),
				"fadeIn" : this.attack,
				"fadeOut" : this.release,
				"curve" : "exponential",
			}).connect(this.output);
			source.start(time, 0, buffer.duration, velocity);
			// add it to the active sources
			if (!Tone.isArray(this._activeSources[midi])){
				this._activeSources[midi] = [];
			}
			this._activeSources[midi].push({
				note : midi,
				source : source
			});
		}
		return this;
	};

	/**
	 * @param  {Frequency} note     The note to release.
	 * @param  {Time=} time     	When to release the note.
	 * @return {Tone.Sampler}	this
	 */
	Tone.Sampler.prototype.triggerRelease = function(note, time){
		var midi = Tone.Frequency(note).toMidi();
		// find the note
		if (this._activeSources[midi] && this._activeSources[midi].length){
			var source = this._activeSources[midi].shift().source;
			time = this.toSeconds(time);
			source.stop(time + this.release, this.release);
		}
	};

	/**
	 * Invoke the attack phase, then after the duration, invoke the release.
	 * @param  {Frequency} note     The note to play
	 * @param  {Time} duration The time the note should be held
	 * @param  {Time=} time     When to start the attack
	 * @param  {NormalRange} [velocity=1] The velocity of the attack
	 * @return {Tone.Sampler}          this
	 */
	Tone.Sampler.prototype.triggerAttackRelease = function(note, duration, time, velocity){
		time = this.toSeconds(time);
		duration = this.toSeconds(duration);
		this.triggerAttack(note, time, velocity);
		this.triggerRelease(note, time + duration);
		return this;
	};

	/**
	 *  Add a note to the sampler.
	 *  @param  {Note|Midi}   note      The buffer's pitch.
	 *  @param  {String|Tone.Buffer|Audiobuffer}  url  Either the url of the bufer,
	 *                                                 or a buffer which will be added
	 *                                                 with the given name.
	 *  @param  {Function=}  callback  The callback to invoke
	 *                                 when the url is loaded.
	 */
	Tone.Sampler.prototype.add = function(note, url, callback){
		if (Tone.isNote(note)){
			//convert the note name to MIDI
			var mid = Tone.Frequency(note).toMidi();
			this._buffers.add(mid, url, callback);
		} else if (!isNaN(parseFloat(note))){
			//otherwise if it's numbers assume it's midi
			this._buffers.add(note, url, callback);
		} else {
			throw new Error("Tone.Sampler: note must be the note's pitch. Instead got "+note);
		}
	};

	/**
	 * If the buffers are loaded or not
	 * @memberOf Tone.Sampler#
	 * @type {Boolean}
	 * @name loaded
	 * @readOnly
	 */
	Object.defineProperty(Tone.Sampler.prototype, "loaded", {
		get : function(){
			return this._buffers.loaded;
		}
	});

	/**
	 * Clean up
	 * @return {Tone.Sampler} this
	 */
	Tone.Sampler.prototype.dispose = function(){
		Tone.Instrument.prototype.dispose.call(this);
		this._buffers.dispose();
		this._buffers = null;
		for (var midi in this._activeSources){
			this._activeSources[midi].forEach(function(event){
				event.source.dispose();
			});
		}
		this._activeSources = null;
		return this;
	};

	return Tone.Sampler;
});
<|endoftext|>


<commit_before>/*
* A quote block that also adds a source URL for the quote.
* Data sent is like this:
*
*/

SirTrevor.Blocks.Sourcedquote = (function(){

  var template = _.template([
    '

',
    'Credit',
    '<input maxlength="140" name="author" placeholder="Credit" class="st-input-string st-required js-cite-input" type="text">',
    'Source',
    '<input name="source" placeholder="Source" class"st-input-string st-required js-cite-input" type="text">',
  ].join("\n"));

  return SirTrevor.Block.extend({

    type: 'sourced_quote',

    icon_name: 'quote',

    editorHTML: function() {
      return template(this);
    },

    loadData: function(data){
      this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type));
      this.$('.js-cite-input').val(data.cite);
    },

  });

})();
<commit_msg>Refactor sourced quote block<commit_after>/*
* A quote block that also adds a source URL for the quote.
* Data sent is like this:
*
*/

SirTrevor.Blocks.SourcedQuote = SirTrevor.Block.extend({

  type: 'sourced_quote',

  title: 'Quote with source',

  icon_name: 'quote',

  editorHTML: [
    '

',
    'Credit',
    '<input maxlength="140" name="author" placeholder="Credit" class="st-input-string st-required js-author-input" type="text">',
    'Source',
    '<input name="source" placeholder="Source" class"st-input-string st-required js-source-input" type="url">',
  ].join("\n"),

  loadData: function (data) {
    this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type));
    this.$('.js-author-input').val(data.author);
    this.$('.js-source-input').val(data.source);
  },

});
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Module dependencies.
 */

var fs = require('fs');
var events = require('events');
var minimist = require('minimist');

var argv = minimist(process.argv.slice(2));

var filenames = argv._;
if (filenames.length !== 1) {
  throw new Error('only one source filename supported at a time');
}
var filename = filenames[0];

var source = fs.createReadStream(filename);
var next = source;

// emulate browserify's API a little bit
var bundle = new events.EventEmitter();
bundle._extensions = Object.keys(require.extensions);
bundle._entries = [ filename ];
bundle.transform = function (t) {
  next = next.pipe(t(filename));
};

// apply any "transform"
var transform = argv.transform || argv.t;
if (transform) {
  var t = require(transform);
  bundle.transform(t);
}

// apply any "plugin"
var plugin = argv.plugin || argv.p;
if (plugin) {
  var p = require(plugin);
  p(bundle);
}

bundle.emit('bundle');

// output the pipeline to `stdout`
next.pipe(process.stdout);
<commit_msg>bin: add --plugin "options" support<commit_after>#!/usr/bin/env node

/**
 * Module dependencies.
 */

var fs = require('fs');
var events = require('events');
var minimist = require('minimist');

var argv = minimist(process.argv.slice(2));

var filenames = argv._;
if (filenames.length !== 1) {
  throw new Error('only one source filename supported at a time');
}
var filename = filenames[0];

var source = fs.createReadStream(filename);
var next = source;

// emulate browserify's API a little bit
var bundle = new events.EventEmitter();
bundle._extensions = Object.keys(require.extensions);
bundle._entries = [ filename ];
bundle.transform = function (t) {
  next = next.pipe(t(filename));
};

// apply any "transform"
var transform = argv.transform || argv.t;
if (transform) {
  var t = require(transform);
  bundle.transform(t);
}

// apply any "plugin"
var plugin = argv.plugin || argv.p;
if (plugin) {
  var pargv = minimist(plugin.split(/\s+/));
  var pname = pargv._[0];
  var p = require(pname);
  p(bundle, pargv);
}

bundle.emit('bundle');

// output the pipeline to `stdout`
next.pipe(process.stdout);
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
    throw err;
});

const spawn = require('react-dev-utils/crossSpawn');
const args = process.argv.slice(2);

const scriptIndex = args.findIndex(
  x => x === 'build' || x === 'eject' || x === 'start' || x === 'test'
);
const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];

switch (script) {
    case 'build':
    case 'start':
    case 'test': {
        const result = spawn.sync(
          'node',
          nodeArgs
            .concat(require.resolve('../scripts/' + script))
            .concat(args.slice(scriptIndex + 1)),
          { stdio: 'inherit' }
        );
        if (result.signal) {
            if (result.signal === 'SIGKILL') {
                console.log(
                  'The build failed because the process exited too early. ' +
                  'This probably means the system ran out of memory or someone called ' +
                  '`kill -9` on the process.'
                );
            } else if (result.signal === 'SIGTERM') {
                console.log(
                  'The build failed because the process exited too early. ' +
                  'Someone might have called `kill` or `killall`, or the system could ' +
                  'be shutting down.'
                );
            }
            process.exit(1);
        }
        process.exit(result.status);
        break;
    }
    default:
        console.log('Unknown script "' + script + '".');
        break;
}
<commit_msg>update to be more like creat-react-app@3.3<commit_after>#!/usr/bin/env node
'use strict';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
    throw err;
});

const spawn = require('react-dev-utils/crossSpawn');
const args = process.argv.slice(2);

const scriptIndex = args.findIndex(
  x => x === 'build' || x === 'eject' || x === 'start' || x === 'test'
);
const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];

if (['build', 'start', 'test'].includes(script)) {
    const result = spawn.sync(
      'node',
      nodeArgs
        .concat(require.resolve('../scripts/' + script))
        .concat(args.slice(scriptIndex + 1)),
      { stdio: 'inherit' }
    );
    if (result.signal) {
        if (result.signal === 'SIGKILL') {
            console.log(
              'The build failed because the process exited too early. ' +
              'This probably means the system ran out of memory or someone called ' +
              '`kill -9` on the process.'
            );
        } else if (result.signal === 'SIGTERM') {
            console.log(
              'The build failed because the process exited too early. ' +
              'Someone might have called `kill` or `killall`, or the system could ' +
              'be shutting down.'
            );
        }
        process.exit(1);
    }
    process.exit(result.status);
} else {
    console.log('Unknown script "' + script + '".');
}
<|endoftext|>


<commit_before>
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

(function($, _, Compilify) {
    var root = this,
        original, connection;

    function htmlEscape(str) {
        ///
        /// Sanitizes a string for display as HTML content.

        return String(str)
                .replace(/&/g, '&')
                .replace(/"/g, '"')
                .replace(/'/g, ''')
                .replace(/</g, '<')
                .replace(/>/g, '>');
    }

    function trackEvent(category, action, label) {
        ///
        /// Tracks an event in Google Analytics if it is initialized.

        var gaq = root._gaq;
        if (gaq && _.isFunction(gaq.push)) {
            gaq.push(['_trackEvent', category, action, label, , false]);
        }
    }

    function save(value) {
        ///
        /// Save content.

        trackEvent('Code', 'Save', window.location.pathname);

        return $.ajax(window.location.pathname, {
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ post: { Content: value } })
        });
    }

    function validate(code) {
        ///
        /// Sends code to the server for validation and displays the resulting
        /// errors, if any.

        trackEvent('Code', 'Validate', window.location.pathname);

        return $.ajax('/validate', {
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ 'code': code }),
            success: function(msg) {
                var data = msg.data;

                if (_.isArray(data)) {
                    var $list = $('#define .messages ul').detach().empty();

                    if (data.length == 0) {
                        $list.append('
Build ' +
                                     'completed successfully.
');
                    } else {
                        for (var i in msg.data) {
                            var error = msg.data[ i ];
                            $list.append('
' +
                                         htmlEscape(error) + '
');
                        }
                    }

                    $('#define .messages').append($list);
                }
            }
        });
    }

    function execute(code) {
        ///
        /// Queues code for execution on the server.

        if (_.isString(code) && code.length > 0) {
            trackEvent('Code', 'Execute', window.location.pathname);
            connection.send(code);
        }
    }

    function setResult(result) {
        ///
        /// Sets the content displayed in the results section.
        $('#results pre').html(result);
    }

    $(function() {
        //
        // Set up the SignalR connection
        //
        connection = $.connection('/execute');

        connection.received(function(msg) {
            if (msg && msg.status === "ok") {
                var data = msg.data;
                if (data && data.result) {
                    var result = htmlEscape(data.result.toString());
                    setResult(result);
                }
            }
        });

        connection.error(function(e) {
            console.error(e);
        });

        connection.start();

        //
        // Set up CodeMirror editor
        //

        // Get the editor and save the current content so we can tell when it
        // changes
        var editor = $('#define .editor textarea')[0];
        original = editor.innerHTML.trim().toUpperCase();

        Compilify.Editor = root.CodeMirror.fromTextArea(editor, {
            indentUnit: 4,
            lineNumbers: true,
            theme: 'neat',
            mode: 'text/x-csharp',
            onChange: _.debounce(function (sender) {
                // throttled to once every 500ms max
                validate(sender.getValue());
            }, 500)
        });

        $('#define .js-save').on('click', function() {
            var code = Compilify.Editor.getValue().trim();

            // Only save the content if it changed since we last loaded it.
            if (code.toUpperCase() !== original) {
                save(code)
                    .done(function (msg) {
                        // Might be able to use the object stored by pushState
                        // hold the original value
                        root.history.pushState({ }, '', msg.data.url);
                        original = value.toUpperCase();
                    });
            }

            return false;
        });

        $('#define .js-execute').on('click', function() {
            var code = Compilify.Editor.getValue().trim();
            execute(code);
            return false;
        });
    });
}).call(window, window.jQuery, window._, window.Compilify || {});
<commit_msg>Fix undefined value error<commit_after>
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

(function($, _, Compilify) {
    var root = this,
        original, connection;

    function htmlEscape(str) {
        ///
        /// Sanitizes a string for display as HTML content.

        return String(str)
                .replace(/&/g, '&')
                .replace(/"/g, '"')
                .replace(/'/g, ''')
                .replace(/</g, '<')
                .replace(/>/g, '>');
    }

    function trackEvent(category, action, label) {
        ///
        /// Tracks an event in Google Analytics if it is initialized.

        var gaq = root._gaq;
        if (gaq && _.isFunction(gaq.push)) {
            gaq.push(['_trackEvent', category, action, label, , false]);
        }
    }

    function save(value) {
        ///
        /// Save content.

        trackEvent('Code', 'Save', window.location.pathname);

        return $.ajax(window.location.pathname, {
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ post: { Content: value } })
        });
    }

    function validate(code) {
        ///
        /// Sends code to the server for validation and displays the resulting
        /// errors, if any.

        trackEvent('Code', 'Validate', window.location.pathname);

        return $.ajax('/validate', {
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ 'code': code }),
            success: function(msg) {
                var data = msg.data;

                if (_.isArray(data)) {
                    var $list = $('#define .messages ul').detach().empty();

                    if (data.length == 0) {
                        $list.append('
Build ' +
                                     'completed successfully.
');
                    } else {
                        for (var i in msg.data) {
                            var error = msg.data[ i ];
                            $list.append('
' +
                                         htmlEscape(error) + '
');
                        }
                    }

                    $('#define .messages').append($list);
                }
            }
        });
    }

    function execute(code) {
        ///
        /// Queues code for execution on the server.

        if (_.isString(code) && code.length > 0) {
            trackEvent('Code', 'Execute', window.location.pathname);
            connection.send(code);
        }
    }

    function setResult(result) {
        ///
        /// Sets the content displayed in the results section.
        $('#results pre').html(result);
    }

    $(function() {
        //
        // Set up the SignalR connection
        //
        connection = $.connection('/execute');

        connection.received(function(msg) {
            if (msg && msg.status === "ok") {
                var data = msg.data;
                if (data && data.result) {
                    var result = htmlEscape(data.result.toString());
                    setResult(result);
                }
            }
        });

        connection.error(function(e) {
            console.error(e);
        });

        connection.start();

        //
        // Set up CodeMirror editor
        //

        // Get the editor and save the current content so we can tell when it
        // changes
        var editor = $('#define .editor textarea')[0];
        original = editor.innerHTML.trim().toUpperCase();

        Compilify.Editor = root.CodeMirror.fromTextArea(editor, {
            indentUnit: 4,
            lineNumbers: true,
            theme: 'neat',
            mode: 'text/x-csharp',
            onChange: _.debounce(function (sender) {
                // throttled to once every 500ms max
                validate(sender.getValue());
            }, 500)
        });

        $('#define .js-save').on('click', function() {
            var code = Compilify.Editor.getValue().trim();

            // Only save the content if it changed since we last loaded it.
            if (code.toUpperCase() !== original) {
                save(code)
                    .done(function (msg) {
                        // Might be able to use the object stored by pushState
                        // hold the original value
                        root.history.pushState({ }, '', msg.data.url);
                        original = code.toUpperCase();
                    });
            }

            return false;
        });

        $('#define .js-execute').on('click', function() {
            var code = Compilify.Editor.getValue().trim();
            execute(code);
            return false;
        });
    });
}).call(window, window.jQuery, window._, window.Compilify || {});
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

const path = require('path');
const fs = require('fs');

module.exports = {
  normalizeEntityName() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall() {
    let dependencies = this.project.dependencies();
    let type;
    let importStatement = '\n@import "ember-power-select";\n';

    if ('ember-cli-sass' in dependencies) {
      type = 'scss';
    } else if ('ember-cli-less' in dependencies) {
      type = 'less';
    }

    if (type) {
      let stylePath = path.join('app', 'styles');
      let file = path.join(stylePath, `app.${type}`);

      if (!fs.existsSync(stylePath)) {
        fs.mkdirSync(stylePath);
      }
      if (fs.existsSync(file)) {
        this.ui.writeLine(`Added import statement to ${file}`);
        return this.insertIntoFile(file, importStatement, {});
      } else {
        fs.writeFileSync(file, importStatement);
        this.ui.writeLine(`Created ${file}`);
      }
    }
  }
};<commit_msg>support mu (#1208)<commit_after>/* eslint-env node */
'use strict';

const path = require('path');
const fs = require('fs');

function isModuleUnificationProject(project) {
  return project && project.isModuleUnification && project.isModuleUnification();
}

module.exports = {
  normalizeEntityName() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall() {
    let dependencies = this.project.dependencies();
    let type;
    let importStatement = '\n@import "ember-power-select";\n';

    if ('ember-cli-sass' in dependencies) {
      type = 'scss';
    } else if ('ember-cli-less' in dependencies) {
      type = 'less';
    }

    if (type) {
      let stylePath = path.join('app', 'styles');
      if (isModuleUnificationProject(this.project)) {
        stylePath = path.join('src', 'ui', 'styles');
      }

      let file = path.join(stylePath, `app.${type}`);

      if (!fs.existsSync(stylePath)) {
        fs.mkdirSync(stylePath);
      }
      if (fs.existsSync(file)) {
        this.ui.writeLine(`Added import statement to ${file}`);
        return this.insertIntoFile(file, importStatement, {});
      } else {
        fs.writeFileSync(file, importStatement);
        this.ui.writeLine(`Created ${file}`);
      }
    }

  }
};
<|endoftext|>


<commit_before>/**
 * Created by ievans3024 on 5/13/15.
 */

var emit = function(){},  // so node doesn't bitch about emit not existing
    replacer = function (k, v) {
        if (typeof v === 'function') {
            return "" + v;  // cast function as a string to get string form
        }
        return v;
    },
    dbname = "blackbook",
    filesystem = require("fs"),
    schema = [
        // Design Docs
        // require("./design_docs/example.js").design

        // API Specs
        // require("./api_specs/example.js").spec(dbname)
    ];

schema_string = JSON.stringify(schema, replacer);

filesystem.writeFile(dbname + ".json", schema_string);<commit_msg>+ added contact design doc and api spec to schema list<commit_after>/**
 * Created by ievans3024 on 5/13/15.
 */

var emit = function(){},  // so node doesn't bitch about emit not existing
    replacer = function (k, v) {
        if (typeof v === 'function') {
            return "" + v;  // cast function as a string to get string form
        }
        return v;
    },
    dbname = "blackbook",
    filesystem = require("fs"),
    schema = [
        // Design Docs
        // require("./design_docs/example.js").design
        require("./design_docs/contact.js").design,

        // API Specs
        // require("./api_specs/example.js").spec(dbname)
        require("./api_specs/contact.js").spec(dbname)
    ];

schema_string = JSON.stringify(schema, replacer);

filesystem.writeFile(dbname + ".json", schema_string);<|endoftext|>


<commit_before>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json"}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      }

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(path, cb) {
        _request("GET", repoPath + "/contents", { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var that = this;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<commit_msg>Update github.js. Removes cache busting timestamp, improves<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw, sync) {
      function getURL() {
        return url = API_URL + path;
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL(), !sync);
      if (!sync) {
        xhr.onreadystatechange = function () {
          if (this.readyState == 4) {
            if (this.status >= 200 && this.status < 300 || this.status === 304) {
              cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
            } else {
              cb({request: this, error: this.status});
            }
          }
        };
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
      if (sync) return xhr.response;
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(branch, path, cb) {
        _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, cb, 'raw');
      };

      this.contentsSync = function(branch, path) {
        return _request("GET", repoPath + "/contents/" + path + "?ref=" + branch, null, null, 'raw', true);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Create the gist
      // --------
      // {
      //  "description": "the description for this gist",
      //    "public": true,
      //    "files": {
      //      "file1.txt": {
      //        "content": "String file contents"
      //      }
      //    }
      // }

      this.create = function(options, cb){
        _request("POST","/gists", options, cb);
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<|endoftext|>


<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])

  .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);

      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });
  })

  .config(function($stateProvider, $urlRouterProvider) {
    $stateProvider

      .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'templates/menu.html',
        controller: 'AppCtrl'
      })

      .state('app.search', {
        url: '/search',
        views: {
          'menuContent': {
            templateUrl: 'templates/search.html'
          }
        }
      })

      .state('app.browse', {
        url: '/browse',
        views: {
          'menuContent': {
            templateUrl: 'templates/browse.html'
          }
        }
      })
      .state('app.main', {
        cache: false,
        url: '/main',
        views: {
          'menuContent': {
            templateUrl: 'templates/main.html',
            controller: 'MainCtrl'
          }
        }
      })

      .state('app.event', {
        url: '/event',
        views: {
          'menuContent': {
            templateUrl: 'templates/event.html',
            controller: 'EventCtrl'
          }
        }
      })

      .state('app.login', {
        url: '/login',
        views: {
          'menuContent': {
            templateUrl: 'templates/login.html',
          }
        }
      })

      .state('app.new_event', {
        url: '/new_event',
        views: {
          'menuContent': {
            templateUrl: 'templates/new_event.html',
            controller: 'CreateEventCtrl'
          }
        }
      })
//adding register controller to register page
      .state('app.register', {
        url: '/register',
        views: {
          'menuContent': {
            templateUrl: 'templates/register.html',

            controller: 'RegisterCtrl'
          }
        }
      })

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/main');
  });
<commit_msg>app.js replaced with newest version<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])

  .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);

      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });
  })

  .config(function($stateProvider, $urlRouterProvider) {
    $stateProvider

      .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'templates/menu.html',
        controller: 'AppCtrl'
      })

      .state('app.search', {
        url: '/search',
        views: {
          'menuContent': {
            templateUrl: 'templates/search.html'
          }
        }
      })

      .state('app.browse', {
        url: '/browse',
        views: {
          'menuContent': {
            templateUrl: 'templates/browse.html'
          }
        }
      })

      .state('app.start', {
        cache: false,
        url: '/start',
        views: {
          'menuContent': {
            templateUrl: 'templates/start.html',
            controller: 'StartCtrl'
          }
        }
      })

      .state('app.main', {
        cache: false,
        url: '/main',
        views: {
          'menuContent': {
            templateUrl: 'templates/main.html',
            controller: 'MainCtrl'
          }
        }
      })

      .state('app.event', {
        url: '/event',
        views: {
          'menuContent': {
            templateUrl: 'templates/event.html',
            controller: 'EventCtrl'
          }
        }
      })

      .state('app.new_event', {
        url: '/new_event',
        views: {
          'menuContent': {
            templateUrl: 'templates/new_event.html',
            controller: 'CreateEventCtrl'
          }
        }
      })

      .state('app.register', {
        url: '/register',
        views: {
          'menuContent': {
            templateUrl: 'templates/register.html',
            controller: 'RegisterCtrl'
          }
        }
      })

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/start');
  });
<|endoftext|>