<commit_before>// --
// Core.Customer.js - provides functions for the customer login
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.Customer.Login.js,v 1.4 2010-11-04 11:59:28 mg Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.Customer = Core.Customer || {};

/**
 * @namespace
 * @exports TargetNS as Core.Customer.Login
 * @description
 *      This namespace contains all functions for the Customer login
 */
Core.Customer.Login = (function (TargetNS) {
    if (!Core.Debug.CheckDependency('Core.Customer.Login', 'Core.UI', 'Core.UI')) {
        return;
    }

    /**
     * @function
     * @param {DOMObject} $PopulatedInput is a filled out input filled
     * @description
     *      This function hides the label of the given field if there is value in the field
     *      or the field has focus, otherwise the label is made visible.
     */
    function ToggleLabel(PopulatedInput) {
        var $PopulatedInput = $(PopulatedInput),
            $Label = $PopulatedInput.prev('label');

        if ($PopulatedInput.val() !== "" || $PopulatedInput[0] == document.activeElement) {
            $Label.hide();
        }
        else {
            $Label.show();
        }
    }

    /**
     * @function
     * @description
     *      This function initializes the login functions.
     *      Time gets tracked in an hidden field.
     *      In the login we have for steps:
     *      1. input field gets focused -> label gets greyed out via class="Focused"
     *      2. something is typed -> label gets hidden
     *      3. user leaves input field -> if the field is blank the label gets shown again, 'focused' class gets removed
     *      4. first input field gets focused
     */
    TargetNS.Init = function (Options) {
        var $Inputs = $('input:not(:checked, :hidden, :radio)'),
            $LocalInputs,
            Location,
            Now = new Date(),
            Diff = Now.getTimezoneOffset(),
            $Label,
            $SliderNavigationLinks = $('#Slider a');

        $('#TimeOffset').val(Diff);

        $Inputs
            .focus(function () {
                $Label = $(this).prev('label');
                $(this).prev('label').addClass('Focused');
                if ($(this).val()) {
                    $Label.hide();
                }
            })
            .bind('keyup change', function () {
                ToggleLabel(this);
            })
            .blur(function () {
                $Label = $(this).prev('label');
                if (!$(this).val()) {
                    $Label.show();
                }
                $Label.removeClass('Focused');
            });

         $('#User').blur(function () {
            if ($(this).val()) {
                // set the username-value and hide the field's label
                $('#ResetUser').val('').prev('label').hide();
            }
         });

         // check labels every 250ms, not all changes can be caught via
         //     events (e. g. when the user selects a predefined value
         //     from a browser auto completion list).
         window.setInterval(function(){
             $.each($Inputs, function(Index, Input) {
                 if($(Input).val()){
                     ToggleLabel(Input);
                 }
             });
         }, 250);

        // Fill the reset-password input field with the same value the user types in the login screen
        // so that the user doesnt have to type in his user name again if he already did
        $('#User').blur(function () {
            if ($(this).val()) {
                // clear the username-value and hide the field's label
                $('#ResetUser').val($(this).val()).prev('label').hide();
            }
        });

        // detect the location ("SignUp", "Reset" or "Login"):
        // default location is "Login"
        Location = '#Login';

        // check if the url contains an anchor
        if (document.location.toString().match('#')) {

            // cut out the anchor
            Location = '#' + document.location.toString().split('#')[1];
        }

        // get the input fields of the current location
        $LocalInputs = $(Location).find('input:not(:checked, :hidden, :radio)');

        // focus the first one
        $LocalInputs.first().focus();

        // add all tab-able inputs
        $LocalInputs.add($(Location + ' a, button'));

        // collect all global tab-able inputs
        // give the input fields of all other slides a negative 'tabindex' to prevent
        // the user from accidentally jumping to a hidden input field via the tab key
        $Inputs.add('a, button').not($LocalInputs).attr('tabindex', -1);

        // Change the 'tabindex' according to the navigation of the user
        $SliderNavigationLinks.click(function () {
            var I = 0,
                TargetID,
                $TargetInputs;

            TargetID = $(this).attr('href');

            // get the target id out of the href attribute of the anchor
            $TargetInputs = $(TargetID + ' input:not(:checked, :hidden, :radio), ' + TargetID +' a, ' + TargetID + ' button');

            // give the inputs on the slide the user just leaves all a 'tabindex' of '-1'
            $(this).parentsUntil('#SlideArea').last().find('input:not(:checked, :hidden, :radio), a, button').attr('tabindex', -1);

            // give all inputs on the new shown slide an increasing 'tabindex'
            for (I; I< $TargetInputs.length; I++) {
                $TargetInputs.eq(I).attr('tabindex', I + 1);
            }
        });

        // shake login box on autentification failed
        if (Options && Options.LastLoginFailed) {
            Core.UI.Shake($('#Login'));
        }
    };

    return TargetNS;
}(Core.Customer.Login || {}));
<commit_msg>Fixed JSLint error.<commit_after>// --
// Core.Customer.js - provides functions for the customer login
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.Customer.Login.js,v 1.5 2010-12-07 18:53:35 ub Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.Customer = Core.Customer || {};

/**
 * @namespace
 * @exports TargetNS as Core.Customer.Login
 * @description
 *      This namespace contains all functions for the Customer login
 */
Core.Customer.Login = (function (TargetNS) {
    if (!Core.Debug.CheckDependency('Core.Customer.Login', 'Core.UI', 'Core.UI')) {
        return;
    }

    /**
     * @function
     * @param {DOMObject} $PopulatedInput is a filled out input filled
     * @description
     *      This function hides the label of the given field if there is value in the field
     *      or the field has focus, otherwise the label is made visible.
     */
    function ToggleLabel(PopulatedInput) {
        var $PopulatedInput = $(PopulatedInput),
            $Label = $PopulatedInput.prev('label');

        if ($PopulatedInput.val() !== "" || $PopulatedInput[0] === document.activeElement) {
            $Label.hide();
        }
        else {
            $Label.show();
        }
    }

    /**
     * @function
     * @description
     *      This function initializes the login functions.
     *      Time gets tracked in an hidden field.
     *      In the login we have for steps:
     *      1. input field gets focused -> label gets greyed out via class="Focused"
     *      2. something is typed -> label gets hidden
     *      3. user leaves input field -> if the field is blank the label gets shown again, 'focused' class gets removed
     *      4. first input field gets focused
     */
    TargetNS.Init = function (Options) {
        var $Inputs = $('input:not(:checked, :hidden, :radio)'),
            $LocalInputs,
            Location,
            Now = new Date(),
            Diff = Now.getTimezoneOffset(),
            $Label,
            $SliderNavigationLinks = $('#Slider a');

        $('#TimeOffset').val(Diff);

        $Inputs
            .focus(function () {
                $Label = $(this).prev('label');
                $(this).prev('label').addClass('Focused');
                if ($(this).val()) {
                    $Label.hide();
                }
            })
            .bind('keyup change', function () {
                ToggleLabel(this);
            })
            .blur(function () {
                $Label = $(this).prev('label');
                if (!$(this).val()) {
                    $Label.show();
                }
                $Label.removeClass('Focused');
            });

         $('#User').blur(function () {
            if ($(this).val()) {
                // set the username-value and hide the field's label
                $('#ResetUser').val('').prev('label').hide();
            }
         });

         // check labels every 250ms, not all changes can be caught via
         //     events (e. g. when the user selects a predefined value
         //     from a browser auto completion list).
         window.setInterval(function(){
             $.each($Inputs, function(Index, Input) {
                 if($(Input).val()){
                     ToggleLabel(Input);
                 }
             });
         }, 250);

        // Fill the reset-password input field with the same value the user types in the login screen
        // so that the user doesnt have to type in his user name again if he already did
        $('#User').blur(function () {
            if ($(this).val()) {
                // clear the username-value and hide the field's label
                $('#ResetUser').val($(this).val()).prev('label').hide();
            }
        });

        // detect the location ("SignUp", "Reset" or "Login"):
        // default location is "Login"
        Location = '#Login';

        // check if the url contains an anchor
        if (document.location.toString().match('#')) {

            // cut out the anchor
            Location = '#' + document.location.toString().split('#')[1];
        }

        // get the input fields of the current location
        $LocalInputs = $(Location).find('input:not(:checked, :hidden, :radio)');

        // focus the first one
        $LocalInputs.first().focus();

        // add all tab-able inputs
        $LocalInputs.add($(Location + ' a, button'));

        // collect all global tab-able inputs
        // give the input fields of all other slides a negative 'tabindex' to prevent
        // the user from accidentally jumping to a hidden input field via the tab key
        $Inputs.add('a, button').not($LocalInputs).attr('tabindex', -1);

        // Change the 'tabindex' according to the navigation of the user
        $SliderNavigationLinks.click(function () {
            var I = 0,
                TargetID,
                $TargetInputs;

            TargetID = $(this).attr('href');

            // get the target id out of the href attribute of the anchor
            $TargetInputs = $(TargetID + ' input:not(:checked, :hidden, :radio), ' + TargetID +' a, ' + TargetID + ' button');

            // give the inputs on the slide the user just leaves all a 'tabindex' of '-1'
            $(this).parentsUntil('#SlideArea').last().find('input:not(:checked, :hidden, :radio), a, button').attr('tabindex', -1);

            // give all inputs on the new shown slide an increasing 'tabindex'
            for (I; I< $TargetInputs.length; I++) {
                $TargetInputs.eq(I).attr('tabindex', I + 1);
            }
        });

        // shake login box on autentification failed
        if (Options && Options.LastLoginFailed) {
            Core.UI.Shake($('#Login'));
        }
    };

    return TargetNS;
}(Core.Customer.Login || {}));
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var pkg = require('../package');

/**
 * Register it with angular
 */

pkg.directive('hyperRedirect', [
  '$location',
  'hyperLink',
  'hyperStatus',
  function($location, hyperLink, status) {
    return {
      link: function($scope, elem, attrs) {
        status.loading(elem);

        hyperLink.watch(attrs.hyperRedirect, $scope, function(href) {
          $location.path(href);
        });
      }
    };
  }
]);
<commit_msg>replace location for hyper-redirect<commit_after>/**
 * Module dependencies
 */

var pkg = require('../package');

/**
 * Register it with angular
 */

pkg.directive('hyperRedirect', [
  '$location',
  'hyperLink',
  'hyperStatus',
  function($location, hyperLink, status) {
    return {
      link: function($scope, elem, attrs) {
        status.loading(elem);

        hyperLink.watch(attrs.hyperRedirect, $scope, function(href) {
          $location.replace();
          $location.path(href);
        });
      }
    };
  }
]);
<|endoftext|>


<commit_before>const request = require('request-promise');
const fetch = require('node-fetch');

const { mapFromActionObject, mapToActionObject } = require('../util');

const getGroupsRoot = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  request({
    method: 'GET',
    url: `http://${hueBridge}/api/${hueUser}/groups`,
    json: true
  })
    .then(result => {
      res.json(
        Object.keys(result).reduce((acc, k) => {
          acc.push({
            id: k,
            name: result[k].name,
            lightIds: result[k].lights,
            state: result[k].state
          });
          return acc;
        }, [])
      );
    })
    .catch(err => {
      console.log(err);
      res.status(500).json(err);
    });
};

const getGroupsRootAsync = async (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  try {
    const response = await fetch(`http://${hueBridge}/api/${hueUser}/groups`, {
      method: 'GET'
    });
    const json = await response.json();

    res.json(
      Object.keys(json).reduce((acc, k) => {
        acc.push({
          id: k,
          name: json[k].name,
          lightIds: json[k].lights,
          state: json[k].state
        });
        return acc;
      }, [])
    );
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

const getGroupsId = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  request({
    method: 'GET',
    url: `http://${hueBridge}/api/${hueUser}/groups/${req.params.id}`,
    json: true
  })
    .then(result => {
      res.json({
        id: req.params.id,
        name: result.name,
        lightIds: result.lights,
        state: result.state,
        action: mapFromActionObject(result.action)
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json(err);
    });
};

const postGroupIdAction = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;
  const validKeys = ['on', 'color', 'colorTemp', 'colorloop'];

  const validRequest = Object.keys(req.body).reduce(
    (acc, k) => acc || validKeys.indexOf(k) !== -1,
    false
  );

  if (validRequest) {
    request({
      method: 'PUT',
      url: `http://${hueBridge}/api/${hueUser}/groups/${req.params.id}/action`,
      body: mapToActionObject(req.body),
      json: true
    })
      .then(result => {
        res.json(result);
      })
      .catch(err => {
        console.log(err);
        res.status(500).json(err);
      });
  } else {
    res.status(400).json({
      status: 400,
      message: 'Malformed request body'
    });
  }
};

module.exports = {
  getGroupsRoot,
  getGroupsRootAsync,
  getGroupsId,
  postGroupIdAction
};
<commit_msg>added a node-fetch based handler for groups/id<commit_after>const request = require('request-promise');
const fetch = require('node-fetch');

const { mapFromActionObject, mapToActionObject } = require('../util');

const getGroupsRoot = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  request({
    method: 'GET',
    url: `http://${hueBridge}/api/${hueUser}/groups`,
    json: true
  })
    .then(result => {
      res.json(
        Object.keys(result).reduce((acc, k) => {
          acc.push({
            id: k,
            name: result[k].name,
            lightIds: result[k].lights,
            state: result[k].state
          });
          return acc;
        }, [])
      );
    })
    .catch(err => {
      console.log(err);
      res.status(500).json(err);
    });
};

const getGroupsRootAsync = async (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  try {
    const response = await fetch(`http://${hueBridge}/api/${hueUser}/groups`, {
      method: 'GET'
    });
    const json = await response.json();

    res.json(
      Object.keys(json).reduce((acc, k) => {
        acc.push({
          id: k,
          name: json[k].name,
          lightIds: json[k].lights,
          state: json[k].state
        });
        return acc;
      }, [])
    );
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

const getGroupsId = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  request({
    method: 'GET',
    url: `http://${hueBridge}/api/${hueUser}/groups/${req.params.id}`,
    json: true
  })
    .then(result => {
      res.json({
        id: req.params.id,
        name: result.name,
        lightIds: result.lights,
        state: result.state,
        action: mapFromActionObject(result.action)
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json(err);
    });
};

const getGroupsIdAsync = async (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;

  try {
    const response = await fetch(
      `http://${hueBridge}/api/${hueUser}/groups/${req.params.id}`,
      {
        method: 'GET'
      }
    );

    const json = await response.json();

    res.json({
      id: req.params.id,
      name: json.name,
      lightIds: json.lights,
      state: json.state,
      action: mapFromActionObject(json.action)
    });
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

const postGroupIdAction = (req, res) => {
  const hueUser = process.env.HUE_BRIDGE_USERNAME;
  const hueBridge = process.env.HUE_BRIDGE_ADDRESS;
  const validKeys = ['on', 'color', 'colorTemp', 'colorloop'];

  const validRequest = Object.keys(req.body).reduce(
    (acc, k) => acc || validKeys.indexOf(k) !== -1,
    false
  );

  if (validRequest) {
    request({
      method: 'PUT',
      url: `http://${hueBridge}/api/${hueUser}/groups/${req.params.id}/action`,
      body: mapToActionObject(req.body),
      json: true
    })
      .then(result => {
        res.json(result);
      })
      .catch(err => {
        console.log(err);
        res.status(500).json(err);
      });
  } else {
    res.status(400).json({
      status: 400,
      message: 'Malformed request body'
    });
  }
};

module.exports = {
  getGroupsRoot,
  getGroupsRootAsync,
  getGroupsId,
  getGroupsIdAsync,
  postGroupIdAction
};
<|endoftext|>


<commit_before>angular.module('fileupload', [])
.directive('myFileupload', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).fileupload({
                dataType: 'json'
              , change: function(e, data) {
 		            $('#changeCoverButton #changeButtonText').html('Uploading...');
                }
              , success: function(data) {
	                $('#changeCoverButton #changeButtonText').html('Crunching Image...');

                    if(data.error) {

                        $('#changeCoverButton #changeButtonText').html(data.error + ' Click to Choose File Again' );

                    } else {

                        $('#coverPhoto').attr('src', data.msg);
                        $('#defaultCoverPhoto').remove();

                        $('<img />')
                            .attr('src', data.msg)
                            .load(function() {
                                $('#changeCoverButton').fadeOut('fast',function(){
                                    $(this).find('#changeButtonText').html('Change Cover');
                                    $('#dragPhoto').fadeIn('fast');
                                    $('#saveCoverButton').fadeIn('fast');
                                });
                                deactivate_drag(true);
                            });
                    }
                }
            });
        }
    }
})
.directive('saveMyupload', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var cover_src = $('#theCover img');
                var img_src_attrs = {
                    src : cover_src.attr('src'),
                    top : cover_src.offset().top,
                    left: 0
                }

                $.ajax({
                    url: "/imageprocessing/savecoverphoto",
                    type: "POST",
                    dataType: "JSON",
                    data: img_src_attrs,
                    success: function(res) {
     		            $(element).html('Cover Saved');

                        var timeout;

                        if(timeout) {
                            clearTimeout(timeout);
                            timeout = null;
                        }

                        timeout = setTimeout(hide_save_button, 1000);
                    }
                });

                e.preventDefault();
            });
        }
    }
})

function deactivate_drag(flag) {
    if(!flag) {
        console.log('Draggable Disabled');
        $("#theCover img").draggable({disabled: true});
    } else {
        console.log('Draggable Enabled');
        $("#theCover img").load(function(){
            var offset = $(this).parent().offset();
            var offsetX = offset.left;
            $(this).each(function(){
                var imgH = $(this).height();
                var parH = $(this).parent().height();
                var imgW = $(this).width();
                var parW = $(this).parent().width();
                var ipH = imgH-parH;
                var ipW = imgW-parW-offsetX;
                $(this).draggable({ containment: [-ipW, -ipH, offsetX, 0], scroll: false, disabled: opt});
            });
        });
    }
}

function hide_save_button(){
    $('#saveCoverButton').fadeOut('fast',function(){
        $(this).html('Save Cover');
    });
    $('#changeCoverButton').fadeIn('fast');
    $('#dragPhoto').fadeOut('fast');
    deactivate_drag(false);
}
<commit_msg>hmmmm<commit_after>angular.module('fileupload', [])
.directive('myFileupload', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).fileupload({
                dataType: 'json'
              , change: function(e, data) {
 		            $('#changeCoverButton #changeButtonText').html('Uploading...');
                }
              , success: function(data) {
	                $('#changeCoverButton #changeButtonText').html('Crunching Image...');

                    if(data.error) {

                        $('#changeCoverButton #changeButtonText').html(data.error + ' Click to Choose File Again' );

                    } else {

                        $('#coverPhoto').attr('src', data.msg);
                        $('#defaultCoverPhoto').remove();

                        $('<img />')
                            .attr('src', data.msg)
                            .load(function() {
                                $('#changeCoverButton').fadeOut('fast',function(){
                                    $(this).find('#changeButtonText').html('Change Cover');
                                    $('#dragPhoto').fadeIn('fast');
                                    $('#saveCoverButton').fadeIn('fast');
                                });
                                deactivate_drag(false);
                            });
                    }
                }
            });
        }
    }
})
.directive('saveMyupload', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var cover_src = $('#theCover img');
                var img_src_attrs = {
                    src : cover_src.attr('src'),
                    top : cover_src.offset().top,
                    left: 0
                }

                $.ajax({
                    url: "/imageprocessing/savecoverphoto",
                    type: "POST",
                    dataType: "JSON",
                    data: img_src_attrs,
                    success: function(res) {
     		            $(element).html('Cover Saved');

                        var timeout;

                        if(timeout) {
                            clearTimeout(timeout);
                            timeout = null;
                        }

                        timeout = setTimeout(hide_save_button, 1000);
                    }
                });

                e.preventDefault();
            });
        }
    }
})

function deactivate_drag(flag) {
    if(!flag) {
        console.log('Draggable Enabled');
        $("#theCover img").load(function(){
            var offset = $(this).parent().offset();
            var offsetX = offset.left;
            $(this).each(function(){
                var imgH = $(this).height();
                var parH = $(this).parent().height();
                var imgW = $(this).width();
                var parW = $(this).parent().width();
                var ipH = imgH-parH;
                var ipW = imgW-parW-offsetX;
                $(this).draggable({ containment: [-ipW, -ipH, offsetX, 0], scroll: false, disabled: opt});
            });
        });
    } else {
        console.log('Draggable Disabled');
        $("#theCover img").draggable({disabled: true});
    }
}

function hide_save_button(){
    $('#saveCoverButton').fadeOut('fast',function(){
        $(this).html('Save Cover');
    });
    $('#changeCoverButton').fadeIn('fast');
    $('#dragPhoto').fadeOut('fast');
    deactivate_drag(true);
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';

const {
  Component,
  computed
} = Ember;

export default Component.extend({
  // HTML
  layout,

  // properties
  allowQuickSearch: true,
  content: [],
  isRemoteHandled: false,
  page: 1,
  perPage: 5,
  searchString: '',
  tableTitle: 'title',
  totalPages: 5,

  // computed
  filteredContent: computed('content', 'searchString', 'isRemoteHandled', function() {
    let content = this.get('content');
    let isRemoteHandled = this.get('isRemoteHandled');
    if (isRemoteHandled) {
      return content;
    } else {
      let searchString = this.get('searchString');
      return content.filter(function(item) {
        Ember.Logger.debug('item -> ', item);
        Ember.Logger.debug(arguments);
        let pattern = new RegExp(searchString, 'i');
        let found = false;
        item.eachAttribute(function(name, meta) {
          if (['number', 'string', 'date'].contains(meta.type)) {
            found = found || pattern.test(item.get(name));
          }
        });
        Ember.Logger.debug('is item %s matching %s ? -> %s', item.get('idNum'), searchString, found);
        return found;
      });
    }
  }),
  currentContent: computed('filteredContent', 'page', 'perPage', 'isRemoteHandled', function() {
    let content = this.get('filteredContent');
    let isRemoteHandled = this.get('isRemoteHandled');
    if (isRemoteHandled) {
      return content;
    } else {
      let page = this.get('page');
      let perPage = this.get('perPage');

      // we are handling the data ourself so:
      // we should display only the items on the current page:
      // a.k.a. perPage items starting at perPageItems*page
      return content.slice(perPage * (page - 1), perPage * (page - 1) + perPage);
    }
  }),
  // overwritable components
  bodyComponent: 'table-pagination.table-body',
  contentComponent: 'table-pagination.table-content',
  pagerComponent: 'table-pagination.table-pager',
  titleComponent: 'table-pagination.table-title',
  toolbarComponent: 'table-pagination.table-toolbar',
  toolsComponent: 'table-pagination.table-tools'
});
<commit_msg>add some JSDoc comments<commit_after>import Ember from 'ember';
import layout from './template';

const {
  Component,
  Object,
  computed
} = Ember;
const {
  alias,
  reads,
  sort
} = computed;

export default Component.extend({
  // HTML
  layout,

  // properties

  /**
   * @public
   * @type boolean
   */
  allowQuickSearch: true,
  /**
   * @public
   * @type Array
   */
  content: [],
  /**
   * @public
   * @typedef {fieldName: string, displayName: string, disableServerInteractions: boolean, enableSearch: boolean} Field
   */
  /**
   * @public
   * @type Field
   */
  fields: [],
  /**
   * @public
   * @type boolean
   */
  isRemoteHandled: false,
  /**
   * @public
   * @type boolean
   */
  loading: false,
  /**
   * @public
   * @type number
   */
  page: 1,
  /**
   * @public
   * @type number
   */
  perPage: 5,
  /**
   * @public
   * @type string
   */
  searchString: '',
  /**
   * @private
   * @type string
   */
  sorting: null,
  /**
   * @private
   * @type string
   */
  sortDirection: null,
  /**
   * @public
   * @type string
   */
  tableTitle: 'title',
  totalPages: 5,

  // computed
  filteredContent: computed('content', 'searchString', 'isRemoteHandled', function() {
    let content = this.get('content');
    let isRemoteHandled = this.get('isRemoteHandled');
    if (isRemoteHandled) {
      return content;
    } else {
      let searchString = this.get('searchString');
      return content.filter(function(item) {
        Ember.Logger.debug('item -> ', item);
        Ember.Logger.debug(arguments);
        let pattern = new RegExp(searchString, 'i');
        let found = false;
        item.eachAttribute(function(name, meta) {
          if (['number', 'string', 'date'].contains(meta.type)) {
            found = found || pattern.test(item.get(name));
          }
        });
        Ember.Logger.debug('is item %s matching %s ? -> %s', item.get('idNum'), searchString, found);
        return found;
      });
    }
  }),
  currentContent: computed('filteredContent', 'page', 'perPage', 'isRemoteHandled', function() {
    let content = this.get('filteredContent');
    let isRemoteHandled = this.get('isRemoteHandled');
    if (isRemoteHandled) {
      return content;
    } else {
      let page = this.get('page');
      let perPage = this.get('perPage');

      // we are handling the data ourself so:
      // we should display only the items on the current page:
      // a.k.a. perPage items starting at perPageItems*page
      return content.slice(perPage * (page - 1), perPage * (page - 1) + perPage);
    }
  }),
  // overwritable components
  bodyComponent: 'table-pagination.table-body',
  contentComponent: 'table-pagination.table-content',
  pagerComponent: 'table-pagination.table-pager',
  titleComponent: 'table-pagination.table-title',
  toolbarComponent: 'table-pagination.table-toolbar',
  toolsComponent: 'table-pagination.table-tools'
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } c<|endoftext|>


<commit_before>import * as ACTIONS from 'constants/action_types';
import { getAuthToken } from 'util/saved-passwords';
import { doNotificationList } from 'redux/actions/notifications';

const NOTIFICATION_WS_URL = 'wss://api.lbry.com/subscribe?auth_token=';
const COMMENT_WS_URL = `wss://comments.lbry.com/api/v2/live-chat/subscribe?subscription_id=`;

let sockets = {};
let closingSockets = {};
let retryCount = 0;

export const doSocketConnect = (url, cb) => {
  function connectToSocket() {
    if (sockets[url] !== undefined && sockets[url] !== null) {
      sockets[url].close();
      sockets[url] = null;
    }

    const timeToWait = retryCount ** 2 * 1000;
    setTimeout(() => {
      sockets[url] = new WebSocket(url);
      sockets[url].onopen = (e) => {
        retryCount = 0;
        console.log('\nConnected to WS \n\n'); // eslint-disable-line
      };

      sockets[url].onmessage = (e) => {
        const data = JSON.parse(e.data);
        cb(data);
      };

      sockets[url].onerror = (e) => {
        console.error('websocket onerror', e); // eslint-disable-line
        // onerror and onclose will both fire, so nothing is needed here
      };

      sockets[url].onclose = () => {
        console.log('\n Disconnected from WS\n\n'); // eslint-disable-line
        if (!closingSockets[url]) {
          retryCount += 1;
          connectToSocket();
        } else {
          closingSockets[url] = null;
        }
      };
    }, timeToWait);
  }

  connectToSocket();
};

export const doSocketDisconnect = (url) => (dispatch) => {
  if (sockets[url] !== undefined && sockets[url] !== null) {
    closingSockets[url] = true;
    sockets[url].close();
    sockets[url] = null;

    dispatch({
      type: ACTIONS.WS_DISCONNECT,
    });
  }
};

export const doNotificationSocketConnect = (enableNotifications) => (dispatch) => {
  const authToken = getAuthToken();
  if (!authToken) {
    console.error('Unable to connect to web socket because auth token is missing'); // eslint-disable-line
    return;
  }

  const url = `${NOTIFICATION_WS_URL}${authToken}`;

  doSocketConnect(url, (data) => {
    switch (data.type) {
      case 'pending_notification':
        if (enableNotifications) {
          dispatch(doNotificationList());
        }
        break;
      case 'swap-status':
        dispatch({
          type: ACTIONS.COIN_SWAP_STATUS_RECEIVED,
          data: data.data,
        });
        break;
    }
  });
};

export const doCommentSocketConnect = (uri, claimId) => (dispatch) => {
  const url = `${COMMENT_WS_URL}${claimId}`;

  doSocketConnect(url, (response) => {
    if (response.type === 'delta') {
      const newComment = response.data.comment;
      dispatch({
        type: ACTIONS.COMMENT_RECEIVED,
        data: { comment: newComment, claimId, uri },
      });
    }
  });
};

export const doCommentSocketDisconnect = (claimId) => (dispatch) => {
  const url = `${COMMENT_WS_URL}${claimId}`;
  dispatch(doSocketDisconnect(url));
};
<commit_msg>new comment websocket url<commit_after>import * as ACTIONS from 'constants/action_types';
import { getAuthToken } from 'util/saved-passwords';
import { doNotificationList } from 'redux/actions/notifications';

const NOTIFICATION_WS_URL = 'wss://api.lbry.com/subscribe?auth_token=';
const COMMENT_WS_URL = 'wss://sockety.lbry.com/ws/commentron?id=';

let sockets = {};
let closingSockets = {};
let retryCount = 0;

export const doSocketConnect = (url, cb) => {
  function connectToSocket() {
    if (sockets[url] !== undefined && sockets[url] !== null) {
      sockets[url].close();
      sockets[url] = null;
    }

    const timeToWait = retryCount ** 2 * 1000;
    setTimeout(() => {
      sockets[url] = new WebSocket(url);
      sockets[url].onopen = (e) => {
        retryCount = 0;
        console.log('\nConnected to WS \n\n'); // eslint-disable-line
      };

      sockets[url].onmessage = (e) => {
        const data = JSON.parse(e.data);
        cb(data);
      };

      sockets[url].onerror = (e) => {
        console.error('websocket onerror', e); // eslint-disable-line
        // onerror and onclose will both fire, so nothing is needed here
      };

      sockets[url].onclose = () => {
        console.log('\n Disconnected from WS\n\n'); // eslint-disable-line
        if (!closingSockets[url]) {
          retryCount += 1;
          connectToSocket();
        } else {
          closingSockets[url] = null;
        }
      };
    }, timeToWait);
  }

  connectToSocket();
};

export const doSocketDisconnect = (url) => (dispatch) => {
  if (sockets[url] !== undefined && sockets[url] !== null) {
    closingSockets[url] = true;
    sockets[url].close();
    sockets[url] = null;

    dispatch({
      type: ACTIONS.WS_DISCONNECT,
    });
  }
};

export const doNotificationSocketConnect = (enableNotifications) => (dispatch) => {
  const authToken = getAuthToken();
  if (!authToken) {
    console.error('Unable to connect to web socket because auth token is missing'); // eslint-disable-line
    return;
  }

  const url = `${NOTIFICATION_WS_URL}${authToken}`;

  doSocketConnect(url, (data) => {
    switch (data.type) {
      case 'pending_notification':
        if (enableNotifications) {
          dispatch(doNotificationList());
        }
        break;
      case 'swap-status':
        dispatch({
          type: ACTIONS.COIN_SWAP_STATUS_RECEIVED,
          data: data.data,
        });
        break;
    }
  });
};

export const doCommentSocketConnect = (uri, claimId) => (dispatch) => {
  const url = `${COMMENT_WS_URL}${claimId}`;

  doSocketConnect(url, (response) => {
    if (response.type === 'delta') {
      const newComment = response.data.comment;
      dispatch({
        type: ACTIONS.COMMENT_RECEIVED,
        data: { comment: newComment, claimId, uri },
      });
    }
  });
};

export const doCommentSocketDisconnect = (claimId) => (dispatch) => {
  const url = `${COMMENT_WS_URL}${claimId}`;
  dispatch(doSocketDisconnect(url));
};
<|endoftext|>


<commit_before>/* global define */

define([
    'underscore',
    'cilantro',
    'backbone',
    'marionette',
    '../../utils'
], function(_, c, Backbone, Marionette, utils) {

    var EffectItem = Marionette.ItemView.extend({
        tagName: 'li',

        template: 'varify/variant/effect-item',

        templateHelpers: function() {
            var hgvsc = this.model.get('hgvs_c') || '',
                segment = this.model.get('segment') || '',
                hgvscOrSegment = '';

            if (hgvsc) {
                hgvscOrSegment = hgvsc + ' ' + segment;
            }
            else {
                hgvscOrSegment = segment;
            }

            var gene, transcript = this.model.get('transcript'),
                uniqueGenes = this.model.get('uniqueGenes');

            if (uniqueGenes && uniqueGenes.length && transcript) {
                gene = transcript.gene;
            }

            var proteinChange, changeString =
                this.model.get('hgvs_p') || this.model.get('amino_acid_change');

            if (changeString) {
                /*
                 *  Key is the basic physicochemical property of the amino acid
                 *  And each character in the value string are the categorizations
                 *  Inspecting the hgvs_p will tell us about the protein change
                 *  For more info refer to
                 *  https://www.ncbi.nlm.nih.gov/Class/Structure/aa/aa_explorer.cgi
                 */

                var changes = {
                    'Non-Polar': 'IFVLWMAGP',
                    'Polar': 'CYTSNQ',
                    'Negative': 'ED',
                    'Positive': 'HKR'
                };
                var initialAminoAcid = changeString[2],
                    finalAminoAcid = changeString[changeString.length - 1],
                    initialProperty = '',
                    finalProperty = '';

                // Check if there was a change in the hgvs_p
                for (var change in changes) {
                    if (changes[change].indexOf(initialAminoAcid) !== -1) {
                        initialProperty = change;
                    }
                    if (changes[change].indexOf(finalAminoAcid) !== -1) {
                        finalProperty = '&#8594' + change;
                    }
                }

                if (initialProperty && finalProperty) {
                    proteinChange = initialProperty + finalProperty;
                }
            }

            return {
                hgvscOrSegment: hgvscOrSegment,
                gene: gene,
                changeString: changeString,
                proteinChange: proteinChange
            };
        }
    });

    var EffectType = Marionette.CompositeView.extend({
        tagName: 'ul',

        className: 'unstyled',

        template: 'varify/variant/effect-type',

        itemViewContainer: '[data-target=items]',

        itemView: EffectItem,

        templateHelpers: function() {
            var priorityClass = '';

            if (this.collection.length) {
                priorityClass = utils.priorityClass(
                    utils.effectImpactPriority(
                        this.collection.models[0].get('impact')));
            }

            return {
                priorityClass: priorityClass
            };
        }
    });

    var NoEffectsView = c.ui.EmptyView.extend({
        className: 'muted',

        icon: '',

        message: 'No SNPEff effects known',

        align: 'left'
    });

    var Effects = Marionette.CompositeView.extend({
        template: 'varify/variant/effects',

        emptyView: NoEffectsView,

        itemViewContainer: '[data-target=items]',

        itemView: EffectType,

        itemViewOptions: function(model) {
            return {
                collection: new Backbone.Collection(model.get('effects'))
            };
        }
    });

    return {
        Effects: Effects
    };

});
<commit_msg>Clarify assignments of variables used in effects region<commit_after>/* global define */

define([
    'underscore',
    'cilantro',
    'backbone',
    'marionette',
    '../../utils'
], function(_, c, Backbone, Marionette, utils) {

    var EffectItem = Marionette.ItemView.extend({
        tagName: 'li',

        template: 'varify/variant/effect-item',

        templateHelpers: function() {
            var hgvsc = this.model.get('hgvs_c') || '',
                segment = this.model.get('segment') || '',
                hgvscOrSegment = '';

            if (hgvsc) {
                hgvscOrSegment = hgvsc + ' ' + segment;
            }
            else {
                hgvscOrSegment = segment;
            }

            var gene, transcript = this.model.get('transcript'),
                uniqueGenes = this.model.get('uniqueGenes');

            if (uniqueGenes && uniqueGenes.length && transcript) {
                gene = transcript.gene;
            }

            var proteinChange,
                changeString = this.model.get('hgvs_p') ||
                    this.model.get('amino_acid_change');

            if (changeString) {
                /*
                 *  Key is the basic physicochemical property of the amino acid
                 *  And each character in the value string are the categorizations
                 *  Inspecting the hgvs_p will tell us about the protein change
                 *  For more info refer to
                 *  https://www.ncbi.nlm.nih.gov/Class/Structure/aa/aa_explorer.cgi
                 */

                var changes = {
                    'Non-Polar': 'IFVLWMAGP',
                    'Polar': 'CYTSNQ',
                    'Negative': 'ED',
                    'Positive': 'HKR'
                };
                var initialAminoAcid = changeString[2],
                    finalAminoAcid = changeString[changeString.length - 1],
                    initialProperty = '',
                    finalProperty = '';

                // Check if there was a change in the hgvs_p
                for (var change in changes) {
                    if (changes[change].indexOf(initialAminoAcid) !== -1) {
                        initialProperty = change;
                    }
                    if (changes[change].indexOf(finalAminoAcid) !== -1) {
                        finalProperty = '&#8594' + change;
                    }
                }

                if (initialProperty && finalProperty) {
                    proteinChange = initialProperty + finalProperty;
                }
            }

            return {
                hgvscOrSegment: hgvscOrSegment,
                gene: gene,
                changeString: changeString,
                proteinChange: proteinChange
            };
        }
    });

    var EffectType = Marionette.CompositeView.extend({
        tagName: 'ul',

        className: 'unstyled',

        template: 'varify/variant/effect-type',

        itemViewContainer: '[data-target=items]',

        itemView: EffectItem,

        templateHelpers: function() {
            var priorityClass = '';

            if (this.collection.length) {
                priorityClass = utils.priorityClass(
                    utils.effectImpactPriority(
                        this.collection.models[0].get('impact')));
            }

            return {
                priorityClass: priorityClass
            };
        }
    });

    var NoEffectsView = c.ui.EmptyView.extend({
        className: 'muted',

        icon: '',

        message: 'No SNPEff effects known',

        align: 'left'
    });

    var Effects = Marionette.CompositeView.extend({
        template: 'varify/variant/effects',

        emptyView: NoEffectsView,

        itemViewContainer: '[data-target=items]',

        itemView: EffectType,

        itemViewOptions: function(model) {
            return {
                collection: new Backbone.Collection(model.get('effects'))
            };
        }
    });

    return {
        Effects: Effects
    };

});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the <commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the r<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 1<commit_msg>Logic error<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.FAKETIME) {
      t_offset = t_offset + timeout;
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = timeout * 10<|endoftext|>


<commit_before>/* globals Ember */
var version = '0.8.0-beta.18';
Ember.libraries.register('Ember Flexberry', version);
<commit_msg>Released 0.8.0-beta.19<commit_after>/* globals Ember */
var version = '0.8.0-beta.19';
Ember.libraries.register('Ember Flexberry', version);
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usag<commit_msg>Really commit all the required changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage<|endoftext|>


<commit_before>'use strict';

var Steppy = require('twostep').Steppy,
	_ = require('underscore'),
	Distributor = require('./lib/distributor').Distributor,
	getAvgProjectBuildDuration = (
		require('./lib/project').getAvgProjectBuildDuration
	),
	db = require('./db'),
	logger = require('./lib/logger')('distributor');

exports.init = function(app, callback) {
	var distributor = new Distributor({
		nodes: app.config.nodes,
		projects: app.projects,
		saveBuild: function(build, callback) {
			Steppy(
				function() {
					if (_(build.project).has('avgBuildDuration')) {
						this.pass(build.project.avgBuildDuration);
					} else {
						getAvgProjectBuildDuration(build.project.name, this.slot());
					}
				},
				function(err, avgBuildDuration) {
					build.project.avgBuildDuration = avgBuildDuration;

					db.builds.put(build, this.slot());
				},
				function() {
					this.pass(build);
				},
				callback
			);
		}
	});

	var buildDataResourcesHash = {};

	// create resource for build data
	var createBuildDataResource = function(buildId) {
		if (buildId in buildDataResourcesHash) {
			return;
		}
		var buildDataResource = app.dataio.resource('build' + buildId);
		buildDataResource.on('connection', function(client) {
			var callback = this.async();
			Steppy(
				function() {
					db.logLines.find({
						start: {buildId: buildId, numberStr: ''},
					}, this.slot());
				},
				function(err, lines) {
					client.emit('sync', 'data', {lines: lines});
					this.pass(true);
				},
				function(err) {
					if (err) {
						logger.error(
							'error during read log for "' + buildId + '":',
							err.stack || err
						);
					}
					callback();
				}
			);
		});
		buildDataResourcesHash[buildId] = buildDataResource;
	};

	exports.createBuildDataResource = createBuildDataResource;

	distributor.on('buildUpdate', function(build, changes) {
		var buildsResource = app.dataio.resource('builds');

		if (build.status === 'queued') {
			createBuildDataResource(build.id);
		}

		// notify about build's project change, coz building affects project
		// related stat (last build date, avg build time, etc)
		if (changes.completed) {
			var projectsResource = app.dataio.resource('projects');
			projectsResource.clientEmitSyncChange({name: build.project.name});
		}

		buildsResource.clientEmitSync('change', {
			buildId: build.id, changes: changes
		});
	});

	var buildLogLineNumbersHash = {};

	distributor.on('buildData', function(build, data) {
		var lines = _(data.split('\n')).chain().invoke('trim').compact().value(),
			logLineNumber = buildLogLineNumbersHash[build.id] || 0;

		lines = _(lines).map(function(line, index) {
			return {
				number: logLineNumber + index,
				text: line
			};
		});
		buildLogLineNumbersHash[build.id] = logLineNumber + lines.length;

		app.dataio.resource('build' + build.id).clientEmitSync(
			'data',
			{lines: lines}
		);

		_(lines).each(function(line) {
			line.buildId = build.id;
		});
		// write build logs to db
		if (lines.length) {
			db.logLines.put(lines, function(err) {
				if (err) {
					logger.error(
						'Error during write log line "' + logLineNumber +
						'" for build "' + build.id + '":',
						err.stack || err
					);
				}
			});
		}
	});

	callback(null, distributor);
};
<commit_msg>replace trim with just \r handler<commit_after>'use strict';

var Steppy = require('twostep').Steppy,
	_ = require('underscore'),
	Distributor = require('./lib/distributor').Distributor,
	getAvgProjectBuildDuration = (
		require('./lib/project').getAvgProjectBuildDuration
	),
	db = require('./db'),
	logger = require('./lib/logger')('distributor');

exports.init = function(app, callback) {
	var distributor = new Distributor({
		nodes: app.config.nodes,
		projects: app.projects,
		saveBuild: function(build, callback) {
			Steppy(
				function() {
					if (_(build.project).has('avgBuildDuration')) {
						this.pass(build.project.avgBuildDuration);
					} else {
						getAvgProjectBuildDuration(build.project.name, this.slot());
					}
				},
				function(err, avgBuildDuration) {
					build.project.avgBuildDuration = avgBuildDuration;

					db.builds.put(build, this.slot());
				},
				function() {
					this.pass(build);
				},
				callback
			);
		}
	});

	var buildDataResourcesHash = {};

	// create resource for build data
	var createBuildDataResource = function(buildId) {
		if (buildId in buildDataResourcesHash) {
			return;
		}
		var buildDataResource = app.dataio.resource('build' + buildId);
		buildDataResource.on('connection', function(client) {
			var callback = this.async();
			Steppy(
				function() {
					db.logLines.find({
						start: {buildId: buildId, numberStr: ''},
					}, this.slot());
				},
				function(err, lines) {
					client.emit('sync', 'data', {lines: lines});
					this.pass(true);
				},
				function(err) {
					if (err) {
						logger.error(
							'error during read log for "' + buildId + '":',
							err.stack || err
						);
					}
					callback();
				}
			);
		});
		buildDataResourcesHash[buildId] = buildDataResource;
	};

	exports.createBuildDataResource = createBuildDataResource;

	distributor.on('buildUpdate', function(build, changes) {
		var buildsResource = app.dataio.resource('builds');

		if (build.status === 'queued') {
			createBuildDataResource(build.id);
		}

		// notify about build's project change, coz building affects project
		// related stat (last build date, avg build time, etc)
		if (changes.completed) {
			var projectsResource = app.dataio.resource('projects');
			projectsResource.clientEmitSyncChange({name: build.project.name});
		}

		buildsResource.clientEmitSync('change', {
			buildId: build.id, changes: changes
		});
	});

	var buildLogLineNumbersHash = {};

	distributor.on('buildData', function(build, data) {
		var lines = _(data.split('\n')).chain().map(function(line) {
				return line.replace('\r', '');
			}).compact().value(),
			logLineNumber = buildLogLineNumbersHash[build.id] || 0;

		lines = _(lines).map(function(line, index) {
			return {
				number: logLineNumber + index,
				text: line
			};
		});
		buildLogLineNumbersHash[build.id] = logLineNumber + lines.length;

		app.dataio.resource('build' + build.id).clientEmitSync(
			'data',
			{lines: lines}
		);

		_(lines).each(function(line) {
			line.buildId = build.id;
		});
		// write build logs to db
		if (lines.length) {
			db.logLines.put(lines, function(err) {
				if (err) {
					logger.error(
						'Error during write log line "' + logLineNumber +
						'" for build "' + build.id + '":',
						err.stack || err
					);
				}
			});
		}
	});

	callback(null, distributor);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("C<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var <commit_msg>Fast-forwarding changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var c<|endoftext|>


<commit_before>;(function() {
  'use strict';

  const extend = require('extend');
  const http = require('http');
  const mongoose = require('mongoose');
  const path = require('path');

  const app = require('./app');
  const logger = require('./logger');

  const _models = ['menu', 'page', 'category', 'publication'];
  const _extensions = ['page', 'markdown', 'form', 'mailer', 'catalog'];

  let settings = {
    port: 3000,
    database: 'mongodb://localhost/verlag',

    views: {
      engine: undefined,
      path: undefined,
      page: undefined,
      error: {
        default: undefined
      }
    },

    logs: {
      name: 'verlag',
      providers: [
        {
          transport: 'Console',
          level: 'debug',
          colorize: true,
          humanReadableUnhandledException: true
        }
      ]
    }
  };

  let locals = {
    appTitle: 'verlag',
    staticPath: 'static/'
  };

  mongoose.promise = global.Promise;

  module.exports = class Verlag {
    constructor() {
      this._onListening = () => {
        let addr = this.server.address();
        let bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;

        this.serverLogger && this.serverLogger.log(this.serverLogger.info, 'listening on {0}', bind);
      };

      this._onError = error => {
        if (error.syscall !== 'listen') {
          throw error;
        }

        let addr = this.server.address();
        let bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;

        switch (error.code) {
          case 'EACCES':
            this.serverLogger && this.serverLogger.log(this.serverLogger.error, '{0} requires elevated privileges', bind);
            process.exit(1);
            break;

          case 'EADDRINUSE':
            this.serverLogger && this.serverLogger.log(this.serverLogger.error, '{0} is already in use', bind);
            process.exit(1);
            break;

          default:
            throw error;
        }
      };
    }

    set settings(opts) {
      this._settings = {};
      extend(true, this._settings, settings);
      extend(true, this._settings, opts);
    }

    set locals(opts) {
      this._locals = {};
      extend(true, this._locals, locals);
      extend(true, this._locals, opts);
    }

    set onListening(func) {
      this._onListening = func;
    }

    set onError(func) {
      this._onError = func;
    }

    start() {
      let mainLogger = logger(this._settings.logs);
      this.serverLogger = mainLogger.create('server');
      this.serverLogger.log(this.serverLogger.info, 'starting server...');

      this.serverLogger.log(this.serverLogger.debug, 'opening database connection...');
      mongoose.connect(this._settings.database);

      const db = mongoose.connection;
      db.on('error', () => this.serverLogger.log(this.serverLogger.error, 'error opening database connection'));
      db.once('open', () => {
        this.serverLogger.log(this.serverLogger.debug, 'database connection opened');

        let models = Object.create(null);
        _models.forEach(function(model) {
          let m = path.join(__dirname, 'models', model);
          models[model] = require(m)(mongoose);
        });

        let extensions = _extensions.map(m => require(path.join(__dirname, 'extensions', m)));

        this.instance = app();
        this.instance.set('locals', this._locals);
        this.instance.set('views', this._settings.views);
        this.instance.set('view engine', this._settings.views.engine);
        this.instance.set('logger', mainLogger.create('app', true));
        this.instance.set('models', models);
        this.instance.set('extensions', extensions);

        this.server = http.createServer(this.instance);
        this.server.listen(this._settings.port);
        this.server.on('error', this._onError);
        this.server.on('listening', this._onListening);
      });
    }
  };
})();
<commit_msg>unix socket server<commit_after>;(function() {
  'use strict';

  const extend = require('extend');
  const fs = require('fs');
  const http = require('http');
  const mongoose = require('mongoose');
  const path = require('path');

  const app = require('./app');
  const logger = require('./logger');

  const _models = ['menu', 'page', 'category', 'publication'];
  const _extensions = ['page', 'markdown', 'form', 'mailer', 'catalog'];

  let settings = {
    port: undefined,
    sock: undefined,
    permissions: undefined,
    database: 'mongodb://localhost/verlag',

    views: {
      engine: undefined,
      path: undefined,
      page: undefined,
      error: {
        default: undefined
      }
    },

    logs: {
      name: 'verlag',
      providers: [
        {
          transport: 'Console',
          level: 'debug',
          colorize: true,
          humanReadableUnhandledException: true
        }
      ]
    }
  };

  let locals = {
    appTitle: 'verlag',
    staticPath: 'static/'
  };

  mongoose.promise = global.Promise;

  module.exports = class Verlag {
    constructor() {
      this._onListening = () => {
        let addr = this.server.address();
        let bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;

        this.serverLogger && this.serverLogger.log(this.serverLogger.info, 'listening on {0}', bind);
      };

      this._onError = error => {
        if (error.syscall !== 'listen') {
          throw error;
        }

        let addr = this.server.address();
        let bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;

        switch (error.code) {
          case 'EACCES':
            this.serverLogger && this.serverLogger.log(this.serverLogger.error, '{0} requires elevated privileges', bind);
            process.exit(1);
            break;

          case 'EADDRINUSE':
            this.serverLogger && this.serverLogger.log(this.serverLogger.error, '{0} is already in use', bind);
            process.exit(1);
            break;

          default:
            throw error;
        }
      };
    }

    set settings(opts) {
      this._settings = {};
      extend(true, this._settings, settings);
      extend(true, this._settings, opts);
    }

    set locals(opts) {
      this._locals = {};
      extend(true, this._locals, locals);
      extend(true, this._locals, opts);
    }

    set onListening(func) {
      this._onListening = func;
    }

    set onError(func) {
      this._onError = func;
    }

    start() {
      let mainLogger = logger(this._settings.logs);
      this.serverLogger = mainLogger.create('server');
      this.serverLogger.log(this.serverLogger.info, 'starting server...');

      this.serverLogger.log(this.serverLogger.debug, 'opening database connection...');
      mongoose.connect(this._settings.database);

      const db = mongoose.connection;
      db.on('error', () => this.serverLogger.log(this.serverLogger.error, 'error opening database connection'));
      db.once('open', () => {
        this.serverLogger.log(this.serverLogger.debug, 'database connection opened');

        let models = Object.create(null);
        _models.forEach(function(model) {
          let m = path.join(__dirname, 'models', model);
          models[model] = require(m)(mongoose);
        });

        let extensions = _extensions.map(m => require(path.join(__dirname, 'extensions', m)));

        this.instance = app();
        this.instance.set('locals', this._locals);
        this.instance.set('views', this._settings.views);
        this.instance.set('view engine', this._settings.views.engine);
        this.instance.set('logger', mainLogger.create('app', true));
        this.instance.set('models', models);
        this.instance.set('extensions', extensions);

        this.server = http.createServer(this.instance);

        this.server.on('error', this._onError);
        this.server.on('listening', this._onListening);

        if (this._settings.port) {
          this.serverLogger.log(this.serverLogger.debug, 'binding server to port {0}', this._settings.port);
          this.server.listen(this._settings.port);
        } else if (this._settings.sock) {
          this.serverLogger.log(this.serverLogger.debug, 'binding server to domain socket {0}', this._settings.sock);

          fs.unlink(this._settings.sock, () => {
            this.server.listen(this._settings.sock, () => {
              if (this._settings.permissions) {
                this.serverLogger.log(this.serverLogger.debug, 'setting domain socket permissions to {0}', this._settings.permissions);
                fs.chmodSync(this._settings.sock, this._settings.permissions);
              }

            });
          });
        } else {
          // TODO: throw error
        }
      });
    }
  };
})();
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    setTimeout(commit, timeout, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   re<commit_msg>Did I do that?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    setTimeout(commit, timeout, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}
<|endoftext|>