<commit_before>'use strict';

angular.module('appointments.admin').controller('addAppointmentController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', 'participantsAdmin', 'appointmentAdmin', 'experimentsAdmin',
  function ($scope, $state, $http, $location, $window, Authentication, PasswordValidator, participantsAdmin, appointmentAdmin, experimentsAdmin) {
    $scope.authentication = Authentication;
    $scope.popoverMsg = PasswordValidator.getPopoverMsg();

    // Query appointments from DB
    appointmentAdmin.query(function (data) {
      $scope.appointments = data;
    });

    participantsAdmin.query(function (data) {
      console.log(data);
      if(data.length === 0){
        $scope.error = 'No Participants to schedule!';
      }else{
        $scope.error = null;
        $scope.participants= data;
      }
    });

    experimentsAdmin.query(function (data) {
      console.log(data);
      if(data.length === 0){
        $scope.error = 'No Experiments to schedule!';
      }else{
        $scope.error = null;
        /*
        var experimentStrings = {};
        for ( var i = 0; i < data.length; i++){
            var string = data[i].experiment_name;
            string = string.concat(':');
            for ( var j = 0; j < data[i].experiment_conditions.length; j++){
                string = string.concat(' '+ data[i].experiment_conditions[j]);
            }
            experimentStrings.data[i] = string;
        }
        console.log(experimentStrings);*/
        $scope.experiments = data;
      }
    });

    $('#datetimepicker11').datetimepicker({
      sideBySide: true
    });

    // Get an eventual error defined in the URL query string:
    $scope.error = $location.search().err;

    $scope.addAppointment = function (isValid) {
      console.log('ADD APPOINTMENT');
      var time = new Date();
      time.setTime(Date.parse($('#datetimepicker11').data('DateTimePicker').date()));
      var today = new Date();
      var duration = $scope.credentials.duration;
      var location = $scope.credentials.location;

      // Verify that date is not in the past
      if(time < today){
        $scope.error = 'Appointment can\'t be scheduled for the past!';
        return;
      }

      //Verify that there are no time conflicts
      for(var i = 0; i < $scope.appointments.length; i++){
        var startTime = new Date();
        startTime.setTime(Date.parse($scope.appointments[i].time));
        var endTime = new Date(startTime.getTime() + ($scope.appointments[i].duration*60000));
        console.log(startTime.getTime());
        console.log(endTime.getTime());
        console.log(time.getTime());
        console.log($scope.appointments[i].location);
        if ((time >= startTime) && (time < endTime)){
          console.log('Potential time conflict, checking location');
          if (location === $scope.appointments[i].location){
            $scope.error = 'There is a time conflict at this location';
            return;
          }
        }
      }

      $scope.error = null;

      $scope.credentials.time = time;
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'appointmentForm');
        console.log('NOT VALID');

        return false;
      }
      console.log($scope.credentials);

      $http.post('/api/appointments', $scope.credentials).success(function (response) {
        console.log('Sucess!');
        // And redirect to the previous or list of users
        $state.go('admin.appointments', $state.previous.params);
      }).error(function (response) {
        console.log('FAIL!');
        $scope.error = response.message;
      });
    };

  }
]);
<commit_msg>verify that a participant cannot be scheduled for two different appointments that are time-conflicting<commit_after>'use strict';

angular.module('appointments.admin').controller('addAppointmentController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', 'participantsAdmin', 'appointmentAdmin', 'experimentsAdmin',
  function ($scope, $state, $http, $location, $window, Authentication, PasswordValidator, participantsAdmin, appointmentAdmin, experimentsAdmin) {
    $scope.authentication = Authentication;
    $scope.popoverMsg = PasswordValidator.getPopoverMsg();

    // Query appointments from DB
    appointmentAdmin.query(function (data) {
      $scope.appointments = data;
    });

    participantsAdmin.query(function (data) {
      console.log(data);
      if(data.length === 0){
        $scope.error = 'No Participants to schedule!';
      }else{
        $scope.error = null;
        $scope.participants= data;
      }
    });

    experimentsAdmin.query(function (data) {
      console.log(data);
      if(data.length === 0){
        $scope.error = 'No Experiments to schedule!';
      }else{
        $scope.error = null;
        /*
        var experimentStrings = {};
        for ( var i = 0; i < data.length; i++){
            var string = data[i].experiment_name;
            string = string.concat(':');
            for ( var j = 0; j < data[i].experiment_conditions.length; j++){
                string = string.concat(' '+ data[i].experiment_conditions[j]);
            }
            experimentStrings.data[i] = string;
        }
        console.log(experimentStrings);*/
        $scope.experiments = data;
      }
    });

    $('#datetimepicker11').datetimepicker({
      sideBySide: true
    });

    // Get an eventual error defined in the URL query string:
    $scope.error = $location.search().err;

    $scope.addAppointment = function (isValid) {
      console.log('ADD APPOINTMENT');
      var time = new Date();
      time.setTime(Date.parse($('#datetimepicker11').data('DateTimePicker').date()));
      var today = new Date();
      var duration = $scope.credentials.duration;
      var location = $scope.credentials.location;
	  var participant = $scope.credentials.participant;

      // Verify that date is not in the past
      if(time < today){
        $scope.error = 'Appointment can\'t be scheduled for the past!';
        return;
      }

      //Verify that there are no time conflicts
      for(var i = 0; i < $scope.appointments.length; i++){
        var startTime = new Date();
        startTime.setTime(Date.parse($scope.appointments[i].time));
        var endTime = new Date(startTime.getTime() + ($scope.appointments[i].duration*60000));
        console.log(startTime.getTime());
        console.log(endTime.getTime());
        console.log(time.getTime());
        console.log($scope.appointments[i].location);
        if ((time >= startTime) && (time < endTime)){
          console.log('Potential time conflict, checking participant and location');
          if ($scope.appointments[i].participant._id === participant){
			$scope.error = 'This participant is already scheduled at this time!';
			return;
		  }
          if (location === $scope.appointments[i].location){
            $scope.error = 'There is a time conflict at this location';
            return;
          }
        }
      }

      $scope.error = null;

      $scope.credentials.time = time;
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'appointmentForm');
        console.log('NOT VALID');

        return false;
      }
      console.log($scope.credentials);

      $http.post('/api/appointments', $scope.credentials).success(function (response) {
        console.log('Sucess!');
        // And redirect to the previous or list of users
        $state.go('admin.appointments', $state.previous.params);
      }).error(function (response) {
        console.log('FAIL!');
        $scope.error = response.message;
      });
    };

  }
]);
<|endoftext|>


<commit_before>$(function(){

    var DEFAULT_TAG_THEME='facebook';
    var ALLOW_FREE_TAG=false;

    function TagPlugin(){
       this.tagContainer='';
    }

    TagPlugin.prototype.init=function(element){
       var tagUrl=element.meta.tagApi;
       this.tagContainer='#'+element.meta.tagContainer||element.id;
       if(!tagUrl){
           console.log('Unable to locate tag api url');
           return;
       }
       fetchInitTags(tagUrl,tagContainer);
    };

    TagPlugin.prototype.getData=function(element){
        var data={};
        var tags;
        var selectedTags;

        selectedTags=$(this.tagContainer).tokenInput('get');

        for(var index in selectedTags){
            tags.push(selectedTags[index].name);
        }

        data[element.id]=JSON.stringify(tags);

        return data;
    }

    var fetchInitTags=function(tagUrl,tagContainer){

        //Obtain all of the tags for the given asset type
        $.ajax({
            url : tagUrl,
            type : 'GET',
            success : function(response) {
                var tags = JSON.parse(response);
                $(tagContainer).tokenInput(tags, {
                    theme : DEFAULT_TAG_THEME,
                    allowFreeTagging :ALLOW_FREE_TAG
                });

            },
            error : function() {
                console.log('unable to fetch tag cloud for ' + type);
            }
        });
    }

    FormManager.register('TagPlugin',TagPlugin);
});<commit_msg>Added tag-plugin to handle tags<commit_after>$(function () {

    var DEFAULT_TAG_THEME = 'facebook';
    var ALLOW_FREE_TAG = true;

    function TagPlugin() {
        this.tagContainer = '';
        this.tagUrl = '';
    }

    TagPlugin.prototype.init = function (element) {
        //TODO: Replace where we get the asset type from
        var type = $('#meta-asset-type').val();
        this.tagUrl = element.meta.tagApi+type;
        this.tagContainer = '#' +element.id;
        if (!this.tagUrl) {
            console.log('Unable to locate tag api url');
            return;
        }
        fetchInitTags(this.tagUrl, this.tagContainer);
    };

    TagPlugin.prototype.getData = function (element) {
        var data = {};
        var tags=[];
        var selectedTags;

        selectedTags = $(this.tagContainer).tokenInput('get');

        for (var index in selectedTags) {
            tags.push(selectedTags[index].name);
        }

        data[element.id] = tags;

        return data;
    }

    var fetchInitTags = function (tagUrl, tagContainer) {

        //Obtain all of the tags for the given asset type
        $.ajax({
            url: tagUrl,
            type: 'GET',
            success: function (response) {
                var tags = JSON.parse(response);
                $(tagContainer).tokenInput(tags, {
                    theme: DEFAULT_TAG_THEME,
                    allowFreeTagging: ALLOW_FREE_TAG
                });

            },
            error: function () {
                console.log('unable to fetch tag cloud for ' + type);
            }
        });
    }

    FormManager.register('TagPlugin', TagPlugin);
});<|endoftext|>


<commit_before>
var video = null;
var mediaElement = document; // If not set, an event from any element will trigger a waitForEvent() callback.
var console = null;
var printFullTestDetails = true; // This is optionaly switched of by test whose tested values can differ. (see disableFullTestDetailsPrinting())
var Failed = false;

var track = null; // Current TextTrack being tested.
var cues = null; // Current TextTrackCueList being tested.
var numberOfTrackTests = 0;
var numberOfTracksLoaded = 0;

findMediaElement();
logConsole();

if (window.testRunner) {
    // Some track element rendering tests require text pixel dump.
    if (typeof requirePixelDump == "undefined")
        testRunner.dumpAsText();

    testRunner.waitUntilDone();
}

function disableFullTestDetailsPrinting()
{
    printFullTestDetails = false;
}

function enableFullTestDetailsPrinting()
{
    printFullTestDetails = true;
}

function logConsole()
{
    if (!console && document.body) {
        console = document.createElement('div');
        document.body.appendChild(console);
    }
    return console;
}

function findMediaElement()
{
    try {
        video = document.getElementsByTagName('video')[0];
        if (video)
            mediaElement = video;
    } catch (ex) { }
}

function testAndEnd(testFuncString)
{
    test(testFuncString, true);
}

function test(testFuncString, endit)
{
    logResult(eval(testFuncString), "TEST(" + testFuncString + ")");
    if (endit)
        endTest();
}

function testExpected(testFuncString, expected, comparison)
{
    try {
        var observed = eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
        return;
    }

    if (comparison === undefined)
        comparison = '==';

    var success = false;
    switch (comparison)
    {
        case '<':   success = observed <  expected; break;
        case '<=': success = observed <= expected; break;
        case '>':   success = observed >  expected; break;
        case '>=': success = observed >= expected; break;
        case '!=':  success = observed != expected; break;
        case '==': success = observed == expected; break;
        case '===': success = observed === expected; break;
    }

    reportExpected(success, testFuncString, comparison, expected, observed)
}

function testArraysEqual(testFuncString, expected)
{
    var observed;
    try {
        observed = eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
        return;
    }

    testExpected(testFuncString + ".length", expected.length);

    for (var i = 0; i < observed.length; i++) {
        testExpected(testFuncString + "[" + i + "]", expected[i]);
    }
}

var testNumber = 0;

function reportExpected(success, testFuncString, comparison, expected, observed)
{
    testNumber++;

    var msg = "Test " + testNumber;

    if (printFullTestDetails || !success)
        msg = "EXPECTED (" + testFuncString + " " + comparison + " '" + expected + "')";

    if (!success)
        msg +=  ", OBSERVED '" + observed + "'";

    logResult(success, msg);
}

function runSilently(testFuncString)
{
    if (printFullTestDetails)
        consoleWrite("RUN(" + testFuncString + ")");
    try {
        eval(testFuncString);
    } catch (ex) {
        if (!printFullTestDetails) {
            // No details were printed previous, give some now.
            // This will be helpful in case of error.
            logResult(Failed, "Error in RUN(" + testFuncString + "):");
        }
        logResult(Failed, ""+ex+"");
    }
}

function run(testFuncString)
{
    consoleWrite("RUN(" + testFuncString + ")");
    try {
        eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
    }
}

function waitForEventOnce(eventName, func, endit)
{
    waitForEvent(eventName, func, endit, true)
}

function waitForEventAndEnd(eventName, funcString)
{
    waitForEvent(eventName, funcString, true)
}

function waitForEvent(eventName, func, endit, oneTimeOnly, element)
{
    if (!element)
        element = mediaElement;

    function _eventCallback(event)
    {
        if (oneTimeOnly)
            element.removeEventListener(eventName, _eventCallback, true);

        consoleWrite("EVENT(" + eventName + ")");

        if (func)
            func(event);

        if (endit)
            endTest();
    }

    element.addEventListener(eventName, _eventCallback, true);
}

function waitForEventTestAndEnd(eventName, testFuncString)
{
    waitForEventAndTest(eventName, testFuncString, true);
}

function waitForEventAndFail(eventName)
{
    waitForEventAndTest(eventName, "false", true);
}

function waitForEventAndTest(eventName, testFuncString, endit)
{
    function _eventCallback(event)
    {
        logResult(eval(testFuncString), "EVENT(" + eventName + ") TEST(" + testFuncString + ")");
        if (endit)
            endTest();
    }

    mediaElement.addEventListener(eventName, _eventCallback, true);
}

function testDOMException(testString, exceptionString)
{
    try {
        eval(testString);
    } catch (ex) {
        var exception = ex;
    }
    logResult(exception instanceof DOMException && exception.code === eval(exceptionString),
        "TEST(" + testString + ") THROWS(" + exceptionString + ")");
}

function testException(testString, exceptionString) {
    try {
        eval(testString);
    } catch (ex) {
        var exception = ex;
    }
    logResult(exception !== undefined && exception == eval(exceptionString),
        "TEST(" + testString + ") THROWS(" + exceptionString + ")");
}

var testEnded = false;

function endTest()
{
    consoleWrite("END OF TEST");
    testEnded = true;
    if (window.testRunner)
        testRunner.notifyDone();
}

function endTestLater()
{
    setTimeout(endTest, 250);
}

function failTestIn(ms)
{
    setTimeout(function () {
        consoleWrite("FAIL: did not end fast enough");
        endTest();
    }, ms);
}

function failTest(text)
{
    logResult(Failed, text);
    endTest();
}

function logResult(success, text)
{
    if (success)
        consoleWrite(text + " OK");
    else
        consoleWrite(text + " FAIL");
}

function consoleWrite(text)
{
    if (testEnded)
        return;
    logConsole().innerHTML += text + "
";
}

function relativeURL(url)
{
    return url.substr(url.lastIndexOf('/media/')+7);
}

function isInTimeRanges(ranges, time)
{
    var i = 0;
    for (i = 0; i < ranges.length; ++i) {
        if (time >= ranges.start(i) && time <= ranges.end(i)) {
          return true;
        }
    }
    return false;
}

function testTracks(expected)
{
    tracks = video.textTracks;
    testExpected("tracks.length", expected.length);

    for (var i = 0; i < tracks.length; i++) {
        consoleWrite("
*** Testing text track " + i);

        track = tracks[i];
        for (j = 0; j < expected.tests.length; j++) {
            var test = expected.tests[j];
            testExpected("track." + test.property, test.values[i]);
        }
    }
}

function testCues(index, expected)
{
    consoleWrite("
*** Testing text track " + index);

    cues = video.textTracks[index].cues;
    testExpected("cues.length", expected.length);
    for (var i = 0; i < cues.length; i++) {
        for (j = 0; j < expected.tests.length; j++) {
            var test = expected.tests[j];
            testExpected("cues[" + i + "]." + test.property, test.values[i]);
        }
    }
}

function allTestsEnded()
{
    numberOfTrackTests--;
    if (numberOfTrackTests == 0)
        endTest();
}

function enableAllTextTracks()
{
    findMediaElement();
    for (var i = 0; i < video.textTracks.length; i++) {
        if (video.textTracks[i].mode == "disabled")
            video.textTracks[i].mode = "hidden";
    }
}

var requiredEvents = [];

function waitForEventsAndCall(eventList, func)
{
    function _eventCallback(event)
    {
        if (!requiredEvents.length)
            return;

        var index = requiredEvents.indexOf(event.type);
        if (index < 0)
            return;

        requiredEvents.splice(index, 1);
        if (requiredEvents.length)
            return;

        func();
    }

    requiredEvents = [];
    for (var i = 0; i < eventList.length; i++) {
        requiredEvents[i] = eventList[i][1];
        eventList[i][0].addEventListener(requiredEvents[i], _eventCallback, true);
    }
}
<commit_msg>Use  in consoleWrite() to improve media LayoutTests speed.<commit_after>
var video = null;
var mediaElement = document; // If not set, an event from any element will trigger a waitForEvent() callback.
var console = null;
var printFullTestDetails = true; // This is optionaly switched of by test whose tested values can differ. (see disableFullTestDetailsPrinting())
var Failed = false;

var track = null; // Current TextTrack being tested.
var cues = null; // Current TextTrackCueList being tested.
var numberOfTrackTests = 0;
var numberOfTracksLoaded = 0;

findMediaElement();
logConsole();

if (window.testRunner) {
    // Some track element rendering tests require text pixel dump.
    if (typeof requirePixelDump == "undefined")
        testRunner.dumpAsText();

    testRunner.waitUntilDone();
}

function disableFullTestDetailsPrinting()
{
    printFullTestDetails = false;
}

function enableFullTestDetailsPrinting()
{
    printFullTestDetails = true;
}

function logConsole()
{
    if (!console && document.body) {
        console = document.createElement('div');
        document.body.appendChild(console);
    }
    return console;
}

function findMediaElement()
{
    try {
        video = document.getElementsByTagName('video')[0];
        if (video)
            mediaElement = video;
    } catch (ex) { }
}

function testAndEnd(testFuncString)
{
    test(testFuncString, true);
}

function test(testFuncString, endit)
{
    logResult(eval(testFuncString), "TEST(" + testFuncString + ")");
    if (endit)
        endTest();
}

function testExpected(testFuncString, expected, comparison)
{
    try {
        var observed = eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
        return;
    }

    if (comparison === undefined)
        comparison = '==';

    var success = false;
    switch (comparison)
    {
        case '<':   success = observed <  expected; break;
        case '<=': success = observed <= expected; break;
        case '>':   success = observed >  expected; break;
        case '>=': success = observed >= expected; break;
        case '!=':  success = observed != expected; break;
        case '==': success = observed == expected; break;
        case '===': success = observed === expected; break;
    }

    reportExpected(success, testFuncString, comparison, expected, observed)
}

function testArraysEqual(testFuncString, expected)
{
    var observed;
    try {
        observed = eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
        return;
    }

    testExpected(testFuncString + ".length", expected.length);

    for (var i = 0; i < observed.length; i++) {
        testExpected(testFuncString + "[" + i + "]", expected[i]);
    }
}

var testNumber = 0;

function reportExpected(success, testFuncString, comparison, expected, observed)
{
    testNumber++;

    var msg = "Test " + testNumber;

    if (printFullTestDetails || !success)
        msg = "EXPECTED (" + testFuncString + " " + comparison + " '" + expected + "')";

    if (!success)
        msg +=  ", OBSERVED '" + observed + "'";

    logResult(success, msg);
}

function runSilently(testFuncString)
{
    if (printFullTestDetails)
        consoleWrite("RUN(" + testFuncString + ")");
    try {
        eval(testFuncString);
    } catch (ex) {
        if (!printFullTestDetails) {
            // No details were printed previous, give some now.
            // This will be helpful in case of error.
            logResult(Failed, "Error in RUN(" + testFuncString + "):");
        }
        logResult(Failed, ""+ex+"");
    }
}

function run(testFuncString)
{
    consoleWrite("RUN(" + testFuncString + ")");
    try {
        eval(testFuncString);
    } catch (ex) {
        consoleWrite(ex);
    }
}

function waitForEventOnce(eventName, func, endit)
{
    waitForEvent(eventName, func, endit, true)
}

function waitForEventAndEnd(eventName, funcString)
{
    waitForEvent(eventName, funcString, true)
}

function waitForEvent(eventName, func, endit, oneTimeOnly, element)
{
    if (!element)
        element = mediaElement;

    function _eventCallback(event)
    {
        if (oneTimeOnly)
            element.removeEventListener(eventName, _eventCallback, true);

        consoleWrite("EVENT(" + eventName + ")");

        if (func)
            func(event);

        if (endit)
            endTest();
    }

    element.addEventListener(eventName, _eventCallback, true);
}

function waitForEventTestAndEnd(eventName, testFuncString)
{
    waitForEventAndTest(eventName, testFuncString, true);
}

function waitForEventAndFail(eventName)
{
    waitForEventAndTest(eventName, "false", true);
}

function waitForEventAndTest(eventName, testFuncString, endit)
{
    function _eventCallback(event)
    {
        logResult(eval(testFuncString), "EVENT(" + eventName + ") TEST(" + testFuncString + ")");
        if (endit)
            endTest();
    }

    mediaElement.addEventListener(eventName, _eventCallback, true);
}

function testDOMException(testString, exceptionString)
{
    try {
        eval(testString);
    } catch (ex) {
        var exception = ex;
    }
    logResult(exception instanceof DOMException && exception.code === eval(exceptionString),
        "TEST(" + testString + ") THROWS(" + exceptionString + ")");
}

function testException(testString, exceptionString) {
    try {
        eval(testString);
    } catch (ex) {
        var exception = ex;
    }
    logResult(exception !== undefined && exception == eval(exceptionString),
        "TEST(" + testString + ") THROWS(" + exceptionString + ")");
}

var testEnded = false;

function endTest()
{
    consoleWrite("END OF TEST");
    testEnded = true;
    if (window.testRunner)
        testRunner.notifyDone();
}

function endTestLater()
{
    setTimeout(endTest, 250);
}

function failTestIn(ms)
{
    setTimeout(function () {
        consoleWrite("FAIL: did not end fast enough");
        endTest();
    }, ms);
}

function failTest(text)
{
    logResult(Failed, text);
    endTest();
}

function logResult(success, text)
{
    if (success)
        consoleWrite(text + " OK");
    else
        consoleWrite(text + " FAIL");
}

function consoleWrite(text)
{
    if (testEnded)
        return;
    var span = document.createElement("span");
    logConsole().appendChild(span);
    span.innerHTML = text + '
';
}

function relativeURL(url)
{
    return url.substr(url.lastIndexOf('/media/')+7);
}

function isInTimeRanges(ranges, time)
{
    var i = 0;
    for (i = 0; i < ranges.length; ++i) {
        if (time >= ranges.start(i) && time <= ranges.end(i)) {
          return true;
        }
    }
    return false;
}

function testTracks(expected)
{
    tracks = video.textTracks;
    testExpected("tracks.length", expected.length);

    for (var i = 0; i < tracks.length; i++) {
        consoleWrite("
*** Testing text track " + i);

        track = tracks[i];
        for (j = 0; j < expected.tests.length; j++) {
            var test = expected.tests[j];
            testExpected("track." + test.property, test.values[i]);
        }
    }
}

function testCues(index, expected)
{
    consoleWrite("
*** Testing text track " + index);

    cues = video.textTracks[index].cues;
    testExpected("cues.length", expected.length);
    for (var i = 0; i < cues.length; i++) {
        for (j = 0; j < expected.tests.length; j++) {
            var test = expected.tests[j];
            testExpected("cues[" + i + "]." + test.property, test.values[i]);
        }
    }
}

function allTestsEnded()
{
    numberOfTrackTests--;
    if (numberOfTrackTests == 0)
        endTest();
}

function enableAllTextTracks()
{
    findMediaElement();
    for (var i = 0; i < video.textTracks.length; i++) {
        if (video.textTracks[i].mode == "disabled")
            video.textTracks[i].mode = "hidden";
    }
}

var requiredEvents = [];

function waitForEventsAndCall(eventList, func)
{
    function _eventCallback(event)
    {
        if (!requiredEvents.length)
            return;

        var index = requiredEvents.indexOf(event.type);
        if (index < 0)
            return;

        requiredEvents.splice(index, 1);
        if (requiredEvents.length)
            return;

        func();
    }

    requiredEvents = [];
    for (var i = 0; i < eventList.length; i++) {
        requiredEvents[i] = eventList[i][1];
        eventList[i][0].addEventListener(requiredEvents[i], _eventCallback, true);
    }
}
<|endoftext|>


<commit_before>var sys = require("sys")
  , fs = require("fs")
  , path = require("path")
  , http = require("http")
  , ws = require('../lib/ws');

/*-----------------------------------------------
  logging:
-----------------------------------------------*/
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}

function timestamp() {
  var d = new Date();
  return [
    d.getDate(),
    months[d.getMonth()],
    [ pad(d.getHours())
    , pad(d.getMinutes())
    , pad(d.getSeconds())
    , (d.getTime() + "").substr( - 4, 4)
    ].join(':')
  ].join(' ');
};

function log(msg) {
  sys.puts(timestamp() + ' - ' + msg.toString());
};

function serveFile(req, res){
  if( req.url.indexOf("favicon") > -1 ){
    log("HTTP: "+req.socket.remotePort+", inbound request, served nothing, (favicon)");

    res.writeHead(200, {'Content-Type': 'image/x-icon', 'Connection': 'close', 'Content-Length': '0'});
    res.end("");
  } else {
    log("HTTP: "+req.socket.remotePort+", inbound request, served client.html");

    res.writeHead(200, {'Content-Type': 'text/html'});
    fs.createReadStream( path.normalize(path.join(__dirname, "client.html")), {
      'flags': 'r',
      'encoding': 'binary',
      'mode': 0666,
      'bufferSize': 4 * 1024
    }).addListener("data", function(chunk){
      res.write(chunk, 'binary');
    }).addListener("close",function() {
      res.end();
    });
  }
};

/*-----------------------------------------------
  Spin up our server:
-----------------------------------------------*/
var httpServer = http.createServer(serveFile);
var connections = 0;

var server = ws.createServer({
  debug: true
}, httpServer);

server.addListener("listening", function(){
  log("Listening for connections.");
});

// Handle WebSocket Requests
server.addListener("connection", function(conn){
//  log("opened connection: "+conn.id);

//  server.manager.metadata(conn.id, "messages", 0);
  log(connections++);
//  server.send(conn.id, "Connected as: "+conn.id);
//  conn.broadcast("<"+conn.id+"> connected");

  conn.addListener("message", function(message){
//    log("<"+conn.id+"> "+message);
    server.broadcast("<"+conn.id+"> "+message);
  });

  // var timer = setInterval(function(){
  //   if(conn._state != 4){
  //     clearInterval(timer);
  //   } else {
  //     conn.write("You have sent: "+server.manager.metadata(conn.id, "messages")+" messages");
  //   }
  // }, 1000);
});

server.addListener("close", function(conn){
//  log("closed connection: "+conn.id);
//  conn.broadcast("<"+conn.id+"> disconnected");
});

server.listen(8000);
// Handle HTTP Requests:

// This will hijack the http server, if the httpserver doesn't
// already respond to http.Server#request

// server.addListener("request", serveFile);
<commit_msg>Adding check for req.method<commit_after>var sys = require("sys")
  , fs = require("fs")
  , path = require("path")
  , http = require("http")
  , ws = require('../lib/ws');

/*-----------------------------------------------
  logging:
-----------------------------------------------*/
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}

function timestamp() {
  var d = new Date();
  return [
    d.getDate(),
    months[d.getMonth()],
    [ pad(d.getHours())
    , pad(d.getMinutes())
    , pad(d.getSeconds())
    , (d.getTime() + "").substr( - 4, 4)
    ].join(':')
  ].join(' ');
};

function log(msg) {
  sys.puts(timestamp() + ' - ' + msg.toString());
};

function serveFile(req, res){
  if(req.method == "GET"){
    if( req.url.indexOf("favicon") > -1 ){
      log("HTTP: inbound request, served nothing, (favicon)");

      res.writeHead(200, {'Content-Type': 'image/x-icon'});
      res.end("");
    } else {
      log("HTTP: inbound request, served client.html");

      res.writeHead(200, {'Content-Type': 'text/html'});
      fs.createReadStream( path.normalize(path.join(__dirname, "client.html")), {
        'flags': 'r',
        'encoding': 'binary',
        'mode': 0666,
        'bufferSize': 4 * 1024
      }).addListener("data", function(chunk){
        res.write(chunk, 'binary');
      }).addListener("close",function() {
        res.end();
      });
    }
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end();
  }
};

/*-----------------------------------------------
  Spin up our server:
-----------------------------------------------*/
var httpServer = http.createServer(serveFile);
var connections = 0;

var server = ws.createServer({
  debug: true
}, httpServer);

server.addListener("listening", function(){
  log("Listening for connections.");
});

// Handle WebSocket Requests
server.addListener("connection", function(conn){
//  log("opened connection: "+conn.id);

//  server.manager.metadata(conn.id, "messages", 0);
  log(connections++);
//  server.send(conn.id, "Connected as: "+conn.id);
//  conn.broadcast("<"+conn.id+"> connected");

  conn.addListener("message", function(message){
//    log("<"+conn.id+"> "+message);
    server.broadcast("<"+conn.id+"> "+message);
  });

  // var timer = setInterval(function(){
  //   if(conn._state != 4){
  //     clearInterval(timer);
  //   } else {
  //     conn.write("You have sent: "+server.manager.metadata(conn.id, "messages")+" messages");
  //   }
  // }, 1000);
});

server.addListener("close", function(conn){
//  log("closed connection: "+conn.id);
//  conn.broadcast("<"+conn.id+"> disconnected");
});

server.listen(8000);
// Handle HTTP Requests:

// This will hijack the http server, if the httpserver doesn't
// already respond to http.Server#request

// server.addListener("request", serveFile);
<|endoftext|>


<commit_before>/**
* Cuepoint definition
*/

_V_.Cuepoint = function(player, type, start, end, opts){
	//Copy attributes
    this.type = type;
    this.start = start;
    this.end = end;
    this.opts = opts;
    this.player = player;
    this.fired = false; //Set fired flag to false
    var self = this; //Copy this
    //Start listening to timepudate event
    this.player.addEvent("timeupdate", function(){
    	//Check if current time is between start and end
        if(this.currentTime() >= self.start && this.currentTime() < self.end){
            if(self.fired) //Do nothing if start has already been called
                return;
            self.fired = true; //Set fired flag to true
            self._start(); //Call start function
        }else{
            if(!self.fired) //Do nothing if end has already been called
                return;
            self.fired = false; //Set fired flat to false
            self._end(); //Call end function
        }
    })
};

//Cuepoint prototype
_V_.Cuepoint.prototype = {
    _start: function(){
        var e = new _V_.Event("cuepointStart");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    },
    _end: function(){
        var e = new _V_.Event("cuepointEnd");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    }
};

/**
* Webcast Component
*/
//Enable Webcast component
_V_.options.components['webcast'] = {
	components: {};
};

//Extends Component
_V_.Webcast = _V_.Component.extend({
    init: function (player, options){
        var p = this._super(player, options);
        //Init webcast
        new _V_.Cuepoint(player, "slideshows", 4, 10, {}); //Test

    },
    buildCSSClass: function(){
        return " vjs-webcast ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass(),
            innerHTML:''
        }, attrs);
        return this._super(type, attrs);
    }
});

/**
* SyncComponent definition
*/

_V_.SyncComponent = _V_.Component.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.SyncComponent.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
        var self = this;
        //Start listening to start cuepoint event
        player.addEvent("cuepointStart", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.start(c); //Call start function
        });
        //Start listenting to end cuepoint event
        player.addEvent("cuepointEnd", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.end(c); //Call end function
        });
    },
    start : function(c){
        console.log(c);
    },
    end : function (c){
        console.log(c);
    }
});
_V_.SyncComponent.options = {
	cuepointfilter : ".*"
};

//Enable slideshow component
_V_.options.components["webcast"].components["slideshow"]= {};

_V_.Slideshow = _V_.SyncComponent.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.Slideshow.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
    },
    buildCSSClass: function(){
        return this._super() +  " vjs-slideshow ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass()
        }, attrs);

        return this._super(type, attrs);
    },
    start : function (c){
    	this._super(c);
      	this.el.innerHTML = "
Slide in
"; //Testing
    },
    end: function(c){
    	this._super(c);
      	this.el.innerHTML = ""; //Testing
    }
});
_V_.Slideshow.options = {
	cuepointfilter : "slideshow"
};<commit_msg>Fixed token error<commit_after>/**
* Cuepoint definition
*/

_V_.Cuepoint = function(player, type, start, end, opts){
	//Copy attributes
    this.type = type;
    this.start = start;
    this.end = end;
    this.opts = opts;
    this.player = player;
    this.fired = false; //Set fired flag to false
    var self = this; //Copy this
    //Start listening to timepudate event
    this.player.addEvent("timeupdate", function(){
    	//Check if current time is between start and end
        if(this.currentTime() >= self.start && this.currentTime() < self.end){
            if(self.fired) //Do nothing if start has already been called
                return;
            self.fired = true; //Set fired flag to true
            self._start(); //Call start function
        }else{
            if(!self.fired) //Do nothing if end has already been called
                return;
            self.fired = false; //Set fired flat to false
            self._end(); //Call end function
        }
    })
};

//Cuepoint prototype
_V_.Cuepoint.prototype = {
    _start: function(){
        var e = new _V_.Event("cuepointStart");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    },
    _end: function(){
        var e = new _V_.Event("cuepointEnd");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    }
};

/**
* Webcast Component
*/
//Enable Webcast component
_V_.options.components['webcast'] = {
	components: {}
};

//Extends Component
_V_.Webcast = _V_.Component.extend({
    init: function (player, options){
        var p = this._super(player, options);
        //Init webcast
        new _V_.Cuepoint(player, "slideshows", 4, 10, {}); //Test

    },
    buildCSSClass: function(){
        return " vjs-webcast ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass(),
            innerHTML:''
        }, attrs);
        return this._super(type, attrs);
    }
});

/**
* SyncComponent definition
*/

_V_.SyncComponent = _V_.Component.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.SyncComponent.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
        var self = this;
        //Start listening to start cuepoint event
        player.addEvent("cuepointStart", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.start(c); //Call start function
        });
        //Start listenting to end cuepoint event
        player.addEvent("cuepointEnd", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.end(c); //Call end function
        });
    },
    start : function(c){
        console.log(c);
    },
    end : function (c){
        console.log(c);
    }
});
_V_.SyncComponent.options = {
	cuepointfilter : ".*"
};

//Enable slideshow component
_V_.options.components["webcast"].components["slideshow"]= {};

_V_.Slideshow = _V_.SyncComponent.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.Slideshow.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
    },
    buildCSSClass: function(){
        return this._super() +  " vjs-slideshow ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass()
        }, attrs);

        return this._super(type, attrs);
    },
    start : function (c){
    	this._super(c);
      	this.el.innerHTML = "
Slide in
"; //Testing
    },
    end: function(c){
    	this._super(c);
      	this.el.innerHTML = ""; //Testing
    }
});
_V_.Slideshow.options = {
	cuepointfilter : "slideshow"
};<|endoftext|>


<commit_before>import Immutable from 'immutable';
import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';

// ESLint can't resolve the module location when running on Travis, so ignore these lints.
// eslint-disable-next-line import/no-unresolved, import/extensions
import { ImmutableVirtualizedList } from 'react-native-immutable-list-view';

import style from './styles';

class ImmutableVirtualizedListExample extends Component {

  state = {
    listDataA: Immutable.List(['Simple', 'List', 'of', 'Items']),
    listDataB: Immutable.Range(1, 100),
  };

  changeDataA() {
    this.setState({
      listDataA: this.state.listDataA.set(3, 'This value was changed!'),
    });
  }

  changeDataB() {
    this.setState({
      listDataB: this.state.listDataB.toSeq().map((n) => n * 2),
    });
  }

  renderItem({ item }) {
    return <Text style={style.listRow}>{item}</Text>;
  }

  render() {
    const { listDataA, listDataB } = this.state;

    return (
      <View style={style.container}>
        <Text style={style.title}>
          ImmutableVirtualizedList Example
        </Text>
        <View style={style.sideBySideLists}>
          <View style={style.list}>
            <View style={style.button}>
              <Button
                onPress={() => this.changeDataA()}
                title="Update Data"
              />
            </View>
            <ImmutableVirtualizedList
              immutableData={listDataA}
              renderItem={this.renderItem}
            />
          </View>
          <View style={style.list}>
            <View style={style.button}>
              <Button
                onPress={() => this.changeDataB()}
                title="Update Data"
              />
            </View>
            <ImmutableVirtualizedList
              immutableData={listDataB}
              renderItem={this.renderItem}
            />
          </View>
        </View>
      </View>
    );
  }

}

export default ImmutableVirtualizedListExample;
<commit_msg>:package: [Example] Provide a keyExtractor for best-practice<commit_after>import Immutable from 'immutable';
import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';

// ESLint can't resolve the module location when running on Travis, so ignore these lints.
// eslint-disable-next-line import/no-unresolved, import/extensions
import { ImmutableVirtualizedList } from 'react-native-immutable-list-view';

import style from './styles';

class ImmutableVirtualizedListExample extends Component {

  state = {
    listDataA: Immutable.List(['Simple', 'List', 'of', 'Items']),
    listDataB: Immutable.Range(1, 100),
  };

  changeDataA() {
    this.setState({
      listDataA: this.state.listDataA.set(3, 'This value was changed!'),
    });
  }

  changeDataB() {
    this.setState({
      listDataB: this.state.listDataB.toSeq().map((n) => n * 2),
    });
  }

  renderItem({ item }) {
    return <Text style={style.listRow}>{item}</Text>;
  }

  render() {
    const { listDataA, listDataB } = this.state;

    return (
      <View style={style.container}>
        <Text style={style.title}>
          ImmutableVirtualizedList Example
        </Text>
        <View style={style.sideBySideLists}>
          <View style={style.list}>
            <View style={style.button}>
              <Button
                onPress={() => this.changeDataA()}
                title="Update Data"
              />
            </View>
            <ImmutableVirtualizedList
              immutableData={listDataA}
              renderItem={this.renderItem}
              keyExtractor={(_, index) => String(index)}
            />
          </View>
          <View style={style.list}>
            <View style={style.button}>
              <Button
                onPress={() => this.changeDataB()}
                title="Update Data"
              />
            </View>
            <ImmutableVirtualizedList
              immutableData={listDataB}
              renderItem={this.renderItem}
              keyExtractor={(_, index) => String(index)}
            />
          </View>
        </View>
      </View>
    );
  }

}

export default ImmutableVirtualizedListExample;
<|endoftext|>


<commit_before>import {h} from 'dom-chef';
import select from 'select-dom';
import {getRepoURL} from '../libs/page-detect';
import fetchApi from '../libs/api';
import {openIssue, closedIssue} from '../libs/icons';

let insertedSidebarItem;

const unsearchableCharactersRegex = /[^\p{Letter}\p{Number}\s]+/gu;
const latinCharactersRegex = /\p{Script=Latin}/u;

export function getSearchableWords(text) {
	return text
		.replace(unsearchableCharactersRegex, ' ') // Only leave letters, numbers and spaces
		.trim()
		.split(/\s+/) // Split words
		.filter(word => {
			// Drop possible "glue" words like articles only in Latin alphabets
			if (latinCharactersRegex.exec(word)) {
				return word.length > 2;
			}

			// Drop 1-digit numbers
			if (/\d/.exec(word)) {
				return word.length > 1;
			}
			return true;
		});
}

async function displayIssueSuggestions(title) {
	if (title.trim().length === 0) {
		return;
	}
	const words = getSearchableWords(title);
	if (words.length === 0) {
		return;
	}

	const repo = getRepoURL();
	const apiQuery = encodeURIComponent(`${words.join(' ')} repo:${repo} is:issue`);
	const response = await fetchApi(`search/issues?q=${apiQuery}&per_page=5`).catch(() => null);
	let sidebarItem;

	if (response && response.items && response.items.length > 0) {
		const {items: issues, total_count: totalCount} = response;
		const linkQuery = encodeURIComponent(`${words.join(' ')} is:issue`);

		sidebarItem = (

Possibly related issues

					{
						issues.map(issue => (

{issue.state === 'open' ? openIssue() : closedIssue()}

{issue.title}

						))
					}

				{
					issues.length < totalCount && (

							There are <a href={`/${repo}/issues?q=${linkQuery}`}>{totalCount - issues.length} more results.

					)
				}

		);
	}

	if (insertedSidebarItem) {
		insertedSidebarItem.remove();
	}
	if (sidebarItem) {
		select('.discussion-sidebar').prepend(sidebarItem);
		insertedSidebarItem = sidebarItem;
	}
}

export default function () {
	const title = select('#issue_title');
	title.addEventListener('blur', ({target}) => displayIssueSuggestions(target.value));
	title.addEventListener('focus', () => {
		if (insertedSidebarItem) {
			select('.Box', insertedSidebarItem).style.opacity = 0.7;
		}
	});
}
<commit_msg>Show colors of related issues (#1411)<commit_after>import {h} from 'dom-chef';
import select from 'select-dom';
import {getRepoURL} from '../libs/page-detect';
import fetchApi from '../libs/api';
import {openIssue, closedIssue} from '../libs/icons';

let insertedSidebarItem;

const unsearchableCharactersRegex = /[^\p{Letter}\p{Number}\s]+/gu;
const latinCharactersRegex = /\p{Script=Latin}/u;

export function getSearchableWords(text) {
	return text
		.replace(unsearchableCharactersRegex, ' ') // Only leave letters, numbers and spaces
		.trim()
		.split(/\s+/) // Split words
		.filter(word => {
			// Drop possible "glue" words like articles only in Latin alphabets
			if (latinCharactersRegex.exec(word)) {
				return word.length > 2;
			}

			// Drop 1-digit numbers
			if (/\d/.exec(word)) {
				return word.length > 1;
			}
			return true;
		});
}

async function displayIssueSuggestions(title) {
	if (title.trim().length === 0) {
		return;
	}
	const words = getSearchableWords(title);
	if (words.length === 0) {
		return;
	}

	const repo = getRepoURL();
	const apiQuery = encodeURIComponent(`${words.join(' ')} repo:${repo} is:issue`);
	const response = await fetchApi(`search/issues?q=${apiQuery}&per_page=5`).catch(() => null);
	let sidebarItem;

	if (response && response.items && response.items.length > 0) {
		const {items: issues, total_count: totalCount} = response;
		const linkQuery = encodeURIComponent(`${words.join(' ')} is:issue`);

		sidebarItem = (

Possibly related issues

					{
						issues.map(issue => (

{issue.state === 'open' ? openIssue() : closedIssue()}

{issue.title}

						))
					}

				{
					issues.length < totalCount && (

							There are <a href={`/${repo}/issues?q=${linkQuery}`}>{totalCount - issues.length} more results.

					)
				}

		);
	}

	if (insertedSidebarItem) {
		insertedSidebarItem.remove();
	}
	if (sidebarItem) {
		select('.discussion-sidebar').prepend(sidebarItem);
		insertedSidebarItem = sidebarItem;
	}
}

export default function () {
	const title = select('#issue_title');
	title.addEventListener('blur', ({target}) => displayIssueSuggestions(target.value));
	title.addEventListener('focus', () => {
		if (insertedSidebarItem) {
			select('.Box', insertedSidebarItem).style.opacity = 0.7;
		}
	});
}
<|endoftext|>


<commit_before>import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
import observeEl from '../libs/simplified-element-observer';

export default function () {
	if (!pageDetect.isPR()) {
		return;
	}

	observeEl('.js-discussion', () => {
		const deployments = select.all('.discussion-item .deployment-meta');
		deployments.pop(); // Don't hide the last deployment, even if it is inactive

		for (const deployment of deployments) {
			if (select.exists('.is-inactive', deployment)) {
				deployment.closest('.discussion-item').classList.add('rgh-inactive-deployment');
			}
		}
	});
}
<commit_msg>Handle conversation updates for hide-active-deployments (#1658)<commit_after>import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
import onNewComments from '../libs/on-new-comments';

export default function () {
	if (!pageDetect.isPR()) {
		return;
	}

	onNewComments(() => {
		const deployments = select.all('.discussion-item .deployment-meta');
		deployments.pop(); // Don't hide the last deployment, even if it is inactive

		for (const deployment of deployments) {
			if (select.exists('.is-inactive', deployment)) {
				deployment.closest('.discussion-item').classList.add('rgh-inactive-deployment');
			}
		}
	});
}
<|endoftext|>


<commit_before>var rZ = 1;
var height = 300;

var svg = d3.select('#newton')
  .append('svg')
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .append('g')
    .attr("transform", "scale(" + 1/rZ + ")")

var points = d3.range(-3, 6, .005)

function phi(x){ return x*x - 5; }
function toCord(point){ return [x(point[0]), y(point[1])]; }
function xToPoint(x){ return [x, phi(x)]; }
var xPosToCord = _.compose(toCord, xToPoint);

function positionCircle(selection, xPos){
  selection.attr({cx: x(xPos), cy: y(phi(xPos))})
}

var xCur = .5
    xVals = [xCur],
    e = .001;
while (Math.abs(_.last(xVals) - xCur) > e || xVals.length === 1){
  xCur = _.last(xVals);
  xVals.push(-phi(xCur)/(2*xCur) + xCur);
}

var rows = d3.select('table').style('margin-top', -height + 'px')
    .select('tbody').selectAll('tr').remove()
    .data(xVals).enter()
  .append('tr')
rows.append('td').text(function(d, i){ return i; })
rows.append('td').text(d3.format('.4f'))
rows.append('td').text(_.compose(d3.format('.4f'), phi))

var x = d3.scale.linear()
    .domain(d3.extent(points))
    .range([0, width*rZ])

var y = d3.scale.linear()
    .domain(d3.extent(points, phi))
    .range([height*rZ, 0])

svg.append('path')
    .attr('d', d3.svg.line().x(x).y(_.compose(y, phi))(points))

svg.append('path')
    .attr('d', ['M', [0, y(0)], 'L', [width, y(0)]].join(''))
svg.append('path')
    .attr('d', ['M', [x(0), 0], 'L', [x(0), height]].join(''))

var activeCircle = svg.append('circle')
    .attr('r', 10)
    .call(positionCircle, xVals[0])
    .classed('down', true)
    .on('mouseenter', update)

var n = 0;
var zoom = 1/rZ;
var resetNext = false;

scaleToZoom();
function update(){
  if (!activeCircle.classed('down')) return  //exit if animation in progress
  if (resetNext){
    //TODO add animation
    //wrap everything in a function and recall
    return svg.selectAll('*').remove();
  }
  if (n < xVals.length - 3){
    n++;
  } else{
    n = 0;
    zoom = 1;
    svg.transition().duration(1000)
        .each(scaleToZoom)
        .attr('transform', 'scale(1)')
    return resetNext = true;
  }
  var prev = xToPoint(xVals[n - 1]),
      cur = xToPoint(xVals[n]),
      next = xToPoint(xVals[n + 1]);

  var xInView = xVals.slice(n, n + 3).concat(_.last(xVals)),
      xRange = d3.extent(xInView, x),
      yRange = d3.extent(xInView, _.compose(y, phi));

  svg.transition().duration(1000)
      .each(function(){
        activeCircle.attr('class', 'inactive')

        svg.append('path').classed('tangent', true).style('stroke-width', 1/zoom)
            .attr('d', ['M', toCord(prev), 'L', toCord(prev)].join(''))
          .transition()
            .attr('d', ['M', toCord(prev), 'L', toCord([cur[0], 0])].join(''))
      })
    .transition()
      .each(function(){
        svg.append('path').classed('vertical', true).style('stroke-width', 1/zoom)
            .attr('d', ['M', toCord([cur[0], 0]), 'L', toCord([cur[0], 0])].join(''))
          .transition()
            .attr('d', ['M', toCord([cur[0], 0]), 'L', toCord(cur)].join(''))

        svg.append('g')
            .attr('transform', 'translate(' + toCord([cur[0], 0]) + ')')
          .append('text')
            .text(d3.format('.4f')(cur[0]))
            .attr('transform', 'scale(' + 1/zoom + ')')
            .style('text-anchor', cur[0] < next[0] ? 'start' : 'end')
      })
    .transition()//.ease('linear')
      .each(function(){
        activeCircle.attr('class', 'inactive')
          .transition().tween('position', function(){
            var i = d3.interpolate(prev[0], cur[0]);
            return function(t){
              activeCircle.call(positionCircle, i(t));
            }
          })
      })
    .transition()
      .each(function(){
        console.log(n);
        var xInView = xVals.slice(n - 1, n + 3).concat(_.last(xVals)),
            xRange = d3.extent(xInView, x),
            yRange = d3.extent(xInView, _.compose(y, phi)),
            zWidth  = xRange[1] - xRange[0],
            zHeight = yRange[1] - yRange[0];

        var oldZoom = zoom;
        zoom = Math.min(width/zWidth, height/zHeight)/rZ;
        console.log(zoom);
        //center ranges
        var x0 = xRange[0] - (width/zoom - zWidth)/2,
            y0 = yRange[0] - (height/zoom - zHeight)/2;

        activeCircle.transition()
            .attr('r', 10/zoom)

        svg.selectAll('path').transition()
            .style('stroke-width', 1/zoom)

        svg.selectAll('text').transition()
            .attr('transform', 'scale(' + 1/zoom + ')')

        svg.transition()
            .tween('transform', function(){
              var i = d3.interpolate(1/oldZoom, 1/zoom);
              return function(t){
                var z = 1/i(t);
                console.log(z);
                return ['translate(', -x0*z, ',', -y0*z, ')scale(', z, ')'].join('')
              }
            })
            .attr('transform', ['translate(', -x0*zoom, ',', -y0*zoom, ')scale(', zoom, ')'].join(''))

        activeCircle.transition().attr('class', 'inactive').transition().attr('class', 'down');
      })

}

function scaleToZoom(){
  activeCircle.transition()
      .attr('r', 10/zoom)

  svg.selectAll('path').transition()
      .style('stroke-width', 1/zoom)

  svg.selectAll('text').transition()
      .attr('transform', 'scale(' + 1/zoom + ')')
}

//todo add shawdo circle
//keep list of previous poinstsn
//adjust function
<commit_msg>more zoom adjustments<commit_after>var rZ = 200;
var height = 300;

var svg = d3.select('#newton')
  .append('svg')
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .append('g')
    .attr("transform", "scale(" + 1/rZ + ")")

var points = d3.range(-3, 6, .005)

function phi(x){ return x*x - 5; }
function toCord(point){ return [x(point[0]), y(point[1])]; }
function xToPoint(x){ return [x, phi(x)]; }
var xPosToCord = _.compose(toCord, xToPoint);

function positionCircle(selection, xPos){
  selection.attr({cx: x(xPos), cy: y(phi(xPos))})
}

var xCur = .5
    xVals = [xCur],
    e = .000000000001;
while (Math.abs(_.last(xVals) - xCur) > e || xVals.length === 1){
  xCur = _.last(xVals);
  xVals.push(-phi(xCur)/(2*xCur) + xCur);
}

var rows = d3.select('table').style('margin-top', -height + 'px')
    .select('tbody').selectAll('tr').remove()
    .data(xVals).enter()
  .append('tr')
rows.append('td').text(function(d, i){ return i; })
rows.append('td').text(d3.format('.10f'))
rows.append('td').text(_.compose(d3.format('.10f'), phi))

var x = d3.scale.linear()
    .domain(d3.extent(points))
    .range([0, width*rZ])

var y = d3.scale.linear()
    .domain(d3.extent(points, phi))
    .range([height*rZ, 0])

svg.append('path')
    .attr('d', d3.svg.line().x(x).y(_.compose(y, phi))(points))

svg.append('path')
    .attr('d', ['M', [0, y(0)], 'L', [width*rZ, y(0)]].join(''))
svg.append('path')
    .attr('d', ['M', [x(0), 0], 'L', [x(0), height*rZ]].join(''))

var activeCircle = svg.append('circle')
    .attr('r', 10)
    .call(positionCircle, xVals[0])
    .classed('down', true)
    .on('mouseenter', update)

var n = 0;
var zoom = 1/rZ;
var resetNext = false;

scaleToZoom();
function update(){
  if (!activeCircle.classed('down')) return  //exit if animation in progress
  if (resetNext){
    //TODO add animation
    //wrap everything in a function and recall
    return svg.selectAll('*').remove();
  }
  if (n < xVals.length - 3){
    n++;
  } else{
    n = 0;
    zoom = 1;
    svg.transition().duration(1000)
        .each(scaleToZoom)
        .attr('transform', 'scale(1)')
    return resetNext = true;
  }
  var prev = xToPoint(xVals[n - 1]),
      cur = xToPoint(xVals[n]),
      next = xToPoint(xVals[n + 1]);

  var xInView = xVals.slice(n, n + 3).concat(_.last(xVals)),
      xRange = d3.extent(xInView, x),
      yRange = d3.extent(xInView, _.compose(y, phi));

  svg.transition().duration(1000)
      .each(function(){
        activeCircle.attr('class', 'inactive')

        svg.append('path').classed('tangent', true).style('stroke-width', 1/zoom)
            .attr('d', ['M', toCord(prev), 'L', toCord(prev)].join(''))
          .transition()
            .attr('d', ['M', toCord(prev), 'L', toCord([cur[0], 0])].join(''))
      })
    .transition()
      .each(function(){
        svg.append('path').classed('vertical', true).style('stroke-width', 1/zoom)
            .attr('d', ['M', toCord([cur[0], 0]), 'L', toCord([cur[0], 0])].join(''))
          .transition()
            .attr('d', ['M', toCord([cur[0], 0]), 'L', toCord(cur)].join(''))

        svg.append('g')
            .attr('transform', 'translate(' + toCord([cur[0], 0]) + ')')
          .append('text')
            .text(d3.format('.10f')(cur[0]))
            .attr('transform', 'scale(' + 1/zoom + ')')
            .style('text-anchor', cur[0] < next[0] ? 'start' : 'end')
      })
    .transition()//.ease('linear')
      .each(function(){
        activeCircle.attr('class', 'inactive')
          .transition().tween('position', function(){
            var i = d3.interpolate(prev[0], cur[0]);
            return function(t){
              activeCircle.call(positionCircle, i(t));
            }
          })
      })
    .transition()
      .each(function(){
        console.log(n);
        var xInView = xVals.slice(n - 1, n + 3).concat(_.last(xVals)),
            xRange = d3.extent(xInView, x),
            yRange = d3.extent(xInView, _.compose(y, phi)),
            zWidth  = xRange[1] - xRange[0],
            zHeight = yRange[1] - yRange[0];

        var oldZoom = zoom;
        zoom = Math.min(width/zWidth, height/zHeight);
        console.log(zoom);
        //center ranges
        var x0 = xRange[0] - (width/zoom - zWidth)/2,
            y0 = yRange[0] - (height/zoom - zHeight)/2;

        activeCircle.transition()
            .attr('r', 10/zoom)

        svg.selectAll('path').transition()
            .style('stroke-width', 1/zoom)

        svg.selectAll('text').transition()
            .attr('transform', 'scale(' + 1/zoom + ')')

        svg.transition()
            .tween('transform', function(){
              var i = d3.interpolate(1/oldZoom, 1/zoom);
              return function(t){
                var z = 1/i(t);
                //console.log(z);
                return ['translate(', -x0*z, ',', -y0*z, ')scale(', z, ')'].join('')
              }
            })
            .attr('transform', ['translate(', -x0*zoom, ',', -y0*zoom, ')scale(', zoom, ')'].join(''))

        activeCircle.transition().attr('class', 'inactive').transition().attr('class', 'down');
      })

}

function scaleToZoom(){
  activeCircle.transition()
      .attr('r', 10/zoom)

  svg.selectAll('path').transition()
      .style('stroke-width', 1/zoom)

  svg.selectAll('text').transition()
      .attr('transform', 'scale(' + 1/zoom + ')')
}

//todo add shawdo circle
//keep list of previous poinstsn
//adjust function
<|endoftext|>


<commit_before>import * as jsdiff from "diff";

export default function mergeText(stimpak, newFile, oldFile, done) {
	const oldContent = oldFile.contents.toString();
	const newContent = newFile.contents.toString();

	const differences = jsdiff.diffLines(
		oldContent,
		newContent
	);

	console.log({
		differences
	});

	const mergedContent = differences
	//.filter(difference => !difference.removed)
	.map(difference => {
		return difference.value;
	}).join("");

	newFile.contents = new Buffer(mergedContent);

	done(null, newFile);
}
<commit_msg>removed a stray console.log<commit_after>import * as jsdiff from "diff";

export default function mergeText(stimpak, newFile, oldFile, done) {
	const oldContent = oldFile.contents.toString();
	const newContent = newFile.contents.toString();

	const differences = jsdiff.diffLines(
		oldContent,
		newContent
	);

	const mergedContent = differences
	//.filter(difference => !difference.removed)
	.map(difference => {
		return difference.value;
	}).join("");

	newFile.contents = new Buffer(mergedContent);

	done(null, newFile);
}
<|endoftext|>


<commit_before>/**
 * @flow
 *
 * An editor for individual building schedules.
 */

import React from 'react'
import xor from 'lodash/xor'
import {View, ScrollView, Platform, Text, StyleSheet} from 'react-native'
import moment from 'moment-timezone'
import {TableView, Section, Cell} from 'react-native-tableview-simple'
import type {SingleBuildingScheduleType, DayOfWeekEnumType} from '../types'
import {Row} from '../../components/layout'
import type {TopLevelViewPropsType} from '../../types'
import {parseHours, blankSchedule} from '../lib'
import * as c from '../../components/colors'
import {DatePicker} from '../../components/datepicker'
import {Touchable} from '../../components/touchable'
import {DeleteButtonCell} from '../../components/cells/delete-button'
import {CellToggle} from '../../components/cells/toggle'
import {ListSeparator} from '../../components/list'

export class BuildingHoursScheduleEditorView extends React.PureComponent {
  static navigationOptions = {
    title: 'Edit Schedule',
  }

  props: TopLevelViewPropsType & {
    navigation: {
      state: {
        params: {
          set: SingleBuildingScheduleType,
          onEditSet: (set: SingleBuildingScheduleType) => any,
          onDeleteSet: () => any,
        },
      },
    },
  }

  state: {
    set: ?SingleBuildingScheduleType,
  } = {
    set: this.props.navigation.state.params.initialSet,
  }

  delete = () => {
    this.props.navigation.state.params.onDeleteSet()
    this.props.navigation.goBack()
  }

  onChangeDays = (newDays: DayOfWeekEnumType[]) => {
    this.setState(
      state => ({...state, set: {...state.set, days: newDays}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  onChangeOpen = (newDate: moment) => {
    this.setState(
      state => ({...state, set: {...state.set, from: newDate.format('h:mma')}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  onChangeClose = (newDate: moment) => {
    this.setState(
      state => ({...state, set: {...state.set, to: newDate.format('h:mma')}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  render() {
    const set = this.state.set || blankSchedule()

    const {open, close} = parseHours(set, moment())

    return (
      <ScrollView>
        <TableView>

            <WeekToggles days={set.days} onChangeDays={this.onChangeDays} />

            <DatePickerCell
              title="Open"
              date={open}
              onChange={this.onChangeOpen}
            />
            <DatePickerCell
              title="Close"
              date={close}
              onChange={this.onChangeClose}
            />

            <DeleteButtonCell title="Delete Hours" onPress={this.delete} />

        </TableView>
      </ScrollView>
    )
  }
}

class WeekTogglesIOS extends React.PureComponent {
  props: {days: DayOfWeekEnumType[], onChangeDays: (DayOfWeekEnumType[]) => any}

  toggleDay = day => {
    this.props.onChangeDays(xor(this.props.days, [day]))
  }

  render() {
    const allDays = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

    return (
      <Row justifyContent="center" alignItems="stretch">
        {allDays.map(day =>
          <ToggleButton
            key={day}
            text={day}
            active={this.props.days.includes(day)}
            onPress={this.toggleDay}
          />,
        )}
      </Row>
    )
  }
}

class WeekTogglesAndroid extends React.PureComponent {
  props: {days: DayOfWeekEnumType[], onChangeDays: (DayOfWeekEnumType[]) => any}

  toggleDay = day => {
    this.props.onChangeDays(xor(this.props.days, [day]))
  }

  render() {
    const allDays = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

    return (
      <View>
        {allDays.map((day, i) =>
          <View key={day}>
            <CellToggle
              key={day}
              label={day}
              value={this.props.days.includes(day)}
              onChange={() => this.toggleDay(day)}
            />
            {i === allDays.length - 1 ? null : <ListSeparator force={true} />}
          </View>,
        )}
      </View>
    )
  }
}

class ToggleButton extends React.PureComponent {
  props: {
    active: boolean,
    text: string,
    onPress: (newState: string) => any,
  }

  onPress = () => this.props.onPress(this.props.text)

  render() {
    const {text, active} = this.props
    return (
      <Touchable
        highlight={false}
        containerStyle={[styles.dayWrapper, active && styles.activeDay]}
        onPress={this.onPress}
      >
        <Text style={[styles.dayText, active && styles.activeDayText]}>
          {text}
        </Text>
      </Touchable>
    )
  }
}

const WeekToggles = Platform.OS === 'ios' ? WeekTogglesIOS : WeekTogglesAndroid

class DatePickerCell extends React.PureComponent {
  props: {
    date: moment,
    title: string,
    onChange?: (date: moment) => any,
  }

  _picker: any
  openPicker = () => this._picker.onPressDate()

  getRef = (ref: any) => (this._picker = ref)

  onChange = (newDate: Date) => {
    const oldMoment = moment(this.props.date)
    const newMoment = moment(newDate)

    oldMoment.hours(newMoment.hours())
    oldMoment.minutes(newMoment.minutes())

    this.props.onChange && this.props.onChange(newDate)
  }

  render() {
    const format = 'h:mma'
    // We need to negate the offset, because moment inverts the offset for
    // POSIX compatability. So, GMT-5 (CST) is shown to be GMT+5.
    const dateInUnixMs = this.props.date.valueOf()
    const tzOffset = -moment.tz.zone('America/Winnipeg').offset(dateInUnixMs)

    const accessory = (
      <DatePicker
        ref={this.getRef}
        initialDate={this.props.date.toDate()}
        minuteInterval={5}
        mode="time"
        format={format}
        timeZoneOffsetInMinutes={tzOffset}
        onDateChange={this.onChange}
      />
    )

    return (
      <Cell
        title={this.props.title}
        cellStyle="RightDetail"
        cellAccessoryView={accessory}
        onPress={this.openPicker}
      />
    )
  }
}

const styles = StyleSheet.create({
  dayWrapper: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 10,
    paddingHorizontal: 2,
    backgroundColor: c.white,
  },
  activeDay: {
    backgroundColor: c.brickRed,
  },
  dayText: {
    fontSize: 16,
  },
  activeDayText: {
    color: c.white,
  },
})
<commit_msg>force onChange to be provided to DatePickerRow<commit_after>/**
 * @flow
 *
 * An editor for individual building schedules.
 */

import React from 'react'
import xor from 'lodash/xor'
import {View, ScrollView, Platform, Text, StyleSheet} from 'react-native'
import moment from 'moment-timezone'
import {TableView, Section, Cell} from 'react-native-tableview-simple'
import type {SingleBuildingScheduleType, DayOfWeekEnumType} from '../types'
import {Row} from '../../components/layout'
import type {TopLevelViewPropsType} from '../../types'
import {parseHours, blankSchedule} from '../lib'
import * as c from '../../components/colors'
import {DatePicker} from '../../components/datepicker'
import {Touchable} from '../../components/touchable'
import {DeleteButtonCell} from '../../components/cells/delete-button'
import {CellToggle} from '../../components/cells/toggle'
import {ListSeparator} from '../../components/list'

export class BuildingHoursScheduleEditorView extends React.PureComponent {
  static navigationOptions = {
    title: 'Edit Schedule',
  }

  props: TopLevelViewPropsType & {
    navigation: {
      state: {
        params: {
          set: SingleBuildingScheduleType,
          onEditSet: (set: SingleBuildingScheduleType) => any,
          onDeleteSet: () => any,
        },
      },
    },
  }

  state: {
    set: ?SingleBuildingScheduleType,
  } = {
    set: this.props.navigation.state.params.initialSet,
  }

  delete = () => {
    this.props.navigation.state.params.onDeleteSet()
    this.props.navigation.goBack()
  }

  onChangeDays = (newDays: DayOfWeekEnumType[]) => {
    this.setState(
      state => ({...state, set: {...state.set, days: newDays}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  onChangeOpen = (newDate: moment) => {
    this.setState(
      state => ({...state, set: {...state.set, from: newDate.format('h:mma')}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  onChangeClose = (newDate: moment) => {
    this.setState(
      state => ({...state, set: {...state.set, to: newDate.format('h:mma')}}),
      () => this.props.navigation.state.params.onEditSet(this.state.set),
    )
  }

  render() {
    const set = this.state.set || blankSchedule()

    const {open, close} = parseHours(set, moment())

    return (
      <ScrollView>
        <TableView>

            <WeekToggles days={set.days} onChangeDays={this.onChangeDays} />

            <DatePickerCell
              title="Open"
              date={open}
              onChange={this.onChangeOpen}
            />
            <DatePickerCell
              title="Close"
              date={close}
              onChange={this.onChangeClose}
            />

            <DeleteButtonCell title="Delete Hours" onPress={this.delete} />

        </TableView>
      </ScrollView>
    )
  }
}

class WeekTogglesIOS extends React.PureComponent {
  props: {days: DayOfWeekEnumType[], onChangeDays: (DayOfWeekEnumType[]) => any}

  toggleDay = day => {
    this.props.onChangeDays(xor(this.props.days, [day]))
  }

  render() {
    const allDays = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

    return (
      <Row justifyContent="center" alignItems="stretch">
        {allDays.map(day =>
          <ToggleButton
            key={day}
            text={day}
            active={this.props.days.includes(day)}
            onPress={this.toggleDay}
          />,
        )}
      </Row>
    )
  }
}

class WeekTogglesAndroid extends React.PureComponent {
  props: {days: DayOfWeekEnumType[], onChangeDays: (DayOfWeekEnumType[]) => any}

  toggleDay = day => {
    this.props.onChangeDays(xor(this.props.days, [day]))
  }

  render() {
    const allDays = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

    return (
      <View>
        {allDays.map((day, i) =>
          <View key={day}>
            <CellToggle
              key={day}
              label={day}
              value={this.props.days.includes(day)}
              onChange={() => this.toggleDay(day)}
            />
            {i === allDays.length - 1 ? null : <ListSeparator force={true} />}
          </View>,
        )}
      </View>
    )
  }
}

class ToggleButton extends React.PureComponent {
  props: {
    active: boolean,
    text: string,
    onPress: (newState: string) => any,
  }

  onPress = () => this.props.onPress(this.props.text)

  render() {
    const {text, active} = this.props
    return (
      <Touchable
        highlight={false}
        containerStyle={[styles.dayWrapper, active && styles.activeDay]}
        onPress={this.onPress}
      >
        <Text style={[styles.dayText, active && styles.activeDayText]}>
          {text}
        </Text>
      </Touchable>
    )
  }
}

const WeekToggles = Platform.OS === 'ios' ? WeekTogglesIOS : WeekTogglesAndroid

class DatePickerCell extends React.PureComponent {
  props: {
    date: moment,
    title: string,
    onChange: (date: moment) => any,
  }

  _picker: any
  openPicker = () => this._picker.onPressDate()

  getRef = (ref: any) => (this._picker = ref)

  onChange = (newDate: Date) => {
    const oldMoment = moment()
    const changedMoment = moment(newDate)

    oldMoment.hours(changedMoment.hours())
    oldMoment.minutes(changedMoment.minutes())

    this.props.onChange(oldMoment)
  }

  render() {
    const format = 'h:mma'
    // We need to negate the offset, because moment inverts the offset for
    // POSIX compatability. So, GMT-5 (CST) is shown to be GMT+5.
    const dateInUnixMs = this.props.date.valueOf()
    const tzOffset = -moment.tz.zone('America/Winnipeg').offset(dateInUnixMs)

    const accessory = (
      <DatePicker
        ref={this.getRef}
        initialDate={this.props.date.toDate()}
        minuteInterval={5}
        mode="time"
        format={format}
        timeZoneOffsetInMinutes={tzOffset}
        onDateChange={this.onChange}
      />
    )

    return (
      <Cell
        title={this.props.title}
        cellStyle="RightDetail"
        cellAccessoryView={accessory}
        onPress={this.openPicker}
      />
    )
  }
}

const styles = StyleSheet.create({
  dayWrapper: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 10,
    paddingHorizontal: 2,
    backgroundColor: c.white,
  },
  activeDay: {
    backgroundColor: c.brickRed,
  },
  dayText: {
    fontSize: 16,
  },
  activeDayText: {
    color: c.white,
  },
})
<|endoftext|>


<commit_before>

var firedax = {
    init: require('./src/_init/init'),
    hello: require('./src/hello/hello'),
};

module.exports = firedax;<commit_msg>test new env vars<commit_after>

var firedax = {
    init: require('./src/_init/init'),
    hello: require('./src/hello/hello'),
};

module.exports = firedax;<|endoftext|>


<commit_before>var fs = require('fs');
var SandCastle = require('../lib').SandCastle;

var sandcastle = new SandCastle({
  api: './stateApi.js'
});

var script = sandcastle.createScript("\
  exports.main = {\
    foo: function() {\
      setState({ fooName: name });\
      exit('Hello ' + name + '!');\
    },\
    bar: function() {\
      var state = getState();\
      state.barName = name;\
      setState(state);\
      \
      exit('Hello ' + name + '! Your old name was: ' + state.fooName);\
    },\
    hello: function() {\
      var state = getState();\
      exit('Hey ' + name + '! You changed your name from ' + state.fooName + ' to ' + state.barName + '!');\
    }\
  }\
");

script.on('exit', function (err, output, methodName) {
  console.log(output);

  run();
});

var start = 0;
var methodsToCall = [
  {
    method: 'foo',
    name: 'Foo'
  },
  {
    method: 'bar',
    name: 'Bar'
  },
  {
    method: 'hello',
    name: 'Hello'
  }
];
var run = function() {
  if (start < methodsToCall.length) {
    script.run('main.' + methodsToCall[start].method, { name: methodsToCall[start].name });
    start++;
  }
};

run();<commit_msg>white-space fix.<commit_after>var fs = require('fs');
var SandCastle = require('../lib').SandCastle;

var sandcastle = new SandCastle({
  api: './stateApi.js'
});

var script = sandcastle.createScript("\
  exports.main = {\
    foo: function() {\
      setState({ fooName: name });\
      exit('Hello ' + name + '!');\
    },\
    bar: function() {\
      var state = getState();\
      state.barName = name;\
      setState(state);\
      \
      exit('Hello ' + name + '! Your old name was: ' + state.fooName);\
    },\
    hello: function() {\
      var state = getState();\
      exit('Hey ' + name + '! You changed your name from ' + state.fooName + ' to ' + state.barName + '!');\
    }\
  }\
");

script.on('exit', function (err, output, methodName) {
  console.log(output);

  run();
});

var start = 0;
var methodsToCall = [
  {
    method: 'foo',
    name: 'Foo'
  },
  {
    method: 'bar',
    name: 'Bar'
  },
  {
    method: 'hello',
    name: 'Hello'
  }
];
var run = function() {
  if (start < methodsToCall.length) {
    script.run('main.' + methodsToCall[start].method, { name: methodsToCall[start].name });
    start++;
  }
};

run();
<|endoftext|>


<commit_before>/*
 * Copyright (C)2012 D. Plaindoux.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*global require */

require([ "Core/utils/jUtils", "Core/test/jCC" ],
    function (jUUID, jCC) {
        "use strict";

        /**
         * Test UUID generation
         */
        jCC.scenario("Check UUID generation", function () {
            var uuid1, uuid2;

            jCC.
                Given(function () {
                    uuid1 = jUUID.uuid();
                }).
                And(function () {
                    uuid2 = jUUID.uuid();
                }).
                When(jCC.Nothing).
                Then(function () {
                    jCC.notEqual(uuid1, uuid2, "Two fresh UUID must be different");
                });
        });
    });<commit_msg>Refactoring / Rename<commit_after>/*
 * Copyright (C)2012 D. Plaindoux.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*global require */

require([ "Core/utils/jUtils", "Core/test/jCC" ],
    function (jUtils, jCC) {
        "use strict";

        /**
         * Test UUID generation
         */
        jCC.scenario("Check UUID generation", function () {
            var uuid1, uuid2;

            jCC.
                Given(function () {
                    uuid1 = jUtils.uuid();
                }).
                And(function () {
                    uuid2 = jUtils.uuid();
                }).
                When(jCC.Nothing).
                Then(function () {
                    jCC.notEqual(uuid1, uuid2, "Two fresh UUID must be different");
                });
        });
    });<|endoftext|>