<commit_before>var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
var INITIAL_LOCATION = [49.0140679, 8.4044366];
var INITIAL_ZOOM = 13;
var ATTRIBUTION = 'Map data © OpenStreetMap ' +
                  'contributors, ' +
                  'CC-BY-SA. Tiles © ' +
                  'CartoDB';

var map;
var nowGroup = L.layerGroup();
var todayGroup = L.layerGroup();
var otherGroup = L.layerGroup();

var now = new Date();
var TIME_NOW = [now.getHours(), now.getMinutes()];
var DAY_INDEX = (now.getDay() + 6) % 7;  // In our data, first day is Monday
var DAY_NAMES = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];

L.AwesomeMarkers.Icon.prototype.options.prefix = 'fa';
var nowIcon = L.AwesomeMarkers.icon({markerColor: 'green', icon: 'shopping-cart'});
var todayIcon = L.AwesomeMarkers.icon({markerColor: 'darkgreen', icon: 'shopping-cart'});
var otherIcon = L.AwesomeMarkers.icon({markerColor: 'cadetblue', icon: 'shopping-cart'});

/*
 * Return 0-padded string of a number.
 */
function pad(num, totalDigits) {
    var s = num.toString();
    while (s.length < totalDigits) {
        s = '0' + s;
    }
    return s;
}

/*
 * Creates time-table HTML code.
 *
 * `openingRanges` is a list of ranges compiled via opening_hours.js.
 * The first and second element of each range item are the starting and closing dates.
 */
function getTimeTable(openingRanges) {
    var html = '
';
    if (openingRanges !== undefined) {
        for (var index = 0, openingRangesLength = openingRanges.length; index < openingRangesLength; ++index) {
            var openingRange = openingRanges[index];

            var dayIsToday = openingRangeMatchesDay(openingRange, now);
            var tableRow = getTableRowForDay(openingRange, dayIsToday);
            html += tableRow;
        }
    }
    html += '
';
    return html;
}

/*
 * Returns table row for a day with opening hours.
 * If the day matches today the row is styled.
 */
function getTableRowForDay(openingRange, dayIsToday) {
    var openFromDate = openingRange[0];
    var openTillDate = openingRange[1];
    var dayNameIndex = openFromDate.getDay();
    var dayName = DAY_NAMES[dayNameIndex - 1];
    var cls = dayIsToday ? ' class="today"' : '';
    var formattedOpenFrom = moment(openFromDate).format('HH:mm');
    var formattedOpenTill = moment(openTillDate).format('HH:mm');
    return '
' + dayName + '	' +
           '' + formattedOpenFrom + ' - ' + formattedOpenTill + ' Uhr
';
}

/*
 * Initialize map.
 */
function initMap() {
    var tiles = new L.TileLayer(TILES_URL, {attribution: ATTRIBUTION});
    map = new L.Map('map').addLayer(tiles).setView(INITIAL_LOCATION, INITIAL_ZOOM);
}

/*
 * Initialize layer controls.
 *
 * Controls which serve no purpose are disabled. For example, if
 * currently no markets are open then the corresponding radio
 * button is disabled.
 */
function initControls() {
    var todayCount = todayGroup.getLayers().length;
    if (todayCount === 0) {
        // No markets today or all of today's markets currently open
        $('#today').attr('disabled', true);
    }
    if (nowGroup.getLayers().length > 0) {
        $('#now').attr('checked', true);
    } else {
        $('#now').attr('disabled', true);
        if (todayCount > 0) {
            $('#today').attr('checked', true);
        } else {
            $('#other').attr('checked', true);
        }
    }
    $("input[name=display]").change(updateLayers);
}

/*
 * Update layer visibility according to layer control settings.
 */
function updateLayers() {
    var value = document.querySelector('[name="display"]:checked').value;
    switch (value) {
        case "now":
            map.removeLayer(todayGroup);
            map.removeLayer(otherGroup);
            break;
        case "today":
            map.addLayer(todayGroup);
            map.removeLayer(otherGroup);
            break;
        case "other":
            map.addLayer(todayGroup);
            map.addLayer(otherGroup);
            break;
    }
}

/*
 * Returns true if opening range matches the day of the given date; otherwise false.
 */
function openingRangeMatchesDay(openingRange, date) {
    var openFromDate = openingRange[0];
    var openTillDate = openingRange[1];
    var dayIndex = date.getDay();
    return openFromDate.getDay() == dayIndex && openTillDate.getDay() == dayIndex;
}

/*
 * Returns true if opening range contains the time of the given date; otherwise false.
 */
function openingRangeContainsTime(openingRange, date) {
    var range = moment.range(openingRange[0], openingRange[1]);
    return range.contains(date);
}

/*
 * Returns opening ranges compiled via opening_hours.js.
 */
function getOpeningRanges(opening_hours_strings) {
    var monday = moment().startOf("week").add(1, 'days').toDate();
    var sunday = moment().endOf("week").add(1, 'days').toDate();
    var oh = new opening_hours(opening_hours_strings);
    return oh.getOpenIntervals(monday, sunday);
}

/*
 * Returns opening range for date or undefined.
 */
function getOpeningRangeForDate(openingRanges, date) {
    if (openingRanges !== undefined) {
        for (var index = 0, openingRangesLength = openingRanges.length; index < openingRangesLength; ++index) {
            var openingRange = openingRanges[index];

            var dayIsToday = openingRangeMatchesDay(openingRange, date);
            if (dayIsToday) {
                return openingRange;
            }
        }
    }
    return undefined;
}

/*
 * Create map markers from JSON market data.
 */
function initMarkers(featureCollection) {
    L.geoJson(featureCollection, {
        onEachFeature: initMarker
    });
}

function initMarker(feature) {
    var properties = feature.properties;
    var opening_hours_strings = properties.opening_hours;
    if (opening_hours_strings === undefined) {
        throw "Missing property 'opening_hours' for " + properties.title + ".";
    }
    var openingRanges = getOpeningRanges(opening_hours_strings);
    var todayOpeningRange = getOpeningRangeForDate(openingRanges, now);

    var coordinates = feature.geometry.coordinates;
    var marker = L.marker(L.latLng(coordinates[1], coordinates[0]));
    var where = properties.location;
    if (where === undefined) {
        throw "Missing property 'location' for " + properties.title + ".";
    }
    if (where !== null) {
        where = '
' + where + '
';
    } else {
        where = '';
    }
    var title = properties.title;
    if (title === undefined) {
        throw "Missing property 'title'.";
    }
    var timeTableHtml = getTimeTable(openingRanges);
    var popupHtml = '
' + title + '
' + where + timeTableHtml;
    marker.bindPopup(popupHtml);
    if (todayOpeningRange !== undefined) {
        if (openingRangeContainsTime(todayOpeningRange, now)) {
            marker.setIcon(nowIcon);
            nowGroup.addLayer(marker);
        } else {
            marker.setIcon(todayIcon);
            todayGroup.addLayer(marker);
        }
    } else {
        marker.setIcon(otherIcon);
        otherGroup.addLayer(marker);
    }
}

/*
 * Initialize legend.
 */
function initLegend() {
    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function (m) {
        return L.DomUtil.get('legend');
    };
    legend.addTo(map);
}

$(document).ready(function() {
    initMap();
    initLegend();
    $.getJSON("maerkte-karlsruhe.json", function(json) {
        initMarkers(json);
        initControls();
        map.addLayer(nowGroup);
        updateLayers();
    });
});
<commit_msg>Allow undefined market title.<commit_after>var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
var INITIAL_LOCATION = [49.0140679, 8.4044366];
var INITIAL_ZOOM = 13;
var ATTRIBUTION = 'Map data © OpenStreetMap ' +
                  'contributors, ' +
                  'CC-BY-SA. Tiles © ' +
                  'CartoDB';

var map;
var nowGroup = L.layerGroup();
var todayGroup = L.layerGroup();
var otherGroup = L.layerGroup();

var now = new Date();
var TIME_NOW = [now.getHours(), now.getMinutes()];
var DAY_INDEX = (now.getDay() + 6) % 7;  // In our data, first day is Monday
var DAY_NAMES = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
var DEFAULT_MARKET_TITLE = 'Markt';

L.AwesomeMarkers.Icon.prototype.options.prefix = 'fa';
var nowIcon = L.AwesomeMarkers.icon({markerColor: 'green', icon: 'shopping-cart'});
var todayIcon = L.AwesomeMarkers.icon({markerColor: 'darkgreen', icon: 'shopping-cart'});
var otherIcon = L.AwesomeMarkers.icon({markerColor: 'cadetblue', icon: 'shopping-cart'});

/*
 * Return 0-padded string of a number.
 */
function pad(num, totalDigits) {
    var s = num.toString();
    while (s.length < totalDigits) {
        s = '0' + s;
    }
    return s;
}

/*
 * Creates time-table HTML code.
 *
 * `openingRanges` is a list of ranges compiled via opening_hours.js.
 * The first and second element of each range item are the starting and closing dates.
 */
function getTimeTable(openingRanges) {
    var html = '
';
    if (openingRanges !== undefined) {
        for (var index = 0, openingRangesLength = openingRanges.length; index < openingRangesLength; ++index) {
            var openingRange = openingRanges[index];

            var dayIsToday = openingRangeMatchesDay(openingRange, now);
            var tableRow = getTableRowForDay(openingRange, dayIsToday);
            html += tableRow;
        }
    }
    html += '
';
    return html;
}

/*
 * Returns table row for a day with opening hours.
 * If the day matches today the row is styled.
 */
function getTableRowForDay(openingRange, dayIsToday) {
    var openFromDate = openingRange[0];
    var openTillDate = openingRange[1];
    var dayNameIndex = openFromDate.getDay();
    var dayName = DAY_NAMES[dayNameIndex - 1];
    var cls = dayIsToday ? ' class="today"' : '';
    var formattedOpenFrom = moment(openFromDate).format('HH:mm');
    var formattedOpenTill = moment(openTillDate).format('HH:mm');
    return '
' + dayName + '	' +
           '' + formattedOpenFrom + ' - ' + formattedOpenTill + ' Uhr
';
}

/*
 * Initialize map.
 */
function initMap() {
    var tiles = new L.TileLayer(TILES_URL, {attribution: ATTRIBUTION});
    map = new L.Map('map').addLayer(tiles).setView(INITIAL_LOCATION, INITIAL_ZOOM);
}

/*
 * Initialize layer controls.
 *
 * Controls which serve no purpose are disabled. For example, if
 * currently no markets are open then the corresponding radio
 * button is disabled.
 */
function initControls() {
    var todayCount = todayGroup.getLayers().length;
    if (todayCount === 0) {
        // No markets today or all of today's markets currently open
        $('#today').attr('disabled', true);
    }
    if (nowGroup.getLayers().length > 0) {
        $('#now').attr('checked', true);
    } else {
        $('#now').attr('disabled', true);
        if (todayCount > 0) {
            $('#today').attr('checked', true);
        } else {
            $('#other').attr('checked', true);
        }
    }
    $("input[name=display]").change(updateLayers);
}

/*
 * Update layer visibility according to layer control settings.
 */
function updateLayers() {
    var value = document.querySelector('[name="display"]:checked').value;
    switch (value) {
        case "now":
            map.removeLayer(todayGroup);
            map.removeLayer(otherGroup);
            break;
        case "today":
            map.addLayer(todayGroup);
            map.removeLayer(otherGroup);
            break;
        case "other":
            map.addLayer(todayGroup);
            map.addLayer(otherGroup);
            break;
    }
}

/*
 * Returns true if opening range matches the day of the given date; otherwise false.
 */
function openingRangeMatchesDay(openingRange, date) {
    var openFromDate = openingRange[0];
    var openTillDate = openingRange[1];
    var dayIndex = date.getDay();
    return openFromDate.getDay() == dayIndex && openTillDate.getDay() == dayIndex;
}

/*
 * Returns true if opening range contains the time of the given date; otherwise false.
 */
function openingRangeContainsTime(openingRange, date) {
    var range = moment.range(openingRange[0], openingRange[1]);
    return range.contains(date);
}

/*
 * Returns opening ranges compiled via opening_hours.js.
 */
function getOpeningRanges(opening_hours_strings) {
    var monday = moment().startOf("week").add(1, 'days').toDate();
    var sunday = moment().endOf("week").add(1, 'days').toDate();
    var oh = new opening_hours(opening_hours_strings);
    return oh.getOpenIntervals(monday, sunday);
}

/*
 * Returns opening range for date or undefined.
 */
function getOpeningRangeForDate(openingRanges, date) {
    if (openingRanges !== undefined) {
        for (var index = 0, openingRangesLength = openingRanges.length; index < openingRangesLength; ++index) {
            var openingRange = openingRanges[index];

            var dayIsToday = openingRangeMatchesDay(openingRange, date);
            if (dayIsToday) {
                return openingRange;
            }
        }
    }
    return undefined;
}

/*
 * Create map markers from JSON market data.
 */
function initMarkers(featureCollection) {
    L.geoJson(featureCollection, {
        onEachFeature: initMarker
    });
}

function initMarker(feature) {
    var properties = feature.properties;
    var opening_hours_strings = properties.opening_hours;
    if (opening_hours_strings === undefined) {
        throw "Missing property 'opening_hours' for " + properties.title + ".";
    }
    var openingRanges = getOpeningRanges(opening_hours_strings);
    var todayOpeningRange = getOpeningRangeForDate(openingRanges, now);

    var coordinates = feature.geometry.coordinates;
    var marker = L.marker(L.latLng(coordinates[1], coordinates[0]));
    var where = properties.location;
    if (where === undefined) {
        throw "Missing property 'location' for " + properties.title + ".";
    }
    if (where !== null) {
        where = '
' + where + '
';
    } else {
        where = '';
    }
    var title = properties.title;
    if (title === undefined) {
        throw "Missing property 'title'.";
    }
    if (title === null || title.length == 0) {
        title = DEFAULT_MARKET_TITLE;
    }
    var timeTableHtml = getTimeTable(openingRanges);
    var popupHtml = '
' + title + '
' + where + timeTableHtml;
    marker.bindPopup(popupHtml);
    if (todayOpeningRange !== undefined) {
        if (openingRangeContainsTime(todayOpeningRange, now)) {
            marker.setIcon(nowIcon);
            nowGroup.addLayer(marker);
        } else {
            marker.setIcon(todayIcon);
            todayGroup.addLayer(marker);
        }
    } else {
        marker.setIcon(otherIcon);
        otherGroup.addLayer(marker);
    }
}

/*
 * Initialize legend.
 */
function initLegend() {
    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function (m) {
        return L.DomUtil.get('legend');
    };
    legend.addTo(map);
}

$(document).ready(function() {
    initMap();
    initLegend();
    $.getJSON("maerkte-karlsruhe.json", function(json) {
        initMarkers(json);
        initControls();
        map.addLayer(nowGroup);
        updateLayers();
    });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global $:false, BUFFERSIZE */

'use strict';

var models = require('./data/models.json').models;
var utils = require('./utils');
utils.initPubSub();
var initViews = require('./views').initViews;
var showerror = require('./views/showerror');
var showError = showerror.showError;

window.BUFFERSIZE = 8192;

$(document).ready(function() {
  var tokenGenerator = utils.createTokenGenerator();

  // Make call to API to try and get token
  tokenGenerator.getToken(function(err, token) {
    window.onbeforeunload = function() {
      localStorage.clear();
    };

    if (!token) {
      console.error('No authorization token available');
      console.error('Attempting to reconnect...');

      if (err && err.code)
        showError('Server error ' + err.code + ': '+ err.error);
      else
        showError('Server error ' + err.code + ': please refresh your browser and try again');
    }

    var viewContext = {
      currentModel: 'en-US_BroadbandModel',
      models: models,
      token: token,
      bufferSize: BUFFERSIZE
    };

    initViews(viewContext);

    // Save models to localstorage
    localStorage.setItem('models', JSON.stringify(models));

    // Set default current model
    localStorage.setItem('currentModel', 'en-US_BroadbandModel');
    localStorage.setItem('sessionPermissions', 'true');

    $.subscribe('clearscreen', function() {
      $('#resultsText').text('');
      $('#resultsJSON').text('');
      $('.error-row').hide();
      $('.notification-row').hide();
      $('.hypotheses > ul').empty();
      $('#metadataTableBody').empty();
    });

  });

});
<commit_msg>Update index.js<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global $:false, BUFFERSIZE */

'use strict';

var models = require('./data/models.json').models;
var utils = require('./utils');
utils.initPubSub();
var initViews = require('./views').initViews;
var showerror = require('./views/showerror');
var showError = showerror.showError;
var getModels = require('./models').getModels;

window.BUFFERSIZE = 8192;

$(document).ready(function() {
  var tokenGenerator = utils.createTokenGenerator();

  // Make call to API to try and get token
  tokenGenerator.getToken(function(err, token) {
    window.onbeforeunload = function() {
      localStorage.clear();
    };

    if (!token) {
      console.error('No authorization token available');
      console.error('Attempting to reconnect...');

      if (err && err.code)
        showError('Server error ' + err.code + ': '+ err.error);
      else
        showError('Server error ' + err.code + ': please refresh your browser and try again');
    }

    var viewContext = {
      currentModel: 'en-US_BroadbandModel',
      models: models,
      token: token,
      bufferSize: BUFFERSIZE
    };

    initViews(viewContext);

    // Save models to localstorage
    localStorage.setItem('models', JSON.stringify(models));

    // Set default current model
    localStorage.setItem('currentModel', 'en-US_BroadbandModel');
    localStorage.setItem('sessionPermissions', 'true');

    getModels(token);

    $.subscribe('clearscreen', function() {
      $('#resultsText').text('');
      $('#resultsJSON').text('');
      $('.error-row').hide();
      $('.notification-row').hide();
      $('.hypotheses > ul').empty();
      $('#metadataTableBody').empty();
    });

  });

});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var fs = require('fs');
var async = require('async');
var raml = require('raml-1-parser');
var _ = require('lodash');
var dataMocker = require('./dataMocker');
var RequestMocker = require('./requestMocker');
var oldMocker = require('raml-mocker');

function generate(options, callback) {
    if (options) {
        if (!callback || !_.isFunction(callback)) {
            console.error('[RAML-MOCKER] You must define a callback function:\n');
            showUsage();
        }
        try {
            if (options.path) {
                generateFromPath(options.path, callback);
            } else if (options.files && _.isArray(options.files)) {
                generateFromFiles(options.files, callback);
            }
        } catch (exception) {
            console.error('[RAML-MOCKER] A runtime error has ocurred:\n');
            console.error(exception.stack);
            showUsage();
        }
    } else {
        console.error('[RAML-MOCKER] You must define a options object:\n');
        showUsage();
    }
}

function showUsage() {
    console.log('--------------------------------------------------------------------');
    console.log('---------------------- HOW TO USE RAML MOCKER ----------------------');
    console.log('--  var ramlMocker = require(\'raml-mocker\');                      --');
    console.log('--  var options = { path: \'test/raml\' };                          --');
    console.log('--  var callback = function (requests){ console.log(requests); }; --');
    console.log('--  ramlMocker.generate(options, callback);                       --');
    console.log('--------------------------------------------------------------------');
}

function generateFromPath(filesPath, callback) {
    fs.readdir(filesPath, function(err, files) {
        if (err) {
            throw err;
        }
        var filesToGenerate = [];
        _.each(files, function(file) {
            if (file.substr(-5) === '.raml') {
                filesToGenerate.push(path.join(filesPath, file));
            }
        });
        generateFromFiles(filesToGenerate, callback);
    });
}

function generateFromFiles(files, callback) {
    var requestsToMock = [];
    async.each(files, function(file, cb) {
        raml.loadApi(file).then(function (raml) {
            if (raml.RAMLVersion() == 'RAML10') {
                getRamlRequestsToMock(raml, raml, '', function(reqs) {
                    requestsToMock = _.union(requestsToMock, reqs);
                    cb();
                });
            }
            else {
                // Old RAMl 0.8 format
                oldMocker.generate({
                    files: [file]
                }, function(requests) {
                    requestsToMock = _.union(requestsToMock, reqs);
                    cb();
                });
            }

        }, function (error) {
            cb('Error parsing: ' + error);
        });
    }, function (err) {
        if (err) {
            console.log(err);
        } else {
            callback(requestsToMock);
        }
    });
}

function getRamlRequestsToMock(definition, api, uri, callback) {
    var requestsToMock = [];

    if (definition.relativeUri && definition.relativeUri()) {
        var nodeUri = definition.relativeUri().value();
        var prepareRegexpUri = function(uriStr, regexpStr, searchStr) {
            var prepareRegexpString = function(str, regexpStr, escaping, needRegexp) {
                var replaceRegexp = function(str, escaping) {
                    return escaping ? str.replace(/([\^\[\.\$\*\(\\\/\+\)\|\?])/g, '\\$1') : str;
                };
                var paramStartPos = uriStr.indexOf(searchStr);
                paramStartPos = paramStartPos > -1 ? paramStartPos : uriStr.length;
                var retStr = [
                    replaceRegexp(uriStr.substring(0, paramStartPos), escaping),
                    _.isRegExp(regexpStr) ? regexpStr.toString().substr(1, regexpStr.toString().length - 2) : regexpStr,
                    replaceRegexp(uriStr.substring(paramStartPos + (searchStr ? searchStr.length : 0)), escaping)
                ].join('');
                return needRegexp ? new RegExp(retStr) : retStr;
            };

            switch (false) {
                case !(_.isRegExp(uriStr)):
                    uri = uri.toString().substr(1, uriStr.toString().length - 2);
                    return prepareRegexpString(uriStr, regexpStr, false, true);
                case !(_.isRegExp(regexpStr)):
                    return prepareRegexpString(uriStr, regexpStr, true, true);
                default:
                    return prepareRegexpString(uriStr, regexpStr, false, false);
            }
        };

        if (definition.uriParameters()) {
            var modifyUri = function(uritoModify, uriParam) {
                var fullParam = '{' + uriParam.name() + '}';
                switch (false) {
                    // TODO: Implements custom types
                    case !(uriParam.kind() == 'IntegerTypeDeclaration'):
                        // TODO: Implements value limits
                        return prepareRegexpUri(uritoModify, /\d+/, fullParam);
                    case !(uriParam.kind() == 'StringTypeDeclaration'):
                        // TODO: Implements min & max Length
                        if (uriParam.pattern()) {
                            // Remove first & end slashes
                            var pattern = uriParam.pattern().replace(/^\//, '').replace(/\/$/, '');
                            return prepareRegexpUri(uritoModify, new RegExp(pattern), fullParam);
                        }
                        return uritoModify.replace(fullParam, ':' + uriParam.name());
                    default:
                        return uritoModify.replace(fullParam, ':' + uriParam.name());
                }
            };
            _.each(definition.uriParameters(), function(uriParam) {
                nodeUri = modifyUri(nodeUri, uriParam);
            });
        }
        uri = prepareRegexpUri(uri, nodeUri);
    }
    var tasks = [];
    if (definition.methods && definition.methods()) {
        tasks.push(function (cb) {
            getRamlRequestsToMockMethods(definition, api, uri, function(reqs) {
                requestsToMock = _.union(requestsToMock, reqs);
                cb();
            });
        });
    }
    if (definition.resources && definition.resources()) {
        tasks.push(function (cb) {
            getRamlRequestsToMockResources(definition, api, uri, function(reqs) {
                requestsToMock = _.union(requestsToMock, reqs);
                cb();
            });
        });
    }
    async.parallel(tasks, function (err) {
        if (err) {
            console.log(err);
        }
        callback(requestsToMock);
    });
}

function getRamlRequestsToMockMethods(definition, api, uri, callback) {
    var responsesByCode = [];
    async.each(definition.methods(), function(method) {
        if (method.method() && /get|post|put|delete/i.test(method.method()) && method.responses()) {
            var responsesMethodByCode = getResponsesByCode(method.responses(), api);
            var methodMocker = new RequestMocker(uri, method.method());
            console.log('index.js:179', method.responses());

            var currentMockDefaultCode = null;
            _.each(responsesMethodByCode, function(reqDefinition) {
                methodMocker.addResponse(reqDefinition.code, function() {
                    if (reqDefinition.schema || reqDefinition.body) {
                        return dataMocker(reqDefinition);
                    } else {
                        return null;
                    }
                }, function() {
                    return reqDefinition.example;
                });
                if ((!currentMockDefaultCode || currentMockDefaultCode > reqDefinition.code) && /^2\d\d$/.test(reqDefinition.code)) {
                    methodMocker.mock = methodMocker.getResponses()[reqDefinition.code];
                    methodMocker.example = methodMocker.getExamples()[reqDefinition.code];
                    currentMockDefaultCode = reqDefinition.code;
                }
            });
            if (currentMockDefaultCode) {
                methodMocker.defaultCode = currentMockDefaultCode;
            }
            responsesByCode.push(methodMocker);
        }
    });
    callback(responsesByCode);
}

function getResponsesByCode(responses, api) {
    var responsesByCode = [];

    var typeByName = _.zipObject(_.map(api.types(), function(item) {
        return item.name();
    }), api.types());

    var parseExample = function (body, code, example) {
        if (body.type()) {
            responsesByCode.push({
                code: code,
                body: body,
                types: typeByName,
                example: example
            });
        }
        else if (body.schema()) {
            var schema = null;
            try {
                schema = JSON.parse(body.schema());
            } catch (exception) {
                console.log(exception.stack);
            }
            responsesByCode.push({
                code: code,
                schema: schema,
                example: example
            });
        }
    };

    _.each(responses, function(response) {
        if (!response) {
            return false;
        }
        var code = response.code() && response.code().value();
        _.each(response.body(), function(body) {
            if (!_.isNaN(Number(code)) && body) {
                code = Number(code);

                if (body.example()) {
                    parseExample(body, code, body.example().value());
                }
                else if (body.examples()) {
                    _.each(body.examples(), function (example) {
                        parseExample(body, code, example.value());
                    });
                }
                else {
                    parseExample(body, code, null);
                }
            }
        });
    });
    return responsesByCode;
}

function getRamlRequestsToMockResources(definition, api, uri, callback) {
    var requestsToMock = [];
    async.each(definition.resources(), function(def, cb) {
        getRamlRequestsToMock(def, api, uri, function(reqs) {
            requestsToMock = _.union(requestsToMock, reqs);
            cb(null);
        });
    }, function (err) {
        if (err) {
            console.log(err);
        }
        callback(requestsToMock);
    });
}
module.exports = {
    generate: generate
};
<commit_msg>Fix undefined example|/examples. Did not generate mock<commit_after>'use strict';
var path = require('path');
var fs = require('fs');
var async = require('async');
var raml = require('raml-1-parser');
var _ = require('lodash');
var dataMocker = require('./dataMocker');
var RequestMocker = require('./requestMocker');
var oldMocker = require('raml-mocker');

function generate(options, callback) {
    if (options) {
        if (!callback || !_.isFunction(callback)) {
            console.error('[RAML-MOCKER] You must define a callback function:\n');
            showUsage();
        }
        try {
            if (options.path) {
                generateFromPath(options.path, callback);
            } else if (options.files && _.isArray(options.files)) {
                generateFromFiles(options.files, callback);
            }
        } catch (exception) {
            console.error('[RAML-MOCKER] A runtime error has ocurred:\n');
            console.error(exception.stack);
            showUsage();
        }
    } else {
        console.error('[RAML-MOCKER] You must define a options object:\n');
        showUsage();
    }
}

function showUsage() {
    console.log('--------------------------------------------------------------------');
    console.log('---------------------- HOW TO USE RAML MOCKER ----------------------');
    console.log('--  var ramlMocker = require(\'raml-mocker\');                      --');
    console.log('--  var options = { path: \'test/raml\' };                          --');
    console.log('--  var callback = function (requests){ console.log(requests); }; --');
    console.log('--  ramlMocker.generate(options, callback);                       --');
    console.log('--------------------------------------------------------------------');
}

function generateFromPath(filesPath, callback) {
    fs.readdir(filesPath, function(err, files) {
        if (err) {
            throw err;
        }
        var filesToGenerate = [];
        _.each(files, function(file) {
            if (file.substr(-5) === '.raml') {
                filesToGenerate.push(path.join(filesPath, file));
            }
        });
        generateFromFiles(filesToGenerate, callback);
    });
}

function generateFromFiles(files, callback) {
    var requestsToMock = [];
    async.each(files, function(file, cb) {
        raml.loadApi(file).then(function (raml) {
            if (raml.RAMLVersion() == 'RAML10') {
                getRamlRequestsToMock(raml, raml, '', function(reqs) {
                    requestsToMock = _.union(requestsToMock, reqs);
                    cb();
                });
            }
            else {
                // Old RAMl 0.8 format
                oldMocker.generate({
                    files: [file]
                }, function(requests) {
                    requestsToMock = _.union(requestsToMock, reqs);
                    cb();
                });
            }

        }, function (error) {
            cb('Error parsing: ' + error);
        });
    }, function (err) {
        if (err) {
            console.log(err);
        } else {
            callback(requestsToMock);
        }
    });
}

function getRamlRequestsToMock(definition, api, uri, callback) {
    var requestsToMock = [];

    if (definition.relativeUri && definition.relativeUri()) {
        var nodeUri = definition.relativeUri().value();
        var prepareRegexpUri = function(uriStr, regexpStr, searchStr) {
            var prepareRegexpString = function(str, regexpStr, escaping, needRegexp) {
                var replaceRegexp = function(str, escaping) {
                    return escaping ? str.replace(/([\^\[\.\$\*\(\\\/\+\)\|\?])/g, '\\$1') : str;
                };
                var paramStartPos = uriStr.indexOf(searchStr);
                paramStartPos = paramStartPos > -1 ? paramStartPos : uriStr.length;
                var retStr = [
                    replaceRegexp(uriStr.substring(0, paramStartPos), escaping),
                    _.isRegExp(regexpStr) ? regexpStr.toString().substr(1, regexpStr.toString().length - 2) : regexpStr,
                    replaceRegexp(uriStr.substring(paramStartPos + (searchStr ? searchStr.length : 0)), escaping)
                ].join('');
                return needRegexp ? new RegExp(retStr) : retStr;
            };

            switch (false) {
                case !(_.isRegExp(uriStr)):
                    uri = uri.toString().substr(1, uriStr.toString().length - 2);
                    return prepareRegexpString(uriStr, regexpStr, false, true);
                case !(_.isRegExp(regexpStr)):
                    return prepareRegexpString(uriStr, regexpStr, true, true);
                default:
                    return prepareRegexpString(uriStr, regexpStr, false, false);
            }
        };

        if (definition.uriParameters()) {
            var modifyUri = function(uritoModify, uriParam) {
                var fullParam = '{' + uriParam.name() + '}';
                switch (false) {
                    // TODO: Implements custom types
                    case !(uriParam.kind() == 'IntegerTypeDeclaration'):
                        // TODO: Implements value limits
                        return prepareRegexpUri(uritoModify, /\d+/, fullParam);
                    case !(uriParam.kind() == 'StringTypeDeclaration'):
                        // TODO: Implements min & max Length
                        if (uriParam.pattern()) {
                            // Remove first & end slashes
                            var pattern = uriParam.pattern().replace(/^\//, '').replace(/\/$/, '');
                            return prepareRegexpUri(uritoModify, new RegExp(pattern), fullParam);
                        }
                        return uritoModify.replace(fullParam, ':' + uriParam.name());
                    default:
                        return uritoModify.replace(fullParam, ':' + uriParam.name());
                }
            };
            _.each(definition.uriParameters(), function(uriParam) {
                nodeUri = modifyUri(nodeUri, uriParam);
            });
        }
        uri = prepareRegexpUri(uri, nodeUri);
    }
    var tasks = [];
    if (definition.methods && definition.methods()) {
        tasks.push(function (cb) {
            getRamlRequestsToMockMethods(definition, api, uri, function(reqs) {
                requestsToMock = _.union(requestsToMock, reqs);
                cb();
            });
        });
    }
    if (definition.resources && definition.resources()) {
        tasks.push(function (cb) {
            getRamlRequestsToMockResources(definition, api, uri, function(reqs) {
                requestsToMock = _.union(requestsToMock, reqs);
                cb();
            });
        });
    }
    async.parallel(tasks, function (err) {
        if (err) {
            console.log(err);
        }
        callback(requestsToMock);
    });
}

function getRamlRequestsToMockMethods(definition, api, uri, callback) {
    var responsesByCode = [];
    async.each(definition.methods(), function(method) {
        if (method.method() && /get|post|put|delete/i.test(method.method()) && method.responses()) {
            var responsesMethodByCode = getResponsesByCode(method.responses(), api);
            var methodMocker = new RequestMocker(uri, method.method());

            var currentMockDefaultCode = null;
            _.each(responsesMethodByCode, function(reqDefinition) {
                methodMocker.addResponse(reqDefinition.code, function() {
                    if (reqDefinition.schema || reqDefinition.body) {
                        return dataMocker(reqDefinition);
                    } else {
                        return null;
                    }
                }, function() {
                    return reqDefinition.example;
                });
                if ((!currentMockDefaultCode || currentMockDefaultCode > reqDefinition.code) && /^2\d\d$/.test(reqDefinition.code)) {
                    methodMocker.mock = methodMocker.getResponses()[reqDefinition.code];
                    methodMocker.example = methodMocker.getExamples()[reqDefinition.code];
                    currentMockDefaultCode = reqDefinition.code;
                }
            });
            if (currentMockDefaultCode) {
                methodMocker.defaultCode = currentMockDefaultCode;
            }
            responsesByCode.push(methodMocker);
        }
    });
    callback(responsesByCode);
}

function getResponsesByCode(responses, api) {
    var responsesByCode = [];

    var typeByName = _.zipObject(_.map(api.types(), function(item) {
        return item.name();
    }), api.types());

    var parseExample = function (body, code, example) {
        if (body.type()) {
            responsesByCode.push({
                code: code,
                body: body,
                types: typeByName,
                example: example
            });
        }
        else if (body.schema()) {
            var schema = null;
            try {
                schema = JSON.parse(body.schema());
            } catch (exception) {
                console.log(exception.stack);
            }
            responsesByCode.push({
                code: code,
                schema: schema,
                example: example
            });
        }
    };

    _.each(responses, function(response) {
        if (!response) {
            return false;
        }
        var code = response.code() && response.code().value();
        _.each(response.body(), function(body) {
            if (!_.isNaN(Number(code)) && body) {
                code = Number(code);

                if (body.example()) {
                    parseExample(body, code, body.example().value());
                }
                else if (body.examples()) {
                    _.each(body.examples(), function (example) {
                        parseExample(body, code, example.value());
                    });
                }
                else {
                    parseExample(body, code, null);
                }
            }
        });
    });
    return responsesByCode;
}

function getRamlRequestsToMockResources(definition, api, uri, callback) {
    var requestsToMock = [];
    async.each(definition.resources(), function(def, cb) {
        getRamlRequestsToMock(def, api, uri, function(reqs) {
            requestsToMock = _.union(requestsToMock, reqs);
            cb(null);
        });
    }, function (err) {
        if (err) {
            console.log(err);
        }
        callback(requestsToMock);
    });
}
module.exports = {
    generate: generate
};
<|endoftext|>


<commit_before>var bcrypto = require('./crypto')
var bscript = require('./script')
var bufferutils = require('./bufferutils')
var bufferReverse = require('buffer-reverse')
var opcodes = require('./opcodes.json')
var typeforce = require('typeforce')
var types = require('./types')

function Transaction () {
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
}

Transaction.DEFAULT_SEQUENCE = 0xffffffff
Transaction.SIGHASH_ALL = 0x01
Transaction.SIGHASH_NONE = 0x02
Transaction.SIGHASH_SINGLE = 0x03
Transaction.SIGHASH_ANYONECANPAY = 0x80

Transaction.fromBuffer = function (buffer, __noStrict) {
  var offset = 0
  function readSlice (n) {
    offset += n
    return buffer.slice(offset - n, offset)
  }

  function readUInt32 () {
    var i = buffer.readUInt32LE(offset)
    offset += 4
    return i
  }

  function readUInt64 () {
    var i = bufferutils.readUInt64LE(buffer, offset)
    offset += 8
    return i
  }

  function readVarInt () {
    var vi = bufferutils.readVarInt(buffer, offset)
    offset += vi.size
    return vi.number
  }

  function readScript () {
    return readSlice(readVarInt())
  }

  var tx = new Transaction()
  tx.version = readUInt32()

  var vinLen = readVarInt()
  for (var i = 0; i < vinLen; ++i) {
    tx.ins.push({
      hash: readSlice(32),
      index: readUInt32(),
      script: readScript(),
      sequence: readUInt32()
    })
  }

  var voutLen = readVarInt()
  for (i = 0; i < voutLen; ++i) {
    tx.outs.push({
      value: readUInt64(),
      script: readScript()
    })
  }

  tx.locktime = readUInt32()

  if (__noStrict) return tx
  if (offset !== buffer.length) throw new Error('Transaction has unexpected data')

  return tx
}

Transaction.fromHex = function (hex) {
  return Transaction.fromBuffer(new Buffer(hex, 'hex'))
}

Transaction.isCoinbaseHash = function (buffer) {
  typeforce(types.Hash256bit, buffer)
  for (var i = 0; i < 32; ++i) {
    if (buffer[i] !== 0) return false
  }
  return true
}

Transaction.prototype.isCoinbase = function () {
  return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
}

var EMPTY_SCRIPT = new Buffer(0)

Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
  typeforce(types.tuple(
    types.Hash256bit,
    types.UInt32,
    types.maybe(types.UInt32),
    types.maybe(types.Buffer)
  ), arguments)

  if (types.Null(sequence)) {
    sequence = Transaction.DEFAULT_SEQUENCE
  }

  // Add the input and return the input's index
  return (this.ins.push({
    hash: hash,
    index: index,
    script: scriptSig || EMPTY_SCRIPT,
    sequence: sequence
  }) - 1)
}

Transaction.prototype.addOutput = function (scriptPubKey, value) {
  typeforce(types.tuple(types.Buffer, types.UInt53), arguments)

  // Add the output and return the output's index
  return (this.outs.push({
    script: scriptPubKey,
    value: value
  }) - 1)
}

Transaction.prototype.byteLength = function () {
  function scriptSize (someScript) {
    var length = someScript.length

    return bufferutils.varIntSize(length) + length
  }

  return (
    8 +
    bufferutils.varIntSize(this.ins.length) +
    bufferutils.varIntSize(this.outs.length) +
    this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
    this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
  )
}

Transaction.prototype.clone = function () {
  var newTx = new Transaction()
  newTx.version = this.version
  newTx.locktime = this.locktime

  newTx.ins = this.ins.map(function (txIn) {
    return {
      hash: txIn.hash,
      index: txIn.index,
      script: txIn.script,
      sequence: txIn.sequence
    }
  })

  newTx.outs = this.outs.map(function (txOut) {
    return {
      script: txOut.script,
      value: txOut.value
    }
  })

  return newTx
}

var ONE = new Buffer('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
var VALUE_UINT64_MAX = new Buffer('ffffffffffffffff', 'hex')
var BLANK_OUTPUT = {
  script: EMPTY_SCRIPT,
  valueBuffer: VALUE_UINT64_MAX
}

/**
 * Hash transaction for signing a specific input.
 *
 * Bitcoin uses a different hash for each signed transaction input.
 * This method copies the transaction, makes the necessary changes based on the
 * hashType, and then hashes the result.
 * This hash can then be used to sign the provided transaction input.
 */
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
  typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)

  // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
  if (inIndex >= this.ins.length) return ONE

  // ignore OP_CODESEPARATOR
  var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
    return x !== opcodes.OP_CODESEPARATOR
  }))

  var txTmp = this.clone()

  // SIGHASH_NONE: ignore all outputs? (wildcard payee)
  if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
    txTmp.outs = []

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })

  // SIGHASH_SINGLE: ignore all outputs, except at the same index?
  } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (inIndex >= this.outs.length) return ONE

    // truncate outputs after
    txTmp.outs.length = inIndex + 1

    // "blank" outputs before
    for (var i = 0; i < inIndex; i++) {
      txTmp.outs[i] = BLANK_OUTPUT
    }

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })
  }

  // SIGHASH_ANYONECANPAY: ignore inputs entirely?
  if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
    txTmp.ins = [txTmp.ins[inIndex]]
    txTmp.ins[0].script = ourScript

  // SIGHASH_ALL: only ignore input scripts
  } else {
    // "blank" others input scripts
    txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
    txTmp.ins[inIndex].script = ourScript
  }

  // serialize and hash
  var buffer = new Buffer(txTmp.byteLength() + 4)
  buffer.writeInt32LE(hashType, buffer.length - 4)
  txTmp.toBuffer(buffer, 0)

  return bcrypto.hash256(buffer)
}

Transaction.prototype.getHash = function () {
  return bcrypto.hash256(this.toBuffer())
}

Transaction.prototype.getId = function () {
  // transaction hash's are displayed in reverse order
  return bufferReverse(this.getHash()).toString('hex')
}

Transaction.prototype.toBuffer = function (buffer, offset) {
  if (!buffer) buffer = new Buffer(this.byteLength())

  offset = offset || 0
  function writeSlice (slice) {
    slice.copy(buffer, offset)
    offset += slice.length
  }

  function writeUInt32 (i) {
    buffer.writeUInt32LE(i, offset)
    offset += 4
  }

  function writeUInt64 (i) {
    bufferutils.writeUInt64LE(buffer, i, offset)
    offset += 8
  }

  function writeVarInt (i) {
    var n = bufferutils.writeVarInt(buffer, i, offset)
    offset += n
  }

  writeUInt32(this.version)
  writeVarInt(this.ins.length)

  this.ins.forEach(function (txIn) {
    writeSlice(txIn.hash)
    writeUInt32(txIn.index)
    writeVarInt(txIn.script.length)
    writeSlice(txIn.script)
    writeUInt32(txIn.sequence)
  })

  writeVarInt(this.outs.length)
  this.outs.forEach(function (txOut) {
    if (!txOut.valueBuffer) {
      writeUInt64(txOut.value)
    } else {
      writeSlice(txOut.valueBuffer)
    }

    writeVarInt(txOut.script.length)
    writeSlice(txOut.script)
  })

  writeUInt32(this.locktime)

  return buffer
}

Transaction.prototype.toHex = function () {
  return this.toBuffer().toString('hex')
}

Transaction.prototype.setInputScript = function (index, scriptSig) {
  typeforce(types.tuple(types.Number, types.Buffer), arguments)

  this.ins[index].script = scriptSig
}

module.exports = Transaction
<commit_msg>Transaction: return a slice, not the original Buffer<commit_after>var bcrypto = require('./crypto')
var bscript = require('./script')
var bufferutils = require('./bufferutils')
var bufferReverse = require('buffer-reverse')
var opcodes = require('./opcodes.json')
var typeforce = require('typeforce')
var types = require('./types')

function Transaction () {
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
}

Transaction.DEFAULT_SEQUENCE = 0xffffffff
Transaction.SIGHASH_ALL = 0x01
Transaction.SIGHASH_NONE = 0x02
Transaction.SIGHASH_SINGLE = 0x03
Transaction.SIGHASH_ANYONECANPAY = 0x80

Transaction.fromBuffer = function (buffer, __noStrict) {
  var offset = 0
  function readSlice (n) {
    offset += n
    return buffer.slice(offset - n, offset)
  }

  function readUInt32 () {
    var i = buffer.readUInt32LE(offset)
    offset += 4
    return i
  }

  function readUInt64 () {
    var i = bufferutils.readUInt64LE(buffer, offset)
    offset += 8
    return i
  }

  function readVarInt () {
    var vi = bufferutils.readVarInt(buffer, offset)
    offset += vi.size
    return vi.number
  }

  function readScript () {
    return readSlice(readVarInt())
  }

  var tx = new Transaction()
  tx.version = readUInt32()

  var vinLen = readVarInt()
  for (var i = 0; i < vinLen; ++i) {
    tx.ins.push({
      hash: readSlice(32),
      index: readUInt32(),
      script: readScript(),
      sequence: readUInt32()
    })
  }

  var voutLen = readVarInt()
  for (i = 0; i < voutLen; ++i) {
    tx.outs.push({
      value: readUInt64(),
      script: readScript()
    })
  }

  tx.locktime = readUInt32()

  if (__noStrict) return tx
  if (offset !== buffer.length) throw new Error('Transaction has unexpected data')

  return tx
}

Transaction.fromHex = function (hex) {
  return Transaction.fromBuffer(new Buffer(hex, 'hex'))
}

Transaction.isCoinbaseHash = function (buffer) {
  typeforce(types.Hash256bit, buffer)
  for (var i = 0; i < 32; ++i) {
    if (buffer[i] !== 0) return false
  }
  return true
}

Transaction.prototype.isCoinbase = function () {
  return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
}

var EMPTY_SCRIPT = new Buffer(0)

Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
  typeforce(types.tuple(
    types.Hash256bit,
    types.UInt32,
    types.maybe(types.UInt32),
    types.maybe(types.Buffer)
  ), arguments)

  if (types.Null(sequence)) {
    sequence = Transaction.DEFAULT_SEQUENCE
  }

  // Add the input and return the input's index
  return (this.ins.push({
    hash: hash,
    index: index,
    script: scriptSig || EMPTY_SCRIPT,
    sequence: sequence
  }) - 1)
}

Transaction.prototype.addOutput = function (scriptPubKey, value) {
  typeforce(types.tuple(types.Buffer, types.UInt53), arguments)

  // Add the output and return the output's index
  return (this.outs.push({
    script: scriptPubKey,
    value: value
  }) - 1)
}

Transaction.prototype.byteLength = function () {
  function scriptSize (someScript) {
    var length = someScript.length

    return bufferutils.varIntSize(length) + length
  }

  return (
    8 +
    bufferutils.varIntSize(this.ins.length) +
    bufferutils.varIntSize(this.outs.length) +
    this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
    this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
  )
}

Transaction.prototype.clone = function () {
  var newTx = new Transaction()
  newTx.version = this.version
  newTx.locktime = this.locktime

  newTx.ins = this.ins.map(function (txIn) {
    return {
      hash: txIn.hash,
      index: txIn.index,
      script: txIn.script,
      sequence: txIn.sequence
    }
  })

  newTx.outs = this.outs.map(function (txOut) {
    return {
      script: txOut.script,
      value: txOut.value
    }
  })

  return newTx
}

var ONE = new Buffer('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
var VALUE_UINT64_MAX = new Buffer('ffffffffffffffff', 'hex')
var BLANK_OUTPUT = {
  script: EMPTY_SCRIPT,
  valueBuffer: VALUE_UINT64_MAX
}

/**
 * Hash transaction for signing a specific input.
 *
 * Bitcoin uses a different hash for each signed transaction input.
 * This method copies the transaction, makes the necessary changes based on the
 * hashType, and then hashes the result.
 * This hash can then be used to sign the provided transaction input.
 */
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
  typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)

  // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
  if (inIndex >= this.ins.length) return ONE

  // ignore OP_CODESEPARATOR
  var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
    return x !== opcodes.OP_CODESEPARATOR
  }))

  var txTmp = this.clone()

  // SIGHASH_NONE: ignore all outputs? (wildcard payee)
  if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
    txTmp.outs = []

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })

  // SIGHASH_SINGLE: ignore all outputs, except at the same index?
  } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (inIndex >= this.outs.length) return ONE

    // truncate outputs after
    txTmp.outs.length = inIndex + 1

    // "blank" outputs before
    for (var i = 0; i < inIndex; i++) {
      txTmp.outs[i] = BLANK_OUTPUT
    }

    // ignore sequence numbers (except at inIndex)
    txTmp.ins.forEach(function (input, i) {
      if (i === inIndex) return

      input.sequence = 0
    })
  }

  // SIGHASH_ANYONECANPAY: ignore inputs entirely?
  if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
    txTmp.ins = [txTmp.ins[inIndex]]
    txTmp.ins[0].script = ourScript

  // SIGHASH_ALL: only ignore input scripts
  } else {
    // "blank" others input scripts
    txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
    txTmp.ins[inIndex].script = ourScript
  }

  // serialize and hash
  var buffer = new Buffer(txTmp.byteLength() + 4)
  buffer.writeInt32LE(hashType, buffer.length - 4)
  txTmp.toBuffer(buffer, 0)

  return bcrypto.hash256(buffer)
}

Transaction.prototype.getHash = function () {
  return bcrypto.hash256(this.toBuffer())
}

Transaction.prototype.getId = function () {
  // transaction hash's are displayed in reverse order
  return bufferReverse(this.getHash()).toString('hex')
}

Transaction.prototype.toBuffer = function (buffer, initialOffset) {
  if (!buffer) buffer = new Buffer(this.byteLength())

  var offset = initialOffset || 0
  function writeSlice (slice) {
    slice.copy(buffer, offset)
    offset += slice.length
  }

  function writeUInt32 (i) {
    buffer.writeUInt32LE(i, offset)
    offset += 4
  }

  function writeUInt64 (i) {
    bufferutils.writeUInt64LE(buffer, i, offset)
    offset += 8
  }

  function writeVarInt (i) {
    var n = bufferutils.writeVarInt(buffer, i, offset)
    offset += n
  }

  writeUInt32(this.version)
  writeVarInt(this.ins.length)

  this.ins.forEach(function (txIn) {
    writeSlice(txIn.hash)
    writeUInt32(txIn.index)
    writeVarInt(txIn.script.length)
    writeSlice(txIn.script)
    writeUInt32(txIn.sequence)
  })

  writeVarInt(this.outs.length)
  this.outs.forEach(function (txOut) {
    if (!txOut.valueBuffer) {
      writeUInt64(txOut.value)
    } else {
      writeSlice(txOut.valueBuffer)
    }

    writeVarInt(txOut.script.length)
    writeSlice(txOut.script)
  })

  writeUInt32(this.locktime)

  // avoid slicing unless necessary
  if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)

  return buffer
}

Transaction.prototype.toHex = function () {
  return this.toBuffer().toString('hex')
}

Transaction.prototype.setInputScript = function (index, scriptSig) {
  typeforce(types.tuple(types.Number, types.Buffer), arguments)

  this.ins[index].script = scriptSig
}

module.exports = Transaction
<|endoftext|>


<commit_before>import jQuery from 'expose-loader?jq!expose-loader?jQuery!expose-loader?$!jquery';

import 'bootstrap';
import 'bootstrap/less/bootstrap.less';

import 'jquery-ui';
import 'jquery-ui/ui/widgets/sortable';
import 'jquery-ui/themes/base/all.css'

import 'select2';
import 'select2/dist/css/select2.css';

import 'script-loader!../libs/jquery.clonePosition.js';

import Chart from 'chart.js';
window.Chart = Chart;

import 'gentelella/production/less/custom.css';

import 'font-awesome/css/font-awesome.css';

import Epesi from './epesi';

window.EpesiClass = Epesi;

window.focus_by_id = (idd) => {
    let xx = document.getElementById(idd);
    if (xx) setTimeout(function () {
        jq(xx).focus();
    }, 200);
};

window.addslashes = x => x.replace(/('|"|\\)/g, "\\$1")

window.wait_while_null = (id, action) => {
    if (eval('typeof(' + id + ')') != 'undefined')
        eval(action);
    else
        setTimeout('wait_while_null(\'' + addslashes(id) + '\', \'' + addslashes(action) + '\')', 200);
};

window.getTotalTopOffet = e => {
    let ret = 0;
    while (e != null) {
        ret += e.offsetTop;
        e = e.offsetParent;
    }
    return ret;
};
window.is_visible = function (element) {
    if (!element) return false;
    let display = jQuery(element).css('display');
    if (display == "none") return false;
    if (element.parentNode && element.parentNode.style) {
        xxx = element.parentNode;
        return is_visible(element.parentNode);
    }
    return true;
};<commit_msg>eslint automatic fix<commit_after>import jQuery from 'expose-loader?jq!expose-loader?jQuery!expose-loader?$!jquery';

import 'bootstrap';
import 'bootstrap/less/bootstrap.less';

import 'jquery-ui';
import 'jquery-ui/ui/widgets/sortable';
import 'jquery-ui/themes/base/all.css';

import 'select2';
import 'select2/dist/css/select2.css';

import 'script-loader!../libs/jquery.clonePosition.js';

import Chart from 'chart.js';

window.Chart = Chart;

import 'gentelella/production/less/custom.css';

import 'font-awesome/css/font-awesome.css';

import Epesi from './epesi';

window.EpesiClass = Epesi;

window.focus_by_id = (idd) => {
  const xx = document.getElementById(idd);
  if (xx) {
    setTimeout(() => {
      jq(xx).focus();
    }, 200);
  }
};

window.addslashes = x => x.replace(/('|"|\\)/g, '\\$1');

window.wait_while_null = (id, action) => {
  if (eval(`typeof(${id})`) != 'undefined') { eval(action); } else { setTimeout(`wait_while_null('${addslashes(id)}', '${addslashes(action)}')`, 200); }
};

window.getTotalTopOffet = (e) => {
  let ret = 0;
  while (e != null) {
    ret += e.offsetTop;
    e = e.offsetParent;
  }
  return ret;
};
window.is_visible = function (element) {
  if (!element) return false;
  const display = jQuery(element).css('display');
  if (display == 'none') return false;
  if (element.parentNode && element.parentNode.style) {
    xxx = element.parentNode;
    return is_visible(element.parentNode);
  }
  return true;
};
<|endoftext|>


<commit_before>var canvas = document.getElementById("output")

canvas.width = (window.innerWidth - 20) * 2
canvas.height = 100
canvas.style.width = (window.innerWidth - 20) + "px"
canvas.style.height = "50px"

var ctx = canvas.getContext("2d")

var sort_counts = "" !== getCookie("sort_counts") ? (getCookie("sort_counts") === "true") : true

$("input#sort-counts").prop("checked", sort_counts);

var separate_with_lines = "" !== getCookie("separate_with_lines") ? (getCookie("separate_with_lines") === "true") : true
$("input#separate-cells-w-lines").prop("checked", separate_with_lines);

var hide_extinct_counts = "" !== getCookie("hide_extinct_counts") ? (getCookie("hide_extinct_counts") === "true") : true

$("input#hide-extinct").prop("checked", hide_extinct_counts);

var make_colors_distinct = "" !== getCookie("make_colors_distinct") ? (getCookie("make_colors_distinct") === "true") : true

$("input#make-colors-distinct").prop("checked", make_colors_distinct);

var chart_counts_enabled = "" !== getCookie("chart_counts_enabled") ? (getCookie("chart_counts_enabled") === "true") : true

$("input#chart-counts").prop("checked", !chart_counts_enabled);

ctx.strokeStyle = "#000000"
ctx.lineWidth = 1

var simulator_interval_id

var population_size = -1
var population = []

var generation_number = 0

var number_of_gens_to_simulate = -1

var running = false

var one_left = false

var do_graph = true

$("input#population-size, input#num-of-gens-to-sim, input#speed").on("keydown", function (e) {
	if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
		if (running) {
			stop()
		} else {
			reset_if_needed()

			if (!running) {
				reset()
			}

			run_auto()
		}
	}
});

$("button#run").click(function () {
	reset_if_needed()

	if (!running) {
		reset()
	}

	run_auto()
})

function reset() {
	stop()

	generation_number = 0

	chart.options.data = []

	population = []

	// Fill it with one of every phenotype
	for (var i = 0; i < population_size; i++) {
		population.push(i)

		var ratio = i / population_size

		var hue;
		if (make_colors_distinct) {
			hue = (128 * (ratio + i))
		} else {
			hue = 255 * ratio
		}

		chart.options.data.push({
			type: "line",
			markerType: "none",
			color: "hsl(" + hue + ", 100%, 50%)",
			dataPoints: []
		});
	}

	one_left = false

	render()
}

function reset_if_needed() {
	stop()

	needs_reset = false

	if (one_left) {
		needs_reset = true
	}

	new_pop_size = parseInt($('input#population-size').val() || 100)
	if (population_size != new_pop_size) {
		population_size = new_pop_size

		needs_reset = true
	}

	new_gens_to_sim = Math.max(parseInt($('input#num-of-gens-to-sim').val()), 0) || -1
	if (number_of_gens_to_simulate != new_gens_to_sim) {
		number_of_gens_to_simulate = new_gens_to_sim

		needs_reset = true
	}

	if (needs_reset) {
		reset()
	}
}

function run_auto() {
	running = true

	set_button_pause()

	var speed = parseInt($('input#speed').val()) || 10
	simulator_interval_id = setInterval(simulate_step, speed)

	render()
}

function manual_step() {
	reset_if_needed()

	var num_of_gens_to_sim_this_step = Math.max(parseInt($('input#gens-per-step').val()) || 1, 1)

	for (var i = 0; i < num_of_gens_to_sim_this_step; i++) {
		simulate_step()
	}

	render()
}

$('button#step').click(manual_step)

$("input#gens-per-step").on("keydown", function (e) {
	if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
		manual_step()
	}
});

$('button#reset').click(function () {
	set_button_unpause()
	reset()

	render()
})

$('button#pause').click(pause)

function stop() {
	clearInterval(simulator_interval_id)
	running = false

	set_button_unpause()
}

function pause() {
	stop()

	set_button_unpause()
}

function unpause() {
	set_button_pause()

	reset_if_needed()
	run_auto()

	render()
}

function set_button_pause() {
	$('button#unpause').unbind('click')
	$('button#unpause').click(pause)

	$('button#unpause').html('Pause')
	$('button#unpause').attr('id', 'pause')
}

function set_button_unpause() {
	$('button#pause').unbind('click')
	$('button#pause').click(unpause)

	$('button#pause').html('Run')
	$('button#pause').attr('id', 'unpause')
}

function simulate_step() {
	new_population = []

	phenotype_counts = []

	for (var i = 0; i < population_size; i++) {
		phenotype_counts[i] = {
			'id': i,
			'count': 0
		}
	}

	var all_the_same = true
	var all_the_same_phenotype_so_far = -1
	for (var i = 0; i < population_size; i++) {
		var selected_idx = Math.floor(Math.random() * population_size)
		var selected_phenotype = population[selected_idx]
		new_population.push(selected_phenotype)

		phenotype_counts[selected_phenotype].count += 1

		if (all_the_same_phenotype_so_far == -1) {
			all_the_same_phenotype_so_far = selected_phenotype
		}

		if (all_the_same && all_the_same_phenotype_so_far != selected_phenotype) {
			all_the_same = false
		}
	}

	if (sort_counts) {
		phenotype_counts = phenotype_counts.sort(function (a, b) {
			return b.count - a.count;
		});
	}

	population = new_population

	// sort for an organized visual effect
	population = population.sort(function (a, b) {
		return a - b;
	});

	phenotype_counts_text = ''

	// NOTE: population_size is used to represent the total number of original phentoypes
	for (var i = 0; i < population_size; i++) {
		var phenotype_id_and_count = phenotype_counts[i]

		var id = phenotype_id_and_count.id
		var count = phenotype_id_and_count.count

		chart.options.data[id].dataPoints.push({
			y: count
		})

		if (hide_extinct_counts && count == 0) {
			continue
		}

		var number_str = '#' + id

		phenotype_counts_text += 'Phentotype '
		phenotype_counts_text += ('     ' + number_str).substring(number_str.length);
		phenotype_counts_text += ': '
		phenotype_counts_text += '' + count
		phenotype_counts_text += '\n'
	}

	$('div#phenotype-counts').text(phenotype_counts_text)

	$('div#gen-num').text(generation_number)
	generation_number++

	if (all_the_same) {
		one_left = true
	}

	if (all_the_same || (number_of_gens_to_simulate != -1 && generation_number > number_of_gens_to_simulate)) {
		stop()
	}
}

function render() {
	if (chart_counts_enabled) {
		chart.render();
	}

	var width_per_cell = canvas.width / population_size

	var last_phenotype = population[0]
	var start_idx = 0

	for (var i = 0; i < population_size; i++) {
		var phenotype = population[i]
		var last_was_different = last_phenotype != phenotype

		if (last_was_different) {
			var x = width_per_cell * i

			var ratio = population[start_idx] / population_size

			var hue;
			if (make_colors_distinct) {
				hue = (128 * (ratio + population[start_idx]))
			} else {
				hue = 255 * ratio
			}

			ctx.fillStyle = "hsl(" + hue + ", 100%, 50%)"

			ctx.fillRect(start_idx * width_per_cell, 0, width_per_cell * (i - start_idx) + 2, canvas.height)

			start_idx = i

			last_phenotype = phenotype
		}
	}

	var ratio = population[start_idx] / population_size

	var hue;
	if (make_colors_distinct) {
		hue = (128 * (ratio + population[start_idx]))
	} else {
		hue = 255 * ratio
	}

	ctx.fillStyle = "hsl(" + hue + ", 100%, 50%)"

	ctx.fillRect(start_idx * width_per_cell, 0, width_per_cell * (population_size - start_idx) + 2, canvas.height)

	last_phenotype = population[0]

	for (var i = 0; i < population_size; i++) {
		var phenotype = population[i]

		var x = width_per_cell * i

		var last_was_different = last_phenotype != phenotype

		if (last_was_different) {
			ctx.lineWidth = 3
		}

		if (separate_with_lines || last_was_different) {
			ctx.beginPath();
			ctx.moveTo(x, 0);
			ctx.lineTo(x, canvas.height);
			ctx.stroke();
			ctx.closePath()
		}

		if (last_was_different) {
			ctx.lineWidth = 1
		}

		last_phenotype = phenotype
	}

	if (running) {
		requestAnimationFrame(render)
	}
}

// w3schools
function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
	var expires = "expires=" + d.toUTCString();
	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// w3schools
function getCookie(cname) {
	var name = cname + "=";
	var decodedCookie = decodeURIComponent(document.cookie);
	var ca = decodedCookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}

$('input#sort-counts').change(function () {
	var ischecked = $(this).is(":checked")
	sort_counts = ischecked

	setCookie("sort_counts", ischecked, 999)
});

$('input#separate-cells-w-lines').change(function () {
	var ischecked = $(this).is(":checked")
	separate_with_lines = ischecked

	setCookie("separate_with_lines", ischecked, 999)
});

$('input#hide-extinct').change(function () {
	var ischecked = $(this).is(":checked")
	hide_extinct_counts = ischecked

	setCookie("hide_extinct_counts", ischecked, 999)
});

$('input#make-colors-distinct').change(function () {
	var ischecked = $(this).is(":checked")
	make_colors_distinct = ischecked

	for (var i = 0; i < population_size; i++) {
		var ratio = i / population_size

		var hue;
		if (make_colors_distinct) {
			hue = (128 * (ratio + i))
		} else {
			hue = 255 * ratio
		}

		chart.options.data[i].color = "hsl(" + hue + ", 100%, 50%)"
	}

	chart.render()

	render()

	setCookie("make_colors_distinct", ischecked, 999)
});

$('input#chart-counts').change(function () {
	var ischecked = $(this).is(":checked")
	chart_counts_enabled = !ischecked

	$('#chartCanvas').toggle(chart_counts_enabled)

	try {
		chart.render()
	} catch (e) {

	}

	setCookie("chart_counts_enabled", !ischecked, 999)
});;
<commit_msg>fix another cookie bug (it was a problem with setting chart visibility)<commit_after>var canvas = document.getElementById("output")

canvas.width = (window.innerWidth - 20) * 2
canvas.height = 100
canvas.style.width = (window.innerWidth - 20) + "px"
canvas.style.height = "50px"

var ctx = canvas.getContext("2d")

var sort_counts = "" !== getCookie("sort_counts") ? (getCookie("sort_counts") === "true") : true

$("input#sort-counts").prop("checked", sort_counts);

var separate_with_lines = "" !== getCookie("separate_with_lines") ? (getCookie("separate_with_lines") === "true") : true
$("input#separate-cells-w-lines").prop("checked", separate_with_lines);

var hide_extinct_counts = "" !== getCookie("hide_extinct_counts") ? (getCookie("hide_extinct_counts") === "true") : true

$("input#hide-extinct").prop("checked", hide_extinct_counts);

var make_colors_distinct = "" !== getCookie("make_colors_distinct") ? (getCookie("make_colors_distinct") === "true") : true

$("input#make-colors-distinct").prop("checked", make_colors_distinct);

var chart_counts_enabled = "" !== getCookie("chart_counts_enabled") ? (getCookie("chart_counts_enabled") === "true") : true

$("input#chart-counts").prop("checked", !chart_counts_enabled);

$('#chartCanvas').toggle(chart_counts_enabled)

ctx.strokeStyle = "#000000"
ctx.lineWidth = 1

var simulator_interval_id

var population_size = -1
var population = []

var generation_number = 0

var number_of_gens_to_simulate = -1

var running = false

var one_left = false

var do_graph = true

$("input#population-size, input#num-of-gens-to-sim, input#speed").on("keydown", function (e) {
	if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
		if (running) {
			stop()
		} else {
			reset_if_needed()

			if (!running) {
				reset()
			}

			run_auto()
		}
	}
});

$("button#run").click(function () {
	reset_if_needed()

	if (!running) {
		reset()
	}

	run_auto()
})

function reset() {
	stop()

	generation_number = 0

	chart.options.data = []

	population = []

	// Fill it with one of every phenotype
	for (var i = 0; i < population_size; i++) {
		population.push(i)

		var ratio = i / population_size

		var hue;
		if (make_colors_distinct) {
			hue = (128 * (ratio + i))
		} else {
			hue = 255 * ratio
		}

		chart.options.data.push({
			type: "line",
			markerType: "none",
			color: "hsl(" + hue + ", 100%, 50%)",
			dataPoints: []
		});
	}

	one_left = false

	render()
}

function reset_if_needed() {
	stop()

	needs_reset = false

	if (one_left) {
		needs_reset = true
	}

	new_pop_size = parseInt($('input#population-size').val() || 100)
	if (population_size != new_pop_size) {
		population_size = new_pop_size

		needs_reset = true
	}

	new_gens_to_sim = Math.max(parseInt($('input#num-of-gens-to-sim').val()), 0) || -1
	if (number_of_gens_to_simulate != new_gens_to_sim) {
		number_of_gens_to_simulate = new_gens_to_sim

		needs_reset = true
	}

	if (needs_reset) {
		reset()
	}
}

function run_auto() {
	running = true

	set_button_pause()

	var speed = parseInt($('input#speed').val()) || 10
	simulator_interval_id = setInterval(simulate_step, speed)

	render()
}

function manual_step() {
	reset_if_needed()

	var num_of_gens_to_sim_this_step = Math.max(parseInt($('input#gens-per-step').val()) || 1, 1)

	for (var i = 0; i < num_of_gens_to_sim_this_step; i++) {
		simulate_step()
	}

	render()
}

$('button#step').click(manual_step)

$("input#gens-per-step").on("keydown", function (e) {
	if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
		manual_step()
	}
});

$('button#reset').click(function () {
	set_button_unpause()
	reset()

	render()
})

$('button#pause').click(pause)

function stop() {
	clearInterval(simulator_interval_id)
	running = false

	set_button_unpause()
}

function pause() {
	stop()

	set_button_unpause()
}

function unpause() {
	set_button_pause()

	reset_if_needed()
	run_auto()

	render()
}

function set_button_pause() {
	$('button#unpause').unbind('click')
	$('button#unpause').click(pause)

	$('button#unpause').html('Pause')
	$('button#unpause').attr('id', 'pause')
}

function set_button_unpause() {
	$('button#pause').unbind('click')
	$('button#pause').click(unpause)

	$('button#pause').html('Run')
	$('button#pause').attr('id', 'unpause')
}

function simulate_step() {
	new_population = []

	phenotype_counts = []

	for (var i = 0; i < population_size; i++) {
		phenotype_counts[i] = {
			'id': i,
			'count': 0
		}
	}

	var all_the_same = true
	var all_the_same_phenotype_so_far = -1
	for (var i = 0; i < population_size; i++) {
		var selected_idx = Math.floor(Math.random() * population_size)
		var selected_phenotype = population[selected_idx]
		new_population.push(selected_phenotype)

		phenotype_counts[selected_phenotype].count += 1

		if (all_the_same_phenotype_so_far == -1) {
			all_the_same_phenotype_so_far = selected_phenotype
		}

		if (all_the_same && all_the_same_phenotype_so_far != selected_phenotype) {
			all_the_same = false
		}
	}

	if (sort_counts) {
		phenotype_counts = phenotype_counts.sort(function (a, b) {
			return b.count - a.count;
		});
	}

	population = new_population

	// sort for an organized visual effect
	population = population.sort(function (a, b) {
		return a - b;
	});

	phenotype_counts_text = ''

	// NOTE: population_size is used to represent the total number of original phentoypes
	for (var i = 0; i < population_size; i++) {
		var phenotype_id_and_count = phenotype_counts[i]

		var id = phenotype_id_and_count.id
		var count = phenotype_id_and_count.count

		chart.options.data[id].dataPoints.push({
			y: count
		})

		if (hide_extinct_counts && count == 0) {
			continue
		}

		var number_str = '#' + id

		phenotype_counts_text += 'Phentotype '
		phenotype_counts_text += ('     ' + number_str).substring(number_str.length);
		phenotype_counts_text += ': '
		phenotype_counts_text += '' + count
		phenotype_counts_text += '\n'
	}

	$('div#phenotype-counts').text(phenotype_counts_text)

	$('div#gen-num').text(generation_number)
	generation_number++

	if (all_the_same) {
		one_left = true
	}

	if (all_the_same || (number_of_gens_to_simulate != -1 && generation_number > number_of_gens_to_simulate)) {
		stop()
	}
}

function render() {
	if (chart_counts_enabled) {
		chart.render();
	}

	var width_per_cell = canvas.width / population_size

	var last_phenotype = population[0]
	var start_idx = 0

	for (var i = 0; i < population_size; i++) {
		var phenotype = population[i]
		var last_was_different = last_phenotype != phenotype

		if (last_was_different) {
			var x = width_per_cell * i

			var ratio = population[start_idx] / population_size

			var hue;
			if (make_colors_distinct) {
				hue = (128 * (ratio + population[start_idx]))
			} else {
				hue = 255 * ratio
			}

			ctx.fillStyle = "hsl(" + hue + ", 100%, 50%)"

			ctx.fillRect(start_idx * width_per_cell, 0, width_per_cell * (i - start_idx) + 2, canvas.height)

			start_idx = i

			last_phenotype = phenotype
		}
	}

	var ratio = population[start_idx] / population_size

	var hue;
	if (make_colors_distinct) {
		hue = (128 * (ratio + population[start_idx]))
	} else {
		hue = 255 * ratio
	}

	ctx.fillStyle = "hsl(" + hue + ", 100%, 50%)"

	ctx.fillRect(start_idx * width_per_cell, 0, width_per_cell * (population_size - start_idx) + 2, canvas.height)

	last_phenotype = population[0]

	for (var i = 0; i < population_size; i++) {
		var phenotype = population[i]

		var x = width_per_cell * i

		var last_was_different = last_phenotype != phenotype

		if (last_was_different) {
			ctx.lineWidth = 3
		}

		if (separate_with_lines || last_was_different) {
			ctx.beginPath();
			ctx.moveTo(x, 0);
			ctx.lineTo(x, canvas.height);
			ctx.stroke();
			ctx.closePath()
		}

		if (last_was_different) {
			ctx.lineWidth = 1
		}

		last_phenotype = phenotype
	}

	if (running) {
		requestAnimationFrame(render)
	}
}

// w3schools
function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
	var expires = "expires=" + d.toUTCString();
	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// w3schools
function getCookie(cname) {
	var name = cname + "=";
	var decodedCookie = decodeURIComponent(document.cookie);
	var ca = decodedCookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}

$('input#sort-counts').change(function () {
	var ischecked = $(this).is(":checked")
	sort_counts = ischecked

	setCookie("sort_counts", ischecked, 999)
});

$('input#separate-cells-w-lines').change(function () {
	var ischecked = $(this).is(":checked")
	separate_with_lines = ischecked

	setCookie("separate_with_lines", ischecked, 999)
});

$('input#hide-extinct').change(function () {
	var ischecked = $(this).is(":checked")
	hide_extinct_counts = ischecked

	setCookie("hide_extinct_counts", ischecked, 999)
});

$('input#make-colors-distinct').change(function () {
	var ischecked = $(this).is(":checked")
	make_colors_distinct = ischecked

	for (var i = 0; i < population_size; i++) {
		var ratio = i / population_size

		var hue;
		if (make_colors_distinct) {
			hue = (128 * (ratio + i))
		} else {
			hue = 255 * ratio
		}

		chart.options.data[i].color = "hsl(" + hue + ", 100%, 50%)"
	}

	chart.render()

	render()

	setCookie("make_colors_distinct", ischecked, 999)
});

$('input#chart-counts').change(function () {
	var ischecked = $(this).is(":checked")
	chart_counts_enabled = !ischecked

	$('#chartCanvas').toggle(chart_counts_enabled)

	try {
		chart.render()
	} catch (e) {

	}

	setCookie("chart_counts_enabled", !ischecked, 999)
});;
<|endoftext|>


<commit_before>import mapValues from 'lodash.mapValues';
import isPlainObject from 'lodash.isPlainObject';
import { Iterable } from 'immutable';

export function isImmutable(obj) {
  return Iterable.isIterable(obj);
}

export function toJS(obj) {
  return obj.toJS();
}

export function toJSDeep(obj) {
  /* eslint no-use-before-define: 0 */
  return mapValues(obj, value => convert(value));
}

export function convert(obj) {
  if (isImmutable(obj)) {
    return toJS(obj);
  } else if (isPlainObject(obj)) {
    return toJSDeep(obj);
  }
  return obj;
}

export default function immutableToJS() {
  return createStore => (reducer, initialState) => {
    const store = createStore(reducer, initialState);
    return {
      ...store,
      getState: () => {
        const state = store.getState();
        return convert(state);
      },
    };
  };
}
<commit_msg>Remove an unnecessary arrow function<commit_after>import mapValues from 'lodash.mapValues';
import isPlainObject from 'lodash.isPlainObject';
import { Iterable } from 'immutable';

export function isImmutable(obj) {
  return Iterable.isIterable(obj);
}

export function toJS(obj) {
  return obj.toJS();
}

export function toJSDeep(obj) {
  /* eslint no-use-before-define: 0 */
  return mapValues(obj, convert);
}

export function convert(obj) {
  if (isImmutable(obj)) {
    return toJS(obj);
  } else if (isPlainObject(obj)) {
    return toJSDeep(obj);
  }
  return obj;
}

export default function immutableToJS() {
  return createStore => (reducer, initialState) => {
    const store = createStore(reducer, initialState);
    return {
      ...store,
      getState: () => {
        const state = store.getState();
        return convert(state);
      },
    };
  };
}
<|endoftext|>


<commit_before>$(function() {

    var lines = [ "KEEP", "CALM", "AND", "CARRY", "ON" ];
    var maxLineLength = 0;
    var nbLines = lines.length;
    var marginPct = 5;
    var marginWidth = 0;
    var marginHeight = 0;
    var pageWidth = $(window).width();
    var pageHeight = $(window).height();

    var params = [ "bg", "fg", "typeface", "graphic" ];

    // var WebFontConfig = {
    //     google: { families: [ 'Raleway:600:latin' ] }
    // };

    WebFont.load({
        google: { families: [ 'Raleway:700:latin' ] }
    });

    for (var j = 0; j < lines.length; j++) {
        var param = $.url().param((j + 1).toString());

        if (param) {
            lines[j] = param.toUpperCase();
        }

        $(".kc")
            .eq(j)
            .html(lines[j]);

        // Whitespace is counted as a letter
        maxLineLength = Math.max(lines[j].length, maxLineLength);
    }

    //var style = window.getComputedStyle($(".kc").eq(0)[0], null).getPropertyValue('font-size');
    //var fontSize = parseFloat(style);

    var marginWidth = pageWidth * marginPct / 100;
    var marginHeight = pageHeight * marginPct / 100;

    var usableWidth = pageWidth - marginWidth * 2; // not needed: - (maxLineLength - 1) * interLetter;
    var usableHeight = pageHeight - marginHeight * 2; // not neede: - (nbLines - 1) * interLine;

    // Decide how tall the crown will be and resize, then include in font size calculation
    var crownPct = 20;
    var crownHeight = usableHeight * 20 / 100;
    $("#crown").attr("height", crownHeight);

    var textUsableHeight = usableHeight - crownHeight;

    var targetFontSize = Math.min(usableWidth / maxLineLength,
                                  textUsableHeight / nbLines);

    // fixme - need to redo this on page resize
    $("#keep-calm").css("margin-top", marginHeight);
    $(".kc").css({"font-size": targetFontSize,
                  "margin-top": 0,
                  "margin-bottom": 0
                 });
    $(".kc").css("line-height", "1em");

    console.log(screen.width);
    console.log(screen.height);
    console.log($(window).width());
    console.log($(window).height());
    //console.log(fontSize);
    console.log(targetFontSize);
    console.log(maxLineLength);
    console.log(marginWidth);
    console.log(marginHeight);
    console.log(usableWidth);
    console.log(usableHeight);
    console.log(maxLineLength);

});

// WebFontConfig = {
//     google: { families: [ 'Raleway:400,800:latin' ] }
// };

// (function() {
//     var wf = document.createElement('script');
//     wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
//         '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
//     wf.type = 'text/javascript';
//     wf.async = 'true';
//     var s = document.getElementsByTagName('script')[0];
//     s.parentNode.insertBefore(wf, s);
// })();
<commit_msg>todos<commit_after>// todo - suggest full screen display
// todo - form mode
// todo - colour
// todo - alternate graphic

$(function() {

    var lines = [ "KEEP", "CALM", "AND", "CARRY", "ON" ];
    var maxLineLength = 0;
    var nbLines = lines.length;
    var marginPct = 5;
    var marginWidth = 0;
    var marginHeight = 0;
    var pageWidth = $(window).width();
    var pageHeight = $(window).height();

    var params = [ "bg", "fg", "typeface", "graphic" ];

    // var WebFontConfig = {
    //     google: { families: [ 'Raleway:600:latin' ] }
    // };

    WebFont.load({
        google: { families: [ 'Raleway:700:latin' ] }
    });

    for (var j = 0; j < lines.length; j++) {
        var param = $.url().param((j + 1).toString());

        if (param) {
            lines[j] = param.toUpperCase();
        }

        $(".kc")
            .eq(j)
            .html(lines[j]);

        // Whitespace is counted as a letter
        maxLineLength = Math.max(lines[j].length, maxLineLength);
    }

    //var style = window.getComputedStyle($(".kc").eq(0)[0], null).getPropertyValue('font-size');
    //var fontSize = parseFloat(style);

    var marginWidth = pageWidth * marginPct / 100;
    var marginHeight = pageHeight * marginPct / 100;

    var usableWidth = pageWidth - marginWidth * 2; // not needed: - (maxLineLength - 1) * interLetter;
    var usableHeight = pageHeight - marginHeight * 2; // not neede: - (nbLines - 1) * interLine;

    // Decide how tall the crown will be and resize, then include in font size calculation
    var crownPct = 20;
    var crownHeight = usableHeight * 20 / 100;
    $("#crown").attr("height", crownHeight);

    var textUsableHeight = usableHeight - crownHeight;

    var targetFontSize = Math.min(usableWidth / maxLineLength,
                                  textUsableHeight / nbLines);

    // fixme - need to redo this on page resize
    $("#keep-calm").css("margin-top", marginHeight);
    $(".kc").css({"font-size": targetFontSize,
                  "margin-top": 0,
                  "margin-bottom": 0
                 });
    $(".kc").css("line-height", "1em");

    console.log(screen.width);
    console.log(screen.height);
    console.log($(window).width());
    console.log($(window).height());
    //console.log(fontSize);
    console.log(targetFontSize);
    console.log(maxLineLength);
    console.log(marginWidth);
    console.log(marginHeight);
    console.log(usableWidth);
    console.log(usableHeight);
    console.log(maxLineLength);

});

// WebFontConfig = {
//     google: { families: [ 'Raleway:400,800:latin' ] }
// };

// (function() {
//     var wf = document.createElement('script');
//     wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
//         '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
//     wf.type = 'text/javascript';
//     wf.async = 'true';
//     var s = document.getElementsByTagName('script')[0];
//     s.parentNode.insertBefore(wf, s);
// })();
<|endoftext|>


<commit_before>module.exports = function(Bookshelf) {
  'use strict';
  var _ = require('lodash'),
      Promise = require('bluebird'),
      proto = Bookshelf.Model.prototype;

  var Model = Bookshelf.Model.extend({
    upsertMetadata: {
      conflictors: ['id'],
      returning: ['id'],
    },

    upsert: Promise.method(function(transaction) {
      const conflictors = this.upsertMetadata.conflictors,
            returning = this.upsertMetadata.returning,
            model = this;

      if (!conflictors) {
        throw new Error('Cannot upsert without uniqueness constraints');
      }

      function buildConflictors(fields, conflictors) {
        return conflictors.map(function(conflictor) {
          const alternates = _.select(fields, function(field) {
            return field !== conflictor;
          });

          const updateStatements = alternates.map(function(field) {
            return `${field}=EXCLUDED.${field}`;
          }).join(', ');

          const fragment = `DO UPDATE SET ${updateStatements}`;

          return (alternates.length) ?
            `ON CONFLICT (${conflictor}) ${fragment}` :
            'ON CONFLICT DO NOTHING RETURNING id';
        }).join(', ');
      }

      const payload = this.attributes;
      const fields = Object.keys(payload);

      const returnStatement = returning.length ? `RETURNING (${returning.join(', ')})` : '';
      const upsertStatement = `
        INSERT INTO ${this.tableName} (${fields.join(', ')})
        VALUES (${_.times(fields.length, function() { return '?'; }).join(', ')})
        ${buildConflictors(fields, conflictors)}
        ${returnStatement}`;

      return transaction
        .raw(upsertStatement, fields.map(function(field) { return payload[field]; }))
        .then(function(response) {
          model.set(response.rows[0]);
          return model;
        });
    }),
  });
  Bookshelf.Model = Model;
}
<commit_msg>[upsert] why they removed select is beyond me<commit_after>module.exports = function(Bookshelf) {
  'use strict';
  var _ = require('lodash'),
      Promise = require('bluebird'),
      proto = Bookshelf.Model.prototype;

  var Model = Bookshelf.Model.extend({
    upsertMetadata: {
      conflictors: ['id'],
      returning: ['id'],
    },

    upsert: Promise.method(function(transaction) {
      const conflictors = this.upsertMetadata.conflictors,
            returning = this.upsertMetadata.returning,
            model = this;

      if (!conflictors) {
        throw new Error('Cannot upsert without uniqueness constraints');
      }

      function buildConflictors(fields, conflictors) {
        return conflictors.map(function(conflictor) {
          const alternates = _.reject(fields, function(field) {
            return field === conflictor;
          });

          const updateStatements = alternates.map(function(field) {
            return `${field}=EXCLUDED.${field}`;
          }).join(', ');

          const fragment = `DO UPDATE SET ${updateStatements}`;

          return (alternates.length) ?
            `ON CONFLICT (${conflictor}) ${fragment}` :
            'ON CONFLICT DO NOTHING RETURNING id';
        }).join(', ');
      }

      const payload = this.attributes;
      const fields = Object.keys(payload);

      const returnStatement = returning.length ? `RETURNING (${returning.join(', ')})` : '';
      const upsertStatement = `
        INSERT INTO ${this.tableName} (${fields.join(', ')})
        VALUES (${_.times(fields.length, function() { return '?'; }).join(', ')})
        ${buildConflictors(fields, conflictors)}
        ${returnStatement}`;

      return transaction
        .raw(upsertStatement, fields.map(function(field) { return payload[field]; }))
        .then(function(response) {
          model.set(response.rows[0]);
          return model;
        });
    }),
  });
  Bookshelf.Model = Model;
}
<|endoftext|>