<commit_before>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      if (hash.length)
        phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivAppeared, function()
        {
          phoxy.Defer.call(Div(), callback, call_delay);
        }, timeout)
      });
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivDisappeared, function()
        {
          phoxy.Defer(callback, call_delay);
        }, timeout);
      });
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy.ScriptsLoaded(answer, callback);
        }
        if (answer.before !== undefined)
          window[answer.before](answer, AfterBefore);
        else
          AfterBefore();
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<commit_msg>Phoxy now makes first request every time<commit_after>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivAppeared, function()
        {
          phoxy.Defer.call(Div(), callback, call_delay);
        }, timeout)
      });
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.Defer(function()
      {
        phoxy.WaitFor(IsDivDisappeared, function()
        {
          phoxy.Defer(callback, call_delay);
        }, timeout);
      });
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy.ScriptsLoaded(answer, callback);
        }
        if (answer.before !== undefined)
          window[answer.before](answer, AfterBefore);
        else
          AfterBefore();
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<|endoftext|>


<commit_before>import { appSizes, appDurations } from '/imports/ui/helpers/settings';
import _ from 'lodash';

const sizes = appSizes();
const dur = appDurations();

/**
 * Hide the zoom image
 *
 * @param clicked
 * @param state
 */
export function hideZoomImage(clicked, state) {
  $('.zoom-image-container')
    .fadeOut(dur.default, function () {
      $(this)
        .remove();
    });
}

/**
 * Show the zoom image
 *
 * @param clicked
 * @param state
 */
export function zoomImage(clicked, state) {

  let selectedHighlightImage = _.find(state.images, function (image) {
    return image.slug == clicked.id.replace('highlighted-', '');
  });

  // Fit the image on the screen by max height
  var imageWidth = selectedHighlightImage.width;
  var imageHeight = selectedHighlightImage.height;
  var imageTopMargin = sizes.zoomTopMargin;
  var maxZoomHeight = (sizes.screenHeight - (sizes.zoomTopMargin * 2));
  console.log(maxZoomHeight);
  console.log('----^ ^ ^ ^ ^ maxZoomHeight ^ ^ ^ ^ ^----');
  if (selectedHighlightImage.height >= maxZoomHeight) {
    imageWidth = (imageWidth * maxZoomHeight) / imageHeight;
    imageHeight = maxZoomHeight;
  } else {
    imageTopMargin = ((sizes.screenHeight - imageHeight) / 2);
  }

  var imageLeftMargin = ((sizes.screenWidth - imageWidth) / 2);

  // Define image
  var $zoomImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('zoom-image')
    .attr('src', 'images/collection/' + selectedHighlightImage.filename);

  // Define close button
  let $zoomClose = $('<i/>')
    .addClass('fa fa-times ')
    .attr('aria-hidden', 'true');

  let $zoomImageCloseContainer = $('<div/>')
    .addClass('zoom-image-close-container')
    .css('margin-left', imageLeftMargin)
    .css('margin-top', imageTopMargin)
    .css('width', imageWidth)
    .css('height', imageHeight);

  // Add image to page
  var $zoomImageContainer = $('<div/>')
    .addClass('zoom-image-container')
    .hide();
  $($zoomImageCloseContainer)
    .append($zoomImage)
    .append($zoomClose);
  $($zoomImageContainer)
    .append($zoomImageCloseContainer);
  $('body')
    .append($zoomImageContainer);
  $($zoomImageContainer)
    .fadeIn(dur.default);

}

export function zoomThenNow(clicked, state) {
  console.log('Clicked');
  const selectedThenNow = _.find(state.thenNow, (thenNowImage) => {
    return thenNowImage._id === clicked.id.replace('then-now-', '');
  });

  // Fit the image on the screen by max height
  var imageWidth = selectedThenNow.width;
  var imageHeight = selectedThenNow.height;
  var imageTopMargin = sizes.zoomTopMargin;
  var maxZoomHeight = (sizes.screenHeight - (sizes.zoomTopMargin * 2));
  if (selectedThenNow.height >= maxZoomHeight) {
    imageWidth = (imageWidth * maxZoomHeight) / imageHeight;
    imageHeight = maxZoomHeight;
  } else {
    imageTopMargin = ((sizes.screenHeight - imageHeight) / 2);
  }
  var imageLeftMargin = ((sizes.screenWidth - imageWidth) / 2);

  // Define the Then image
  var $thenImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('then-zoom-image')
    .addClass('then-now-zoom-image')
    .attr('draggable', false)
    .attr('src', 'images/then-now/' + selectedThenNow.thenFilename);
  const imageMiddle = (imageWidth / 2);
  var $nowImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('now-zoom-image')
    .addClass('then-now-zoom-image')
    .attr('draggable', false)
    .css('clip', `rect(0px, ${imageWidth}px, ${imageHeight}px, ${imageMiddle}px)`)
    .attr('src', 'images/then-now/' + selectedThenNow.nowFilename);

  var $thenDate = $('<div/>')
    .addClass('then-date')
    .html(selectedThenNow.thenYear);

  // Define close button
  let $thenNowZoomClose = $('<i/>')
    .addClass('fa fa-times ')
    .attr('aria-hidden', 'true');

  let $thenNowZoomCloseContainer = $('<div/>')
    .addClass('then-now-zoom-image-close-container')
    .css('margin-left', imageLeftMargin)
    .css('margin-top', imageTopMargin)
    .css('width', imageWidth)
    .css('height', imageHeight);

  // Add image to page
  var $thenNowImageContainer = $('<div/>')
    .addClass('then-now-zoom-image-container')
    .hide();
  $($thenNowZoomCloseContainer)
    .append($thenImage)
    .append($thenDate)
    .append($nowImage)
    .append($thenNowZoomClose);
  $($thenNowImageContainer)
    .append($thenNowZoomCloseContainer);
  $('body')
    .append($thenNowImageContainer);
  $($thenNowImageContainer)
    .fadeIn(dur.default);
}

/**
 * Hide the zoom then now
 */
export function hideZoomThenNow(clicked, state) {
  $('.then-now-zoom-image-container')
    .fadeOut(dur.default, function () {
      $(this)
        .remove();
    });
}

<commit_msg>Append the data to the ten-now div<commit_after>import { appSizes, appDurations } from '/imports/ui/helpers/settings';
import _ from 'lodash';

const sizes = appSizes();
const dur = appDurations();

/**
 * Hide the zoom image
 *
 * @param clicked
 * @param state
 */
export function hideZoomImage(clicked, state) {
  $('.zoom-image-container')
    .fadeOut(dur.default, function () {
      $(this)
        .remove();
    });
}

/**
 * Show the zoom image
 *
 * @param clicked
 * @param state
 */
export function zoomImage(clicked, state) {

  let selectedHighlightImage = _.find(state.images, function (image) {
    return image.slug == clicked.id.replace('highlighted-', '');
  });

  // Fit the image on the screen by max height
  var imageWidth = selectedHighlightImage.width;
  var imageHeight = selectedHighlightImage.height;
  var imageTopMargin = sizes.zoomTopMargin;
  var maxZoomHeight = (sizes.screenHeight - (sizes.zoomTopMargin * 2));
  console.log(maxZoomHeight);
  console.log('----^ ^ ^ ^ ^ maxZoomHeight ^ ^ ^ ^ ^----');
  if (selectedHighlightImage.height >= maxZoomHeight) {
    imageWidth = (imageWidth * maxZoomHeight) / imageHeight;
    imageHeight = maxZoomHeight;
  } else {
    imageTopMargin = ((sizes.screenHeight - imageHeight) / 2);
  }

  var imageLeftMargin = ((sizes.screenWidth - imageWidth) / 2);

  // Define image
  var $zoomImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('zoom-image')
    .attr('src', 'images/collection/' + selectedHighlightImage.filename);

  // Define close button
  let $zoomClose = $('<i/>')
    .addClass('fa fa-times ')
    .attr('aria-hidden', 'true');

  let $zoomImageCloseContainer = $('<div/>')
    .addClass('zoom-image-close-container')
    .css('margin-left', imageLeftMargin)
    .css('margin-top', imageTopMargin)
    .css('width', imageWidth)
    .css('height', imageHeight);

  // Add image to page
  var $zoomImageContainer = $('<div/>')
    .addClass('zoom-image-container')
    .hide();
  $($zoomImageCloseContainer)
    .append($zoomImage)
    .append($zoomClose);
  $($zoomImageContainer)
    .append($zoomImageCloseContainer);
  $('body')
    .append($zoomImageContainer);
  $($zoomImageContainer)
    .fadeIn(dur.default);

}

export function zoomThenNow(clicked, state) {
  console.log('Clicked');
  const selectedThenNow = _.find(state.thenNow, (thenNowImage) => {
    return thenNowImage._id === clicked.id.replace('then-now-', '');
  });

  // Fit the image on the screen by max height
  var imageWidth = selectedThenNow.width;
  var imageHeight = selectedThenNow.height;
  var imageTopMargin = sizes.zoomTopMargin;
  var maxZoomHeight = (sizes.screenHeight - (sizes.zoomTopMargin * 2));
  if (selectedThenNow.height >= maxZoomHeight) {
    imageWidth = (imageWidth * maxZoomHeight) / imageHeight;
    imageHeight = maxZoomHeight;
  } else {
    imageTopMargin = ((sizes.screenHeight - imageHeight) / 2);
  }
  var imageLeftMargin = ((sizes.screenWidth - imageWidth) / 2);

  // Define the Then image
  var $thenImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('then-zoom-image')
    .addClass('then-now-zoom-image')
    .attr('draggable', false)
    .attr('src', 'images/then-now/' + selectedThenNow.thenFilename);
  const imageMiddle = (imageWidth / 2);
  var $nowImage = $('<img/>')
    .attr('height', imageHeight)
    .addClass('now-zoom-image')
    .addClass('then-now-zoom-image')
    .attr('draggable', false)
    .css('clip', `rect(0px, ${imageWidth}px, ${imageHeight}px, ${imageMiddle}px)`)
    .attr('src', 'images/then-now/' + selectedThenNow.nowFilename);

  var $thenDate = $('<div/>')
    .addClass('then-date')
    .html(selectedThenNow.thenYear);

  // Define close button
  let $thenNowZoomClose = $('<i/>')
    .addClass('fa fa-times ')
    .attr('aria-hidden', 'true');

  let $thenNowZoomCloseContainer = $('<div/>')
    .addClass('then-now-zoom-image-close-container')
    .css('margin-left', imageLeftMargin)
    .css('margin-top', imageTopMargin)
    .css('width', imageWidth)
    .css('height', imageHeight);

  // Add image to page
  var $thenNowImageContainer = $('<div/>')
    .addClass('then-now-zoom-image-container')
    .hide();
  $($thenNowZoomCloseContainer)
    .append($thenImage)
    .append($thenDate)
    .append($nowImage)
    .append($thenNowZoomClose);
  $($thenNowImageContainer)
    .append($thenNowZoomCloseContainer);
  $('#then-now')
    .append($thenNowImageContainer);
  $($thenNowImageContainer)
    .fadeIn(dur.default);
}

/**
 * Hide the zoom then now
 */
export function hideZoomThenNow(clicked, state) {
  $('.then-now-zoom-image-container')
    .fadeOut(dur.default, function () {
      $(this)
        .remove();
    });
}

<|endoftext|>


<commit_before>//META{"name":"lineNumbers"}*//

var lineNumbers = function () {};

(function () {
    "use strict";

    // Settings panel helpers

    // Create and return a new top-level settings panel
    function topPanel() {
        var panel = $("<form>")
            .addClass("form")
            .css("width", "100%");

        return panel;
    }

    // Create and return a container for control groups
    function controlGroups() {
        return $("
").addClass("control-groups");
    }

    // Create and return a flexible control group
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    function controlGroup(settings) {
        var group = $("
").addClass("control-group");

        if (typeof settings.label === "string") {
            group.append($("").text(settings.label));
        } else if (settings.label !== undefined) {
            group.append($("").append(settings.label));
        }

        return group;
    }

    // Create and return a group of checkboxes
    // settings (object)
    //   items (array)
    //     an array of settings objects to be passed to checkbox()
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is an array of boolean values
    function checkboxGroup(settings) {
        settings = $.extend({
            items: [],
            callback: $.noop,
        }, settings);

        var state = settings.items.map(item => item.checked === true);
        function onClick(i, itemState) {
            if (settings.items[i].callback !== undefined) {
                settings.items[i].callback(itemState);
            }
            state[i] = itemState;
            settings.callback(state);
        }

        var group = $("
").addClass("checkbox-group");

        group.append(settings.items.map(function (item, i) {
            return checkbox($.extend({}, item, {
                callback: onClick.bind(undefined, i),
            }));
        }));

        return group;
    }

    // Create and return a checkbox
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   help
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   checked (boolean)
    //   disabled (boolean)
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is a boolean
    function checkbox(settings) {
        settings = $.extend({
            checked: false,
            disabled: false,
            callback: $.noop,
        }, settings);

        var input = $("<input>").attr("type", "checkbox")
            .prop("checked", settings.checked)
            .prop("disabled", settings.disabled);

        var inner = $("
").addClass("checkbox-inner")
            .append(input)
            .append($(""));

        var outer = $("
").addClass("checkbox").append(inner);

        if (settings.disabled) {
            outer.addClass("disabled");
        }

        if (typeof settings.label === "string") {
            outer.append($("").text(settings.label));
        } else if (settings.label !== undefined) {
            outer.append($("").append(settings.label));
        }

        outer.on("click.kawaiiSettings", function () {
            if (!input.prop("disabled")) {
                var checked = !input.prop("checked");
                input.prop("checked", checked);
                settings.callback(checked);
            }
        });

        var item = $("
").append(outer);

        var help;
        if (typeof settings.help === "string") {
            help = $("
").text(settings.help);
        } else if (settings.help !== undefined) {
            help = $("
").append(settings.help);
        }

        if (help !== undefined) {
            help.appendTo(item)
                .addClass("help-text")
                .css("margin-top", "-3px")
                .css("margin-left", "27px");
        }

        return item;
    }

    // End settings panel helpers

    function processCodeBlocks(mutation) {
        mutationFind(mutation, ".hljs").not(":has(ol)")
            .filter((_, e) => !(settings.ignoreNoLanguage && e.className == "hljs"))
            .each(function () {
                this.innerHTML = this.innerHTML.split("\n").map(line => "
"+line+"
").join("");
            })
            .wrapInner($("
").addClass("kawaii-linenumbers"));
    }

    // Helper function for finding all elements matching selector affected by a mutation
    function mutationFind(mutation, selector) {
        var target = $(mutation.target), addedNodes = $(mutation.addedNodes);
        var mutated = target.add(addedNodes).filter(selector);
        var descendants = addedNodes.find(selector);
        var ancestors = target.parents(selector);
        return mutated.add(descendants).add(ancestors);
    }

    lineNumbers.prototype.start = function () {
        if (!settings.noStyle) {
            BdApi.injectCSS("kawaii-linenumbers-css",
                    ".hljs > ol {\n"+
                    "    list-style: decimal-leading-zero inside;\n"+
                    "}");
        }
        // process entire document
        var mutation = {target: document, addedNodes: [document]};
        processCodeBlocks(mutation);
    };

    lineNumbers.prototype.observer = function (mutation) {
        processCodeBlocks(mutation);
    };

    // Settings
    //   ignoreNoLanguage
    //     false - apply even when no language is specified
    //     true  - apply only to code blocks with a specified language
    //   noStyle
    //     false - add some simple CSS for styling line-numbered code blocks
    //     true  - leave styling up to themes or custom CSS

    var settings, defaultSettings = {
        ignoreNoLanguage: false,
        noStyle: false,
    };

    // Load or store settings from localStorage
    function localSettings(settings) {
        if (settings === undefined) {
            var localSettings;
            try {
                localSettings = JSON.parse(localStorage.lineNumbers);
            } catch (err) {
                localSettings = {};
            }
            return $.extend({}, defaultSettings, localSettings);
        }

        localStorage.lineNumbers = JSON.stringify(settings);
    }

    lineNumbers.prototype.load = function () {
        settings = localSettings();
    };

    lineNumbers.prototype.unload = function () {
        localSettings(settings);
    };

    lineNumbers.prototype.stop = function () {
        BdApi.clearCSS("kawaii-linenumbers-css");
        $(".kawaii-linenumbers")
            .removeClass("kawaii-linenumbers")
            .children()
            .not(":last-child").append(document.createTextNode("\n")).end()
            .contents().unwrap().unwrap();
    };

    lineNumbers.prototype.restart = function () {
        this.stop();
        this.start();
    };

    lineNumbers.prototype.getSettingsPanel = function () {
        var panel = topPanel();

        var filterControls = controlGroups().appendTo(panel);

        var Control = controlGroup({label: "Filtering options"})
            .appendTo(filterControls)
            .append(checkboxGroup({
                callback: state => {
                    localSettings(settings);
                    this.restart();
                },
                items: [
                    {
                        label: "Ignore code blocks with no language specified.",
                        checked: settings.ignoreNoLanguage,
                        callback: state => { settings.ignoreNoLanguage = state; },
                    },
                    {
                        label: "Don't add style rules.",
                        help: "Leave styling up to themes or custom CSS.",
                        checked: settings.noStyle,
                        callback: state => { settings.noStyle = state; },
                    },
                ],
            }));

        return panel;
    };

    lineNumbers.prototype.getName = function () {
        return "Line Numbers";
    };

    lineNumbers.prototype.getDescription = function () {
        return "Add line numbers to code blocks";
    };

    lineNumbers.prototype.getVersion = function () {
        return "0.1.0";
    };

    lineNumbers.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();
<commit_msg>Bump LineNumbers version to 1.0.0<commit_after>//META{"name":"lineNumbers"}*//

var lineNumbers = function () {};

(function () {
    "use strict";

    // Settings panel helpers

    // Create and return a new top-level settings panel
    function topPanel() {
        var panel = $("<form>")
            .addClass("form")
            .css("width", "100%");

        return panel;
    }

    // Create and return a container for control groups
    function controlGroups() {
        return $("
").addClass("control-groups");
    }

    // Create and return a flexible control group
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    function controlGroup(settings) {
        var group = $("
").addClass("control-group");

        if (typeof settings.label === "string") {
            group.append($("").text(settings.label));
        } else if (settings.label !== undefined) {
            group.append($("").append(settings.label));
        }

        return group;
    }

    // Create and return a group of checkboxes
    // settings (object)
    //   items (array)
    //     an array of settings objects to be passed to checkbox()
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is an array of boolean values
    function checkboxGroup(settings) {
        settings = $.extend({
            items: [],
            callback: $.noop,
        }, settings);

        var state = settings.items.map(item => item.checked === true);
        function onClick(i, itemState) {
            if (settings.items[i].callback !== undefined) {
                settings.items[i].callback(itemState);
            }
            state[i] = itemState;
            settings.callback(state);
        }

        var group = $("
").addClass("checkbox-group");

        group.append(settings.items.map(function (item, i) {
            return checkbox($.extend({}, item, {
                callback: onClick.bind(undefined, i),
            }));
        }));

        return group;
    }

    // Create and return a checkbox
    // settings (object)
    //   label
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   help
    //     an element or something JQuery-ish
    //     or, if string, use as plain text
    //   checked (boolean)
    //   disabled (boolean)
    //   callback (function(state))
    //     called with the current state, when it changes
    //     state is a boolean
    function checkbox(settings) {
        settings = $.extend({
            checked: false,
            disabled: false,
            callback: $.noop,
        }, settings);

        var input = $("<input>").attr("type", "checkbox")
            .prop("checked", settings.checked)
            .prop("disabled", settings.disabled);

        var inner = $("
").addClass("checkbox-inner")
            .append(input)
            .append($(""));

        var outer = $("
").addClass("checkbox").append(inner);

        if (settings.disabled) {
            outer.addClass("disabled");
        }

        if (typeof settings.label === "string") {
            outer.append($("").text(settings.label));
        } else if (settings.label !== undefined) {
            outer.append($("").append(settings.label));
        }

        outer.on("click.kawaiiSettings", function () {
            if (!input.prop("disabled")) {
                var checked = !input.prop("checked");
                input.prop("checked", checked);
                settings.callback(checked);
            }
        });

        var item = $("
").append(outer);

        var help;
        if (typeof settings.help === "string") {
            help = $("
").text(settings.help);
        } else if (settings.help !== undefined) {
            help = $("
").append(settings.help);
        }

        if (help !== undefined) {
            help.appendTo(item)
                .addClass("help-text")
                .css("margin-top", "-3px")
                .css("margin-left", "27px");
        }

        return item;
    }

    // End settings panel helpers

    function processCodeBlocks(mutation) {
        mutationFind(mutation, ".hljs").not(":has(ol)")
            .filter((_, e) => !(settings.ignoreNoLanguage && e.className == "hljs"))
            .each(function () {
                this.innerHTML = this.innerHTML.split("\n").map(line => "
"+line+"
").join("");
            })
            .wrapInner($("
").addClass("kawaii-linenumbers"));
    }

    // Helper function for finding all elements matching selector affected by a mutation
    function mutationFind(mutation, selector) {
        var target = $(mutation.target), addedNodes = $(mutation.addedNodes);
        var mutated = target.add(addedNodes).filter(selector);
        var descendants = addedNodes.find(selector);
        var ancestors = target.parents(selector);
        return mutated.add(descendants).add(ancestors);
    }

    lineNumbers.prototype.start = function () {
        if (!settings.noStyle) {
            BdApi.injectCSS("kawaii-linenumbers-css",
                    ".hljs > ol {\n"+
                    "    list-style: decimal-leading-zero inside;\n"+
                    "}");
        }
        // process entire document
        var mutation = {target: document, addedNodes: [document]};
        processCodeBlocks(mutation);
    };

    lineNumbers.prototype.observer = function (mutation) {
        processCodeBlocks(mutation);
    };

    // Settings
    //   ignoreNoLanguage
    //     false - apply even when no language is specified
    //     true  - apply only to code blocks with a specified language
    //   noStyle
    //     false - add some simple CSS for styling line-numbered code blocks
    //     true  - leave styling up to themes or custom CSS

    var settings, defaultSettings = {
        ignoreNoLanguage: false,
        noStyle: false,
    };

    // Load or store settings from localStorage
    function localSettings(settings) {
        if (settings === undefined) {
            var localSettings;
            try {
                localSettings = JSON.parse(localStorage.lineNumbers);
            } catch (err) {
                localSettings = {};
            }
            return $.extend({}, defaultSettings, localSettings);
        }

        localStorage.lineNumbers = JSON.stringify(settings);
    }

    lineNumbers.prototype.load = function () {
        settings = localSettings();
    };

    lineNumbers.prototype.unload = function () {
        localSettings(settings);
    };

    lineNumbers.prototype.stop = function () {
        BdApi.clearCSS("kawaii-linenumbers-css");
        $(".kawaii-linenumbers")
            .removeClass("kawaii-linenumbers")
            .children()
            .not(":last-child").append(document.createTextNode("\n")).end()
            .contents().unwrap().unwrap();
    };

    lineNumbers.prototype.restart = function () {
        this.stop();
        this.start();
    };

    lineNumbers.prototype.getSettingsPanel = function () {
        var panel = topPanel();

        var filterControls = controlGroups().appendTo(panel);

        var Control = controlGroup({label: "Filtering options"})
            .appendTo(filterControls)
            .append(checkboxGroup({
                callback: state => {
                    localSettings(settings);
                    this.restart();
                },
                items: [
                    {
                        label: "Ignore code blocks with no language specified.",
                        checked: settings.ignoreNoLanguage,
                        callback: state => { settings.ignoreNoLanguage = state; },
                    },
                    {
                        label: "Don't add style rules.",
                        help: "Leave styling up to themes or custom CSS.",
                        checked: settings.noStyle,
                        callback: state => { settings.noStyle = state; },
                    },
                ],
            }));

        return panel;
    };

    lineNumbers.prototype.getName = function () {
        return "Line Numbers";
    };

    lineNumbers.prototype.getDescription = function () {
        return "Add line numbers to code blocks";
    };

    lineNumbers.prototype.getVersion = function () {
        return "1.0.0";
    };

    lineNumbers.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();
<|endoftext|>


<commit_before>import { transfer } from "jsua/lib/transferring";
import { build } from "jsua/lib/views/building";

export function contentViewBuilder(node) {
  var url = node.value.src;

  if (!url) {
    url = "data:" + node.value.type;

    if (node.value.encoding) {
      url += ";" + node.value.encoding;
    }

    url += "," + node.value.data;
  }

  return transfer(url)
    .then(build)
    .then(function (view) {
      if (node.value.alt) {
        view.setAttribute("alt", node.value.alt);
      }

      return view;
    });
}
<commit_msg>Fix Transfer Call<commit_after>import { transfer } from "jsua/lib/transferring";
import { build } from "jsua/lib/views/building";

export function contentViewBuilder(node) {
  var url = node.value.src;

  if (!url) {
    url = "data:" + node.value.type;

    if (node.value.encoding) {
      url += ";" + node.value.encoding;
    }

    url += "," + node.value.data;
  }

  return transfer({ url })
    .then(build)
    .then(function (view) {
      if (node.value.alt) {
        view.setAttribute("alt", node.value.alt);
      }

      return view;
    });
}
<|endoftext|>


<commit_before>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        require: '^form',
        template:
            '
' +
                '
' +
                    '{{error}}' +
                '
' +
            '
',
        replace: true,
        transclude: true,
        restrict: 'AE',
        link: function postLink(scope, elem, attrs, ctrl) {
            // list of some default error reasons
            var defaultErrorReasons = {
                    required: 'is required.',
                    minlength: 'is too short.',
                    maxlength: 'is too long.',
                    email: 'is not a valid email address.',
                    pattern: 'does not match the expected pattern.',
                    number: 'is not a number.',

                    fallback: 'is invalid.'
                },
                // humanize words, turning:
                //     camelCase  --> Camel Case
                //     dash-case  --> Dash Case
                //     snake_case --> Snake Case
                humanize = function (str) {
                    return str.replace(/[-_+]/g, ' ') // turn _ and - into spaces
                              .replace(/([A-Z])/g, ' $1') // put a splace before every capital letter
                              .replace(/^([a-z])|\s+([a-z])/g, // capitalize the first letter of each word
                                    function ($1) { return $1.toUpperCase(); }
                    );
                },
                // this is where we form our message
                errorMessage = function (name, error, props) {
                    // get the nice name if they used the niceName
                    // directive or humanize the name and call it good
                    var niceName = props.$niceName || humanize(name);

                    // get a reason from our default set
                    var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;

                    // if they used the errorMessages directive, grab that message
                    if(typeof props.$errorMessages === 'object')
                        reason = props.$errorMessages[error];
                    else if(typeof props.$errorMessages === 'string')
                        reason = props.$errorMessages;

                    // return our nicely formatted message
                    return niceName + ' ' + reason;
                };

            // only update the list of errors if there was actually a change in $error
            scope.$watch(function() { return ctrl.$error; }, function() {
                // reset error array
                scope.errors = [];
                angular.forEach(ctrl, function(props, name) {
                    // name has some internal properties we don't want to iterate over
                    if(name[0] === '$') return;
                    angular.forEach(props.$error, function(isInvalid, error) {
                        // don't need to even try and get a a message unless it's invalid
                        if(isInvalid) {
                            scope.errors.push(errorMessage(name, error, props));
                        }
                    });
                });
            }, true);
        }
    };
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            ctrl.$niceName = attrs.niceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch(e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }
        }
    };
}]);<commit_msg>isValid for funsies...<commit_after>angular.module('FormErrors', [])

// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
    return {
        // only works if embedded in a form or an ngForm (that's in a form).
        // It does use its closest parent that is a form OR ngForm
        require: '^form',
        template:
            '
' +
                '
' +
                    '{{error}}' +
                '
' +
            '
',
        replace: true,
        transclude: true,
        restrict: 'AE',
        scope: { isValid: '=' },
        link: function postLink(scope, elem, attrs, ctrl) {
            // list of some default error reasons
            var defaultErrorReasons = {
                    required: 'is required.',
                    minlength: 'is too short.',
                    maxlength: 'is too long.',
                    email: 'is not a valid email address.',
                    pattern: 'does not match the expected pattern.',
                    number: 'is not a number.',

                    fallback: 'is invalid.'
                },
                // humanize words, turning:
                //     camelCase  --> Camel Case
                //     dash-case  --> Dash Case
                //     snake_case --> Snake Case
                humanize = function (str) {
                    return str.replace(/[-_+]/g, ' ') // turn _ and - into spaces
                              .replace(/([A-Z])/g, ' $1') // put a splace before every capital letter
                              .replace(/^([a-z])|\s+([a-z])/g, // capitalize the first letter of each word
                                    function ($1) { return $1.toUpperCase(); }
                    );
                },
                // this is where we form our message
                errorMessage = function (name, error, props) {
                    // get the nice name if they used the niceName
                    // directive or humanize the name and call it good
                    var niceName = props.$niceName || humanize(name);

                    // get a reason from our default set
                    var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;

                    // if they used the errorMessages directive, grab that message
                    if(typeof props.$errorMessages === 'object')
                        reason = props.$errorMessages[error];
                    else if(typeof props.$errorMessages === 'string')
                        reason = props.$errorMessages;

                    // return our nicely formatted message
                    return niceName + ' ' + reason;
                };

            // only update the list of errors if there was actually a change in $error
            scope.$watch(function() { return ctrl.$error; }, function() {
                // we can pass in a variable to keep track of form validity in page's ctrl
                scope.isValid = ctrl.$valid;
                scope.errors = [];
                angular.forEach(ctrl, function(props, name) {
                    // name has some internal properties we don't want to iterate over
                    if(name[0] === '$') return;
                    angular.forEach(props.$error, function(isInvalid, error) {
                        // don't need to even try and get a a message unless it's invalid
                        if(isInvalid) {
                            scope.errors.push(errorMessage(name, error, props));
                        }
                    });
                });
            }, true);
        }
    };
}])

// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            ctrl.$niceName = attrs.niceName;
        }
    };
}])

// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            // attrs.errorMessages can be:
            //    1) "must be filled out."
            //    2) "'must be filled out.'"
            //    3) "{ required: 'must be filled out.' }"
            try {
                ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
            } catch(e) {
                ctrl.$errorMessages = attrs.errorMessages;
            }
        }
    };
}]);<|endoftext|>


<commit_before><commit_msg>add build sources<commit_after><|endoftext|>


<commit_before>var rethinkdbdash = require('rethinkdbdash');
var Model = require(__dirname+'/model.js');

/*
 * Main method
 * Create the default database
 *
 * Fields in `options` can be:
 *  - `min`: <number> - minimum number of connections in the pool, default 50
 *  - `max`: <number> -  maximum number of connections in the pool, default 1000
 *  - `bufferSize`: <number> - minimum number of connections available in the pool, default 50
 *  - `timeoutError`: <number> - wait time before reconnecting in case of an error (in ms), default 1000
 *  - `timeoutGb`: <number> - how long the pool keep a connection that hasn't been used (in ms), default 60*60*1000
 *  - `enforce`: {missing: <boolean>, extra: <boolean>, type: <boolean>}
 *  - `timeFormat`: "raw" or "native"
 *
 */
function Thinky(config) {
    var self = this;

    config = config || {};
    config.db = config.db || 'test'; // We need the default db to create it.

    this._options = {}
    this._options.enforce_missing = (config.enforce_missing != null) ? config.enforce_missing : false;
    this._options.enforce_extra = (config.enforce_extra != null) ? config.enforce_extra : false;
    this._options.enforce_type = (config.enforce_type != null) ? config.enforce_type : 'loose'; // loose, strict, none
    this._options.timeFormat = (config.timeFormat != null) ? config.timeFormat : 'native';
    this._options.validate = (config.validate != null) ? config.validate : 'onsave'; // 'onsave' or 'oncreate'

    this.r = rethinkdbdash(config);
    this.models = {};

    // Can we start using the database?
    this._dbReady = false;
    this._onDbReady = []; // functions to execute once the database is ready

    // Create the default database
    this.r.dbCreate(config.db).run().then(function(result) {
        self._dbReady = true;
    }).error(function(error) {
        if (error.message.match(/^Database .* already exists.*/)) {
            self._dbReady = true;
        }
        else {
            throw error;
        }
    });
}

Thinky.prototype.getOptions = function() {
    return this._options;
}

Thinky.prototype.createModel = function(name, schema, options) {
    var self = this;

    options = options || {};

    if (self.models[name] !== undefined) {
        throw new Error("Cannot redefine a Model");
    }

    model = Model.new(name, schema, options, self);
    self.models[name] = model;

    if (options.init !== false) {
        // Create the table, or push the table name in the queue.
        if (self._dbReady) {
            self.r.tableCreate(name).run().then(function(result) {
                model._setReady();
            }).error(function(error) {
                if (error.message.match(/^Database .* already exists.*/)) {
                    model._setReady();
                }
                else {
                    model._error = error;
                }
            })
        }
        else {
            self._onDbReady.push(function() {
                self.r.tableCreate(name).run().then(function(result) {
                    model._setReady();
                }).error(function(error) {
                    if (error.message.match(/^Database .* already exists.*/)) {
                        model._setReady();
                    }
                    else {
                        model._error = error;
                    }
                })
            });
        }
    }

    return model;
}

module.exports = function(config) {
    return new Thinky(config);
}
<commit_msg>Improve dbCreate<commit_after>var rethinkdbdash = require('rethinkdbdash');
var Model = require(__dirname+'/model.js');

/*
 * Main method
 * Create the default database
 *
 * Fields in `options` can be:
 *  - `min`: <number> - minimum number of connections in the pool, default 50
 *  - `max`: <number> -  maximum number of connections in the pool, default 1000
 *  - `bufferSize`: <number> - minimum number of connections available in the pool, default 50
 *  - `timeoutError`: <number> - wait time before reconnecting in case of an error (in ms), default 1000
 *  - `timeoutGb`: <number> - how long the pool keep a connection that hasn't been used (in ms), default 60*60*1000
 *  - `enforce`: {missing: <boolean>, extra: <boolean>, type: <boolean>}
 *  - `timeFormat`: "raw" or "native"
 *
 */
function Thinky(config) {
    var self = this;

    config = config || {};
    config.db = config.db || 'test'; // We need the default db to create it.

    this._options = {}
    this._options.enforce_missing = (config.enforce_missing != null) ? config.enforce_missing : false;
    this._options.enforce_extra = (config.enforce_extra != null) ? config.enforce_extra : false;
    this._options.enforce_type = (config.enforce_type != null) ? config.enforce_type : 'loose'; // loose, strict, none
    this._options.timeFormat = (config.timeFormat != null) ? config.timeFormat : 'native';
    this._options.validate = (config.validate != null) ? config.validate : 'onsave'; // 'onsave' or 'oncreate'

    this.r = rethinkdbdash(config);
    this.models = {};

    // Can we start using the database?
    this._dbReady = false;
    this._onDbReady = []; // functions to execute once the database is ready

    // Create the default database
    var r = this.r;
    r.dbList().contains(config.db).do(function(result) {
        return r.branch(
            result,
            {created: 1},
            r.dbCreate(config.db)
        )
    }).run().then(function(result) {
        self._dbReady = true;
    }).error(function(error) {
        throw error;
    });
}

Thinky.prototype.getOptions = function() {
    return this._options;
}

Thinky.prototype.createModel = function(name, schema, options) {
    var self = this;

    options = options || {};

    if (self.models[name] !== undefined) {
        throw new Error("Cannot redefine a Model");
    }

    model = Model.new(name, schema, options, self);
    self.models[name] = model;

    if (options.init !== false) {
        // Create the table, or push the table name in the queue.
        if (self._dbReady) {
            self.r.tableCreate(name).run().then(function(result) {
                model._setReady();
            }).error(function(error) {
                if (error.message.match(/^Database .* already exists.*/)) {
                    model._setReady();
                }
                else {
                    model._error = error;
                }
            })
        }
        else {
            self._onDbReady.push(function() {
                self.r.tableCreate(name).run().then(function(result) {
                    model._setReady();
                }).error(function(error) {
                    if (error.message.match(/^Database .* already exists.*/)) {
                        model._setReady();
                    }
                    else {
                        model._error = error;
                    }
                })
            });
        }
    }

    return model;
}

module.exports = function(config) {
    return new Thinky(config);
}
<|endoftext|>


<commit_before>define(["sprd/data/SprdModel", "sprd/entity/ConcreteElement", "sprd/entity/Price"], function (SprdModel, ConcreteElement, Price) {
    return SprdModel.inherit("sprd.model.BasketItem", {

        schema: {
            element: ConcreteElement,
            quantity: Number,
            price: Price,
            priceItem: Price,
            origin: String
        },

        defaults: {
            quantity: 1,
            element: null,
            price: null
        },

        increaseQuantity: function (quantity) {
            quantity = quantity || 1;
            this.set('quantity', this.$.quantity + quantity);
        },

        decreaseQuantity: function (quantity) {
            quantity = quantity || 1;
            this.set('quantity', this.$.quantity - quantity);
        },

        _updatePrices: function () {
            this.totalVatIncluded.trigger();
            this.totalVatExcluded.trigger();
        },

        vatIncluded: function () {
            if (this.$.priceItem) {
                return this.$.priceItem.$.vatIncluded;
            }
            return this.get('element.item.price().vatIncluded') || 0;
        },

        vatExcluded: function () {
            if (this.$.priceItem) {
                return this.$.priceItem.$.vatExcluded;
            }
            return this.get('element.item.price().vatExcluded') || 0;
        },

        discountPriceVatIncluded: function(){
            if(this.$.price){
                return this.$.price.$.vatIncluded;
            }
            return 0;
        }.onChange("price"),

        totalVatIncluded: function () {
            return this.vatIncluded() * this.$.quantity;
        }.on('change:quantity'),

        totalVatExcluded: function () {
            return this.vatExcluded() * this.$.quantity;
        }.on('change:quantity'),

        totalDiscountVatIncluded: function(){
            return this.discountPriceVatIncluded() * this.$.quantity;
        }.onChange("price","quantity")

    });
});
<commit_msg>include article commission in basket, if an article was references for the basketItem<commit_after>define(["sprd/data/SprdModel", "sprd/entity/ConcreteElement", "sprd/entity/Price"], function (SprdModel, ConcreteElement, Price) {
    return SprdModel.inherit("sprd.model.BasketItem", {

        schema: {
            element: ConcreteElement,
            quantity: Number,
            price: Price,
            priceItem: Price,
            origin: String
        },

        defaults: {
            quantity: 1,
            element: null,
            price: null
        },

        increaseQuantity: function (quantity) {
            quantity = quantity || 1;
            this.set('quantity', this.$.quantity + quantity);
        },

        decreaseQuantity: function (quantity) {
            quantity = quantity || 1;
            this.set('quantity', this.$.quantity - quantity);
        },

        _updatePrices: function () {
            this.totalVatIncluded.trigger();
            this.totalVatExcluded.trigger();
        },

        vatIncluded: function () {
            if (this.$.priceItem) {
                return this.$.priceItem.$.vatIncluded;
            }

            return (this.get('element.item.price().vatIncluded') || 0) +
                (this.get('element.article.commission.vatIncluded') || 0);
        },

        vatExcluded: function () {
            if (this.$.priceItem) {
                return this.$.priceItem.$.vatExcluded;
            }

            return (this.get('element.item.price().vatExcluded') || 0) + +
                (this.get('element.article.commission.vatExcluded') || 0);
        },

        discountPriceVatIncluded: function(){
            if(this.$.price){
                return this.$.price.$.vatIncluded;
            }
            return 0;
        }.onChange("price"),

        totalVatIncluded: function () {
            return this.vatIncluded() * this.$.quantity;
        }.on('change:quantity'),

        totalVatExcluded: function () {
            return this.vatExcluded() * this.$.quantity;
        }.on('change:quantity'),

        totalDiscountVatIncluded: function(){
            return this.discountPriceVatIncluded() * this.$.quantity;
        }.onChange("price","quantity")

    });
});
<|endoftext|>


<commit_before>( function( querystring ){
  var querystringToObject = function( querystring ){
    var params = {};
    querystring.replace(
        new RegExp( '([^?=&]+)(=([^&]*))?', 'g' ),
        function( $0, $1, $2, $3 ) { params[ $1 ] = $3; }
    );
    return params;
  };

  var objectToQueryString = function( params ){
    var values = [];
    for( var param in params ){
      var value = ( params[ param ] === null ? '' : params[ param ] );
      values.push( encodeURIComponent( param ) + '=' + encodeURIComponent( value ) );
    }
    return values.join( '&' ).replace( /%20/g, '+' );
  };

  var toggleW = function( params, whitespace ){
    if( whitespace ){
      delete params.w;
    }
    else {
      params.w = true;
    }
    return params;
  };

  var addWhitespaceToggleButton = function( button_group, querystring ){
    var code = document.createElement( 'code' ); // this is a hack to fix some weird height issues with their CSS
    code.textContent = ' ';

    var a = document.createElement( 'a' );
    a.className = button_group.querySelector( 'a' ).className + ' ' + toggler_classname;
    a.href = '?' + querystring;
    a.title = 'Toggle Whitespace';
    a.textContent = ' \u2423';
    a.appendChild(code);

    button_group.insertBefore( a, button_group.firstChild );
  };

  var addWhitespaceToggleButtons = function( querystring ){
    Array.prototype.forEach.call(
      document.querySelectorAll( button_group_selector ),
      function( button_group, index, button_groups ){
        addWhitespaceToggleButton( button_group, querystring );
      }
    );
  };

  var invertButtonGradients = function(){
    var sheet = document.createElement('style');
    var selector = button_group_selector + ' .' + toggler_classname;
    sheet.innerHTML = selector + "{ background: -moz-linear-gradient(#EAEAEA,#FAFAFA);" +
                                  " background: -webkit-linear-gradient(#EAEAEA,#FAFAFA);}" +
               selector + ":hover { background: -moz-linear-gradient(#3072B3, #599BDC);" +
                                  " background: -webkit-linear-gradient(#3072B3,#599BDC);}";
    document.body.appendChild(sheet);
  };

  var button_group_selector = '.diff-view .actions .button-group';
  var toggler_classname = 'toggle-whitespace';
  var params = querystringToObject( querystring );
  var whitespace = Boolean(params.w);
  querystring = objectToQueryString( toggleW( params, whitespace ) );
  addWhitespaceToggleButtons( querystring );

  if(whitespace) { invertButtonGradients(); }

})( location.search );
<commit_msg>Update button selector for new GitHub markup<commit_after>( function( querystring ){
  var querystringToObject = function( querystring ){
    var params = {};
    querystring.replace(
        new RegExp( '([^?=&]+)(=([^&]*))?', 'g' ),
        function( $0, $1, $2, $3 ) { params[ $1 ] = $3; }
    );
    return params;
  };

  var objectToQueryString = function( params ){
    var values = [];
    for( var param in params ){
      var value = ( params[ param ] === null ? '' : params[ param ] );
      values.push( encodeURIComponent( param ) + '=' + encodeURIComponent( value ) );
    }
    return values.join( '&' ).replace( /%20/g, '+' );
  };

  var toggleW = function( params, whitespace ){
    if( whitespace ){
      delete params.w;
    }
    else {
      params.w = true;
    }
    return params;
  };

  var addWhitespaceToggleButton = function( button_group, querystring ){
    var code = document.createElement( 'code' ); // this is a hack to fix some weird height issues with their CSS
    code.textContent = ' ';

    var a = document.createElement( 'a' );
    a.className = button_group.querySelector( 'a' ).className + ' ' + toggler_classname;
    a.href = '?' + querystring;
    a.title = 'Toggle Whitespace';
    a.textContent = ' \u2423';
    a.appendChild(code);

    button_group.insertBefore( a, button_group.firstChild );
  };

  var addWhitespaceToggleButtons = function( querystring ){
    Array.prototype.forEach.call(
      document.querySelectorAll( button_group_selector ),
      function( button_group, index, button_groups ){
        addWhitespaceToggleButton( button_group, querystring );
      }
    );
  };

  var invertButtonGradients = function(){
    var sheet = document.createElement('style');
    var selector = button_group_selector + ' .' + toggler_classname;
    sheet.innerHTML = selector + "{ background: -moz-linear-gradient(#EAEAEA,#FAFAFA);" +
                                  " background: -webkit-linear-gradient(#EAEAEA,#FAFAFA);}" +
               selector + ":hover { background: -moz-linear-gradient(#3072B3, #599BDC);" +
                                  " background: -webkit-linear-gradient(#3072B3,#599BDC);}";
    document.body.appendChild(sheet);
  };

  var button_group_selector = '#files .meta .actions';
  var toggler_classname = 'toggle-whitespace';
  var params = querystringToObject( querystring );
  var whitespace = Boolean(params.w);
  querystring = objectToQueryString( toggleW( params, whitespace ) );
  addWhitespaceToggleButtons( querystring );

  if(whitespace) { invertButtonGradients(); }

})( location.search );
<|endoftext|>


<commit_before>import { isObject } from 'lodash';

const mewApiError = 'Websocket connection failed';

export const knownErrors = {
  'Can\'t assign to property "request"': mewApiError,
  "Cannot create property 'request'": mewApiError,
  'GATT Server is disconnected. Cannot perform GATT operations.': mewApiError,
  "'CONNECTION ERROR: Couldn't connect to node on WS.'": mewApiError,
  'Interaction timeout': 'Please unlock your deveice',
  "CONNECTION ERROR: Couldn't connect to node on WS":
    "Couldn't connect to WS node. Please refresh and try again.",
  'connection not open on send': mewApiError,
  'Ledger device: Condition of use not satisfied': mewApiError,
  'Provided address null is invalid': 'No address provided',
  'transaction underpriced': 'Transaction gas price too low',
  'invalid remainder': 'invalid remainder',
  'Internal JSON-RPC error': 'Internal JSON-RPC error. Execution Reverted',
  'Transaction has been reverted by the EVM':
    'Transaction has been reverted by the EVM',
  'TypeError: Failed to fetch': 'Request Failed. Please refresh and try again.',
  "TypeError: Cannot read properties of null (reading 'errorHandler')":
    'There was an error signing transaction with this wallet',
  "Returned values aren't valid, did it run Out of Gas?":
    "Returned values aren't valid, did it run Out of Gas?" +
    'You might also see this error if you are not using the ' +
    'correct ABI for the contract you are retrieving data from, ' +
    'requesting data from a block number that does not exist, ' +
    'or querying a node which is not fully synced.',
  '未能完成该操作。无效的自变量':
    'The operation could not be completed. Invalid argument.'
};

const handleError = err => {
  const errorValues = Object.keys(knownErrors);
  const foundError = errorValues.find(item => {
    const message =
      err && err.message
        ? isObject(err.message)
          ? err.message.message
          : err.message
        : err;
    if (!message) return false;
    return message.includes(item);
  });
  return foundError ? true : false;
};

export default handleError;
<commit_msg>devop: 🔧 added error to error handler<commit_after>import { isObject } from 'lodash';

const mewApiError = 'Websocket connection failed';

export const knownErrors = {
  'Can\'t assign to property "request"': mewApiError,
  "Cannot create property 'request'": mewApiError,
  'GATT Server is disconnected. Cannot perform GATT operations.': mewApiError,
  "'CONNECTION ERROR: Couldn't connect to node on WS.'": mewApiError,
  'Interaction timeout': 'Please unlock your deveice',
  "CONNECTION ERROR: Couldn't connect to node on WS":
    "Couldn't connect to WS node. Please refresh and try again.",
  'connection not open on send': mewApiError,
  'Ledger device: Condition of use not satisfied': mewApiError,
  'Provided address null is invalid': 'No address provided',
  'transaction underpriced': 'Transaction gas price too low',
  'invalid remainder': 'invalid remainder',
  'Internal JSON-RPC error': 'Internal JSON-RPC error. Execution Reverted',
  'Transaction has been reverted by the EVM':
    'Transaction has been reverted by the EVM',
  'TypeError: Failed to fetch': 'Request Failed. Please refresh and try again.',
  "TypeError: Cannot read properties of null (reading 'errorHandler')":
    'There was an error signing transaction with this wallet',
  "Returned values aren't valid, did it run Out of Gas?":
    "Returned values aren't valid, did it run Out of Gas?" +
    'You might also see this error if you are not using the ' +
    'correct ABI for the contract you are retrieving data from, ' +
    'requesting data from a block number that does not exist, ' +
    'or querying a node which is not fully synced.',
  '未能完成该操作。无效的自变量':
    'The operation could not be completed. Invalid argument.',
  "Cannot read properties of undefined (reading 'click')": ''
};

const handleError = err => {
  const errorValues = Object.keys(knownErrors);
  const foundError = errorValues.find(item => {
    const message =
      err && err.message
        ? isObject(err.message)
          ? err.message.message
          : err.message
        : err;
    if (!message) return false;
    return message.includes(item);
  });
  return foundError ? true : false;
};

export default handleError;
<|endoftext|>


<commit_before>/*
 *    (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function () {
  'use strict';

  // Constants used within this file
  var VOLUME_RESOURCE_TYPE = 'OS::Cinder::Volume';

  /**
   * @ngdoc overview
   * @name horizon.app.core
   * @description
   *
   * # horizon.app.core
   *
   * This module hosts modules of core functionality and services that supports
   * components added to Horizon via its plugin mechanism.
   */
  angular
    .module('horizon.app.core', [
      'horizon.app.core.cloud-services',
      'horizon.app.core.images',
      'horizon.app.core.metadata',
      'horizon.app.core.openstack-service-api',
      'horizon.app.core.workflow',
      'horizon.framework.conf',
      'horizon.framework.util',
      'horizon.framework.widgets',
      'horizon.dashboard.project.workflow'
    ], config)
    // NOTE: this will move into the correct module as that resource type
    // becomes available.  For now there is no volumes module.
    .constant('horizon.app.core.volumes.resourceType', VOLUME_RESOURCE_TYPE)
    .run([
      'horizon.framework.conf.resource-type-registry.service',
      performRegistrations
    ]);

  config.$inject = ['$provide', '$windowProvider'];

  function config($provide, $windowProvider) {
    var path = $windowProvider.$get().STATIC_URL + 'app/core/';
    $provide.constant('horizon.app.core.basePath', path);
  }

  function performRegistrations(registry) {
    // The items in this long list of registrations should ideally placed into
    // respective module declarations.  However, until they are more fully
    // fleshed out there's no reason to pollute the directory/file structure.
    // As a model, the Images registration happens in the images module.
    registry.getResourceType('OS::Glance::Metadef', {
      names: [gettext('Metadata Definition'), gettext('Metadata Definitions')]
    });
    registry.getResourceType('OS::Nova::Server', {
      names: [gettext('Instance'), gettext('Instances')]
    });
    registry.getResourceType('OS::Nova::Flavor', {
      names: [gettext('Flavor'), gettext('Flavors')]
    });
    registry.getResourceType('OS::Nova::Keypair', {
      names: [gettext('Key Pair'), gettext('Key Pairs')]
    });
    registry.getResourceType('OS::Designate::Zone', {
      names: [gettext('DNS Domain'), gettext('DNS Domains')]
    });
    registry.getResourceType('OS::Designate::RecordSet', {
      names: [gettext('DNS Record'), gettext('DNS Records')]
    });
    registry.getResourceType('OS::Cinder::Backup', {
      names: [gettext('Volume Backup'), gettext('Volume Backups')]
    });
    registry.getResourceType('OS::Cinder::Snapshot', {
      names: [gettext('Volume Snapshot'), gettext('Volume Snapshots')]
    });
    registry.getResourceType(VOLUME_RESOURCE_TYPE, {
      names: [gettext('Volume'), gettext('Volumes')]
    });
    registry.getResourceType('OS::Nova::Flavor', {
      names: [gettext('Flavor'), gettext('Flavors')]
    });
    registry.getResourceType('OS::Swift::Account', {
      names: [gettext('Object Account'), gettext('Object Accounts')]
    });
    registry.getResourceType('OS::Swift::Container', {
      names: [gettext('Object Container'), gettext('Object Containers')]
    });
    registry.getResourceType('OS::Swift::Object', {
      names: [gettext('Object'), gettext('Objects')]
    });
    registry.getResourceType('OS::Neutron::HealthMonitor', {
      names: [gettext('Network Health Monitor'), gettext('Network Health Monitors')]
    });
    registry.getResourceType('OS::Neutron::Net', {
      names: [gettext('Network'), gettext('Networks')]
    });
    registry.getResourceType('OS::Neutron::Pool', {
      names: [gettext('Load Balancer Pool'), gettext('Load Balancer Pools')]
    });
    registry.getResourceType('OS::Neutron::PoolMember', {
      names: [gettext('Load Balancer Pool Member'), gettext('Load Balancer Pool Members')]
    });
    registry.getResourceType('OS::Neutron::Port', {
      names: [gettext('Network Port'), gettext('Network Ports')]
    });
    registry.getResourceType('OS::Neutron::Router', {
      names: [gettext('Network Router'), gettext('Network Routers')]
    });
    registry.getResourceType('OS::Neutron::Subnet', {
      names: [gettext('Network Subnet'), gettext('Network Subnets')]
    });
  }

})();
<commit_msg>Add OS::Nova::Hypervisor display name registration<commit_after>/*
 *    (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function () {
  'use strict';

  // Constants used within this file
  var VOLUME_RESOURCE_TYPE = 'OS::Cinder::Volume';

  /**
   * @ngdoc overview
   * @name horizon.app.core
   * @description
   *
   * # horizon.app.core
   *
   * This module hosts modules of core functionality and services that supports
   * components added to Horizon via its plugin mechanism.
   */
  angular
    .module('horizon.app.core', [
      'horizon.app.core.cloud-services',
      'horizon.app.core.images',
      'horizon.app.core.metadata',
      'horizon.app.core.openstack-service-api',
      'horizon.app.core.workflow',
      'horizon.framework.conf',
      'horizon.framework.util',
      'horizon.framework.widgets',
      'horizon.dashboard.project.workflow'
    ], config)
    // NOTE: this will move into the correct module as that resource type
    // becomes available.  For now there is no volumes module.
    .constant('horizon.app.core.volumes.resourceType', VOLUME_RESOURCE_TYPE)
    .run([
      'horizon.framework.conf.resource-type-registry.service',
      performRegistrations
    ]);

  config.$inject = ['$provide', '$windowProvider'];

  function config($provide, $windowProvider) {
    var path = $windowProvider.$get().STATIC_URL + 'app/core/';
    $provide.constant('horizon.app.core.basePath', path);
  }

  function performRegistrations(registry) {
    // The items in this long list of registrations should ideally placed into
    // respective module declarations.  However, until they are more fully
    // fleshed out there's no reason to pollute the directory/file structure.
    // As a model, the Images registration happens in the images module.
    registry.getResourceType('OS::Glance::Metadef', {
      names: [gettext('Metadata Definition'), gettext('Metadata Definitions')]
    });
    registry.getResourceType('OS::Nova::Server', {
      names: [gettext('Instance'), gettext('Instances')]
    });
    registry.getResourceType('OS::Nova::Flavor', {
      names: [gettext('Flavor'), gettext('Flavors')]
    });
    registry.getResourceType('OS::Nova::Hypervisor', {
      names: [gettext('Hypervisor'), gettext('Hypervisors')]
    });
    registry.getResourceType('OS::Nova::Keypair', {
      names: [gettext('Key Pair'), gettext('Key Pairs')]
    });
    registry.getResourceType('OS::Designate::Zone', {
      names: [gettext('DNS Domain'), gettext('DNS Domains')]
    });
    registry.getResourceType('OS::Designate::RecordSet', {
      names: [gettext('DNS Record'), gettext('DNS Records')]
    });
    registry.getResourceType('OS::Cinder::Backup', {
      names: [gettext('Volume Backup'), gettext('Volume Backups')]
    });
    registry.getResourceType('OS::Cinder::Snapshot', {
      names: [gettext('Volume Snapshot'), gettext('Volume Snapshots')]
    });
    registry.getResourceType(VOLUME_RESOURCE_TYPE, {
      names: [gettext('Volume'), gettext('Volumes')]
    });
    registry.getResourceType('OS::Nova::Flavor', {
      names: [gettext('Flavor'), gettext('Flavors')]
    });
    registry.getResourceType('OS::Swift::Account', {
      names: [gettext('Object Account'), gettext('Object Accounts')]
    });
    registry.getResourceType('OS::Swift::Container', {
      names: [gettext('Object Container'), gettext('Object Containers')]
    });
    registry.getResourceType('OS::Swift::Object', {
      names: [gettext('Object'), gettext('Objects')]
    });
    registry.getResourceType('OS::Neutron::HealthMonitor', {
      names: [gettext('Network Health Monitor'), gettext('Network Health Monitors')]
    });
    registry.getResourceType('OS::Neutron::Net', {
      names: [gettext('Network'), gettext('Networks')]
    });
    registry.getResourceType('OS::Neutron::Pool', {
      names: [gettext('Load Balancer Pool'), gettext('Load Balancer Pools')]
    });
    registry.getResourceType('OS::Neutron::PoolMember', {
      names: [gettext('Load Balancer Pool Member'), gettext('Load Balancer Pool Members')]
    });
    registry.getResourceType('OS::Neutron::Port', {
      names: [gettext('Network Port'), gettext('Network Ports')]
    });
    registry.getResourceType('OS::Neutron::Router', {
      names: [gettext('Network Router'), gettext('Network Routers')]
    });
    registry.getResourceType('OS::Neutron::Subnet', {
      names: [gettext('Network Subnet'), gettext('Network Subnets')]
    });
  }

})();
<|endoftext|>


<commit_before>'use strict'

var gulp        = require('gulp'),
    browserSync = require('browser-sync').get('static-boilerplate'),
    browserify  = require('browserify'),
    source      = require('vinyl-source-stream'),
    buffer      = require('vinyl-buffer'),
    uglify      = require('gulp-uglify');

gulp.task('javascript', function() {
  return browserify('src/js/main.js')
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
    .pipe(browserSync.stream());
});
<commit_msg>enable javascript sourcemaps<commit_after>'use strict'

var gulp        = require('gulp'),
    browserSync = require('browser-sync').get('static-boilerplate'),
    browserify  = require('browserify'),
    source      = require('vinyl-source-stream'),
    sourcemaps  = require('gulp-sourcemaps'),
    buffer      = require('vinyl-buffer'),
    uglify      = require('gulp-uglify');

gulp.task('javascript', function() {
  return browserify('src/js/main.js')
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'))
    .pipe(browserSync.stream());
});
<|endoftext|>