<commit_before>/** @jsx React.DOM */
define(['exports', 'jquery', 'class', 'react', 'globals'],
function (collection, $, class_, React, globals) {
    'use strict';

    var Collection = collection.Collection = React.createClass({
        render: function () {
            var context = this.props.context;
            var location = this.props.location;
            return (

{context.title}

{context.description}

            );
        }
    });

    globals.content_views.register(Collection, 'collection');

    var Cell = class_({
        constructor: function(value, sortable) {
            this.value = value;
            this.sortable = sortable;
        }
    });

    var Row = class_({
        constructor: function(item, cells, text) {
            this.item = item;
            this.cells = cells;
            this.text = text;
        }
    });

    var Data = class_({
        constructor: function(rows) {
            this.rows = rows;
            this.sortedOn = null;
            this.reversed = false;
        },
        sort: function(sortColumn, reverse) {
            reverse = !!reverse;
            if (this.sortedOn === sortColumn && this.reversed === reverse) return;
            this.sortedOn = sortColumn;
            this.reversed = reverse;
            this.rows.sort(function (rowA, rowB) {
                var a = '' + rowA.cells[sortColumn].sortable;
                var b = '' + rowB.cells[sortColumn].sortable;
                if (a  b) {
                    return reverse ? 1 : -1;
                }
                return 0;
            });
        }
    });

    var Table = collection.Table = React.createClass({
        getDefaultProps: function () {
            return {
                defaultSortOn: 0
            };
        },

        getInitialState: function () {
            var state = this.extractParams(this.props);
            var columns = state.columns = this.guessColumns(this.props);
            state.data = this.extractData(this.props, columns);
            state.communicating = this.fetchAll(this.props);
            return state;
        },

        componentWillReceiveProps: function (nextProps) {
            var updateData = false;
            if (nextProps.context !== this.props.context) {
                updateData = true;
                this.fetchAll(nextProps);
            }
            if (nextProps.columns !== this.props.columns) {
                updateData = true;
            }
            if (updateData) {
                var columns = this.guessColumns(nextProps);
                this.extractData(nextProps, columns);
            }
            if (nextProps.location.href !== this.props.location.href) {
                this.extractParams(nextProps);
            }

        },

        extractParams: function(props) {
            var params = props.location.params();
            var sorton = parseInt(params.sorton, 10);
            if (isNaN(sorton)) {
                sorton = props.defaultSortOn;
            }
            var state = {
                sortOn: sorton,
                reversed: params.reversed || false,
                searchTerm: params.q || ''
            };
            this.setState(state);
            return state;
        },

        guessColumns: function (props) {
            var column_list = props.context.columns;
            var columns = []
            if (Object.keys(column_list).length === 0) {
                for (var key in props.context['@graph'][0]) {
                    if (key.slice(0, 1) != '@' && key.search(/(uuid|_no|accession)/) == -1) {
                        columns.push(key);
                    }
                }
                columns.sort();
                columns.unshift('@id');
            } else {
                for(var column in column_list) {
                    columns.push(column)
                }
            }
            this.setState({columns: columns});
            return columns;
        },

        extractData: function (props, columns) {
            var context = props.context;
            columns = columns || this.state.columns;
            var rows = context['@graph'].map(function (item) {
                var cells = columns.map(function (column) {
                    var factory;
                    // cell factories
                    //if (factory) {
                    //    return factory({context: item, column: column});
                    //}
                    var value = item[column];
                    if (column == '@id') {
                        factory = globals.listing_titles.lookup(item);
                        value = factory({context: item});
                    } else if (value == null) {
                        value = '';
                    } else if (value instanceof Array) {
                        value = value;
                    } else if (value['@type']) {
                        factory = globals.listing_titles.lookup(value);
                        value = factory({context: value});
                    }
                    var sortable = ('' + value).toLowerCase();
                    return Cell(value, sortable);
                });
                var text = cells.map(function (cell) {
                    return cell.value;
                }).join(' ').toLowerCase();
                return Row(item, cells, text);
            });
            var data = Data(rows);
            this.setState({data: data})
            return data;
        },

        fetchAll: function (props) {
            var context = props.context;
            var communicating;
            if (this.allRequest && this.allRequest.state() == 'pending') {
                this.allRequest.abort();
            }
            var self = this;
            if (context.all) {
                communicating = true;
                this.setState({communicating: true});
                this.allRequest = $.ajax({
                    url: context.all,
                    type: 'GET',
                    dataType: 'json'
                }).done(function (data) {
                    self.extractData({context: data});
                    self.setState({communicating: false});
                });
            }
            return communicating;
        },

        render: function () {
            var columns = this.state.columns;
            var context = this.props.context;
            var defaultSortOn = this.props.defaultSortOn;
            var sortOn = this.state.sortOn;
            var reversed = this.state.reversed;
            var searchTerm = this.state.searchTerm;
            var titles = context.columns;
            var data = this.state.data;
            var params = this.props.location.params();
            var total = context.count || data.rows.length;
            data.sort(sortOn, reversed);
            var self = this;
            var headers = columns.map(function (column, index) {
                var className = "sortdirection icon-";
                if (index === sortOn) {
                    className += reversed ? " icon-chevron-up" : " icon-chevron-down";
                }
                return (

                        {titles[column] || column}

                );
            });
            var searchTermLower = this.state.searchTerm.toLowerCase();
            var found = 0;
            var rows = data.rows.map(function (row) {
                var tds = row.cells.map( function (cell, index) {
                    if (index === 0) {
                        return (
                            {cell.value}
                        );
                    }
                    return (
                        {cell.value}
                    );
                });
                var id = row.item['@id'];
                // Keep DOM nodes around but hidden
                var hidden = (searchTerm && row.text.indexOf(searchTermLower) == -1) || undefined;
                if (!hidden) found += 1;
                return (

{tds}

                );
            });
            var table_class = "sticky-area collection-table";
            var loading_or_total;
            if (this.state.communicating) {
                table_class += ' communicating';
                loading_or_total = (
                    Loading...
                );
            } else {
                loading_or_total = (

                        {found}
                        of {total} records

                );
            }
            return (

                                {loading_or_total}
                                <form ref="form" class="table-filter" onKeyUp={this.handleKeyUp} data-skiprequest="true" data-removeempty="true" >
                                    <input disabled={this.state.communicating || undefined} name="q" type="search" defaultValue={searchTerm} placeholder="Filter table by..." />
                                    <input ref="sorton" type="hidden" name="sorton" defaultValue={sortOn !== defaultSortOn ? sortOn : ''} />
                                    <input ref="reversed" type="hidden" name="reversed" defaultValue={!!reversed || ''} />
                                </form>

                            {headers}

                        {rows}

            );
        },

        handleClickHeader: function (event) {
            var target = event.target;
            while (target.tagName != 'TH') {
                target = target.parentElement;
            }
            var cellIndex = target.cellIndex;
            var reversed = '';
            var sorton = this.refs.sorton.getDOMNode()
            if (this.props.defaultSortOn !== cellIndex) {
                sorton.value = cellIndex;
            } else {
                sorton.value = '';
            }
            if (this.state.sortOn == cellIndex) {
                reversed = !this.state.reversed || ''
            }
            this.refs.reversed.getDOMNode().value = reversed;
            event.preventDefault();
            // defer until this event is handled
            setTimeout(this.submit);
        },

        handleKeyUp: function (event) {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            // Skip when enter key is pressed
            if (event.nativeEvent.keyCode == 13) return;
            this.submitTimer = setTimeout(this.submit, 200);
        },

        submit: function () {
            // form.submit() does not fire onsubmit handlers...
            var event = new Event('submit', {bubbles: true, cancelable: true});
            this.refs.form.getDOMNode().dispatchEvent(event);
        },

        componentWillUnmount: function () {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            if (this.allRequest && this.allRequest.state() == 'pending') {
                this.allRequest.abort();
            }
        }

    });

    return collection;
});
<commit_msg>defering the submit call no longer necessary.<commit_after>/** @jsx React.DOM */
define(['exports', 'jquery', 'class', 'react', 'globals'],
function (collection, $, class_, React, globals) {
    'use strict';

    var Collection = collection.Collection = React.createClass({
        render: function () {
            var context = this.props.context;
            var location = this.props.location;
            return (

{context.title}

{context.description}

            );
        }
    });

    globals.content_views.register(Collection, 'collection');

    var Cell = class_({
        constructor: function(value, sortable) {
            this.value = value;
            this.sortable = sortable;
        }
    });

    var Row = class_({
        constructor: function(item, cells, text) {
            this.item = item;
            this.cells = cells;
            this.text = text;
        }
    });

    var Data = class_({
        constructor: function(rows) {
            this.rows = rows;
            this.sortedOn = null;
            this.reversed = false;
        },
        sort: function(sortColumn, reverse) {
            reverse = !!reverse;
            if (this.sortedOn === sortColumn && this.reversed === reverse) return;
            this.sortedOn = sortColumn;
            this.reversed = reverse;
            this.rows.sort(function (rowA, rowB) {
                var a = '' + rowA.cells[sortColumn].sortable;
                var b = '' + rowB.cells[sortColumn].sortable;
                if (a  b) {
                    return reverse ? 1 : -1;
                }
                return 0;
            });
        }
    });

    var Table = collection.Table = React.createClass({
        getDefaultProps: function () {
            return {
                defaultSortOn: 0
            };
        },

        getInitialState: function () {
            var state = this.extractParams(this.props);
            var columns = state.columns = this.guessColumns(this.props);
            state.data = this.extractData(this.props, columns);
            state.communicating = this.fetchAll(this.props);
            return state;
        },

        componentWillReceiveProps: function (nextProps) {
            var updateData = false;
            if (nextProps.context !== this.props.context) {
                updateData = true;
                this.fetchAll(nextProps);
            }
            if (nextProps.columns !== this.props.columns) {
                updateData = true;
            }
            if (updateData) {
                var columns = this.guessColumns(nextProps);
                this.extractData(nextProps, columns);
            }
            if (nextProps.location.href !== this.props.location.href) {
                this.extractParams(nextProps);
            }

        },

        extractParams: function(props) {
            var params = props.location.params();
            var sorton = parseInt(params.sorton, 10);
            if (isNaN(sorton)) {
                sorton = props.defaultSortOn;
            }
            var state = {
                sortOn: sorton,
                reversed: params.reversed || false,
                searchTerm: params.q || ''
            };
            this.setState(state);
            return state;
        },

        guessColumns: function (props) {
            var column_list = props.context.columns;
            var columns = []
            if (Object.keys(column_list).length === 0) {
                for (var key in props.context['@graph'][0]) {
                    if (key.slice(0, 1) != '@' && key.search(/(uuid|_no|accession)/) == -1) {
                        columns.push(key);
                    }
                }
                columns.sort();
                columns.unshift('@id');
            } else {
                for(var column in column_list) {
                    columns.push(column)
                }
            }
            this.setState({columns: columns});
            return columns;
        },

        extractData: function (props, columns) {
            var context = props.context;
            columns = columns || this.state.columns;
            var rows = context['@graph'].map(function (item) {
                var cells = columns.map(function (column) {
                    var factory;
                    // cell factories
                    //if (factory) {
                    //    return factory({context: item, column: column});
                    //}
                    var value = item[column];
                    if (column == '@id') {
                        factory = globals.listing_titles.lookup(item);
                        value = factory({context: item});
                    } else if (value == null) {
                        value = '';
                    } else if (value instanceof Array) {
                        value = value;
                    } else if (value['@type']) {
                        factory = globals.listing_titles.lookup(value);
                        value = factory({context: value});
                    }
                    var sortable = ('' + value).toLowerCase();
                    return Cell(value, sortable);
                });
                var text = cells.map(function (cell) {
                    return cell.value;
                }).join(' ').toLowerCase();
                return Row(item, cells, text);
            });
            var data = Data(rows);
            this.setState({data: data})
            return data;
        },

        fetchAll: function (props) {
            var context = props.context;
            var communicating;
            if (this.allRequest && this.allRequest.state() == 'pending') {
                this.allRequest.abort();
            }
            var self = this;
            if (context.all) {
                communicating = true;
                this.setState({communicating: true});
                this.allRequest = $.ajax({
                    url: context.all,
                    type: 'GET',
                    dataType: 'json'
                }).done(function (data) {
                    self.extractData({context: data});
                    self.setState({communicating: false});
                });
            }
            return communicating;
        },

        render: function () {
            var columns = this.state.columns;
            var context = this.props.context;
            var defaultSortOn = this.props.defaultSortOn;
            var sortOn = this.state.sortOn;
            var reversed = this.state.reversed;
            var searchTerm = this.state.searchTerm;
            var titles = context.columns;
            var data = this.state.data;
            var params = this.props.location.params();
            var total = context.count || data.rows.length;
            data.sort(sortOn, reversed);
            var self = this;
            var headers = columns.map(function (column, index) {
                var className = "sortdirection icon-";
                if (index === sortOn) {
                    className += reversed ? " icon-chevron-up" : " icon-chevron-down";
                }
                return (

                        {titles[column] || column}

                );
            });
            var searchTermLower = this.state.searchTerm.toLowerCase();
            var found = 0;
            var rows = data.rows.map(function (row) {
                var tds = row.cells.map( function (cell, index) {
                    if (index === 0) {
                        return (
                            {cell.value}
                        );
                    }
                    return (
                        {cell.value}
                    );
                });
                var id = row.item['@id'];
                // Keep DOM nodes around but hidden
                var hidden = (searchTerm && row.text.indexOf(searchTermLower) == -1) || undefined;
                if (!hidden) found += 1;
                return (

{tds}

                );
            });
            var table_class = "sticky-area collection-table";
            var loading_or_total;
            if (this.state.communicating) {
                table_class += ' communicating';
                loading_or_total = (
                    Loading...
                );
            } else {
                loading_or_total = (

                        {found}
                        of {total} records

                );
            }
            return (

                                {loading_or_total}
                                <form ref="form" class="table-filter" onKeyUp={this.handleKeyUp} data-skiprequest="true" data-removeempty="true" >
                                    <input disabled={this.state.communicating || undefined} name="q" type="search" defaultValue={searchTerm} placeholder="Filter table by..." />
                                    <input ref="sorton" type="hidden" name="sorton" defaultValue={sortOn !== defaultSortOn ? sortOn : ''} />
                                    <input ref="reversed" type="hidden" name="reversed" defaultValue={!!reversed || ''} />
                                </form>

                            {headers}

                        {rows}

            );
        },

        handleClickHeader: function (event) {
            var target = event.target;
            while (target.tagName != 'TH') {
                target = target.parentElement;
            }
            var cellIndex = target.cellIndex;
            var reversed = '';
            var sorton = this.refs.sorton.getDOMNode()
            if (this.props.defaultSortOn !== cellIndex) {
                sorton.value = cellIndex;
            } else {
                sorton.value = '';
            }
            if (this.state.sortOn == cellIndex) {
                reversed = !this.state.reversed || ''
            }
            this.refs.reversed.getDOMNode().value = reversed;
            event.preventDefault();
            this.submit();
        },

        handleKeyUp: function (event) {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            // Skip when enter key is pressed
            if (event.nativeEvent.keyCode == 13) return;
            this.submitTimer = setTimeout(this.submit, 200);
        },

        submit: function () {
            // form.submit() does not fire onsubmit handlers...
            var event = new Event('submit', {bubbles: true, cancelable: true});
            this.refs.form.getDOMNode().dispatchEvent(event);
        },

        componentWillUnmount: function () {
            if (typeof this.submitTimer != 'undefined') {
                clearTimeout(this.submitTimer);
            }
            if (this.allRequest && this.allRequest.state() == 'pending') {
                this.allRequest.abort();
            }
        }

    });

    return collection;
});
<|endoftext|>


<commit_before>/*
colors.js

Copyright (c) 2010

Marak Squires
Alexis Sellier (cloudhead)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var isHeadless = false;

if (typeof module !== 'undefined') {
  isHeadless = true;
}

if (!isHeadless) {
  var exports = {};
  var module = {};
  var colors = exports;
  exports.mode = "browser";
} else {
  exports.mode = "console";
}

//
// Prototypes the string object to have additional method calls that add terminal colors
//
var addProperty = function (color, func) {
  exports[color] = function (str) {
    return func.apply(str);
  };
  String.prototype.__defineGetter__(color, func);
};

function stylize(str, style) {

  var styles;

  if (exports.mode === 'console') {
    styles = {
      //styles
      'bold'      : ['\x1B[1m',  '\x1B[22m'],
      'italic'    : ['\x1B[3m',  '\x1B[23m'],
      'underline' : ['\x1B[4m',  '\x1B[24m'],
      'inverse'   : ['\x1B[7m',  '\x1B[27m'],
      'strikethrough' : ['\x1B[9m',  '\x1B[29m'],
      //grayscale
      'white'     : ['\x1B[37m', '\x1B[39m'],
      'grey'      : ['\x1B[90m', '\x1B[39m'],
      'black'     : ['\x1B[30m', '\x1B[39m'],
      //colors
      'blue'      : ['\x1B[34m', '\x1B[39m'],
      'cyan'      : ['\x1B[36m', '\x1B[39m'],
      'green'     : ['\x1B[32m', '\x1B[39m'],
      'magenta'   : ['\x1B[35m', '\x1B[39m'],
      'red'       : ['\x1B[31m', '\x1B[39m'],
      'yellow'    : ['\x1B[33m', '\x1B[39m']
    };
  } else if (exports.mode === 'browser') {
    styles = {
      //styles
      'bold'      : ['',  ''],
      'italic'    : ['',  ''],
      'underline' : ['',  ''],
      'inverse'   : ['',  ''],
      'strikethrough' : ['',  ''],
      //grayscale
      'white'     : ['',   ''],
      'grey'      : ['',    ''],
      'black'     : ['',   ''],
      //colors
      'blue'      : ['',    ''],
      'cyan'      : ['',    ''],
      'green'     : ['',   ''],
      'magenta'   : ['', ''],
      'red'       : ['',     ''],
      'yellow'    : ['',  '']
    };
  } else if (exports.mode === 'none') {
    return str+'';
  } else {
    console.log('unsupported mode, try "browser", "console" or "none"');
  }
  return styles[style][0] + str + styles[style][1];
}

function applyTheme(theme) {

  //
  // Remark: This is a list of methods that exist
  // on String that you should not overwrite.
  //
  var stringPrototypeBlacklist = [
    '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor',
    'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt',
    'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring',
    'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight'
  ];

  Object.keys(theme).forEach(function (prop) {
    if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
      console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name');
    }
    else {
      if (typeof(theme[prop]) === 'string') {
        addProperty(prop, function () {
            return exports[theme[prop]](this);
        });
      }
      else {
        addProperty(prop, function () {
          var ret = this;
          for (var t = 0; t < theme[prop].length; t++) {
              ret = exports[theme[prop][t]](ret);
          }
          return ret;
        });
      }
    }
  });
}

//
// Iterate through all default styles and colors
//
var x = ['bold', 'underline', 'strikethrough', 'italic', 'inverse', 'grey', 'black', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
x.forEach(function (style) {

  // __defineGetter__ at the least works in more browsers
  // http://robertnyman.com/javascript/javascript-getters-setters.html
  // Object.defineProperty only works in Chrome
  addProperty(style, function () {
    return stylize(this, style);
  });
});

function sequencer(map) {
  return function () {
    if (!isHeadless) {
      return this.replace(/( )/, '$1');
    }
    var exploded = this.split(""), i = 0;
    exploded = exploded.map(map);
    return exploded.join("");
  };
}

var rainbowMap = (function () {
  var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
  return function (letter, i, exploded) {
    if (letter === " ") {
      return letter;
    } else {
      return stylize(letter, rainbowColors[i++ % rainbowColors.length]);
    }
  };
})();

exports.themes = {};

exports.addSequencer = function (name, map) {
  addProperty(name, sequencer(map));
};

exports.addSequencer('rainbow', rainbowMap);
exports.addSequencer('zebra', function (letter, i, exploded) {
  return i % 2 === 0 ? letter : letter.inverse;
});

exports.setTheme = function (theme) {
  if (typeof theme === 'string') {
    try {
      exports.themes[theme] = require(theme);
      applyTheme(exports.themes[theme]);
      return exports.themes[theme];
    } catch (err) {
      console.log(err);
      return err;
    }
  } else {
    applyTheme(theme);
  }
};

addProperty('stripColors', function () {
  return ("" + this).replace(/\x1B\[\d+m/g, '');
});

// please no
function zalgo(text, options) {
  var soul = {
    "up" : [
      '̍', '̎', '̄', '̅',
      '̿', '̑', '̆', '̐',
      '͒', '͗', '͑', '̇',
      '̈', '̊', '͂', '̓',
      '̈', '͊', '͋', '͌',
      '̃', '̂', '̌', '͐',
      '̀', '́', '̋', '̏',
      '̒', '̓', '̔', '̽',
      '̉', 'ͣ', 'ͤ', 'ͥ',
      'ͦ', 'ͧ', 'ͨ', 'ͩ',
      'ͪ', 'ͫ', 'ͬ', 'ͭ',
      'ͮ', 'ͯ', '̾', '͛',
      '͆', '̚'
    ],
    "down" : [
      '̖', '̗', '̘', '̙',
      '̜', '̝', '̞', '̟',
      '̠', '̤', '̥', '̦',
      '̩', '̪', '̫', '̬',
      '̭', '̮', '̯', '̰',
      '̱', '̲', '̳', '̹',
      '̺', '̻', '̼', 'ͅ',
      '͇', '͈', '͉', '͍',
      '͎', '͓', '͔', '͕',
      '͖', '͙', '͚', '̣'
    ],
    "mid" : [
      '̕', '̛', '̀', '́',
      '͘', '̡', '̢', '̧',
      '̨', '̴', '̵', '̶',
      '͜', '͝', '͞',
      '͟', '͠', '͢', '̸',
      '̷', '͡', ' ҉'
    ]
  },
  all = [].concat(soul.up, soul.down, soul.mid),
  zalgo = {};

  function randomNumber(range) {
    var r = Math.floor(Math.random() * range);
    return r;
  }

  function is_char(character) {
    var bool = false;
    all.filter(function (i) {
      bool = (i === character);
    });
    return bool;
  }

  function heComes(text, options) {
    var result = '', counts, l;
    options = options || {};
    options["up"] = options["up"] || true;
    options["mid"] = options["mid"] || true;
    options["down"] = options["down"] || true;
    options["size"] = options["size"] || "maxi";
    text = text.split('');
    for (l in text) {
      if (is_char(l)) {
        continue;
      }
      result = result + text[l];
      counts = {"up" : 0, "down" : 0, "mid" : 0};
      switch (options.size) {
        case 'mini':
          counts.up = randomNumber(8);
          counts.min = randomNumber(2);
          counts.down = randomNumber(8);
        break;
        case 'maxi':
          counts.up = randomNumber(16) + 3;
          counts.min = randomNumber(4) + 1;
          counts.down = randomNumber(64) + 3;
        break;
        default:
          counts.up = randomNumber(8) + 1;
          counts.mid = randomNumber(6) / 2;
          counts.down = randomNumber(8) + 1;
        break;
      }

      var arr = ["up", "mid", "down"];
      for (var d in arr) {
        var index = arr[d];
        for (var i = 0 ; i <= counts[index]; i++) {
          if (options[index]) {
            result = result + soul[index][randomNumber(soul[index].length)];
          }
        }
      }
    }
    return result;
  }
  return heComes(text);
}

// don't summon zalgo
addProperty('zalgo', function () {
  return zalgo(this);
});
<commit_msg>Change 'grey' to 'gray' in HTML/CSS output<commit_after>/*
colors.js

Copyright (c) 2010

Marak Squires
Alexis Sellier (cloudhead)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var isHeadless = false;

if (typeof module !== 'undefined') {
  isHeadless = true;
}

if (!isHeadless) {
  var exports = {};
  var module = {};
  var colors = exports;
  exports.mode = "browser";
} else {
  exports.mode = "console";
}

//
// Prototypes the string object to have additional method calls that add terminal colors
//
var addProperty = function (color, func) {
  exports[color] = function (str) {
    return func.apply(str);
  };
  String.prototype.__defineGetter__(color, func);
};

function stylize(str, style) {

  var styles;

  if (exports.mode === 'console') {
    styles = {
      //styles
      'bold'      : ['\x1B[1m',  '\x1B[22m'],
      'italic'    : ['\x1B[3m',  '\x1B[23m'],
      'underline' : ['\x1B[4m',  '\x1B[24m'],
      'inverse'   : ['\x1B[7m',  '\x1B[27m'],
      'strikethrough' : ['\x1B[9m',  '\x1B[29m'],
      //grayscale
      'white'     : ['\x1B[37m', '\x1B[39m'],
      'grey'      : ['\x1B[90m', '\x1B[39m'],
      'black'     : ['\x1B[30m', '\x1B[39m'],
      //colors
      'blue'      : ['\x1B[34m', '\x1B[39m'],
      'cyan'      : ['\x1B[36m', '\x1B[39m'],
      'green'     : ['\x1B[32m', '\x1B[39m'],
      'magenta'   : ['\x1B[35m', '\x1B[39m'],
      'red'       : ['\x1B[31m', '\x1B[39m'],
      'yellow'    : ['\x1B[33m', '\x1B[39m']
    };
  } else if (exports.mode === 'browser') {
    styles = {
      //styles
      'bold'      : ['',  ''],
      'italic'    : ['',  ''],
      'underline' : ['',  ''],
      'inverse'   : ['',  ''],
      'strikethrough' : ['',  ''],
      //grayscale
      'white'     : ['',   ''],
      'grey'      : ['',    ''],
      'black'     : ['',   ''],
      //colors
      'blue'      : ['',    ''],
      'cyan'      : ['',    ''],
      'green'     : ['',   ''],
      'magenta'   : ['', ''],
      'red'       : ['',     ''],
      'yellow'    : ['',  '']
    };
  } else if (exports.mode === 'none') {
    return str+'';
  } else {
    console.log('unsupported mode, try "browser", "console" or "none"');
  }
  return styles[style][0] + str + styles[style][1];
}

function applyTheme(theme) {

  //
  // Remark: This is a list of methods that exist
  // on String that you should not overwrite.
  //
  var stringPrototypeBlacklist = [
    '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor',
    'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt',
    'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring',
    'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight'
  ];

  Object.keys(theme).forEach(function (prop) {
    if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
      console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name');
    }
    else {
      if (typeof(theme[prop]) === 'string') {
        addProperty(prop, function () {
            return exports[theme[prop]](this);
        });
      }
      else {
        addProperty(prop, function () {
          var ret = this;
          for (var t = 0; t < theme[prop].length; t++) {
              ret = exports[theme[prop][t]](ret);
          }
          return ret;
        });
      }
    }
  });
}

//
// Iterate through all default styles and colors
//
var x = ['bold', 'underline', 'strikethrough', 'italic', 'inverse', 'grey', 'black', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
x.forEach(function (style) {

  // __defineGetter__ at the least works in more browsers
  // http://robertnyman.com/javascript/javascript-getters-setters.html
  // Object.defineProperty only works in Chrome
  addProperty(style, function () {
    return stylize(this, style);
  });
});

function sequencer(map) {
  return function () {
    if (!isHeadless) {
      return this.replace(/( )/, '$1');
    }
    var exploded = this.split(""), i = 0;
    exploded = exploded.map(map);
    return exploded.join("");
  };
}

var rainbowMap = (function () {
  var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
  return function (letter, i, exploded) {
    if (letter === " ") {
      return letter;
    } else {
      return stylize(letter, rainbowColors[i++ % rainbowColors.length]);
    }
  };
})();

exports.themes = {};

exports.addSequencer = function (name, map) {
  addProperty(name, sequencer(map));
};

exports.addSequencer('rainbow', rainbowMap);
exports.addSequencer('zebra', function (letter, i, exploded) {
  return i % 2 === 0 ? letter : letter.inverse;
});

exports.setTheme = function (theme) {
  if (typeof theme === 'string') {
    try {
      exports.themes[theme] = require(theme);
      applyTheme(exports.themes[theme]);
      return exports.themes[theme];
    } catch (err) {
      console.log(err);
      return err;
    }
  } else {
    applyTheme(theme);
  }
};

addProperty('stripColors', function () {
  return ("" + this).replace(/\x1B\[\d+m/g, '');
});

// please no
function zalgo(text, options) {
  var soul = {
    "up" : [
      '̍', '̎', '̄', '̅',
      '̿', '̑', '̆', '̐',
      '͒', '͗', '͑', '̇',
      '̈', '̊', '͂', '̓',
      '̈', '͊', '͋', '͌',
      '̃', '̂', '̌', '͐',
      '̀', '́', '̋', '̏',
      '̒', '̓', '̔', '̽',
      '̉', 'ͣ', 'ͤ', 'ͥ',
      'ͦ', 'ͧ', 'ͨ', 'ͩ',
      'ͪ', 'ͫ', 'ͬ', 'ͭ',
      'ͮ', 'ͯ', '̾', '͛',
      '͆', '̚'
    ],
    "down" : [
      '̖', '̗', '̘', '̙',
      '̜', '̝', '̞', '̟',
      '̠', '̤', '̥', '̦',
      '̩', '̪', '̫', '̬',
      '̭', '̮', '̯', '̰',
      '̱', '̲', '̳', '̹',
      '̺', '̻', '̼', 'ͅ',
      '͇', '͈', '͉', '͍',
      '͎', '͓', '͔', '͕',
      '͖', '͙', '͚', '̣'
    ],
    "mid" : [
      '̕', '̛', '̀', '́',
      '͘', '̡', '̢', '̧',
      '̨', '̴', '̵', '̶',
      '͜', '͝', '͞',
      '͟', '͠', '͢', '̸',
      '̷', '͡', ' ҉'
    ]
  },
  all = [].concat(soul.up, soul.down, soul.mid),
  zalgo = {};

  function randomNumber(range) {
    var r = Math.floor(Math.random() * range);
    return r;
  }

  function is_char(character) {
    var bool = false;
    all.filter(function (i) {
      bool = (i === character);
    });
    return bool;
  }

  function heComes(text, options) {
    var result = '', counts, l;
    options = options || {};
    options["up"] = options["up"] || true;
    options["mid"] = options["mid"] || true;
    options["down"] = options["down"] || true;
    options["size"] = options["size"] || "maxi";
    text = text.split('');
    for (l in text) {
      if (is_char(l)) {
        continue;
      }
      result = result + text[l];
      counts = {"up" : 0, "down" : 0, "mid" : 0};
      switch (options.size) {
        case 'mini':
          counts.up = randomNumber(8);
          counts.min = randomNumber(2);
          counts.down = randomNumber(8);
        break;
        case 'maxi':
          counts.up = randomNumber(16) + 3;
          counts.min = randomNumber(4) + 1;
          counts.down = randomNumber(64) + 3;
        break;
        default:
          counts.up = randomNumber(8) + 1;
          counts.mid = randomNumber(6) / 2;
          counts.down = randomNumber(8) + 1;
        break;
      }

      var arr = ["up", "mid", "down"];
      for (var d in arr) {
        var index = arr[d];
        for (var i = 0 ; i <= counts[index]; i++) {
          if (options[index]) {
            result = result + soul[index][randomNumber(soul[index].length)];
          }
        }
      }
    }
    return result;
  }
  return heComes(text);
}

// don't summon zalgo
addProperty('zalgo', function () {
  return zalgo(this);
});
<|endoftext|>


<commit_before>(function() {
    var m = angular.module('parkandride', [
        'ui.bootstrap',

        'templates-app',
        'templates-common',

        'ui.router',

        'filters',
        'featureToggle',

        'parkandride.hubList',

        'parkandride.dev'
    ]);

    m.constant('FEATURES_URL', 'assets/features.json');

    m.config(function myAppConfig($stateProvider, $urlRouterProvider, $httpProvider) {
        $urlRouterProvider.otherwise('/hubs');

        $stateProvider.state('root', {
            abstract: true,
            template: '

',
            resolve: {
                features: function(FeatureResource) {
                    return FeatureResource.getFeatures();
                }
            },
            controller: function($scope, features) {
                $scope.features = features;
            }
        });

        $httpProvider.interceptors.push(function($q, $translate, $rootScope) {
            return {
                responseError: function(rejection) {
                    if (rejection.status == 400 && rejection.data.violations) {
                        $rootScope.$broadcast("validationErrors", rejection.data.violations);
                        return $q.reject(rejection);
                    } else {
                        swal({
                            title: $translate.instant('error.' + rejection.status + '.title'),
                            text: rejection.data.message,
                            confirmButtonText: $translate.instant('error.buttonText')
                        });
                        return $q.reject(rejection);
                    }
                },
                response: function(response) {
                    $rootScope.$broadcast("validationErrors", []);
                    return response;
                },
                request: function(response) {
                    $rootScope.$broadcast("validationErrors", []);
                    return response;
                }
            };
        });
    });

    m.value("schema", { capacityTypes:[] });

    m.run(function run(schema, FacilityResource) {
        // Use the main applications run method to execute any code after services have been instantiated
        FacilityResource.getCapacityTypes().then(function(types) {
            schema.capacityTypes = types;
        });
    });

    m.controller('AppCtrl', function AppCtrl($scope, $location) {
        $scope.common = {};
        $scope.$on("validationErrors", function(event, violations) {
                $scope.common.violations = _.map(violations, function(violation) {
                    violation.path = violation.path.replace(/\[\d+\]/, "");
                    return violation;
                });
            });
        this.hasValidationErrors = function() {
            return !_.isEmpty($scope.violations);
        };
        // This is a good place for logic not specific to the template or route, such as menu logic or page title wiring
        $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (angular.isDefined(toState.data.pageTitle)) {
                $scope.pageTitle = toState.data.pageTitle + ' | parkandride';
            }
        });

        this.validateAndSubmit = function(form, submitFn) {
            $scope.$broadcast('show-errors-check-validity');
            if (form.$valid) {
                submitFn();
            }
        };
    });
})();
<commit_msg>refactor(ng): resolve capacityTypes in root state<commit_after>(function() {
    var m = angular.module('parkandride', [
        'ui.bootstrap',

        'templates-app',
        'templates-common',

        'ui.router',

        'filters',
        'featureToggle',

        'parkandride.hubList',

        'parkandride.dev'
    ]);

    m.constant('FEATURES_URL', 'assets/features.json');

    m.value("schema", { capacityTypes:[] });

    m.config(function myAppConfig($stateProvider, $urlRouterProvider, $httpProvider) {
        $urlRouterProvider.otherwise('/hubs');

        $stateProvider.state('root', {
            abstract: true,
            template: '

',
            resolve: {
                features: function(FeatureResource) {
                    return FeatureResource.getFeatures();
                },
                capacityTypes: function(schema, FacilityResource) {
                    // Use the main applications run method to execute any code after services have been instantiated
                    return FacilityResource.getCapacityTypes().then(function(types) {
                        schema.capacityTypes = types;
                        return types;
                    });
                }
            },
            controller: function($scope, features) {
                $scope.features = features;
            }
        });

        $httpProvider.interceptors.push(function($q, $translate, $rootScope) {
            return {
                responseError: function(rejection) {
                    if (rejection.status == 400 && rejection.data.violations) {
                        $rootScope.$broadcast("validationErrors", rejection.data.violations);
                        return $q.reject(rejection);
                    } else {
                        swal({
                            title: $translate.instant('error.' + rejection.status + '.title'),
                            text: rejection.data.message,
                            confirmButtonText: $translate.instant('error.buttonText')
                        });
                        return $q.reject(rejection);
                    }
                },
                response: function(response) {
                    $rootScope.$broadcast("validationErrors", []);
                    return response;
                },
                request: function(response) {
                    $rootScope.$broadcast("validationErrors", []);
                    return response;
                }
            };
        });
    });

    m.controller('AppCtrl', function AppCtrl($scope, $location) {
        $scope.common = {};
        $scope.$on("validationErrors", function(event, violations) {
                $scope.common.violations = _.map(violations, function(violation) {
                    violation.path = violation.path.replace(/\[\d+\]/, "");
                    return violation;
                });
            });
        this.hasValidationErrors = function() {
            return !_.isEmpty($scope.violations);
        };
        // This is a good place for logic not specific to the template or route, such as menu logic or page title wiring
        $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (angular.isDefined(toState.data.pageTitle)) {
                $scope.pageTitle = toState.data.pageTitle + ' | parkandride';
            }
        });

        this.validateAndSubmit = function(form, submitFn) {
            $scope.$broadcast('show-errors-check-validity');
            if (form.$valid) {
                submitFn();
            }
        };
    });
})();
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line

const fs = require('fs');
const crypto = require('crypto');
const async = require('async');
const diskusage = require('diskusage');
const werelogs = require('werelogs');

const errors = require('../../../errors');
const stringHash = require('../../../stringHash');
const jsutil = require('../../../jsutil');
const storageUtils = require('../../utils');

// The FOLDER_HASH constant refers to the number of base directories
// used for directory hashing of stored objects.
//
// It MUST not be changed on anything else than a clean new storage
// backend.
//
// It may be changed for such system if the default hash value is too
// low for the estimated number of objects to be stored and the file
// system performance (be cautious though), and cannot be changed once
// the system contains data.

const FOLDER_HASH = 3511;

/**
 * @class
 * @classdesc File-based object blob store
 *
 * Each object/part becomes a file and the files are stored in a
 * directory hash structure under the configured dataPath.
 */
class DataFileStore {

    /**
     * @constructor
     * @param {Object} dataConfig - configuration of the file backend
     * @param {String} dataConfig.dataPath - absolute path where to
     *   store the files
     * @param {Boolean} [dataConfig.noSync=false] - If true, disable
     *   sync calls that ensure files and directories are fully
     *   written on the physical drive before returning an
     *   answer. Used to speed up unit tests, may have other uses.
     * @param {werelogs.API} [logApi] - object providing a constructor function
     *                                for the Logger object
     */
    constructor(dataConfig, logApi) {
        this.logger = new (logApi || werelogs).Logger('DataFileStore');
        this.dataPath = dataConfig.dataPath;
        this.noSync = dataConfig.noSync || false;
    }

    /**
     * Setup the storage backend before starting to read or write
     * files in it.
     *
     * The function ensures that dataPath is accessible and
     * pre-creates the directory hashes under dataPath.
     *
     * @param {function} callback - called when done with no argument
     * @return {undefined}
     */
    setup(callback) {
        fs.access(this.dataPath, fs.F_OK | fs.R_OK | fs.W_OK, err => {
            if (err) {
                this.logger.error('Data path is not readable or writable',
                                  { error: err });
                return callback(err);
            }

            // Create FOLDER_HASH subdirectories
            const subDirs = Array.from({ length: FOLDER_HASH },
                                       (v, k) => (k).toString());
            this.logger.info(`pre-creating ${subDirs.length} subdirs...`);
            if (!this.noSync) {
                storageUtils.setDirSyncFlag(this.dataPath, this.logger);
            }
            async.eachSeries(subDirs, (subDirName, next) => {
                fs.mkdir(`${this.dataPath}/${subDirName}`, err => {
                    // If already exists, move on
                    if (err && err.code !== 'EEXIST') {
                        return next(err);
                    }
                    return next();
                });
            },
            err => {
                if (err) {
                    this.logger.error('Error creating subdirs',
                                      { error: err });
                    return callback(err);
                }
                this.logger.info('data file store init complete, ' +
                                 'go forth and store data.');
                return callback();
            });
            return undefined;
        });
    }

    /**
     * Get the filesystem path to a stored object file from its key
     *
     * @param {String} key - the object key
     * @return {String} the absolute path to the file containing the
     *   object contents
     */
    getFilePath(key) {
        const hash = stringHash(key);
        const folderHashPath = ((hash % FOLDER_HASH)).toString();
        return `${this.dataPath}/${folderHashPath}/${key}`;
    }

    /**
     * Put a new object to the storage backend
     *
     * @param {stream.Readable} dataStream - input stream providing the
     *   object data
     * @param {Number} size - Total byte size of the data to put
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~putCallback} callback - called when done
     * @return {undefined}
     */
    put(dataStream, size, log, callback) {
        const key = crypto.pseudoRandomBytes(20).toString('hex');
        const filePath = this.getFilePath(key);
        log.debug('starting to write data', { method: 'put', key, filePath });
        dataStream.pause();
        fs.open(filePath, 'wx', (err, fd) => {
            if (err) {
                log.error('error opening filePath',
                          { method: 'put', key, filePath, error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: open() returned ${err.code}`));
            }
            const cbOnce = jsutil.once(callback);
            // disable autoClose so that we can close(fd) only after
            // fsync() has been called
            const fileStream = fs.createWriteStream(filePath,
                { fd,
                    autoClose: false });

            fileStream.on('finish', () => {
                function ok() {
                    log.debug('finished writing data',
                              { method: 'put', key, filePath });
                    return cbOnce(null, key);
                }
                if (this.noSync) {
                    fs.close(fd);
                    return ok();
                }
                fs.fsync(fd, err => {
                    fs.close(fd);
                    if (err) {
                        log.error('fsync error',
                            { method: 'put', key, filePath,
                                error: err });
                        return cbOnce(
                            errors.InternalError.customizeDescription(
                                'filesystem error: fsync() returned ' +
                                    `${err.code}`));
                    }
                    return ok();
                });
                return undefined;
            }).on('error', err => {
                log.error('error streaming data on write',
                          { method: 'put', key, filePath, error: err });
                // destroying the write stream forces a close(fd)
                fileStream.destroy();
                return cbOnce(errors.InternalError.customizeDescription(
                    `write stream error: ${err.code}`));
            });
            dataStream.resume();
            dataStream.pipe(fileStream);
            dataStream.on('error', err => {
                log.error('error streaming data on read',
                    { method: 'put', key, filePath, error: err });
                // destroying the write stream forces a close(fd)
                fileStream.destroy();
                return cbOnce(errors.InternalError.customizeDescription(
                    `read stream error: ${err.code}`));
            });
            return undefined;
        });
    }

    /**
     * Get info about a stored object (see DataFileStore~statCallback
     * to know which info is returned)
     *
     * @param {String} key - key of the object
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~statCallback} callback - called when done
     * @return {undefined}
     */
    stat(key, log, callback) {
        const filePath = this.getFilePath(key);
        log.debug('stat file', { key, filePath });
        fs.stat(filePath, (err, stat) => {
            if (err) {
                if (err.code === 'ENOENT') {
                    return callback(errors.ObjNotFound);
                }
                log.error('error on \'stat\' of file',
                          { key, filePath, error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: stat() returned ${err.code}`));
            }
            const info = { objectSize: stat.size };
            return callback(null, info);
        });
    }

    /**
     * Retrieve data of a stored object
     *
     * @param {String} key - key of the object
     * @param {Object} [byteRange] - optional absolute inclusive byte
     *   range to retrieve.
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~getCallback} callback - called when done
     * @return {undefined}
     */
    get(key, byteRange, log, callback) {
        const filePath = this.getFilePath(key);

        const readStreamOptions = {
            flags: 'r',
            encoding: null,
            fd: null,
            autoClose: true,
        };
        if (byteRange) {
            readStreamOptions.start = byteRange[0];
            readStreamOptions.end = byteRange[1];
        }
        log.debug('opening readStream to get data',
                  { method: 'get', key, filePath, byteRange });
        const cbOnce = jsutil.once(callback);
        const rs = fs.createReadStream(filePath, readStreamOptions)
                  .on('error', err => {
                      if (err.code === 'ENOENT') {
                          return cbOnce(errors.ObjNotFound);
                      }
                      log.error('error retrieving file',
                          { method: 'get', key, filePath,
                              error: err });
                      return cbOnce(
                          errors.InternalError.customizeDescription(
                              `filesystem read error: ${err.code}`));
                  })
                  .on('open', () => { cbOnce(null, rs); });
    }

    /**
     * Delete a stored object
     *
     * @param {String} key - key of the object
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~deleteCallback} callback - called when done
     * @return {undefined}
     */
    delete(key, log, callback) {
        const filePath = this.getFilePath(key);
        log.debug('deleting file', { method: 'delete', key, filePath });
        return fs.unlink(filePath, err => {
            if (err) {
                if (err.code === 'ENOENT') {
                    return callback(errors.ObjNotFound);
                }
                log.error('error deleting file', { method: 'delete',
                    key, filePath,
                    error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: unlink() returned ${err.code}`));
            }
            return callback();
        });
    }

    /**
     * Retrieve disk usage information
     *
     * @param {DataFileStore~diskUsageCallback} callback - called when done
     * @return {undefined}
     */
    getDiskUsage(callback) {
        diskusage.check(this.dataPath, callback);
    }
}

/**
 * @callback DataFileStore~putCallback
 * @param {Error} - The encountered error
 * @param {String} key - The key to access the data
 */

/**
 * @callback DataFileStore~statCallback
 * @param {Error} - The encountered error
 * @param {Object} info - Information about the object
 * @param {Number} info.objectSize - Byte size of the object
 */

/**
 * @callback DataFileStore~getCallback
 * @param {Error} - The encountered error
 *   arsenal.errors.ObjNotFound is returned if the object does not exist
 * @param {stream.Readable} stream - The stream of requested object data
 */

/**
 * @callback DataFileStore~deleteCallback
 * @param {Error} - The encountered error
 *   arsenal.errors.ObjNotFound is returned if the object does not exist
 */

/**
 * @callback DataFileStore~diskUsageCallback
 * @param {Error} - The encountered error
 * @param {object} - The disk usage info
 */

module.exports = DataFileStore;
<commit_msg>improvement: S3C-2127 fix callback deprecation<commit_after>'use strict'; // eslint-disable-line

const fs = require('fs');
const crypto = require('crypto');
const async = require('async');
const diskusage = require('diskusage');
const werelogs = require('werelogs');

const errors = require('../../../errors');
const stringHash = require('../../../stringHash');
const jsutil = require('../../../jsutil');
const storageUtils = require('../../utils');

// The FOLDER_HASH constant refers to the number of base directories
// used for directory hashing of stored objects.
//
// It MUST not be changed on anything else than a clean new storage
// backend.
//
// It may be changed for such system if the default hash value is too
// low for the estimated number of objects to be stored and the file
// system performance (be cautious though), and cannot be changed once
// the system contains data.

const FOLDER_HASH = 3511;

/**
 * @class
 * @classdesc File-based object blob store
 *
 * Each object/part becomes a file and the files are stored in a
 * directory hash structure under the configured dataPath.
 */
class DataFileStore {

    /**
     * @constructor
     * @param {Object} dataConfig - configuration of the file backend
     * @param {String} dataConfig.dataPath - absolute path where to
     *   store the files
     * @param {Boolean} [dataConfig.noSync=false] - If true, disable
     *   sync calls that ensure files and directories are fully
     *   written on the physical drive before returning an
     *   answer. Used to speed up unit tests, may have other uses.
     * @param {werelogs.API} [logApi] - object providing a constructor function
     *                                for the Logger object
     */
    constructor(dataConfig, logApi) {
        this.logger = new (logApi || werelogs).Logger('DataFileStore');
        this.dataPath = dataConfig.dataPath;
        this.noSync = dataConfig.noSync || false;
    }

    /**
     * Setup the storage backend before starting to read or write
     * files in it.
     *
     * The function ensures that dataPath is accessible and
     * pre-creates the directory hashes under dataPath.
     *
     * @param {function} callback - called when done with no argument
     * @return {undefined}
     */
    setup(callback) {
        fs.access(this.dataPath, fs.F_OK | fs.R_OK | fs.W_OK, err => {
            if (err) {
                this.logger.error('Data path is not readable or writable',
                                  { error: err });
                return callback(err);
            }

            // Create FOLDER_HASH subdirectories
            const subDirs = Array.from({ length: FOLDER_HASH },
                                       (v, k) => (k).toString());
            this.logger.info(`pre-creating ${subDirs.length} subdirs...`);
            if (!this.noSync) {
                storageUtils.setDirSyncFlag(this.dataPath, this.logger);
            }
            async.eachSeries(subDirs, (subDirName, next) => {
                fs.mkdir(`${this.dataPath}/${subDirName}`, err => {
                    // If already exists, move on
                    if (err && err.code !== 'EEXIST') {
                        return next(err);
                    }
                    return next();
                });
            },
            err => {
                if (err) {
                    this.logger.error('Error creating subdirs',
                                      { error: err });
                    return callback(err);
                }
                this.logger.info('data file store init complete, ' +
                                 'go forth and store data.');
                return callback();
            });
            return undefined;
        });
    }

    /**
     * Get the filesystem path to a stored object file from its key
     *
     * @param {String} key - the object key
     * @return {String} the absolute path to the file containing the
     *   object contents
     */
    getFilePath(key) {
        const hash = stringHash(key);
        const folderHashPath = ((hash % FOLDER_HASH)).toString();
        return `${this.dataPath}/${folderHashPath}/${key}`;
    }

    /**
     * Put a new object to the storage backend
     *
     * @param {stream.Readable} dataStream - input stream providing the
     *   object data
     * @param {Number} size - Total byte size of the data to put
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~putCallback} callback - called when done
     * @return {undefined}
     */
    put(dataStream, size, log, callback) {
        const key = crypto.pseudoRandomBytes(20).toString('hex');
        const filePath = this.getFilePath(key);
        log.debug('starting to write data', { method: 'put', key, filePath });
        dataStream.pause();
        fs.open(filePath, 'wx', (err, fd) => {
            if (err) {
                log.error('error opening filePath',
                          { method: 'put', key, filePath, error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: open() returned ${err.code}`));
            }
            const cbOnce = jsutil.once(callback);
            // disable autoClose so that we can close(fd) only after
            // fsync() has been called
            const fileStream = fs.createWriteStream(filePath,
                { fd,
                    autoClose: false });

            fileStream.on('finish', () => {
                function ok() {
                    log.debug('finished writing data',
                              { method: 'put', key, filePath });
                    return cbOnce(null, key);
                }
                if (this.noSync) {
                    fs.closeSync(fd);
                    return ok();
                }
                fs.fsync(fd, err => {
                    fs.close(fd);
                    if (err) {
                        log.error('fsync error',
                            { method: 'put', key, filePath,
                                error: err });
                        return cbOnce(
                            errors.InternalError.customizeDescription(
                                'filesystem error: fsync() returned ' +
                                    `${err.code}`));
                    }
                    return ok();
                });
                return undefined;
            }).on('error', err => {
                log.error('error streaming data on write',
                          { method: 'put', key, filePath, error: err });
                // destroying the write stream forces a close(fd)
                fileStream.destroy();
                return cbOnce(errors.InternalError.customizeDescription(
                    `write stream error: ${err.code}`));
            });
            dataStream.resume();
            dataStream.pipe(fileStream);
            dataStream.on('error', err => {
                log.error('error streaming data on read',
                    { method: 'put', key, filePath, error: err });
                // destroying the write stream forces a close(fd)
                fileStream.destroy();
                return cbOnce(errors.InternalError.customizeDescription(
                    `read stream error: ${err.code}`));
            });
            return undefined;
        });
    }

    /**
     * Get info about a stored object (see DataFileStore~statCallback
     * to know which info is returned)
     *
     * @param {String} key - key of the object
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~statCallback} callback - called when done
     * @return {undefined}
     */
    stat(key, log, callback) {
        const filePath = this.getFilePath(key);
        log.debug('stat file', { key, filePath });
        fs.stat(filePath, (err, stat) => {
            if (err) {
                if (err.code === 'ENOENT') {
                    return callback(errors.ObjNotFound);
                }
                log.error('error on \'stat\' of file',
                          { key, filePath, error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: stat() returned ${err.code}`));
            }
            const info = { objectSize: stat.size };
            return callback(null, info);
        });
    }

    /**
     * Retrieve data of a stored object
     *
     * @param {String} key - key of the object
     * @param {Object} [byteRange] - optional absolute inclusive byte
     *   range to retrieve.
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~getCallback} callback - called when done
     * @return {undefined}
     */
    get(key, byteRange, log, callback) {
        const filePath = this.getFilePath(key);

        const readStreamOptions = {
            flags: 'r',
            encoding: null,
            fd: null,
            autoClose: true,
        };
        if (byteRange) {
            readStreamOptions.start = byteRange[0];
            readStreamOptions.end = byteRange[1];
        }
        log.debug('opening readStream to get data',
                  { method: 'get', key, filePath, byteRange });
        const cbOnce = jsutil.once(callback);
        const rs = fs.createReadStream(filePath, readStreamOptions)
                  .on('error', err => {
                      if (err.code === 'ENOENT') {
                          return cbOnce(errors.ObjNotFound);
                      }
                      log.error('error retrieving file',
                          { method: 'get', key, filePath,
                              error: err });
                      return cbOnce(
                          errors.InternalError.customizeDescription(
                              `filesystem read error: ${err.code}`));
                  })
                  .on('open', () => { cbOnce(null, rs); });
    }

    /**
     * Delete a stored object
     *
     * @param {String} key - key of the object
     * @param {werelogs.RequestLogger} log - logging object
     * @param {DataFileStore~deleteCallback} callback - called when done
     * @return {undefined}
     */
    delete(key, log, callback) {
        const filePath = this.getFilePath(key);
        log.debug('deleting file', { method: 'delete', key, filePath });
        return fs.unlink(filePath, err => {
            if (err) {
                if (err.code === 'ENOENT') {
                    return callback(errors.ObjNotFound);
                }
                log.error('error deleting file', { method: 'delete',
                    key, filePath,
                    error: err });
                return callback(errors.InternalError.customizeDescription(
                    `filesystem error: unlink() returned ${err.code}`));
            }
            return callback();
        });
    }

    /**
     * Retrieve disk usage information
     *
     * @param {DataFileStore~diskUsageCallback} callback - called when done
     * @return {undefined}
     */
    getDiskUsage(callback) {
        diskusage.check(this.dataPath, callback);
    }
}

/**
 * @callback DataFileStore~putCallback
 * @param {Error} - The encountered error
 * @param {String} key - The key to access the data
 */

/**
 * @callback DataFileStore~statCallback
 * @param {Error} - The encountered error
 * @param {Object} info - Information about the object
 * @param {Number} info.objectSize - Byte size of the object
 */

/**
 * @callback DataFileStore~getCallback
 * @param {Error} - The encountered error
 *   arsenal.errors.ObjNotFound is returned if the object does not exist
 * @param {stream.Readable} stream - The stream of requested object data
 */

/**
 * @callback DataFileStore~deleteCallback
 * @param {Error} - The encountered error
 *   arsenal.errors.ObjNotFound is returned if the object does not exist
 */

/**
 * @callback DataFileStore~diskUsageCallback
 * @param {Error} - The encountered error
 * @param {object} - The disk usage info
 */

module.exports = DataFileStore;
<|endoftext|>


<commit_before><commit_msg>Sets up server.js<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var webpackMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = './webpack.config.js'

var app = express();
compiler = webpack(config);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false}));

app.use(express.static(path.join(__dirname, '/public'));
app.use(webpackMiddleware(compiler);
app.use(webpackHotMiddleware(compiler));

app.listen(process.env.PORT || 3000);

<|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.w<commit_msg>Correcting style<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.wr<|endoftext|>


<commit_before>/**
 * Returns a platform specific path e. g. "windows-x86_64-msvc18.0.40863-d"
 */
function platformSignature(/*Module qbs*/qbs,
                           /*Module cpp*/cpp,
                           /*[optional] bool*/noTargetOS,
                           /*[optional] bool*/noArchitecture,
                           /*[optional] bool*/noCompiler,
                           /*[optional] bool*/noBuildVariant) {
    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    var parts = [];

    if(noTargetOS === undefined || noTargetOS === false) {
        parts.push(qbs.targetOS.join("_"));
    }

    if(noArchitecture === undefined || noArchitecture === false) {
        parts.push(qbs.architecture);
    }

    if(noCompiler === undefined || noCompiler === false) {
        var compiler = qbs.toolchain.join("_");

        var versionParts = [];
        versionParts.push(cpp.compilerVersionMajor);
        versionParts.push(cpp.compilerVersionMinor);
        versionParts.push(cpp.compilerVersionPatch);
        compiler = compiler.concat(versionParts.join("."));

        parts.push(compiler);
    }

    if(noBuildVariant === undefined || noBuildVariant === false) {
        var buildVariant = qbs.buildVariant;
        if(buildVariant.contains("debug")) {
            parts.push("d");
        }
    }

    return parts.join("-");
}

/**
 * Returns a path for crossplatform libs like:
 * "windows-x86" or "linux-x86_64"
 */
function libDir(/*Module qbs*/qbs,
                /*Module cpp*/cpp,
                /*[optional] bool*/noTargetOS,
                /*[optional] bool*/noArchitecture) {
    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    return platformSignature(qbs, cpp, noTargetOS, noArchitecture, true, true);
}

/**
 * Returns a filename for crossplatform libs like:
 * "mylib-msvc-18.0.40863-d" or "mylib-mingw_g++-4.9.2"
 */
function libTargetName(/*Module qbs*/qbs,
                       /*Module cpp*/cpp,
                       /*string*/target,
                       /*[optional] bool*/noCompiler,
                       /*[optional] bool*/noBuildVariant) {

    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(target === undefined) {
        throw "Argument 'target' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof target !== "string") {
        throw "Argument 'target' must have type 'string' in function '" + arguments.callee.name + "'!";
    }

    var parts = [];

    parts.push(target);
    parts.push(platformSignature(qbs, cpp, true, true, noCompiler, noBuildVariant));

    return parts.join("-");
}
<commit_msg>* Shortened architecture and targetOs string generation.<commit_after>/**
 * Returns a platform specific path e. g. "windows-x86_64-msvc18.0.40863-d"
 */
function platformSignature(/*Module qbs*/qbs,
                           /*Module cpp*/cpp,
                           /*[optional] bool*/noTargetOS,
                           /*[optional] bool*/noArchitecture,
                           /*[optional] bool*/noCompiler,
                           /*[optional] bool*/noBuildVariant) {
    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    var parts = [];

    if(noTargetOS === undefined || noTargetOS === false) {
        var targetOS = (qbs.targetOS.length > 0) ? qbs.targetOS[0] : "na";
        parts.push(targetOS);
    }

    if(noArchitecture === undefined || noArchitecture === false) {
        var architecture = (qbs.architecture === "x86_64") ? "x64" : qbs.architecture;
        parts.push(architecture);
    }

    if(noCompiler === undefined || noCompiler === false) {
        var compiler = qbs.toolchain.join("_");

        var versionParts = [];
        versionParts.push(cpp.compilerVersionMajor);
        versionParts.push(cpp.compilerVersionMinor);
        versionParts.push(cpp.compilerVersionPatch);
        compiler = compiler.concat(versionParts.join("."));

        parts.push(compiler);
    }

    if(noBuildVariant === undefined || noBuildVariant === false) {
        var buildVariant = qbs.buildVariant;
        if(buildVariant.contains("debug")) {
            parts.push("d");
        }
    }

    return parts.join("-");
}

/**
 * Returns a path for crossplatform libs like:
 * "windows-x86" or "linux-x86_64"
 */
function libDir(/*Module qbs*/qbs,
                /*Module cpp*/cpp,
                /*[optional] bool*/noTargetOS,
                /*[optional] bool*/noArchitecture) {
    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    return platformSignature(qbs, cpp, noTargetOS, noArchitecture, true, true);
}

/**
 * Returns a filename for crossplatform libs like:
 * "mylib-msvc-18.0.40863-d" or "mylib-mingw_g++-4.9.2"
 */
function libTargetName(/*Module qbs*/qbs,
                       /*Module cpp*/cpp,
                       /*string*/target,
                       /*[optional] bool*/noCompiler,
                       /*[optional] bool*/noBuildVariant) {

    if(qbs === undefined) {
        throw "Argument 'qbs' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof qbs !== "object") {
        throw "Argument 'qbs' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(cpp === undefined) {
        throw "Argument 'cpp' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof cpp !== "object") {
        throw "Argument 'cpp' must have type 'object' in function '" + arguments.callee.name + "'!";
    }

    if(target === undefined) {
        throw "Argument 'target' not provided to function '" + arguments.callee.name + "'!";
    }

    if(typeof target !== "string") {
        throw "Argument 'target' must have type 'string' in function '" + arguments.callee.name + "'!";
    }

    var parts = [];

    parts.push(target);
    parts.push(platformSignature(qbs, cpp, true, true, noCompiler, noBuildVariant));

    return parts.join("-");
}
<|endoftext|>


<commit_before>import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js';
import XYZ from '../src/ol/source/XYZ.js';

const osm = new TileLayer({
  source: new OSM()
});

const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '© MapTiler ' +
  '© OpenStreetMap contributors';

const aerial = new TileLayer({
  source: new XYZ({
    attributions: attributions,
    url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
    maxZoom: 20
  })
});

const map = new Map({
  layers: [osm, aerial],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

const swipe = document.getElementById('swipe');

aerial.on('prerender', function(event) {
  const ctx = event.context;
  const width = ctx.canvas.width * (swipe.value / 100);

  ctx.save();
  ctx.beginPath();
  ctx.rect(width, 0, ctx.canvas.width - width, ctx.canvas.height);
  ctx.clip();
});

aerial.on('postrender', function(event) {
  const ctx = event.context;
  ctx.restore();
});

swipe.addEventListener('input', function() {
  map.render();
}, false);
<commit_msg>Adjust for layer canvas rotation<commit_after>import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js';
import XYZ from '../src/ol/source/XYZ.js';
import {getRenderPixel} from '../src/ol/render.js';

const osm = new TileLayer({
  source: new OSM()
});

const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions = '© MapTiler ' +
  '© OpenStreetMap contributors';

const aerial = new TileLayer({
  source: new XYZ({
    attributions: attributions,
    url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
    maxZoom: 20
  })
});

const map = new Map({
  layers: [osm, aerial],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

const swipe = document.getElementById('swipe');

aerial.on('prerender', function(event) {
  const ctx = event.context;
  const width = ctx.canvas.width * (swipe.value / 100);
  const tl = getRenderPixel(event, [width, 0]);
  const tr = getRenderPixel(event, [mapSize[0], 0]);
  const bl = getRenderPixel(event, [width, mapSize[1]]);
  const br = getRenderPixel(event, mapSize);

  ctx.save();
  ctx.beginPath();
  ctx.moveTo(tl[0], tl[1]);
  ctx.lineTo(bl[0], bl[1]);
  ctx.lineTo(br[0], br[1]);
  ctx.lineTo(tr[0], tr[1]);
  ctx.closePath();
  ctx.clip();
});

aerial.on('postrender', function(event) {
  const ctx = event.context;
  ctx.restore();
});

swipe.addEventListener('input', function() {
  map.render();
}, false);
<|endoftext|>


<commit_before>import EmberObject from '@ember/object';
import Service from '@ember/service';
import RSVP from 'rsvp';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
import { startMirage } from 'ilios/initializers/ember-cli-mirage';

const { resolve } = RSVP;

moduleForComponent('unassigned-students-summary', 'Integration | Component | unassigned students summary', {
  integration: true,
  setup(){
    this.server = startMirage();
  },
  teardown() {
    this.server.shutdown();
  }
});

test('it renders', function (assert) {
  const school = this.server.create('school', {
    id: 1,
    title: 'school 0',
  });
  this.server.create('school', {
    id: 2,
    title: 'school 1',
  });
  this.server.create('user', {
    school
  });
  const school1Mock = EmberObject.create(this.server.db.schools[0]);
  const school2Mock = EmberObject.create(this.server.db.schools[1]);
  const currentUserMock = Service.extend({
    model: resolve(EmberObject.create({
      school: resolve(school1Mock)
    }))
  });
  const studentRole = this.server.create('user-role', {
    id: 4,
    title: 'Student'
  });
  this.server.createList('user', 5, {
    school,
    roles: [studentRole]
  });

  this.server.get('api/users', ({ db }, { queryParams }) => {
    assert.equal(queryParams['filters[school]'], 1);
    assert.deepEqual(queryParams['filters[roles]'], ['4']);
    assert.equal(queryParams['filters[cohorts]'], '');

    const users = db.users.find([2, 3, 4, 5, 6]);

    return { users };
  });

  this.register('service:currentUser', currentUserMock);

  this.set('schools', [school1Mock, school2Mock]);
  this.render(hbs`{{unassigned-students-summary schools=schools}}`);

  return wait().then(() => {
    assert.equal(this.$().text().trim().search(/Students Requiring Cohort Assignment/), 0);
    assert.notEqual(this.$().text().trim().search(/There are 5 students needing assignment to a cohort/), -1);

    let options = this.$('option');
    assert.equal(options.length, 2);
    assert.equal(options.eq(0).text().trim(), 'school 0');
    assert.equal(options.eq(1).text().trim(), 'school 1');

    assert.equal(this.$('button').length, 1);

    assert.ok(this.$('div').eq(0).hasClass('alert'));
  });
});

test('it renders empty', function(assert) {
  let primarySchool = EmberObject.create({
    id: 1,
    title: 'school 0',
  });
  let user = EmberObject.create({
    school: resolve(primarySchool)
  });
  let currentUserMock = Service.extend({
    model: resolve(user)
  });

  this.register('service:currentUser', currentUserMock);

  this.set('schools', [primarySchool]);
  this.render(hbs`{{unassigned-students-summary schools=schools}}`);

  return wait().then(() => {
    assert.equal(this.$().text().trim().search(/Students Requiring Cohort Assignment/), 0);
    assert.notEqual(this.$().text().trim().search(/There are 0 students needing assignment to a cohort/), -1);

    assert.notOk(this.$('div').eq(0).hasClass('alert'));
    assert.equal(this.$('button').length, 0);
  });
});
<commit_msg>Migrate tests to the new API<commit_after>import EmberObject from '@ember/object';
import Service from '@ember/service';
import RSVP from 'rsvp';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, settled, findAll, find } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

const { resolve } = RSVP;

module('Integration | Component | unassigned students summary', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  test('it renders', async function(assert) {
    const school = this.server.create('school', {
      id: 1,
      title: 'school 0',
    });
    this.server.create('school', {
      id: 2,
      title: 'school 1',
    });
    this.server.create('user', {
      school
    });
    const school1Mock = EmberObject.create(this.server.db.schools[0]);
    const school2Mock = EmberObject.create(this.server.db.schools[1]);
    const currentUserMock = Service.extend({
      model: resolve(EmberObject.create({
        school: resolve(school1Mock)
      }))
    });
    const studentRole = this.server.create('user-role', {
      id: 4,
      title: 'Student'
    });
    this.server.createList('user', 5, {
      school,
      roles: [studentRole]
    });

    this.server.get('api/users', ({ db }, { queryParams }) => {
      assert.equal(queryParams['filters[school]'], 1);
      assert.deepEqual(queryParams['filters[roles]'], ['4']);
      assert.equal(queryParams['filters[cohorts]'], '');

      const users = db.users.find([2, 3, 4, 5, 6]);

      return { users };
    });

    this.owner.register('service:currentUser', currentUserMock);

    this.set('schools', [school1Mock, school2Mock]);
    await render(hbs`{{unassigned-students-summary schools=schools}}`);

    assert.equal(this.element.textContent.trim().search(/Students Requiring Cohort Assignment/), 0);
    assert.notEqual(this.element.textContent.trim().search(/There are 5 students needing assignment to a cohort/), -1);

    let options = this.$('option');
    assert.equal(options.length, 2);
    assert.equal(options.eq(0).text().trim(), 'school 0');
    assert.equal(options.eq(1).text().trim(), 'school 1');

    assert.equal(findAll('button').length, 1);

    assert.ok(find('div:nth-of-type(2)').classList.contains('alert'));
  });

  test('it renders empty', async function(assert) {
    let primarySchool = EmberObject.create({
      id: 1,
      title: 'school 0',
    });
    let user = EmberObject.create({
      school: resolve(primarySchool)
    });
    let currentUserMock = Service.extend({
      model: resolve(user)
    });

    this.owner.register('service:currentUser', currentUserMock);

    this.set('schools', [primarySchool]);
    await render(hbs`{{unassigned-students-summary schools=schools}}`);

    return settled().then(() => {
      assert.equal(this.element.textContent.trim().search(/Students Requiring Cohort Assignment/), 0);
      assert.notEqual(this.element.textContent.trim().search(/There are 0 students needing assignment to a cohort/), -1);

      assert.notOk(this.$('div').eq(0).hasClass('alert'));
      assert.equal(findAll('button').length, 0);
    });
  });
});
<|endoftext|>