code
stringlengths
2
1.05M
/** * Created by RSC on 05.04.2016. */ myApp.factory('HomeWatchFactory', function ($http, $q, $rootScope, $log) { return { getFhemJsonList: function (name, type) { var url = ''; if ($rootScope.config.connection.isDebug) { url = 'json/homewatch/data/' + name + '.json'; } else { url = $rootScope.MetaDatafhemweb_url + $rootScope.config.globals.cmd + type + '=' + name + $rootScope.config.globals.param; } $log.debug('HomeWatchFactory: ' + url); var deferred = $q.defer(); $http({method: "GET", url: url}) .success(function (data, status, headers, config) { deferred.resolve(data); }).error(function (data, status, headers, config) { deferred.reject(status); }); return deferred.promise; }, getJson: function (name) { var url = 'json/homewatch/' + name + '.json'; var deferred = $q.defer(); $http({method: "GET", url: url}) .success(function (data, status, headers, config) { deferred.resolve(data); }).error(function (data, status, headers, config) { deferred.reject(status); }); return deferred.promise; }, getLocationWidgets: function (location) { // no values if (angular.isUndefined(location) || location == '') { $log.debug('HomeWatchFactory.getLocationWidgets: location isUndefined'); return; } var widget = $rootScope.config.home; if (widget.length == 0) return; var deferred = $q.defer(); var len = widget.length; for (var i = 0; i < len; i++) { if (widget[i].location == location) { data = widget[i]; deferred.resolve(data); break; } } return deferred.promise; } }; });
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bowercopy: { options: { clean: false }, glob: { files: { 'static/libs/js': [ 'sprintf/dist/*.js', 'mocha/*.js', 'assert/*.js' ], 'static/libs/css': [ 'mocha/*.css' ], 'static/libs/fonts': [ ] } } } }) grunt.loadNpmTasks('grunt-bowercopy'); // Default tasks grunt.registerTask('default', ['bowercopy']); }
import _ from 'lodash' import Vue from 'vue' import test from 'ava' import FlexTableColumn from '../../src/components/FlexTableColumn.vue' Vue.config.productionTip = false test('has a mounted hook', (t) => { t.true(_.isFunction(FlexTableColumn.mounted)) }) test('has data as function', (t) => { t.true(_.isFunction(FlexTableColumn.data)) })
export const plus = (f, l) => { let next = {}; if (typeof l === 'number') { next.low = l; next.high = 0; } else if (typeof l === 'object') { if (l.high && l.low && l.unsigned) { next = l; } else { throw new Error('Not a uint64 data'); } } return { high: f.high + next.high, low: f.low + next.low, unsigned: true }; }; export const generateKeyString = (uint64Object) => { if (typeof uint64Object === 'number') { return uint64Object.toString(); } if (typeof uint64Object === 'object' && typeof uint64Object.high === 'number') { return `${uint64Object.high}${uint64Object.low}`; } return Symbol(uint64Object).toString(); };
'use strict'; var maxBot = 11; var mode; var mw = {}; var mwId; function getMwId() { mwId = $.url().segment(4); } function isNewMicroworld() { return ($.url().segment(3) === 'new'); } function showStatusTableOptions() { var behaviour_name = $(this).attr('id'); var behaviour_type = $(this).text(); $(this).closest('.dropdown').find('span#btn_txt').text(behaviour_type+" ") $("."+behaviour_name).removeClass('hide'); if(behaviour_name == "static_option"){ $(".dynamic_option").addClass('hide'); } else { $(".static_option").addClass('hide'); } } function readyTooltips() { $('#early-end-tooltip').tooltip(); $('#max-fish-tooltip').tooltip(); $('#available-mystery-tooltip').tooltip(); $('#reported-mystery-tooltip').tooltip(); $('#spawn-factor-tooltip').tooltip(); $('#chance-catch-tooltip').tooltip(); $('#show-fisher-status-tooltip').tooltip(); $('#erratic-tooltip').tooltip(); $('#greed-tooltip').tooltip(); $('#greed-spread-tooltip').tooltip(); $('#trend-tooltip').tooltip(); $('#predictability-tooltip').tooltip(); $('#prob-action-tooltip').tooltip(); $('#attempts-second-tooltip').tooltip(); } function changeBotRowVisibility() { var numFishers = parseInt($('#num-fishers').val(), 10); var numHumans = parseInt($('#num-humans').val(), 10); if (numFishers < 1) numFishers = 1; if (numFishers > maxBot + numHumans) { numFishers = maxBot + numHumans; } if (numHumans > numFishers) numHumans = numFishers; for (var i = 1; i <= numFishers - numHumans; i++) { $('#bot-' + i + '-row').removeClass('collapse'); } for (var i = numFishers - numHumans + 1; i <= maxBot; i++) { $('#bot-' + i + '-row').addClass('collapse'); } } function changeGreedUniformity() { if ($('#uniform-greed').prop('checked') === true) { var greed = $('#bot-1-greed').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed').val(greed).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed').attr('disabled', false); } } } function changeGreedSpreadUniformity() { if ($('#uniform-greed-spread').prop('checked') === true) { var greedSpread = $('#bot-1-greed-spread').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed-spread').val(greedSpread).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greedSpread').attr('disabled', false); } } } function changeTrendUniformity() { if ($('#uniform-trend').prop('checked') === true) { var trend = $('#bot-1-trend').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-trend').val(trend).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-trend').attr('disabled', false); } } } function changePredictabilityUniformity() { if ($('#uniform-predictability').prop('checked') === true) { var predictability = $('#bot-1-predictability').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-predictability').val(predictability).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-predictability').attr('disabled', false); } } } function changeProbActionUniformity() { if ($('#uniform-prob-action').prop('checked') === true) { var probAction = $('#bot-1-prob-action').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-prob-action').val(probAction).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-prob-action').attr('disabled', false); } } } function changeAttemptsSecondUniformity() { if ($('#uniform-attempts-second').prop('checked') === true) { var attemptsSecond = $('#bot-1-attempts-second').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-attempts-second').val(attemptsSecond).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-attempts-second').attr('disabled', false); } } } function validate() { var errors = []; if ($('#name').val().length < 1) { errors.push('The microworld name is missing.'); } var numFishers = parseInt($('#num-fishers').val(), 10); if (numFishers < 1) { errors.push('There must be at least one fisher per simulation'); } if (numFishers > 12) { errors.push('The maximum number of fishers per simulation is twelve.'); } var numHumans = parseInt($('#num-humans').val(), 10); if (numHumans < 0) { errors.push('There must be zero or more humans per simulation.'); } if (numHumans > numFishers) { errors.push('There cannot be more human fishers than total fishers.'); } if (parseInt($('#num-seasons').val(), 10) < 1) { errors.push('There must be at least one season per simulation.'); } if (parseInt($('#season-duration').val(), 10) < 1) { errors.push('Seasons must have a duration of at least one second.'); } if (parseInt($('#initial-delay').val(), 10) < 1) { errors.push('The initial delay must be at least one second long.'); } if (parseInt($('#season-delay').val(), 10) < 1) { errors.push('The delay between seasons must be at least one second.'); } if (parseFloat($('#fish-value').val()) < 0) { errors.push('The value per fish cannot be negative'); } if (parseFloat($('#cost-cast').val()) < 0) { errors.push('The cost to attempt to fish cannot be negative.'); } if (parseFloat($('#cost-departure').val()) < 0) { errors.push('The cost to set sail cannot be negative.'); } if (parseFloat($('#cost-second').val()) < 0) { errors.push('The cost per second at sea cannot be negative.'); } var certainFish = parseInt($('#certain-fish').val(), 10); if (certainFish < 1) { errors.push('There must be at least one initial fish.'); } var availMysteryFish = parseInt($('#available-mystery-fish').val(), 10); if (availMysteryFish < 0) { errors.push('The number of available mystery fish cannot be negative'); } var repMysteryFish = parseInt($('#reported-mystery-fish').val(), 10); if (repMysteryFish < availMysteryFish) { errors.push('The number of reported mystery fish must be equal or ' + 'greater than the number of actually available mystery fish.'); } var maxFish = parseInt($('#max-fish').val(), 10); if (maxFish < certainFish + availMysteryFish) { errors.push('The maximum fish capacity must be equal or greater ' + 'than the sum of certain and available mystery fish.'); } if (parseFloat($('#spawn-factor').val()) < 0) { errors.push('The spawn factor cannot be negative.'); } var chanceCatch = parseFloat($('#chance-catch').val()); if (chanceCatch < 0 || chanceCatch > 1) { errors.push('The chance of catch must be a number between 0 and 1.'); } if ($('#preparation-text').val().length < 1) { errors.push('The preparation text is missing.'); } if ($('#end-time-text').val().length < 1) { errors.push('The text for ending on time is missing.'); } if ($('#end-depletion-text').val().length < 1) { errors.push('The text for ending on depletion is missing.'); } for (var i = 1; i <= (numFishers - numHumans); i++) { if ($('#bot-' + i + '-name').val().length < 1) { errors.push('Bot ' + i + ' needs a name.'); } var botGreed = parseFloat($('#bot-' + i + '-greed').val()); if (botGreed < 0 || botGreed > 1) { errors.push('The greed of bot ' + i + ' must be between 0 and 1.'); } var botGreedSpread = parseFloat($('#bot-' + i + '-greed-spread').val()); if (botGreedSpread < 0) { errors.push('The greed spread of bot ' + i + ' must be greater than 0.'); } if (botGreedSpread > 2 * botGreed) { errors.push('The greed spread of bot ' + i + ' must be less than twice its greed.'); } var botProbAction = parseFloat($('#bot-' + i + '-prob-action').val()); if (botProbAction < 0 || botProbAction > 1) { errors.push('The probability of action of bot ' + i + ' must be between 0 and 1.'); } var botAttempts = parseFloat($('#bot-' + i + '-attempts-second').val()); if (botAttempts < 1) { errors.push('The attempts per second of bot ' + i + ' must be between at least 1.'); } } if (errors.length === 0) return null; return errors; } function prepareMicroworldObject() { var mw = {}; mw.name = $('#name').val(); mw.desc = $('#desc').val(); mw.numFishers = $('#num-fishers').val(); mw.numHumans = $('#num-humans').val(); mw.numSeasons = $('#num-seasons').val(); mw.seasonDuration = $('#season-duration').val(); mw.initialDelay = $('#initial-delay').val(); mw.seasonDelay = $('#season-delay').val(); mw.enablePause = $('#enable-pause').prop('checked'); mw.enableEarlyEnd = $('#enable-early-end').prop('checked'); mw.enableTutorial = $('#enable-tutorial').prop('checked'); mw.enableRespawnWarning = $('#change-ocean-colour').prop('checked'); mw.fishValue = $('#fish-value').val(); mw.costCast = $('#cost-cast').val(); mw.costDeparture = $('#cost-departure').val(); mw.costSecond = $('#cost-second').val(); mw.currencySymbol = $('#currency-symbol').val(); mw.certainFish = $('#certain-fish').val(); mw.availableMysteryFish = $('#available-mystery-fish').val(); mw.reportedMysteryFish = $('#reported-mystery-fish').val(); mw.maxFish = $('#max-fish').val(); mw.spawnFactor = $('#spawn-factor').val(); mw.chanceCatch = $('#chance-catch').val(); mw.showFishers = $('#show-fishers').prop('checked'); mw.showFisherNames = $('#show-fisher-names').prop('checked'); mw.showFisherStatus = $('#show-fisher-status').prop('checked'); mw.showNumCaught = $('#show-num-caught').prop('checked'); mw.showFisherBalance = $('#show-fisher-balance').prop('checked'); mw.preparationText = $('#preparation-text').val(); mw.endTimeText = $('#end-time-text').val(); mw.endDepletionText = $('#end-depletion-text').val(); mw.bots = []; for (var i = 1; i <= mw.numFishers - mw.numHumans; i++) { var botPrefix = '#bot-' + i + '-'; mw.bots.push({ name: $(botPrefix + 'name').val(), greed: $(botPrefix + 'greed').val(), greedSpread: $(botPrefix + 'greed-spread').val(), trend: $(botPrefix + 'trend').val(), predictability: $(botPrefix + 'predictability').val(), probAction: $(botPrefix + 'prob-action').val(), attemptsSecond: $(botPrefix + 'attempts-second').val() }); } mw.oceanOrder = $("input[name=ocean_order]:checked").val(); return mw; } function reportErrors(err) { var errMessage = 'The form has the following errors:\n\n'; for (var i in err) { errMessage += err[i] + '\n'; } alert(errMessage); return; } function badMicroworld(jqXHR) { reportErrors(JSON.parse(jqXHR.responseText).errors); return; } function goodMicroworld() { location.href = '../dashboard'; } function createMicroworld() { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); $.ajax({ type: 'POST', url: '/microworlds', data: mw, error: badMicroworld, success: goodMicroworld }); } function cloneMicroworld() { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); mw.clone = true; $.ajax({ type: 'POST', url: '/microworlds', data: mw, error: badMicroworld, success: goodMicroworld }); } function updateMicroworld(changeTo) { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); if (changeTo) mw.changeTo = changeTo; $.ajax({ type: 'PUT', url: '/microworlds/' + mwId, data: mw, error: badMicroworld, success: goodMicroworld }); } function saveMicroworld() { updateMicroworld(); } function activateMicroworld() { updateMicroworld('active'); } function archiveMicroworld() { updateMicroworld('archived'); } function deleteMicroworld() { $.ajax({ type: 'DELETE', url: '/microworlds/' + mwId, error: badMicroworld, success: goodMicroworld }); } function populatePage() { $('#name').val(mw.name); $('#desc').val(mw.desc); $('#num-fishers').val(mw.params.numFishers); $('#num-humans').val(mw.params.numHumans); $('#num-seasons').val(mw.params.numSeasons); $('#season-duration').val(mw.params.seasonDuration); $('#initial-delay').val(mw.params.initialDelay); $('#season-delay').val(mw.params.seasonDelay); $('#enable-pause').prop('checked', mw.params.enablePause); $('#enable-early-end').prop('checked', mw.params.enableEarlyEnd); $('#enable-tutorial').prop('checked', mw.params.enableTutorial); $('#change-ocean-colour').prop('checked', mw.params.enableRespawnWarning); $('#fish-value').val(mw.params.fishValue); $('#cost-cast').val(mw.params.costCast); $('#cost-departure').val(mw.params.costDeparture); $('#cost-second').val(mw.params.costSecond); $('#currency-symbol').val(mw.params.currencySymbol); $('#certain-fish').val(mw.params.certainFish); $('#available-mystery-fish').val(mw.params.availableMysteryFish); $('#reported-mystery-fish').val(mw.params.reportedMysteryFish); $('#max-fish').val(mw.params.maxFish); $('#spawn-factor').val(mw.params.spawnFactor); $('#chance-catch').val(mw.params.chanceCatch); $('#preparation-text').val(mw.params.preparationText); $('#end-time-text').val(mw.params.endTimeText); $('#end-depletion-text').val(mw.params.endDepletionText); $('#show-fishers').prop('checked', mw.params.showFishers); $('#show-fisher-names').prop('checked', mw.params.showFisherNames); $('#show-fisher-status').prop('checked', mw.params.showFisherStatus); $('#show-num-caught').prop('checked', mw.params.showNumCaught); $('#show-fisher-balance').prop('checked', mw.params.showFisherBalance); $('#uniform-greed').prop('checked', false); $('#uniform-greed-spread').prop('checked', false); $('#uniform-trend').prop('checked', false); $('#uniform-predictability').prop('checked', false); $('#uniform-prob-action').prop('checked', false); $('#uniform-attempts-second').prop('checked', false); for (var i = 1; i <= mw.params.numFishers - mw.params.numHumans; i++) { var botPrefix = '#bot-' + i + '-'; $(botPrefix + 'name').val(mw.params.bots[i - 1].name); $(botPrefix + 'greed').val(mw.params.bots[i - 1].greed); $(botPrefix + 'greed-spread').val(mw.params.bots[i - 1].greedSpread); $(botPrefix + 'trend').val(mw.params.bots[i - 1].trend); $(botPrefix + 'predictability').val(mw.params.bots[i - 1].predictability); $(botPrefix + 'prob-action').val(mw.params.bots[i - 1].probAction); $(botPrefix + 'attempts-second').val(mw.params.bots[i - 1].attemptsSecond); } $("#"+mw.params.oceanOrder).prop('checked', true); changeBotRowVisibility(); } function noMicroworld(jqXHR) { alert(jqXHR.responseText); } function gotMicroworld(m) { mw = m; mode = mw.status; populatePage(); prepareControls(); } function getMicroworld() { $.ajax({ type: 'GET', url: '/microworlds/' + mwId, error: noMicroworld, success: gotMicroworld }); } function noRuns(jqXHR) { alert(jqXHR.responseText); } function gotRuns(r) { var table = ''; for (var i in r) { var button = '<button class="btn btn-sm btn-info" type="submit" onclick=location.href=\'/runs/' + r[i]._id + '?csv=true\'>Download <span class="glyphicon glyphicon-download-alt"></span></button>'; table += '<tr><td><a href="../runs/' + r[i]._id + '">' + moment(r[i].time).format('llll') + '</a></td>' + '<td>' + r[i].participants + '</td>' + '<td>' + button + '</tr>'; } $('#microworld-runs-table-rows').html(table); // enabled or disable the download all button depending on if there are any completed runs if (r.length == 0) { $('#download-all-button').attr("disabled", "disabled"); } else { $('#download-all-button').removeAttr("disabled"); } setTimeout(getRuns, 60000); } function getRuns() { $.ajax({ type: 'GET', url: '/runs/?mw=' + mwId, error: noRuns, success: gotRuns }); } function backToList() { location.href = '../dashboard'; } // Makes downloading all runs possible function initDownloadAll() { $('#download-all-button').attr("onclick", "location.href='/runs?csv=true&mw="+mwId+"'"); } function setButtons() { $('#create').click(createMicroworld); $('#create-2').click(createMicroworld); $('#save').click(saveMicroworld); $('#save-2').click(saveMicroworld); $('#cancel').click(backToList); $('#cancel-2').click(backToList); $('#clone-confirmed').click(cloneMicroworld) $('#activate-confirmed').click(activateMicroworld); $('#archive-confirmed').click(archiveMicroworld); $('#delete-confirmed').click(deleteMicroworld); $(".behaviour_group_select").click(showStatusTableOptions); initDownloadAll(); } function setOnPageChanges() { $('#num-fishers').on('change', changeBotRowVisibility); $('#num-humans').on('change', changeBotRowVisibility); $('#uniform-greed').on('change', changeGreedUniformity); $('#bot-1-greed').on('input', changeGreedUniformity); $('#uniform-greed-spread').on('change', changeGreedSpreadUniformity); $('#bot-1-greed-spread').on('input', changeGreedSpreadUniformity); $('#uniform-trend').on('change', changeTrendUniformity); $('#bot-1-trend').on('change', changeTrendUniformity); $('#uniform-predictability').on('change', changePredictabilityUniformity); $('#bot-1-predictability').on('change', changePredictabilityUniformity); $('#uniform-prob-action').on('change', changeProbActionUniformity); $('#bot-1-prob-action').on('input', changeProbActionUniformity); $('#uniform-attempts-second').on('change', changeAttemptsSecondUniformity); $('#bot-1-attempts-second').on('input', changeAttemptsSecondUniformity); } function loadTexts() { $('#preparation-text').val(prepText); $('#end-time-text').val(endTimeText); $('#end-depletion-text').val(endDepletedText); } function prepareControls() { $('#microworld-panel-body-text').text(panelBody[mode]); $('#microworld-panel-2-body-text').text(panelBody[mode]); if (mode === 'new') { $('#microworld-header').text(pageHeader[mode]); $('#microworld-panel-title').text(panelTitle[mode]); $('#microworld-panel-2-title').text(panelTitle[mode]); loadTexts(); $('#create').removeClass('collapse'); $('#create-2').removeClass('collapse'); $("#ocean_order_user_top").prop("checked", true); uniformityChanges(); } else if (mode === 'test') { $('title').text('Fish - Microworld in Test'); $('#microworld-header').text(pageHeader[mode] + mw.code); $('#microworld-panel-title').text(panelTitle[mode] + mw.code); $('#microworld-panel-2-title').text(panelTitle[mode] + mw.code); $('#save').removeClass('collapse'); $('#save-2').removeClass('collapse'); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#activate').removeClass('collapse'); $('#activate-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); if($('input[type="radio"]:checked').parent().parent().hasClass('dynamic_option')) { $(".static_option").addClass('hide'); $(".dynamic_option").removeClass("hide"); $('span#btn_txt').text("Dynamic Behaviour\xa0\xa0"); //\xa0 is the char &nbsp; makes } uniformityChanges(); } else if (mode === 'active') { $('title').text('Fish - Active Microworld'); $('#microworld-header').text(pageHeader[mode] + mw.code); $('#microworld-panel-title').text(panelTitle[mode] + mw.code); $('#microworld-panel-2-title').text(panelTitle[mode] + mw.code); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#archive').removeClass('collapse'); $('#archive-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); $('.to-disable').each( function() { $(this).prop('disabled', true); }); $('#results').removeClass('collapse'); $(".dynamic_option").removeClass("hide"); } else if (mode === 'archived') { $('title').text('Fish - Archived Microworld'); $('#microworld-header').text(pageHeader[mode]); $('#microworld-panel-title').text(panelTitle[mode]); $('#microworld-panel-2-title').text(panelTitle[mode]); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#activate').removeClass('collapse'); $('#activate-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); $('.to-disable').each( function() { $(this).prop('disabled', true); }); $('#results').removeClass('collapse'); $(".dynamic_option").removeClass("hide"); } } function loadData() { if (isNewMicroworld()) { mode = 'new'; prepareControls(); } else { getMicroworld(); // will eventually call prepareControls() getRuns(); } } function uniformityChanges() { changeGreedUniformity(); changeGreedSpreadUniformity(); changeTrendUniformity(); changePredictabilityUniformity(); changeProbActionUniformity(); changeAttemptsSecondUniformity(); } function main() { getMwId(); isNewMicroworld() readyTooltips(); setButtons(); setOnPageChanges(); loadData(); } $(document).ready(main);
/* ===================================================== file.js ======================================================== */ (function($){ // jQuery no conflict 'use strict'; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - Section - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ console.log('file.js loaded'); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */ })(jQuery); // jQuery no conflict
var q = require("./quasi"); exports.ps = function (opt) { opt = opt || {}; var strokeWidth = opt.strokeWidth || "0.015"; if (opt.color) console.error("The ps module does not support the `color` option."); // PS header var ret = [ "%%!PS-Adobe-1.0 " , "%%%%BoundingBox: -1 -1 766.354 567.929 " , "%%%%EndComments " , "%%%%EndProlog " , "gsave " , " " , "/f {findfont exch scalefont setfont} bind def " , "/s {show} bind def " , "/ps {true charpath} bind def " , "/l {lineto} bind def " , "/m {newpath moveto} bind def " , "/sg {setgray} bind def" , "/a {stroke} bind def" , "/cp {closepath} bind def" , "/g {gsave} bind def" , "/h {grestore} bind def" , "matrix currentmatrix /originmat exch def " , "/umatrix {originmat matrix concatmatrix setmatrix} def " , " " , "%% Flipping coord system " , "[8.35928e-09 28.3465 -28.3465 8.35928e-09 609.449 28.6299] umatrix " , "[] 0 setdash " , "0 0 0 setrgbcolor " , "0 0 m " , strokeWidth + " setlinewidth " ]; q.quasi( opt , { newPath: function () {} , moveTo: function (x, y) { ret.push(x.toFixed(2) + " " + y.toFixed(2) + " m"); } , lineTo: function (x, y) { ret.push(x.toFixed(2) + " " + y.toFixed(2) + " l"); } , closePath: function () { ret.push("cp"); } , startGroup: function () { ret.push("g"); } , endGroup: function () { ret.push("h"); } , setFillGrey: function (colour) { ret.push(colour + " sg"); ret.push("fill"); } , setStrokeGrey: function (colour) { ret.push(colour + " sg"); ret.push("a"); } // we don't take these into account , boundaries: function () {} } ); // PS Footer ret.push("showpage grestore "); ret.push("%%%%Trailer"); return ret.join("\n"); };
print('this is a'); print(__FILE__, __LINE__, __DIR__); load('./b.js'); // 不能简单的加载同目录的 b,因为 engine.get(FILENAME) 未变
import PropTypes from 'prop-types'; export const validAxisType = PropTypes.oneOf([ 'category', 'linear', 'logarithmic', 'datetime' ]); export const validChartType = PropTypes.oneOf([ 'area', 'arearange', 'areaspline', 'areasplinerange', 'bar', 'boxplot', 'bubble', 'candlestick', 'column', 'columnrange', 'errorbar', 'flags', 'funnel', 'line', 'ohlc', 'pie', 'polygon', 'pyramid', 'scatter', 'solidgauge', 'spline', 'waterfall' ]);
/** * @author Richard Davey <[email protected]> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var Line = require('./Line'); Line.Angle = require('./Angle'); Line.BresenhamPoints = require('./BresenhamPoints'); Line.CenterOn = require('./CenterOn'); Line.Clone = require('./Clone'); Line.CopyFrom = require('./CopyFrom'); Line.Equals = require('./Equals'); Line.Extend = require('./Extend'); Line.GetMidPoint = require('./GetMidPoint'); Line.GetNearestPoint = require('./GetNearestPoint'); Line.GetNormal = require('./GetNormal'); Line.GetPoint = require('./GetPoint'); Line.GetPoints = require('./GetPoints'); Line.GetShortestDistance = require('./GetShortestDistance'); Line.Height = require('./Height'); Line.Length = require('./Length'); Line.NormalAngle = require('./NormalAngle'); Line.NormalX = require('./NormalX'); Line.NormalY = require('./NormalY'); Line.Offset = require('./Offset'); Line.PerpSlope = require('./PerpSlope'); Line.Random = require('./Random'); Line.ReflectAngle = require('./ReflectAngle'); Line.Rotate = require('./Rotate'); Line.RotateAroundPoint = require('./RotateAroundPoint'); Line.RotateAroundXY = require('./RotateAroundXY'); Line.SetToAngle = require('./SetToAngle'); Line.Slope = require('./Slope'); Line.Width = require('./Width'); module.exports = Line;
'use strict'; // User routes use users controller var users = require('../controllers/users'); module.exports = function(app, passport) { app.route('/logout') .get(users.signout); app.route('/users/me') .get(users.me); // Setting up the users api app.route('/register') .post(users.create); // Setting up the userId param app.param('userId', users.user); // AngularJS route to check for authentication app.route('/loggedin') .get(function(req, res) { res.send(req.isAuthenticated() ? req.user : '0'); }); // Setting the local strategy route app.route('/login') .post(passport.authenticate('local', { failureFlash: true }), function(req, res) { res.send({ user: req.user, redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false }); }); };
'use strict'; // Disable eval and Buffer. window.eval = global.eval = global.Buffer = function() { throw new Error("Can't use eval and Buffer."); } const Electron = require('electron') const IpcRenderer = Electron.ipcRenderer; var Urlin = null; // element of input text window.addEventListener('load', ()=> { Urlin = document.getElementById('input-url'); Urlin.addEventListener("keypress", (event)=>{ if(13!=event.keyCode) return; Urlin.blur(); IpcRenderer.sendToHost('url-input', Urlin.value); }, false); }, false); IpcRenderer.on('url-input', (event, s_url)=>{ Urlin.value = s_url; });
var roshamboApp = angular.module('roshamboApp', []), roshambo= [ { name:'Rock', src:'img/rock.png' }, { name:'Paper', src:'img/paper.png' }, { name:'Scissors', src:'img/scissors.png' } ], roshamboMap=roshambo.reduce(function(roshamboMap,thro){ roshamboMap[thro.name.toLowerCase()]=thro.src; return roshamboMap; },{}); roshamboApp.controller('RoshamboCtrl', function ($scope,$http) { $scope.roshambo=roshambo; $scope.selection=roshambo[0]; $scope.outcome=void 0; $scope.selectThrow=function(selected){ $scope.outcome=void 0; $scope.selection=selected; }; $scope.throwSelected=function(){ $http.post('http://localhost:8080/api/throw',{playerThrow:$scope.selection.name}) .then(function(successResponse){ $scope.outcome=successResponse.data; $scope.outcome.playerSrc=roshamboMap[$scope.outcome.playerThrow]; $scope.outcome.opponentSrc=roshamboMap[$scope.outcome.opponentThrow]; $scope.outcome.announce=function(){ if($scope.outcome.outcome==='draw'){ return 'It\'s a Draw!'; }else{ return $scope.outcome.outcome.charAt(0).toUpperCase()+$scope.outcome.outcome.slice(1)+' Wins!'; } } },function(errorResponse){ alert('Error!'); console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2)); }); }; });
"use strict"; module.exports = { "wires.json": { ":path/": `./path-`, }, "path-test.js"() { module.exports = `parent`; }, "/child": { "wires-defaults.json": { ":path/": `./defaults-`, }, "wires.json": { ":path/": `./child-`, }, "defaults-test.js"() { module.exports = `defaults`; }, "child-test.js"() { module.exports = `child`; }, "dirRouteOverride.unit.js"() { module.exports = { "dir route override"( __ ) { __.expect( 1 ); __.strictEqual( require( `:path/test` ), `child` ); __.done(); }, }; }, }, };
/** * highcharts-ng * @version v0.0.13 - 2016-10-04 * @link https://github.com/pablojim/highcharts-ng * @author Barry Fitzgerald <> * @license MIT License, http://www.opensource.org/licenses/MIT */ if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports){ module.exports = 'highcharts-ng'; } (function () { 'use strict'; /*global angular: false, Highcharts: false */ angular.module('highcharts-ng', []) .factory('highchartsNG', ['$q', '$window', highchartsNG]) .directive('highchart', ['highchartsNG', '$timeout', highchart]); //IE8 support function indexOf(arr, find, i /*opt*/) { if (i === undefined) i = 0; if (i < 0) i += arr.length; if (i < 0) i = 0; for (var n = arr.length; i < n; i++) if (i in arr && arr[i] === find) return i; return -1; } function prependMethod(obj, method, func) { var original = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); func.apply(this, args); if (original) { return original.apply(this, args); } else { return; } }; } function deepExtend(destination, source) { //Slightly strange behaviour in edge cases (e.g. passing in non objects) //But does the job for current use cases. if (angular.isArray(source)) { destination = angular.isArray(destination) ? destination : []; for (var i = 0; i < source.length; i++) { destination[i] = deepExtend(destination[i] || {}, source[i]); } } else if (angular.isObject(source)) { destination = angular.isObject(destination) ? destination : {}; for (var property in source) { destination[property] = deepExtend(destination[property] || {}, source[property]); } } else { destination = source; } return destination; } function highchartsNG($q, $window) { var highchartsProm = $q.when($window.Highcharts); function getHighchartsOnce() { return highchartsProm; } return { getHighcharts: getHighchartsOnce, ready: function ready(callback, thisArg) { getHighchartsOnce().then(function() { callback.call(thisArg); }); } }; } function highchart(highchartsNGUtils, $timeout) { // acceptable shared state var seriesId = 0; var ensureIds = function (series) { var changed = false; angular.forEach(series, function(s) { if (!angular.isDefined(s.id)) { s.id = 'series-' + seriesId++; changed = true; } }); return changed; }; // immutable var axisNames = [ 'xAxis', 'yAxis' ]; var chartTypeMap = { 'stock': 'StockChart', 'map': 'Map', 'chart': 'Chart' }; var getMergedOptions = function (scope, element, config) { var mergedOptions = {}; var defaultOptions = { chart: { events: {} }, title: {}, subtitle: {}, series: [], credits: {}, plotOptions: {}, navigator: {enabled: false}, xAxis: { events: {} }, yAxis: { events: {} } }; if (config.options) { mergedOptions = deepExtend(defaultOptions, config.options); } else { mergedOptions = defaultOptions; } mergedOptions.chart.renderTo = element[0]; angular.forEach(axisNames, function(axisName) { if(angular.isDefined(config[axisName])) { mergedOptions[axisName] = deepExtend(mergedOptions[axisName] || {}, config[axisName]); if(angular.isDefined(config[axisName].currentMin) || angular.isDefined(config[axisName].currentMax)) { prependMethod(mergedOptions.chart.events, 'selection', function(e){ var thisChart = this; if (e[axisName]) { scope.$apply(function () { scope.config[axisName].currentMin = e[axisName][0].min; scope.config[axisName].currentMax = e[axisName][0].max; }); } else { //handle reset button - zoom out to all scope.$apply(function () { scope.config[axisName].currentMin = thisChart[axisName][0].dataMin; scope.config[axisName].currentMax = thisChart[axisName][0].dataMax; }); } }); prependMethod(mergedOptions.chart.events, 'addSeries', function(e){ scope.config[axisName].currentMin = this[axisName][0].min || scope.config[axisName].currentMin; scope.config[axisName].currentMax = this[axisName][0].max || scope.config[axisName].currentMax; }); prependMethod(mergedOptions[axisName].events, 'setExtremes', function (e) { if (e.trigger && e.trigger !== 'zoom') { // zoom trigger is handled by selection event $timeout(function () { scope.config[axisName].currentMin = e.min; scope.config[axisName].currentMax = e.max; scope.config[axisName].min = e.min; // set min and max to adjust scrollbar/navigator scope.config[axisName].max = e.max; }, 0); } }); } } }); if(config.title) { mergedOptions.title = config.title; } if (config.subtitle) { mergedOptions.subtitle = config.subtitle; } if (config.credits) { mergedOptions.credits = config.credits; } if(config.size) { if (config.size.width) { mergedOptions.chart.width = config.size.width; } if (config.size.height) { mergedOptions.chart.height = config.size.height; } } return mergedOptions; }; var updateZoom = function (axis, modelAxis) { var extremes = axis.getExtremes(); if(modelAxis.currentMin !== extremes.dataMin || modelAxis.currentMax !== extremes.dataMax) { if (axis.setExtremes) { axis.setExtremes(modelAxis.currentMin, modelAxis.currentMax, false); } else { axis.detachedsetExtremes(modelAxis.currentMin, modelAxis.currentMax, false); } } }; var processExtremes = function(chart, axis, axisName) { if(axis.currentMin || axis.currentMax) { chart[axisName][0].setExtremes(axis.currentMin, axis.currentMax, true); } }; var chartOptionsWithoutEasyOptions = function (options) { return angular.extend( deepExtend({}, options), { data: null, visible: null } ); }; var getChartType = function(scope) { if (scope.config === undefined) return 'Chart'; return chartTypeMap[('' + scope.config.chartType).toLowerCase()] || (scope.config.useHighStocks ? 'StockChart' : 'Chart'); }; function linkWithHighcharts(Highcharts, scope, element, attrs) { // We keep some chart-specific variables here as a closure // instead of storing them on 'scope'. // prevSeriesOptions is maintained by processSeries var prevSeriesOptions = {}; // chart is maintained by initChart var chart = false; var processSeries = function(series, seriesOld) { var i; var ids = []; if(series) { var setIds = ensureIds(series); if(setIds && !scope.disableDataWatch) { //If we have set some ids this will trigger another digest cycle. //In this scenario just return early and let the next cycle take care of changes return false; } //Find series to add or update angular.forEach(series, function(s, idx) { ids.push(s.id); var chartSeries = chart.get(s.id); if (chartSeries) { if (!angular.equals(prevSeriesOptions[s.id], chartOptionsWithoutEasyOptions(s))) { chartSeries.update(angular.copy(s), false); } else { if (s.visible !== undefined && chartSeries.visible !== s.visible) { chartSeries.setVisible(s.visible, false); } // Make sure the current series index can be accessed in seriesOld if (idx < seriesOld.length) { var sOld = seriesOld[idx]; var sCopy = angular.copy(sOld); // Get the latest data point from the new series var ptNew = s.data[s.data.length - 1]; // Check if the new and old series are identical with the latest data point added // If so, call addPoint without shifting sCopy.data.push(ptNew); if (angular.equals(sCopy, s)) { chartSeries.addPoint(ptNew, false); } // Check if the data change was a push and shift operation // If so, call addPoint WITH shifting else { sCopy.data.shift(); if (angular.equals(sCopy, s)) { chartSeries.addPoint(ptNew, false, true); } else { chartSeries.setData(angular.copy(s.data), false); } } } else { chartSeries.setData(angular.copy(s.data), false); } } } else { chart.addSeries(angular.copy(s), false); } prevSeriesOptions[s.id] = chartOptionsWithoutEasyOptions(s); }); // Shows no data text if all series are empty if(scope.config.noData) { var chartContainsData = false; for(i = 0; i < series.length; i++) { if (series[i].data && series[i].data.length > 0) { chartContainsData = true; break; } } if (!chartContainsData) { chart.showLoading(scope.config.noData); } else { chart.hideLoading(); } } } //Now remove any missing series for(i = chart.series.length - 1; i >= 0; i--) { var s = chart.series[i]; if (s.options.id !== 'highcharts-navigator-series' && indexOf(ids, s.options.id) < 0) { s.remove(false); } } return true; }; var initChart = function() { if (chart) chart.destroy(); prevSeriesOptions = {}; var config = scope.config || {}; var mergedOptions = getMergedOptions(scope, element, config); var func = config.func || undefined; var chartType = getChartType(scope); chart = new Highcharts[chartType](mergedOptions, func); for (var i = 0; i < axisNames.length; i++) { if (config[axisNames[i]]) { processExtremes(chart, config[axisNames[i]], axisNames[i]); } } if(config.loading) { chart.showLoading(); } config.getHighcharts = function() { return chart; }; }; initChart(); if(scope.disableDataWatch){ scope.$watchCollection('config.series', function (newSeries, oldSeries) { processSeries(newSeries); chart.redraw(); }); } else { scope.$watch('config.series', function (newSeries, oldSeries) { var needsRedraw = processSeries(newSeries, oldSeries); if(needsRedraw) { chart.redraw(); } }, true); } scope.$watch('config.title', function (newTitle) { chart.setTitle(newTitle, true); }, true); scope.$watch('config.subtitle', function (newSubtitle) { chart.setTitle(true, newSubtitle); }, true); scope.$watch('config.loading', function (loading) { if(loading) { chart.showLoading(loading === true ? null : loading); } else { chart.hideLoading(); } }); scope.$watch('config.noData', function (noData) { if(scope.config && scope.config.loading) { chart.showLoading(noData); } }, true); scope.$watch('config.credits.enabled', function (enabled) { if (enabled) { chart.credits.show(); } else if (chart.credits) { chart.credits.hide(); } }); scope.$watch(getChartType, function (chartType, oldChartType) { if (chartType === oldChartType) return; initChart(); }); angular.forEach(axisNames, function(axisName) { scope.$watch('config.' + axisName, function(newAxes) { if (!newAxes) { return; } if (angular.isArray(newAxes)) { for (var axisIndex = 0; axisIndex < newAxes.length; axisIndex++) { var axis = newAxes[axisIndex]; if (axisIndex < chart[axisName].length) { chart[axisName][axisIndex].update(axis, false); updateZoom(chart[axisName][axisIndex], angular.copy(axis)); } } } else { // update single axis chart[axisName][0].update(newAxes, false); updateZoom(chart[axisName][0], angular.copy(newAxes)); } chart.redraw(); }, true); }); scope.$watch('config.options', function (newOptions, oldOptions, scope) { //do nothing when called on registration if (newOptions === oldOptions) return; initChart(); processSeries(scope.config.series); chart.redraw(); }, true); scope.$watch('config.size', function (newSize, oldSize) { if(newSize === oldSize) return; if(newSize) { chart.setSize(newSize.width || chart.chartWidth, newSize.height || chart.chartHeight); } }, true); scope.$on('highchartsng.reflow', function () { chart.reflow(); }); scope.$on('$destroy', function() { if (chart) { try{ chart.destroy(); }catch(ex){ // fail silently as highcharts will throw exception if element doesn't exist } $timeout(function(){ element.remove(); }, 0); } }); } function link(scope, element, attrs) { function highchartsCb(Highcharts) { linkWithHighcharts(Highcharts, scope, element, attrs); } highchartsNGUtils .getHighcharts() .then(highchartsCb); } return { restrict: 'EAC', replace: true, template: '<div></div>', scope: { config: '=', disableDataWatch: '=' }, link: link }; } }()); (function (angular) { 'use strict'; angular.module('tubular-hchart.directives', ['tubular.services', 'highcharts-ng']) /** * @ngdoc component * @name tbHighcharts * * @description * The `tbHighcharts` component is the base to create any Highcharts component. * * @param {string} serverUrl Set the HTTP URL where the data comes. * @param {string} chartName Defines the chart name. * @param {string} chartType Defines the chart type. * @param {string} title Defines the title. * @param {bool} requireAuthentication Set if authentication check must be executed, default true. * @param {function} onLoad Defines a method to run in chart data load * @param {string} emptyMessage The empty message. * @param {string} errorMessage The error message. * @param {object} options The Highcharts options method. */ .component('tbHighcharts', { template: '<div class="tubular-chart">' + '<highchart config="$ctrl.options" ng-hide="$ctrl.isEmpty || $ctrl.hasError">' + '</highchart>' + '<div class="alert alert-info" ng-show="$ctrl.isEmpty">{{$ctrl.emptyMessage}}</div>' + '<div class="alert alert-warning" ng-show="$ctrl.hasError">{{$ctrl.errorMessage}}</div>' + '</div>', bindings: { serverUrl: '@', title: '@?', requireAuthentication: '=?', name: '@?chartName', chartType: '@?', emptyMessage: '@?', errorMessage: '@?', onLoad: '=?', options: '=?', onClick: '=?' }, controller: [ '$scope', 'tubularHttp', '$timeout', 'tubularConfig', function ($scope, tubularHttp, $timeout, tubularConfig) { var $ctrl = this; $ctrl.dataService = tubularHttp.getDataService($ctrl.dataServiceName); $ctrl.showLegend = angular.isUndefined($ctrl.showLegend) ? true : $ctrl.showLegend; $ctrl.chartType = $ctrl.chartType || 'line'; $ctrl.options = angular.extend({}, $ctrl.options, { options: { chart: { type: $ctrl.chartType }, plotOptions: { pie: { point: { events: { click: ($ctrl.onClick || angular.noop) } } }, series: { point: { events: { click: ($ctrl.onClick || angular.noop) } } } } }, title: { text: $ctrl.title || '' }, xAxis: { categories: [] }, yAxis: {}, series: [] }); // Setup require authentication $ctrl.requireAuthentication = angular.isUndefined($ctrl.requireAuthentication) ? true : $ctrl.requireAuthentication; $ctrl.loadData = function () { tubularConfig.webApi.requireAuthentication($ctrl.requireAuthentication); $ctrl.hasError = false; tubularHttp.get($ctrl.serverUrl).then($ctrl.handleData, function (error) { $scope.$emit('tbChart_OnConnectionError', error); $ctrl.hasError = true; }); }; $ctrl.handleData = function (data) { if (!data || !data.Data || data.Data.length === 0) { $ctrl.isEmpty = true; $ctrl.options.series = [{ data: [] }]; if ($ctrl.onLoad) { $ctrl.onLoad($ctrl.options, {}); } return; } $ctrl.isEmpty = false; if (data.Series) { $ctrl.options.xAxis.categories = data.Labels; $ctrl.options.series = data.Series.map(function (el, ix) { return { name: el, data: data.Data[ix] }; }); } else { var uniqueSerie = data.Labels.map(function (el, ix) { return { name: el, y: data.Data[ix] }; }); $ctrl.options.series = [{ name: data.SerieName || '', data: uniqueSerie, showInLegend: (data.SerieName || '') !== '' }]; } if ($ctrl.onLoad) { $timeout(function () { $ctrl.onLoad($ctrl.options, {}, $ctrl.options.getHighcharts().series); }, 100); $ctrl.onLoad($ctrl.options, {}, null); } }; $scope.$watch('$ctrl.serverUrl', function (val) { if (angular.isDefined(val) && val != null && val !== '') { $ctrl.loadData(); } }); $scope.$watch('$ctrl.chartType', function (val) { if (angular.isDefined(val) && val != null) { $ctrl.options.options.chart.type = val; } }); } ] }); })(angular);
angular.module("uiSwitch",[]).directive("switch",function(){return{restrict:"AE",replace:!0,transclude:!0,template:function(n,e){var s="";return s+="<span",s+=' class="switch'+(e['class']?" "+e['class']:"")+'"',s+=e.ngModel?' ng-click="'+e.disabled+" ? "+e.ngModel+" : "+e.ngModel+"=!"+e.ngModel+(e.ngChange?"; "+e.ngChange+'()"':'"'):"",s+=' ng-class="{ checked:'+e.ngModel+", disabled:"+e.disabled+' }"',s+=">",s+="<small></small>",s+='<input type="checkbox"',s+=e.id?' id="'+e.id+'"':"",s+=e.name?' name="'+e.name+'"':"",s+=e.ngModel?' ng-model="'+e.ngModel+'"':"",s+=' style="display:none" />',s+='<span class="switch-text">',s+=e.on?'<span class="on">'+e.on+"</span>":"",s+=e.off?'<span class="off">'+e.off+"</span>":" ",s+="</span>"}}});
var assert = require('assert') var parse = require('../').parse function addTest(arg, bulk) { function fn_json5() { //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) { x = 'fail' } try { var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()') } catch(err) { z = 'fail' } assert.deepEqual(x, z) } function fn_strict() { //console.log('testing: ', arg) try { var x = parse(arg, {mode: 'json'}) } catch(err) { x = 'fail' } try { var z = JSON.parse(arg) } catch(err) { z = 'fail' } assert.deepEqual(x, z) } if (typeof(describe) === 'function' && !bulk) { it('test_parse_json5: ' + JSON.stringify(arg), fn_json5) it('test_parse_strict: ' + JSON.stringify(arg), fn_strict) } else { fn_json5() fn_strict() } } addTest('"\\uaaaa\\u0000\\uFFFF\\uFaAb"') addTest(' "\\xaa\\x00\xFF\xFa\0\0" ') addTest('"\\\'\\"\\b\\f\\t\\n\\r\\v"') addTest('"\\q\\w\\e\\r\\t\\y\\\\i\\o\\p\\[\\/\\\\"') addTest('"\\\n\\\r\n\\\n"') addTest('\'\\\n\\\r\n\\\n\'') addTest(' null') addTest('true ') addTest('false') addTest(' Infinity ') addTest('+Infinity') addTest('[]') addTest('[ 0xA2, 0X024324AaBf]') addTest('-0x12') addTest(' [1,2,3,4,5]') addTest('[1,2,3,4,5,] ') addTest('[1e-13]') addTest('[null, true, false]') addTest(' [1,2,"3,4,",5,]') addTest('[ 1,\n2,"3,4," \r\n,\n5,]') addTest('[ 1 , 2 , 3 , 4 , 5 , ]') addTest('{} ') addTest('{"2":1,"3":null,}') addTest('{ "2 " : 1 , "3":null , }') addTest('{ \"2\" : 25e245 , \"3\": 23 }') addTest('{"2":1,"3":nul,}') addTest('{:1,"3":nul,}') addTest('[1,2] // ssssssssss 3,4,5,] ') addTest('[1,2 , // ssssssssss \n//xxx\n3,4,5,] ') addTest('[1,2 /* ssssssssss 3,4,*/ /* */ , 5 ] ') addTest('[1,2 /* ssssssssss 3,4,*/ /* * , 5 ] ') addTest('{"3":1,"3":,}') addTest('{ чйуач:1, щцкшчлм : 4,}') addTest('{ qef-:1 }') addTest('{ $$$:1 , ___: 3}') addTest('{3:1,2:1}') addTest('{3.4e3:1}') addTest('{-3e3:1}') addTest('{+3e3:1}') addTest('{.3e3:1}') for (var i=0; i<200; i++) { addTest('"' + String.fromCharCode(i) + '"', true) } // strict JSON test cases addTest('"\\xaa"') addTest('"\\0"') addTest('"\0"') addTest('"\\v"') addTest('{null: 123}') addTest("{'null': 123}") assert.throws(function() { parse('0o') }) assert.strictEqual(parse('01234567'), 342391) assert.strictEqual(parse('0o1234567'), 342391) // undef assert.strictEqual(parse(undefined), undefined) // whitespaces addTest('[1,\r\n2,\r3,\n]') '\u0020\u00A0\uFEFF\x09\x0A\x0B\x0C\x0D\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000'.split('').forEach(function(x) { addTest(x+'[1,'+x+'2]'+x) addTest('"'+x+'"'+x) }) '\u000A\u000D\u2028\u2029'.split('').forEach(function(x) { addTest(x+'[1,'+x+'2]'+x) addTest('"\\'+x+'"'+x) }) /* weird ES6 stuff, not working if (process.version > 'v0.11.7') { assert(Array.isArray(parse('{__proto__:[]}').__proto__)) assert.equal(parse('{__proto__:{xxx:5}}').xxx, undefined) assert.equal(parse('{__proto__:{xxx:5}}').__proto__.xxx, 5) var o1 = parse('{"__proto__":[]}') assert.deepEqual([], o1.__proto__) assert.deepEqual(["__proto__"], Object.keys(o1)) assert.deepEqual([], Object.getOwnPropertyDescriptor(o1, "__proto__").value) assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o1)) assert(o1.hasOwnProperty("__proto__")) assert(Object.prototype.isPrototypeOf(o1)) // Parse a non-object value as __proto__. var o2 = JSON.parse('{"__proto__":5}') assert.deepEqual(5, o2.__proto__) assert.deepEqual(["__proto__"], Object.keys(o2)) assert.deepEqual(5, Object.getOwnPropertyDescriptor(o2, "__proto__").value) assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o2)) assert(o2.hasOwnProperty("__proto__")) assert(Object.prototype.isPrototypeOf(o2)) }*/ assert.throws(parse.bind(null, "{-1:42}")) for (var i=0; i<100; i++) { var str = '-01.e'.split('') var rnd = [1,2,3,4,5].map(function(x) { x = ~~(Math.random()*str.length) return str[x] }).join('') try { var x = parse(rnd) } catch(err) { x = 'fail' } try { var y = JSON.parse(rnd) } catch(err) { y = 'fail' } try { var z = eval(rnd) } catch(err) { z = 'fail' } //console.log(rnd, x, y, z) if (x !== y && x !== z) throw 'ERROR' }
/** * options.js * * A test helper to detect which html-snapshots options to use * * phantomjs * If a global phantomjs is defined, decorates html-snapshots options to specify that global * In some test environments (travis), local phantomjs will not install if a global is found. */ const spawn = require("child_process").spawn; module.exports = { // for now, callback is passed true if global phantomjs should be used detector: callback => { // try to run phantom globally const cp = spawn("phantomjs", ["--version"]); // if it fails, use local per the defaults cp.on("error", () => { callback(false); }); // if it succeeds, use the global cp.on("exit", code => { if (code === 0) { callback(true); } }); } };
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame, assertDataProperty, assertBuiltinConstructor, assertBuiltinPrototype, } = Assert; function assertFunctionProperty(object, name, value = object[name]) { return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true}); } function assertCreateFunctionProperty(object, name, value = object[name]) { return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: true}); } function assertConstructorProperty(object, name = "constructor", value = object[name]) { return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true}); } function assertPrototypeProperty(object, name = "prototype", value = object[name]) { return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: false}); } /* Promise Objects */ assertBuiltinConstructor(Promise, "Promise", 1); assertBuiltinPrototype(Promise.prototype); assertSame(Promise, Promise.prototype.constructor); /* Properties of the Promise Constructor */ assertPrototypeProperty(Promise); assertCreateFunctionProperty(Promise, Symbol.create); assertFunctionProperty(Promise, "all"); assertFunctionProperty(Promise, "cast"); assertFunctionProperty(Promise, "race"); assertFunctionProperty(Promise, "reject"); assertFunctionProperty(Promise, "resolve"); /* Properties of the Promise Prototype Object */ assertConstructorProperty(Promise.prototype); assertFunctionProperty(Promise.prototype, "catch"); assertFunctionProperty(Promise.prototype, "then");
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @name mdBackdrop * @module material.components.backdrop * * @restrict E * * @description * `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet. * Apply class `opaque` to make the backdrop use the theme backdrop color. * */ angular .module('material.components.backdrop', ['material.core']) .directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) { var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container."; return { restrict: 'E', link: postLink }; function postLink(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10)); element.css({ height: hViewport + 'px' }); } // backdrop may be outside the $rootElement, tell ngAnimate to animate regardless if ($animate.pin) $animate.pin(element, $rootElement); $$rAF(function () { // Often $animate.enter() is used to append the backDrop element // so let's wait until $animate is done... var parent = element.parent()[0]; if (parent) { if ( parent.nodeName == 'BODY' ) { element.css({position : 'fixed'}); } var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent position:static (default) $log.warn(ERROR_CSS_POSITION); } } $mdTheming.inherit(element, element.parent()); }); } }]); ng.material.components.backdrop = angular.module("material.components.backdrop");
const errors = require('@tryghost/errors'); const should = require('should'); const sinon = require('sinon'); const fs = require('fs-extra'); const moment = require('moment'); const Promise = require('bluebird'); const path = require('path'); const LocalFileStore = require('../../../../../core/server/adapters/storage/LocalFileStorage'); let localFileStore; const configUtils = require('../../../../utils/configUtils'); describe('Local File System Storage', function () { let image; let momentStub; function fakeDate(mm, yyyy) { const month = parseInt(mm, 10); const year = parseInt(yyyy, 10); momentStub.withArgs('YYYY').returns(year.toString()); momentStub.withArgs('MM').returns(month < 10 ? '0' + month.toString() : month.toString()); } beforeEach(function () { // Fake a date, do this once for all tests in this file momentStub = sinon.stub(moment.fn, 'format'); }); afterEach(function () { sinon.restore(); configUtils.restore(); }); beforeEach(function () { sinon.stub(fs, 'mkdirs').resolves(); sinon.stub(fs, 'copy').resolves(); sinon.stub(fs, 'stat').rejects(); sinon.stub(fs, 'unlink').resolves(); image = { path: 'tmp/123456.jpg', name: 'IMAGE.jpg', type: 'image/jpeg' }; localFileStore = new LocalFileStore(); fakeDate(9, 2013); }); it('should send correct path to image when date is in Sep 2013', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); it('should send correct path to image when original file has spaces', function (done) { image.name = 'AN IMAGE.jpg'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/AN-IMAGE.jpg'); done(); }).catch(done); }); it('should allow "@" symbol to image for Apple hi-res (retina) modifier', function (done) { image.name = '[email protected]'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/[email protected]'); done(); }).catch(done); }); it('should send correct path to image when date is in Jan 2014', function (done) { fakeDate(1, 2014); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2014/01/IMAGE.jpg'); done(); }).catch(done); }); it('should create month and year directory', function (done) { localFileStore.save(image).then(function () { fs.mkdirs.calledOnce.should.be.true(); fs.mkdirs.args[0][0].should.equal(path.resolve('./content/images/2013/09')); done(); }).catch(done); }); it('should copy temp file to new location', function (done) { localFileStore.save(image).then(function () { fs.copy.calledOnce.should.be.true(); fs.copy.args[0][0].should.equal('tmp/123456.jpg'); fs.copy.args[0][1].should.equal(path.resolve('./content/images/2013/09/IMAGE.jpg')); done(); }).catch(done); }); it('can upload two different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).rejects(); // if on windows need to setup with back slashes // doesn't hurt for the test to cope with both fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-1.jpg'); done(); }).catch(done); }); it('can upload five different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-4.jpg')).rejects(); // windows setup fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-4.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-4.jpg'); done(); }).catch(done); }); describe('read image', function () { beforeEach(function () { // we have some example images in our test utils folder localFileStore.storagePath = path.join(__dirname, '../../../../utils/fixtures/images/'); }); it('success', function (done) { localFileStore.read({path: 'ghost-logo.png'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('success', function (done) { localFileStore.read({path: '/ghost-logo.png/'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('image does not exist', function (done) { localFileStore.read({path: 'does-not-exist.png'}) .then(function () { done(new Error('image should not exist')); }) .catch(function (err) { (err instanceof errors.NotFoundError).should.eql(true); err.code.should.eql('ENOENT'); done(); }); }); }); describe('validate extentions', function () { it('name contains a .\d as extension', function (done) { localFileStore.save({ name: 'test-1.1.1' }).then(function (url) { should.exist(url.match(/test-1.1.1/)); done(); }).catch(done); }); it('name contains a .zip as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.zip' }).then(function (url) { should.exist(url.match(/test-1.1.1.zip/)); done(); }).catch(done); }); it('name contains a .jpeg as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.jpeg' }).then(function (url) { should.exist(url.match(/test-1.1.1.jpeg/)); done(); }).catch(done); }); }); describe('when a custom content path is used', function () { beforeEach(function () { const configPaths = configUtils.defaultConfig.paths; configUtils.set('paths:contentPath', configPaths.appRoot + '/var/ghostcms'); }); it('should send the correct path to image', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); }); // @TODO: remove path.join mock... describe('on Windows', function () { const truePathSep = path.sep; beforeEach(function () { sinon.stub(path, 'join'); sinon.stub(configUtils.config, 'getContentPath').returns('content/images/'); }); afterEach(function () { path.sep = truePathSep; }); it('should return url in proper format for windows', function (done) { path.sep = '\\'; path.join.returns('content\\images\\2013\\09\\IMAGE.jpg'); localFileStore.save(image).then(function (url) { if (truePathSep === '\\') { url.should.equal('/content/images/2013/09/IMAGE.jpg'); } else { // if this unit test is run on an OS that uses forward slash separators, // localfilesystem.save() will use a path.relative() call on // one path with backslash separators and one path with forward // slashes and it returns a path that needs to be normalized path.normalize(url).should.equal('/content/images/2013/09/IMAGE.jpg'); } done(); }).catch(done); }); }); });
import UnexpectedHtmlLike from 'unexpected-htmllike'; import React from 'react'; import REACT_EVENT_NAMES from '../reactEventNames'; const PENDING_TEST_EVENT_TYPE = { dummy: 'Dummy object to identify a pending event on the test renderer' }; function getDefaultOptions(flags) { return { diffWrappers: flags.exactly || flags.withAllWrappers, diffExtraChildren: flags.exactly || flags.withAllChildren, diffExtraAttributes: flags.exactly || flags.withAllAttributes, diffExactClasses: flags.exactly, diffExtraClasses: flags.exactly || flags.withAllClasses }; } /** * * @param options {object} * @param options.ActualAdapter {function} constructor function for the HtmlLike adapter for the `actual` value (usually the renderer) * @param options.ExpectedAdapter {function} constructor function for the HtmlLike adapter for the `expected` value * @param options.QueryAdapter {function} constructor function for the HtmlLike adapter for the query value (`queried for` and `on`) * @param options.actualTypeName {string} name of the unexpected type for the `actual` value * @param options.expectedTypeName {string} name of the unexpected type for the `expected` value * @param options.queryTypeName {string} name of the unexpected type for the query value (used in `queried for` and `on`) * @param options.actualRenderOutputType {string} the unexpected type for the actual output value * @param options.getRenderOutput {function} called with the actual value, and returns the `actualRenderOutputType` type * @param options.getDiffInputFromRenderOutput {function} called with the value from `getRenderOutput`, result passed to HtmlLike diff * @param options.rewrapResult {function} called with the `actual` value (usually the renderer), and the found result * @param options.wrapResultForReturn {function} called with the `actual` value (usually the renderer), and the found result * from HtmlLike `contains()` call (usually the same type returned from `getDiffInputFromRenderOutput`. Used to create a * value that can be passed back to the user as the result of the promise. Used by `queried for` when no further assertion is * provided, therefore the return value is provided as the result of the promise. If this is not present, `rewrapResult` is used. * @param options.triggerEvent {function} called the `actual` value (renderer), the optional target (or null) as the result * from the HtmlLike `contains()` call target, the eventName, and optional eventArgs when provided (undefined otherwise) * @constructor */ function AssertionGenerator(options) { this._options = Object.assign({}, options); this._PENDING_EVENT_IDENTIFIER = (options.mainAssertionGenerator && options.mainAssertionGenerator.getEventIdentifier()) || { dummy: options.actualTypeName + 'PendingEventIdentifier' }; this._actualPendingEventTypeName = options.actualTypeName + 'PendingEvent'; } AssertionGenerator.prototype.getEventIdentifier = function () { return this._PENDING_EVENT_IDENTIFIER; }; AssertionGenerator.prototype.installInto = function installInto(expect) { this._installEqualityAssertions(expect); this._installQueriedFor(expect); this._installPendingEventType(expect); this._installWithEvent(expect); this._installWithEventOn(expect); this._installEventHandlerAssertions(expect); }; AssertionGenerator.prototype.installAlternativeExpected = function (expect) { this._installEqualityAssertions(expect); this._installEventHandlerAssertions(expect); } AssertionGenerator.prototype._installEqualityAssertions = function (expect) { const { actualTypeName, expectedTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, ActualAdapter, ExpectedAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualTypeName}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput) .then(() => subject); }); expect.addAssertion([ `<${actualRenderOutputType}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualRenderOutputType}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>` ], function (expect, subject, renderOutput) { const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const actualAdapter = new ActualAdapter(); const expectedAdapter = new ExpectedAdapter(); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { expectedAdapter.setOptions({concatTextContent: true}); actualAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const diffResult = testHtmlLike.diff(expectedAdapter, getDiffInputFromRenderOutput(subject), renderOutput, expect, options); return testHtmlLike.withResult(diffResult, result => { if (result.weight !== 0) { return expect.fail({ diff: function (output, diff, inspect) { return output.append(testHtmlLike.render(result, output.clone(), diff, inspect)); } }); } return result; }); }); expect.addAssertion([`<${actualTypeName}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput); }); expect.addAssertion([`<${actualRenderOutputType}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualRenderOutputType}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, expected) { var not = this.flags.not; var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var expectedAdapter = new ExpectedAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); expectedAdapter.setOptions({concatTextContent: true}); } var options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const containsResult = testHtmlLike.contains(expectedAdapter, getDiffInputFromRenderOutput(subject), expected, expect, options); return testHtmlLike.withResult(containsResult, result => { if (not) { if (result.found) { expect.fail({ diff: (output, diff, inspect) => { return output.error('but found the following match').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } return; } if (!result.found) { expect.fail({ diff: function (output, diff, inspect) { return output.error('the best match was').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } }); }); // More generic assertions expect.addAssertion(`<${actualTypeName}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to equal', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have exactly rendered', expected); }); expect.addAssertion(`<${actualTypeName}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to satisfy', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have rendered', expected); }); }; AssertionGenerator.prototype._installQueriedFor = function (expect) { const { actualTypeName, queryTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, rewrapResult, wrapResultForReturn, ActualAdapter, QueryAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualTypeName}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>` ], function (expect, subject, query, assertion) { return expect.apply(expect, [ getRenderOutput(subject), 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', query ].concat(Array.prototype.slice.call(arguments, 3))); }); expect.addAssertion([`<${actualRenderOutputType}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualRenderOutputType}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, query) { var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var queryAdapter = new QueryAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); queryAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'queryTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(subject), query, expect, options); const args = arguments; return testHtmlLike.withResult(containsResult, function (result) { if (!result.found) { expect.fail({ diff: (output, diff, inspect) => { const resultOutput = output.error('`queried for` found no match.'); if (result.bestMatch) { resultOutput.error(' The best match was') .nl() .append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return resultOutput; } }); } if (args.length > 3) { // There is an assertion continuation... expect.errorMode = 'nested' const s = rewrapResult(subject, result.bestMatch.target || result.bestMatchItem); return expect.apply(null, [ rewrapResult(subject, result.bestMatch.target || result.bestMatchItem) ].concat(Array.prototype.slice.call(args, 3))) return expect.shift(rewrapResult(subject, result.bestMatch.target || result.bestMatchItem)); } // There is no assertion continuation, so we need to wrap the result for public consumption // i.e. create a value that we can give back from the `expect` promise return expect.shift((wrapResultForReturn || rewrapResult)(subject, result.bestMatch.target || result.bestMatchItem)); }); }); }; AssertionGenerator.prototype._installPendingEventType = function (expect) { const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addType({ name: actualPendingEventTypeName, base: 'object', identify(value) { return value && typeof value === 'object' && value.$$typeof === PENDING_EVENT_IDENTIFIER; }, inspect(value, depth, output, inspect) { return output.append(inspect(value.renderer)).red(' with pending event \'').cyan(value.eventName).red('\''); } }); }; AssertionGenerator.prototype._installWithEvent = function (expect) { const { actualTypeName, actualRenderOutputType, triggerEvent, canTriggerEventsOnOutputType } = this._options; let { wrapResultForReturn = (value) => value } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addAssertion(`<${actualTypeName}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualTypeName}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject, null, eventName, eventArgs); return expect.shift(subject); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); if (canTriggerEventsOnOutputType) { expect.addAssertion(`<${actualRenderOutputType}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, isOutputType: true }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualRenderOutputType}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, args) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: args, isOutputType: true }); } else { triggerEvent(subject, null, eventName, args); return expect.shift(subject); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); } expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <assertion?>`, function (expect, subject, eventName) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 3) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName }); } else { triggerEvent(subject.renderer, null, eventName); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject.renderer, null, eventName, eventArgs); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); }; AssertionGenerator.prototype._installWithEventOn = function (expect) { const { actualTypeName, queryTypeName, expectedTypeName, getRenderOutput, getDiffInputFromRenderOutput, triggerEvent, ActualAdapter, QueryAdapter } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion(`<${actualPendingEventTypeName}> on [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]<${queryTypeName}> <assertion?>`, function (expect, subject, target) { const actualAdapter = new ActualAdapter({ convertToString: true, concatTextContent: true }); const queryAdapter = new QueryAdapter({ convertToString: true, concatTextContent: true }); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const options = getDefaultOptions({ exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'eventTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(getRenderOutput(subject.renderer)), target, expect, options); return testHtmlLike.withResult(containsResult, result => { if (!result.found) { return expect.fail({ diff: function (output, diff, inspect) { output.error('Could not find the target for the event. '); if (result.bestMatch) { output.error('The best match was').nl().nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return output; } }); } const newSubject = Object.assign({}, subject, { target: result.bestMatch.target || result.bestMatchItem }); if (arguments.length > 3) { return expect.shift(newSubject); } else { triggerEvent(newSubject.renderer, newSubject.target, newSubject.eventName, newSubject.eventArgs); return expect.shift(newSubject.renderer); } }); }); expect.addAssertion([`<${actualPendingEventTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualPendingEventTypeName}> queried for [with all children] [with all wrappers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect.apply(expect, [subject.renderer, 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected] .concat(Array.prototype.slice.call(arguments, 3))); } ); }; AssertionGenerator.prototype._installEventHandlerAssertions = function (expect) { const { actualTypeName, expectedTypeName, triggerEvent } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion([`<${actualPendingEventTypeName}> [not] to contain [exactly] <${expectedTypeName}>`, `<${actualPendingEventTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); expect.addAssertion(`<${actualPendingEventTypeName}> to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`, function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); }; export default AssertionGenerator;
// Generated by CoffeeScript 1.7.1 (function() { var $, CSV, ES, TEXT, TRM, TYPES, alert, badge, create_readstream, debug, echo, help, info, log, njs_fs, rainbow, route, rpr, urge, warn, whisper; njs_fs = require('fs'); TYPES = require('coffeenode-types'); TEXT = require('coffeenode-text'); TRM = require('coffeenode-trm'); rpr = TRM.rpr.bind(TRM); badge = 'TIMETABLE/read-gtfs-data'; log = TRM.get_logger('plain', badge); info = TRM.get_logger('info', badge); whisper = TRM.get_logger('whisper', badge); alert = TRM.get_logger('alert', badge); debug = TRM.get_logger('debug', badge); warn = TRM.get_logger('warn', badge); help = TRM.get_logger('help', badge); urge = TRM.get_logger('urge', badge); echo = TRM.echo.bind(TRM); rainbow = TRM.rainbow.bind(TRM); create_readstream = require('../create-readstream'); /* http://c2fo.github.io/fast-csv/index.html, https://github.com/C2FO/fast-csv */ CSV = require('fast-csv'); ES = require('event-stream'); $ = ES.map.bind(ES); this.$count = function(input_stream, title) { var count; count = 0; input_stream.on('end', function() { return info((title != null ? title : 'Count') + ':', count); }); return $((function(_this) { return function(record, handler) { count += 1; return handler(null, record); }; })(this)); }; this.$skip_empty = function() { return $((function(_this) { return function(record, handler) { if (record.length === 0) { return handler(); } return handler(null, record); }; })(this)); }; this.$show = function() { return $((function(_this) { return function(record, handler) { urge(rpr(record.toString())); return handler(null, record); }; })(this)); }; this.read_trips = function(route, handler) { var input; input = CSV.fromPath(route); input.on('end', function() { log('ok: trips'); return handler(null); }); input.setMaxListeners(100); input.pipe(this.$count(input, 'trips A')).pipe(this.$show()); return null; }; if (!module.parent) { route = '/Volumes/Storage/cnd/node_modules/timetable-data/germany-berlin-2014/agency.txt'; this.read_trips(route, function(error) { if (error != null) { throw error; } return log('ok'); }); } }).call(this);
"use strict"; var request = require(__dirname + "/request"); var db = require(__dirname + "/db"); /** * Steam utils */ var steamapi = {}; /** * Request to our api * @param {string} type * @param {string[]} ids * @param {function} callback */ steamapi.request = function (type, ids, callback) { if (!ids.length) { callback({}); return; } var res = {}; var missingIds = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; var steamData = steamapi.getDataForId(type, id); if (steamData) { res[id] = steamData; } else { missingIds.push(id); } } if (missingIds.length) { request.get("https://scripts.0x.at/steamapi/api.php?action=" + type + "&ids=" + missingIds.join(","), false, function (result) { if (result !== null) { var steamData = null; var data = JSON.parse(result); if (type == "bans") { for (var i = 0; i < data.players.length; i++) { steamData = data.players[i]; steamapi.saveDataForId(type, steamData.SteamId, steamData); res[steamData.SteamId] = steamData; } } if (type == "summaries") { if(data.response){ for (var playerIndex in data.response.players) { if (data.response.players.hasOwnProperty(playerIndex)) { steamData = data.response.players[playerIndex]; steamapi.saveDataForId(type, steamData.steamid, steamData); res[steamData.steamid] = steamData; } } } } } callback(res); }); } else { callback(res); } }; /** * Get db data for steamid * @param {string} type * @param {string} id * @returns {*} */ steamapi.getDataForId = function (type, id) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData || !playerData[type]) return null; if (playerData[type].timestamp < (new Date().getTime() / 1000 - 86400)) { delete playerData[type]; } return playerData[type] || null; }; /** * Save db data for steamid * @param {string} type * @param {string} id * @param {object} data * @returns {*} */ steamapi.saveDataForId = function (type, id, data) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData) playerData = {}; data.timestamp = new Date().getTime() / 1000; playerData[type] = data; sdb.set(id, playerData).value(); }; /** * Delete old entries */ steamapi.cleanup = function () { try { var data = db.get("steamapi").value(); var timeout = new Date() / 1000 - 86400; for (var steamId in data) { if (data.hasOwnProperty(steamId)) { var entries = data[steamId]; for (var entryIndex in entries) { if (entries.hasOwnProperty(entryIndex)) { var entryRow = entries[entryIndex]; if (entryRow.timestamp < timeout) { delete entries[entryIndex]; } } } } } db.get("steamapi").setState(data); } catch (e) { console.error(new Date(), "Steamapi cleanup failed", e, e.stack); } }; // each 30 minutes cleanup the steamapi db and remove old entries setInterval(steamapi.cleanup, 30 * 60 * 1000); steamapi.cleanup(); module.exports = steamapi;
//THREEJS RELATED VARIABLES var scene, camera, fieldOfView, aspectRatio, nearPlane, farPlane, gobalLight, shadowLight, backLight, renderer, container, controls; //SCREEN & MOUSE VARIABLES var HEIGHT, WIDTH, windowHalfX, windowHalfY, mousePos = { x: 0, y: 0 }, oldMousePos = {x:0, y:0}, ballWallDepth = 28; //3D OBJECTS VARIABLES var hero; //INIT THREE JS, SCREEN AND MOUSE EVENTS function initScreenAnd3D() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; scene = new THREE.Scene(); aspectRatio = WIDTH / HEIGHT; fieldOfView = 50; nearPlane = 1; farPlane = 2000; camera = new THREE.PerspectiveCamera( fieldOfView, aspectRatio, nearPlane, farPlane ); camera.position.x = 0; camera.position.z = 300; camera.position.y = 250; camera.lookAt(new THREE.Vector3(0, 60, 0)); renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize(WIDTH, HEIGHT); renderer.shadowMapEnabled = true; container = document.getElementById('world'); container.appendChild(renderer.domElement); window.addEventListener('resize', handleWindowResize, false); document.addEventListener('mousemove', handleMouseMove, false); document.addEventListener('touchmove', handleTouchMove, false); /* controls = new THREE.OrbitControls(camera, renderer.domElement); controls.minPolarAngle = -Math.PI / 2; controls.maxPolarAngle = Math.PI / 2; controls.noZoom = true; controls.noPan = true; //*/ } function handleWindowResize() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; renderer.setSize(WIDTH, HEIGHT); camera.aspect = WIDTH / HEIGHT; camera.updateProjectionMatrix(); } function handleMouseMove(event) { mousePos = {x:event.clientX, y:event.clientY}; } function handleTouchMove(event) { if (event.touches.length == 1) { event.preventDefault(); mousePos = {x:event.touches[0].pageX, y:event.touches[0].pageY}; } } function createLights() { globalLight = new THREE.HemisphereLight(0xffffff, 0xffffff, .5) shadowLight = new THREE.DirectionalLight(0xffffff, .9); shadowLight.position.set(200, 200, 200); shadowLight.castShadow = true; shadowLight.shadowDarkness = .2; shadowLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; backLight = new THREE.DirectionalLight(0xffffff, .4); backLight.position.set(-100, 100, 100); backLight.castShadow = true; backLight.shadowDarkness = .1; backLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; scene.add(globalLight); scene.add(shadowLight); scene.add(backLight); } function createFloor(){ floor = new THREE.Mesh(new THREE.PlaneBufferGeometry(1000,1000), new THREE.MeshBasicMaterial({color: 0x004F65})); floor.rotation.x = -Math.PI/2; floor.position.y = 0; floor.receiveShadow = true; scene.add(floor); } function createHero() { hero = new Cat(); scene.add(hero.threeGroup); } function createBall() { ball = new Ball(); scene.add(ball.threeGroup); } // BALL RELATED CODE var woolNodes = 10, woolSegLength = 2, gravity = -.8, accuracy =1; Ball = function(){ var redMat = new THREE.MeshLambertMaterial ({ color: 0x630d15, shading:THREE.FlatShading }); var stringMat = new THREE.LineBasicMaterial({ color: 0x630d15, linewidth: 3 }); this.threeGroup = new THREE.Group(); this.ballRay = 8; this.verts = []; // string var stringGeom = new THREE.Geometry(); for (var i=0; i< woolNodes; i++ ){ var v = new THREE.Vector3(0, -i*woolSegLength, 0); stringGeom.vertices.push(v); var woolV = new WoolVert(); woolV.x = woolV.oldx = v.x; woolV.y = woolV.oldy = v.y; woolV.z = 0; woolV.fx = woolV.fy = 0; woolV.isRootNode = (i==0); woolV.vertex = v; if (i > 0) woolV.attach(this.verts[(i - 1)]); this.verts.push(woolV); } this.string = new THREE.Line(stringGeom, stringMat); // body var bodyGeom = new THREE.SphereGeometry(this.ballRay, 5,4); this.body = new THREE.Mesh(bodyGeom, redMat); this.body.position.y = -woolSegLength*woolNodes; var wireGeom = new THREE.TorusGeometry( this.ballRay, .5, 3, 10, Math.PI*2 ); this.wire1 = new THREE.Mesh(wireGeom, redMat); this.wire1.position.x = 1; this.wire1.rotation.x = -Math.PI/4; this.wire2 = this.wire1.clone(); this.wire2.position.y = 1; this.wire2.position.x = -1; this.wire1.rotation.x = -Math.PI/4 + .5; this.wire1.rotation.y = -Math.PI/6; this.wire3 = this.wire1.clone(); this.wire3.rotation.x = -Math.PI/2 + .3; this.wire4 = this.wire1.clone(); this.wire4.position.x = -1; this.wire4.rotation.x = -Math.PI/2 + .7; this.wire5 = this.wire1.clone(); this.wire5.position.x = 2; this.wire5.rotation.x = -Math.PI/2 + 1; this.wire6 = this.wire1.clone(); this.wire6.position.x = 2; this.wire6.position.z = 1; this.wire6.rotation.x = 1; this.wire7 = this.wire1.clone(); this.wire7.position.x = 1.5; this.wire7.rotation.x = 1.1; this.wire8 = this.wire1.clone(); this.wire8.position.x = 1; this.wire8.rotation.x = 1.3; this.wire9 = this.wire1.clone(); this.wire9.scale.set(1.2,1.1,1.1); this.wire9.rotation.z = Math.PI/2; this.wire9.rotation.y = Math.PI/2; this.wire9.position.y = 1; this.body.add(this.wire1); this.body.add(this.wire2); this.body.add(this.wire3); this.body.add(this.wire4); this.body.add(this.wire5); this.body.add(this.wire6); this.body.add(this.wire7); this.body.add(this.wire8); this.body.add(this.wire9); this.threeGroup.add(this.string); this.threeGroup.add(this.body); this.threeGroup.traverse( function ( object ) { if ( object instanceof THREE.Mesh ) { object.castShadow = true; object.receiveShadow = true; }}); } /* The next part of the code is largely inspired by this codepen : http://codepen.io/dissimulate/pen/KrAwx?editors=001 thanks to dissimulate for his great work */ /* Copyright (c) 2013 dissimulate at Codepen 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. */ WoolVert = function(){ this.x = 0; this.y = 0; this.z = 0; this.oldx = 0; this.oldy = 0; this.fx = 0; this.fy = 0; this.isRootNode = false; this.constraints = []; this.vertex = null; } WoolVert.prototype.update = function(){ var wind = 0;//.1+Math.random()*.5; this.add_force(wind, gravity); nx = this.x + ((this.x - this.oldx)*.9) + this.fx; ny = this.y + ((this.y - this.oldy)*.9) + this.fy; this.oldx = this.x; this.oldy = this.y; this.x = nx; this.y = ny; this.vertex.x = this.x; this.vertex.y = this.y; this.vertex.z = this.z; this.fy = this.fx = 0 } WoolVert.prototype.attach = function(point) { this.constraints.push(new Constraint(this, point)); }; WoolVert.prototype.add_force = function(x, y) { this.fx += x; this.fy += y; }; Constraint = function(p1, p2) { this.p1 = p1; this.p2 = p2; this.length = woolSegLength; }; Ball.prototype.update = function(posX, posY, posZ){ var i = accuracy; while (i--) { var nodesCount = woolNodes; while (nodesCount--) { var v = this.verts[nodesCount]; if (v.isRootNode) { v.x = posX; v.y = posY; v.z = posZ; } else { var constraintsCount = v.constraints.length; while (constraintsCount--) { var c = v.constraints[constraintsCount]; var diff_x = c.p1.x - c.p2.x, diff_y = c.p1.y - c.p2.y, dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y), diff = (c.length - dist) / dist; var px = diff_x * diff * .5; var py = diff_y * diff * .5; c.p1.x += px; c.p1.y += py; c.p2.x -= px; c.p2.y -= py; c.p1.z = c.p2.z = posZ; } if (nodesCount == woolNodes-1){ this.body.position.x = this.verts[nodesCount].x; this.body.position.y = this.verts[nodesCount].y; this.body.position.z = this.verts[nodesCount].z; this.body.rotation.z += (v.y <= this.ballRay)? (v.oldx-v.x)/10 : Math.min(Math.max( diff_x/2, -.1 ), .1); } } if (v.y < this.ballRay) { v.y = this.ballRay; } } } nodesCount = woolNodes; while (nodesCount--) this.verts[nodesCount].update(); this.string.geometry.verticesNeedUpdate = true; } Ball.prototype.receivePower = function(tp){ this.verts[woolNodes-1].add_force(tp.x, tp.y); } // Enf of the code inspired by dissmulate // Make everything work together : var t=0; function loop(){ render(); t+=.05; hero.updateTail(t); var ballPos = getBallPos(); ball.update(ballPos.x,ballPos.y, ballPos.z); ball.receivePower(hero.transferPower); hero.interactWithBall(ball.body.position); requestAnimationFrame(loop); } function getBallPos(){ var vector = new THREE.Vector3(); vector.set( ( mousePos.x / window.innerWidth ) * 2 - 1, - ( mousePos.y / window.innerHeight ) * 2 + 1, 0.1 ); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = (ballWallDepth - camera.position.z) / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance ) ); return pos; } function render(){ if (controls) controls.update(); renderer.render(scene, camera); } window.addEventListener('load', init, false); function init(event){ initScreenAnd3D(); createLights(); createFloor() createHero(); createBall(); loop(); }
var class_redis_cache_test = [ [ "__construct", "class_redis_cache_test.html#ae22c12eb0d136f444b6c9c0735f70382", null ], [ "testArray", "class_redis_cache_test.html#a76100cea2dba0b01bfffb70a193dfb9f", null ], [ "testGet", "class_redis_cache_test.html#afb35249bbbb21b7eac20b12d6f5a8739", null ], [ "testHas", "class_redis_cache_test.html#a8ff5d29b2ceab16b9e10aead821f3707", null ], [ "testLeveledArray", "class_redis_cache_test.html#a56c8a7551fcbda565b8f81bd9a9e3b57", null ], [ "testReinitializedGet", "class_redis_cache_test.html#addb63e1b14cdbfcdc65837dff633f7f2", null ], [ "testReinitializedHas", "class_redis_cache_test.html#a39dc99ba8e9efe29f3939ecbe99210be", null ], [ "testRemove", "class_redis_cache_test.html#a10b3034f21731f5a6507dbb5207097cf", null ] ];
import { Widget, startAppLoop, Url, History } from 'cx/ui'; import { Timing, Debug } from 'cx/util'; import { Store } from 'cx/data'; import Routes from './routes'; import 'whatwg-fetch'; import "./index.scss"; let stop; const store = new Store(); if(module.hot) { // accept itself module.hot.accept(); // remember data on dispose module.hot.dispose(function (data) { data.state = store.getData(); if (stop) stop(); }); //apply data on hot replace if (module.hot.data) store.load(module.hot.data.state); } Url.setBaseFromScript('app.js'); History.connect(store, 'url'); Widget.resetCounter(); Timing.enable('app-loop'); Debug.enable('app-data'); stop = startAppLoop(document.getElementById('app'), store, Routes);
import React from 'react'; import { default as TriggersContainer } from './TriggersContainer'; import { mount } from 'enzyme'; const emptyDispatch = () => null; const emptyActions = { setGeoJSON: () => null }; describe('(Container) TriggersContainer', () => { it('Renders a TriggersContainer', () => { const _component = mount(<TriggersContainer dispatch={emptyDispatch} actions={emptyActions} />); expect(_component.type()).to.eql(TriggersContainer); }); });
window.NavigationStore = function() { function isSet(menu) { return localStorage["navigation_" + menu] !== undefined; } function fetch(menu) { return localStorage["navigation_" + menu] == "true" || false; } function set(menu, value) { localStorage["navigation_" + menu] = value; } return { isSet: isSet, fetch: fetch, set: set } }();
import { describe, it, beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import startApp from 'my-app/tests/helpers/start-app'; import { run } from '@ember/runloop'; describe('Acceptance | foo', function () { let application; beforeEach(function () { application = startApp(); }); afterEach(function () { run(application, 'destroy'); }); it('can visit /foo', function () { visit('/foo'); return andThen(() => { expect(currentURL()).to.equal('/foo'); }); }); });
let mongoose = require('mongoose') let userSchema = mongoose.Schema({ // userModel properties here... local: { email: { type: String, required: true }, password: { type: String, required: true } }, facebook: { id: String, token: String, email: String, name: String } }) userSchema.methods.generateHash = async function(password) { return await bcrypt.promise.hash(password, 8) } userSchema.methods.validatePassword = async function(password) { return await bcrypt.promise.compare(password, this.password) } userSchema.methods.linkAccount = function(type, values) { // linkAccount('facebook', ...) => linkFacebookAccount(values) return this['link' + _.capitalize(type) + 'Account'](values) } userSchema.methods.linkLocalAccount = function({ email, password }) { throw new Error('Not Implemented.') } userSchema.methods.linkFacebookAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkTwitterAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkGoogleAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkLinkedinAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.unlinkAccount = function(type) { throw new Error('Not Implemented.') } module.exports = mongoose.model('User', userSchema)
Photos = new orion.collection('photos', { singularName: 'photo', pluralName: 'photos', link: { title: 'Photos' }, tabular: { columns: [ {data: 'title', title: 'Title'}, {data: 'state', title: 'State'}, //ToDo: Thumbnail orion.attributeColumn('markdown', 'body', 'Content'), orion.attributeColumn('createdAt', 'createdAt', 'Created At'), orion.attributeColumn('createdBy', 'createdBy', 'Created By') ] } }); Photos.attachSchema(new SimpleSchema({ title: {type: String}, state: { type: String, allowedValues: [ "draft", "published", "archived" ], label: "State" }, userId: orion.attribute('hasOne', { type: String, label: 'Author', optional: false }, { collection: Meteor.users, // the key whose value you want to show for each Post document on the Update form titleField: 'profile.name', publicationName: 'PB_Photos_Author', }), image: orion.attribute('image', { optional: true, label: 'Image' }), body: orion.attribute('markdown', { label: 'Body' }), createdBy: orion.attribute('createdBy', { label: 'Created By' }), createdAt: orion.attribute('createdAt', { label: 'Created At' }), lockedBy: { type: String, autoform: { type: 'hidden' }, optional: true } }));
import browserSync from 'browser-sync'; import config from '../../config'; import middlewaresStack from '../middlewares_stack'; import apiMiddleware from '../middlewares/api'; import mockMiddleware from '../middlewares/mock'; export default () => { const port = process.env.PORT; const middlewares = apiMiddleware() || mockMiddleware(); const server = browserSync.create(); server.init({ port, open: false, notify: false, server: { baseDir: config.distDir, middleware(req, res, next) { middlewaresStack(middlewares, req, res, next); } }, files: [ `${config.distDir}/**/*`, `!${config.distDir}/**/*.map` ] }); };
'use strict'; module.exports.name = 'cssnano/postcss-minify-font-values'; module.exports.tests = [{ message: 'should unquote font names', fixture: 'h1{font-family:"Helvetica Neue"}', expected: 'h1{font-family:Helvetica Neue}' }, { message: 'should unquote and join identifiers with a slash, if numeric', fixture: 'h1{font-family:"Bond 007"}', expected: 'h1{font-family:Bond\\ 007}' }, { message: 'should not unquote if it would produce a bigger identifier', fixture: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}', expected: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}' }, { message: 'should not unquote font names if they contain keywords', fixture: 'h1{font-family:"slab serif"}', expected: 'h1{font-family:"slab serif"}' }, { message: 'should minimise space inside a legal font name', fixture: 'h1{font-family:Lucida Grande}', expected: 'h1{font-family:Lucida Grande}' }, { message: 'should minimise space around a list of font names', fixture: 'h1{font-family:Arial, Helvetica, sans-serif}', expected: 'h1{font-family:Arial,Helvetica,sans-serif}' }, { message: 'should dedupe font family names', fixture: 'h1{font-family:Helvetica,Arial,Helvetica,sans-serif}', expected: 'h1{font-family:Helvetica,Arial,sans-serif}' }, { message: 'should discard the rest of the declaration after a keyword', fixture: 'h1{font-family:Arial,sans-serif,Arial,"Trebuchet MS"}', expected: 'h1{font-family:Arial,sans-serif}' }, { message: 'should convert the font shorthand property', fixture: 'h1{font:italic small-caps normal 13px/150% "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/150% Helvetica Neue,sans-serif}' }, { message: 'should convert shorthand with zero unit line height', fixture: 'h1{font:italic small-caps normal 13px/1.5 "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/1.5 Helvetica Neue,sans-serif}', }, { message: 'should convert the font shorthand property, unquoted', fixture: 'h1{font:italic Helvetica Neue,sans-serif,Arial}', expected: 'h1{font:italic Helvetica Neue,sans-serif}' }, { message: 'should join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007",sans-serif}', expected: 'h1{font:italic Bond\\ 007,sans-serif}' }, { message: 'should join non-digit identifiers in the shorthand property', fixture: 'h1{font:italic "Bond !",serif}', expected: 'h1{font:italic Bond\\ !,serif}' }, { message: 'should correctly escape special characters at the start', fixture: 'h1{font-family:"$42"}', expected: 'h1{font-family:\\$42}' }, { message: 'should not escape legal characters', fixture: 'h1{font-family:€42}', expected: 'h1{font-family:€42}', options: {normalizeCharset: false} }, { message: 'should not join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007 008 009",sans-serif}', expected: 'h1{font:italic "Bond 007 008 009",sans-serif}' }, { message: 'should escape special characters if unquoting', fixture: 'h1{font-family:"Ahem!"}', expected: 'h1{font-family:Ahem\\!}' }, { message: 'should not escape multiple special characters', fixture: 'h1{font-family:"Ahem!!"}', expected: 'h1{font-family:"Ahem!!"}' }, { message: 'should not mangle legal unquoted values', fixture: 'h1{font-family:\\$42}', expected: 'h1{font-family:\\$42}' }, { message: 'should not mangle font names', fixture: 'h1{font-family:Glyphicons Halflings}', expected: 'h1{font-family:Glyphicons Halflings}' }];
function Tw2VectorSequencer() { this.name = ''; this.start = 0; this.value = vec3.create(); this.operator = 0; this.functions = []; this._tempValue = vec3.create(); } Tw2VectorSequencer.prototype.GetLength = function () { var length = 0; for (var i = 0; i < this.functions.length; ++i) { if ('GetLength' in this.functions[i]) { length = Math.max(length, this.functions[i].GetLength()); } } return length; } Tw2VectorSequencer.prototype.UpdateValue = function (t) { this.GetValueAt(t, this.value); } Tw2VectorSequencer.prototype.GetValueAt = function (t, value) { if (this.operator == 0) { value[0] = 1; value[1] = 1; value[2] = 1; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] *= tempValue[0]; value[1] *= tempValue[1]; value[2] *= tempValue[2]; } } else { value[0] = 0; value[1] = 0; value[2] = 0; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] += tempValue[0]; value[1] += tempValue[1]; value[2] += tempValue[2]; } } return value; }
// Include gulp var gulp = require('gulp'); // Include Our Plugins var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var header = require('gulp-header'); var footer = require('gulp-footer'); // Build Task gulp.task('default', function() { gulp.src([ "src/promises.js", "src/util.js", "src/request.js", "src/legends.js", "src/static.js" ]) .pipe(concat('legends.js', { newLine: "\n\n" })) .pipe(header("/*!\n" + " * Legends.js\n" + " * Copyright (c) {{year}} Tyler Johnson\n" + " * MIT License\n" + " */\n\n" + "(function() {\n")) .pipe(footer("\n// API Factory\n" + "if (typeof module === \"object\" && module.exports != null) {\n" + "\tmodule.exports = Legends;\n" + "} else if (typeof window != \"undefined\") {\n" + "\twindow.Legends = Legends;\n" + "}\n\n" + "})();")) .pipe(gulp.dest('./dist')) .pipe(rename('legends.min.js')) .pipe(uglify({ output: { comments: /^!/i } })) .pipe(gulp.dest('./dist')); });
var myTimeout = 12000; Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { var value = this.getItem(key); return value && JSON.parse(value); }; // Обеспечиваем поддержу XMLHttpRequest`а в IE var xmlVersions = new Array( "Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ); if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() { for(var i in xmlVersions) { try { return new ActiveXObject(xmlVersions[i]); } catch(e) {} } throw new Error( "This browser does not support XMLHttpRequest." ); }; // Собственно, сам наш обработчик. function myErrHandler(message, url, line) { var tmp = window.location.toString().split("/"); var server_url = tmp[0] + '//' + tmp[2]; var params = "logJSErr=logJSErr&message="+message+'&url='+url+'&line='+line; var req = new XMLHttpRequest(); req.open('POST', server_url+'/jslogerror?ajax=1', true); req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); req.setRequestHeader("Content-length", params.length); req.setRequestHeader("Connection", "close"); req.send(params); // Чтобы подавить стандартный диалог ошибки JavaScript, // функция должна возвратить true return true; } // window.onerror = myErrHandler; //назначаем обработчик для события onerror // ПОТОМ ВКЛЮЧИТЬ window.onerror = myErrHandler; function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function nl2br(str) { return str.replace(/([^>])\n/g, '$1<br>'); } function htmlspecialchars(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
/*! YAD - v1.0.0 - 82bbc70 - 2014-12-02 * Yahoo Personalised Content Widget * Copyright (c) 2014 ; Licensed */ (function(){var f=window.document,e={Error:function(a){this.message=a},Bootstrap:function(a,b,c){this.widgetInitialisationStartedAt=this.timeSinceNavigationStart();this.snippetLoadedAt=c?this.timeSinceNavigationStart(c):null;this.config=b;this.publisherId=a;this.config.analytics||(this.config.analytics={});this.id=this.config.id;this.config.analytics.pageURL=e.Helper.detectPageURL();this.config.analytics.referrer=e.Helper.detectReferrer();this.config.analytics.click_postmsg={payload:{action:"redirect", id:this.id}};this.config.canonicalURL=e.Helper.detectCanonical();this.init()}};e.Bootstrap.prototype={init:function(){this.element="undefined"!==typeof this.config.element?this.config.element:e.Helper.detectScriptTag();delete this.config.element;var a=this.iframeURL();this.iframe=this.createIframeElement(a);var b=this;window.addEventListener?this.iframe.addEventListener("load",function(){b.sendPostMessage({action:"init",config:b.config,id:b.id,url:e.Helper.detectPageURL(),tti:b.widgetInitialisationStartedAt, tts:b.snippetLoadedAt,cid:b.publisherId})}):window.attachEvent&&this.iframe.attachEvent("onload",function(){b.sendPostMessage({action:"init",config:b.config,id:b.id,url:e.Helper.detectPageURL(),tti:b.widgetInitialisationStartedAt,tts:b.snippetLoadedAt,cid:b.publisherId})});this.listen();this.render()},listenForViewport:function(){var a=this,b=null,c=null,d=function(d){return function(){var e=a.isElementInViewport(d,0);e&&!a.hasBeenInViewport&&(a.hasBeenInViewport=!0,a.sendPostMessage({action:"inViewport"})); if(e){var f=function(){var b=a.iframeRelativeScrollPosition(d);a.sendPostMessage({action:"scroll",scrollTop:b[0],scrollLeft:b[1],height:a.iframeRelativeHeight(d),width:a.iframeRelativeWidth(d)})};window.clearTimeout(b);b=window.setTimeout(function(){window.clearInterval(c);f();c=null},350);null===c&&(c=window.setInterval(f,500),f())}}}(this.iframe);window.addEventListener?(window.addEventListener("DOMContentLoaded",d,!1),window.addEventListener("load",d,!1),window.addEventListener("scroll",d,!1), window.addEventListener("resize",d,!1)):window.attachEvent&&(window.attachEvent("DOMContentLoaded",d),window.attachEvent("onload",d),window.attachEvent("onscroll",d),window.attachEvent("onresize",d));d()},iframeURL:function(){return e.Bootstrap.IFRAME_URL},createIframeElement:function(a){var b=f.createElement("iframe");b.frameBorder=0;b.width="100%";b.height="0";b.setAttribute("style","display:block");b.setAttribute("src",a);b.setAttribute("allowtransparency",!0);return b},sendPostMessage:function(a){return e.PostMessage.send(a, e.Bootstrap.IFRAME_DOMAIN,this.iframe.contentWindow)},listen:function(){e.PostMessage.listen(this.onReceivePostMessage,e.Bootstrap.IFRAME_DOMAIN,this)},render:function(){this.element.appendChild(this.iframe)},onReceivePostMessage:function(a){if(a.id===this.id)switch(a.action){case "data":this.listenForViewport();break;case "height":this.setHeight(a.height);break;case "redirect":this.redirect(a.href);break;case "hide":this.hide();break;case "error":this.config.onError&&"function"===typeof this.config.onError&& this.config.onError.apply(this,[Error("widget failed to load")]);break;case "about":e.Lightbox.About()}},hide:function(){this.iframe&&(this.iframe.style.display="none");this.element&&this.element.setAttribute("class",this.element.getAttribute("class")+" yad-empty")},redirect:function(a){window.location=a},setHeight:function(a){this.iframe.height=a+"px"},isElementInViewport:function(a,b){"undefined"===typeof b&&(b=0);var c,d;"undefined"!==typeof window.pageXOffset?c=window.pageXOffset:f.documentElement&& "undefined"!==typeof f.documentElement.scrollLeft?c=f.documentElement.scrollLeft:"undefined"!==typeof f.body.scrollLeft&&(c=f.body.scrollLeft);"undefined"!==typeof window.pageYOffset?d=window.pageYOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollTop?d=f.documentElement.scrollTop:"undefined"!==typeof f.body.scrollTop&&(d=f.body.scrollTop);var e,g;g=e=0;e="undefined"!==typeof window.innerWidth?window.innerWidth:f.documentElement.clientWidth;g="undefined"!==typeof window.innerHeight? window.innerHeight:f.documentElement.clientHeight;e=c+e;g=d+g;var h=b,k=a.getBoundingClientRect(),l=k.right-k.left,n=k.bottom-k.top,m=k.top+d,k=k.left+c,p,q;p=k+l*(1-h);q=m+n*(1-h);return!(e<k+l*h||c>p||g<m+n*h||d>q)},iframeRelativeHeight:function(a){var b=a.getBoundingClientRect(),c=b.top,d=window.innerHeight||f.documentElement.clientHeight;a=a.scrollTop;b=b.bottom-b.top;return c<a&&b-a>=d?d:c<a?Math.max(0,b-(a-c)):c>a&&c+b<d?b:Math.max(0,d-(c-a))},iframeRelativeWidth:function(a){var b=a.getBoundingClientRect(), c=b.left,d=window.innerWidth||f.documentElement.clientWidth;a=a.scrollLeft;b=b.right-b.left;return c<a&&b-a>=d?d:c<a?Math.max(0,b-(a-c)):c>a&&c+b<d?b:Math.max(0,d-(c-a))},iframeRelativeScrollPosition:function(a){a=a.getBoundingClientRect();var b=-1*a.top,c=-1*a.left;0<a.left&&(c=0);0<a.top&&(b=0);return 0>b||0>c?[0,0]:[Math.max(0,b),Math.max(0,c)]},timeSinceNavigationStart:function(a){if("undefined"===typeof window.performance)return!1;a||(a=(new Date).getTime());return a-window.performance.timing.domLoading}}; e.Helper={templateShortname:function(a){switch(a){case "single-column-text":return"sctext";case "single-column-thumbnail":return"scthumb";case "dual-column-thumbnail":return"dcthumb";case "dual-column-text":return"dctext";case "dual-column-text-web":return"dcwtext";case "dual-column-thumbnail-web":return"dcwthumb";case "single-row-carousel":return"srcarousel";case "dual-row-carousel":return"drcarousel";case "dual-row-carousel-web":return"drwcarousel";case "instrumentation-beacon":return"insbeacon"; case "error":return"error";default:throw new e.Error("Could not get shortname for template: "+a);}},addClass:function(a,b){var c,d=a instanceof Array?a:[a];for(c=0;c<d.length;c++)e.Helper._addClass(d[c],b)},_addClass:function(a,b){a.classList?a.classList.add(b):e.Helper.containClass(a,b)||(a.className+=" "+b)},removeClass:function(a,b){var c,d=a instanceof Array?a:[a];for(c=0;c<d.length;c++)e.Helper._removeClass(d[c],b)},_removeClass:function(a,b){var c=RegExp("(\\s|^)"+b+"(\\s|$)","g");a.classList? a.classList.remove(b):a.className=a.className.replace(c," ").replace(/\s\s+/g," ")},replaceClass:function(a,b,c){var d=a instanceof Array?a:[a];for(a=0;a<d.length;a++)e.Helper._removeClass(d[a],b),e.Helper._addClass(d[a],c)},toggleClass:function(a,b,c){var d=a instanceof Array?a:[a];for(a=0;a<d.length;a++)!0===c?e.Helper._addClass(d[a],b):!1===c?e.Helper._removeClass(d[a],b):e.Helper.containClass(d[a],b)?e.Helper._removeClass(d[a],b):e.Helper._addClass(d[a],b)},containClass:function(a,b){var c=RegExp("(\\s|^)"+ b+"(\\s|$)");return a.classList?a.classList.contains(b):c.test(a.className)},getEventListenerCompatible:function(){return f.createElement("div").addEventListener?!0:!1},bind:function(a,b,c,d,f){if(!a)throw new e.Error("Valid event not supplied");if(!b)throw new e.Error("Valid element not supplied");if(!c)throw new e.Error("Valid callback not supplied");f=f||[];a=a.split(" ");for(var g=0;g<a.length;g++)e.Helper._addEventListener(a[g],b,c,d,f)},unbind:function(a,b,c){if(!a)throw new e.Error("Valid event not supplied"); if(!b)throw new e.Error("Valid element not supplied");if(!c)throw new e.Error("Valid callback not supplied");a=a.split(" ");for(var d=0;d<a.length;d++)e.Helper._removeEventListener(a[d],b,c)},bindCustom:function(a,b,c,d,f){if(b.addEventListener)return e.Helper.bind(a,b,c,d,f);b[a]=0;return e.Helper.bind("propertychange",b,function(b){b.propertyName===a&&c.call(this,Array.prototype.slice.call(arguments,1))},d,f)},bindAll:function(a,b,c,d,f){if(b)for(var g=b.length-1;0<=g;g-=1)e.Helper.bind(a,b[g], c,d,f)},_addEventListener:function(a,b,c,d,f){if(b.addEventListener)b.addEventListener(a,function(a){a.preventDefault||(a.preventDefault=function(){this.returnValue=!1});c.apply(d,[a].concat(f))},!1);else if(b.attachEvent)b.attachEvent("on"+a,function(a){a.preventDefault||(a.preventDefault=function(){this.returnValue=!1});c.apply(d,[a].concat(f))});else throw new e.Error("Tried to bind event to incompatible object. Object needs addEventListener (or attachEvent).");},_removeEventListener:function(a, b,c){if(b.removeEventListener)b.removeEventListener(a,c,!1);else if(b.detachEvent)b.detachEvent("on"+a,c);else throw new e.Error("Tried to bind event to incompatible object. Object needs removeEventListener (or detachEvent).");},dispatchEvent:function(a,b,c){var d;f.createEvent?(d=f.createEvent("HTMLEvents"),d.initEvent(b,!0,!0)):f.createEventObject&&(d=f.createEventObject(),d.eventType=b);if(!d)throw new e.Error("dispatchEvent could not create click event");for(var r in c)c.hasOwnProperty(r)&&(d[r]= c[r]);d.eventName=b;if(a.dispatchEvent)a.dispatchEvent(d);else if(a.fireEvent)switch(d.eventType){case "click":case "mousedown":case "mouseover":a.fireEvent("on"+d.eventType,d);break;default:a[d.eventType]=d}else if(a[b])a[b](d);else if(a["on"+b])a["on"+b](d)},createElement:function(a){return f.createElement(a)},addScript:function(a,b,c){return e.Helper.Ajax.addScript(a,b,c)},isVisible:function(a){return a===f?!0:a&&a.parentNode&&"none"!==e.Helper.getComputedStyleCssProperty(a,"display")&&"hidden"!== e.Helper.getComputedStyleCssProperty(a,"visibility")?e.Helper.isVisible(a.parentNode):!1},getOuterHeight:function(a){var b=e.Helper.getComputedStyleCssProperty(a,"margin-top"),c=e.Helper.getComputedStyleCssProperty(a,"margin-bottom");try{b=parseInt(b,10),c=parseInt(c,10)}catch(d){c=b=0}return a.offsetHeight+b+c},getComputedStyleCssProperty:function(a,b){var c;if(window.getComputedStyle)return window.getComputedStyle(a).getPropertyValue(b);c=e.Helper._getCamelCasedCssProperty(b);return a.currentStyle? a.currentStyle[c]:a.style[c]},_getCamelCasedCssProperty:function(a){return a.replace(/-([a-z])/g,function(a){return a[1].toUpperCase()})},truncateString:function(a,b){if("undefined"===typeof a)return"";if(void 0===b||a.length<b)return a;if(0>=b)return"";var c=a.substring(0,b-1),d=c.lastIndexOf(" ");d<b&&-1!==d&&(c=c.substr(0,Math.min(c.length,d)));return c+"\u2026"},htmlEntities:function(a){return String(a).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g, "&gt;").replace(/\//g,"&#x2F;").replace(/`/g,"&#x60;")},fragmentFromString:function(a){var b=f.createDocumentFragment(),c=f.createElement("body");for(c.innerHTML=a;null!==(a=c.firstChild);)b.appendChild(a);return b},stringFromFragment:function(a){var b=f.createElement("div");b.appendChild(a);return b.innerHTML},template:function(a,b){var c,d=0,f=[];for(c in b)if(b.hasOwnProperty(c)){var g=b[c];if(this.isDocumentFragment(g)){var h="yad-template-fragment-"+d;f.push([h,g]);g='<span id="'+h+'"></span>'; d++}a=a.split("{{"+c.toUpperCase()+"}}").join(g)}c=e.Helper.fragmentFromString(a);for(d=0;d<f.length;d++)g=c.querySelector("#"+f[d][0]),g.parentNode.replaceChild(f[d][1],g);return c},isDocumentFragment:function(a){try{return"undefined"!==typeof DocumentFragment&&a instanceof DocumentFragment||"undefined"!==typeof HTMLDocument&&a instanceof HTMLDocument}catch(b){return"string"!==typeof a&&"number"!==typeof a}},merge:function(a,b){for(var c in b)b[c]&&b[c].constructor&&b[c].constructor===Object?(a[c]= a[c]||{},e.Helper.merge(a[c],b[c])):a[c]=b[c];return a},clone:function(a){return JSON.parse(JSON.stringify(a))},addStyleTag:function(a){var b=e.Helper.createElement("style");b.setAttribute("type","text/css");b.styleSheet?(f.getElementsByTagName("head")[0].appendChild(b),b.styleSheet.cssText=a):(b.innerHTML=a,f.getElementsByTagName("head")[0].appendChild(b))},addLinkTag:function(a){var b,c=e.Helper.createElement("link");for(b in a)a.hasOwnProperty(b)&&c.setAttribute(b,a[b]);f.getElementsByTagName("head")[0].appendChild(c)}, addDynamicCSS:function(a){var b,c={rel:"stylesheet",type:"text/css"},d;a.hasConfigCSS()&&e.Helper.addStyleTag("/* config CSS */ "+a.getConfigCSS());if(a.hasCSSURLs())for(b=a.getCSSURLs(),d=0;d<b.length;d++)c.href=b[d],e.Helper.addLinkTag(c);a.hasCustomCSS()&&e.Helper.addStyleTag("/* custom CSS */ "+a.getCustomCSS())},isElementInViewport:function(a,b,c,d,e,g){"undefined"===typeof b&&(b=0);var h,k;"undefined"!==typeof window.pageXOffset?h=window.pageXOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollLeft? h=f.documentElement.scrollLeft:"undefined"!==typeof f.body.scrollLeft&&(h=f.body.scrollLeft);"undefined"!==typeof window.pageYOffset?k=window.pageYOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollTop?k=f.documentElement.scrollTop:"undefined"!==typeof f.body.scrollTop&&(k=f.body.scrollTop);var l=0,n=0,l="undefined"!==typeof e?e:"undefined"!==typeof window.innerWidth?window.innerWidth:f.documentElement.clientWidth,n="undefined"!==typeof g?g:"undefined"!==typeof window.innerHeight? window.innerHeight:f.documentElement.clientHeight;c=c?c:k;d=d?d:h;l=d+l;n=c+n;g=a.getBoundingClientRect();a=g.right-g.left;h=g.bottom-g.top;e=g.top;g=g.left;var m;k=g+a*(1-b);m=e+h*(1-b);return!(l<g+a*b||d>k||n<e+h*b||c>m)},arrayIndexOf:function(a,b){if(Array.prototype.indexOf)return b.indexOf(a);var c=b.length>>>0,d=0;Infinity===Math.abs(d)&&(d=0);0>d&&(d+=c,0>d&&(d=0));for(;d<c;d++)if(b[d]===a)return d;return-1},detectPageURL:function(){return window.location.href},detectReferrer:function(){return window.document.referrer}, detectCanonical:function(){var a=f.querySelector("link[rel='canonical']");return a?a.href:!1},detectScriptTag:function(){var a=f.querySelectorAll("script");if(!a)throw new e.Error("No script tags could be found on the page");return a[a.length-1]},getRSSUrls:function(){var a=f.querySelectorAll('link[type="application/rss+xml"]'),b,c=[];if(a){for(b=0;b<a.length;b+=1)a[b].getAttribute("href")&&c.push(a[b].getAttribute("href"));return c}},getDocumentHeight:function(a){return a.documentElement.scrollHeight}, timestamp:function(){return Math.floor((new Date).valueOf()/1E3)},urlencode:function(a){return window.encodeURIComponent(a)},stripProtocol:function(a){var b=a.split("://");return 1<b.length?b[1]:a},applyEllipsis:function(a,b){a.textContent=b&&b.replace?b.replace(/\s+$/g,"")+"\u2026":""},computeStyle:function(a,b){return window.getComputedStyle?window.getComputedStyle(a,null).getPropertyValue(b):!1},getLineHeight:function(a){var b=this.computeStyle(a,"line-height");"normal"===b&&(b=Math.ceil(1.2*parseFloat(this.computeStyle(a, "font-size"),10)));return parseFloat(b,10)},getMaxHeight:function(a,b){return this.getLineHeight(b)*a},getLastChild:function(a,b){if(a.lastChild.children&&0<a.lastChild.children.length)return this.getLastChild(Array.prototype.slice.call(a.children).pop(),b);if(a.lastChild&&""!==a.lastChild.nodeValue)return a.lastChild;a.lastChild.parentNode.removeChild(a.lastChild);return this.getLastChild(b,b)},truncateToHeight:function(a,b,c,d){if(b&&!(0>=b)){var e=a.textContent.replace("\u2026",""),g=d.element, f=d.splitOnChars,k=d.splitChar,l=d.chunks,n=d.lastChunk;l||(k=0<f.length?f.shift():"",l=e.split(k));1<l.length?(n=l.pop(),this.applyEllipsis(a,l.join(k))):l=null;if(l){if(g.clientHeight&&g.clientHeight<=b||g.offsetHeight&&g.offsetHeight<=b)if(0<=f.length&&""!==k)this.applyEllipsis(a,l.join(k)+k+n);else return!1}else""===k&&(this.applyEllipsis(a,""),a=this.getLastChild(g,g),d.splitOnChars=c.slice(0),d.splitChar=d.splitOnChars[0],d.chunks=null,d.lastChunk=null);this.truncateToHeight(a,b,c,d)}},clamp:function(a, b){b=b||{};if(!("undefined"!==typeof b.clamp&&1>b.clamp)){var c={clamp:b.clamp||2,splitOnChars:b.splitOnChars||[".","-"," "]},d=c.splitOnChars.slice(0),e=d[0],c=this.getMaxHeight(c.clamp,a);(a.clientHeight&&c<a.clientHeight||a.offsetHeight&&c<a.offsetHeight)&&this.truncateToHeight(this.getLastChild(a,a),c,d,{element:a,splitOnChars:d,splitChar:e,chunks:null,lastChunk:null})}},clampTitle:function(a,b,c){if(!(1>c)&&!1!==c&&window.getComputedStyle)for(a=a.querySelectorAll(b),b=0;b<a.length;b++)this.clamp(a[b], {clamp:c})}};e.PostMessage={lastHeight:null,send:function(a,b,c){if("undefined"===typeof b)throw new e.Error("You must supply a target as a string");"undefined"===typeof c&&(c=window.parent);c.postMessage(e.PostMessage._serialize(a),b)},listen:function(a,b,c){if("undefined"===typeof b)throw new e.Error("You must supply an origin or an array of origins");var d=function(d){if("*"!==b&&b!==d.origin)return!1;a.call(c,e.PostMessage._unserialize(d.data),d.origin,d.source)};window.addEventListener?window.addEventListener("message", d,!1):window.attachEvent("onmessage",d)},sendHeight:function(a,b,c){e.PostMessage._sendUpdateHeightMessage(a,b,c);window.setInterval(function(){e.PostMessage._sendUpdateHeightMessage(a,b,c)},1E3)},_sendUpdateHeightMessage:function(a,b,c){var d=e.Helper.getDocumentHeight(f);e.PostMessage.lastHeight!==d&&(void 0===c&&(c={}),c.action="height",c.height=d,e.PostMessage.send(c,a,b),e.PostMessage.lastHeight=d)},_unserialize:function(a){var b=null;if("string"===typeof a){try{b=JSON.parse(a)}catch(c){}return b}return a}, _serialize:function(a){return JSON.stringify(a)}};e.Lightbox=function(){this.init()};e.Lightbox.MASK_STYLE="position:fixed;top:0;left:0;z-index:99999;background-color:#000;background-color:rgba(0,0,0,0.5);width:100%;height:100%;";e.Lightbox.CONTENT_STYLE='position:relative;margin:0 auto;top:10%;z-index:999999;background-color:#fff;width:100%;min-height:100px;max-height:80%;overflow:auto;width:400px;max-width:90%;border-radius: 5px;box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.55);"';e.Lightbox.CLOSE_STYLE= "position:absolute;right:0;top:0;padding:5px;cursor:pointer;text-decoration:none;color: #5f5f5f;line-height: 6px;text-align:center;margin: 6px;font-size: 22px;";e.Lightbox.About=function(){var a=new e.Lightbox;a.setContent("<iframe src='"+e.Lightbox.ABOUT_IFRAME_URL+"' style='width:100%;height:300px' frameborder='0'></iframe>");a.show();return a};e.Lightbox.prototype={init:function(){this.lightboxContent=""},show:function(){this.exists()?this.container().style.display="block":(this.create(),this.show())}, hide:function(){this.exists()&&(this.container().style.display="none")},create:function(){this.createMask();this.createContentPane();this.createCloseButton();this.bindClose()},createMask:function(){var a=f.createElement("div");a.setAttribute("class","yad-lightbox");a.setAttribute("style",e.Lightbox.MASK_STYLE);a.style.display="none";f.getElementsByTagName("body")[0].appendChild(a);return this.containerDiv=a},createContentPane:function(){var a=f.createElement("div");a.setAttribute("class","yad-lightbox-content"); a.setAttribute("style",e.Lightbox.CONTENT_STYLE);this.container().appendChild(a);this.lightboxContent&&"string"===typeof this.lightboxContent?a.innerHTML=this.lightboxContent:this.lightboxContent&&a.appendChild(this.lightboxContent);return this.contentPane=a},createCloseButton:function(){var a=f.createElement("a");a.setAttribute("class","yad-lightbox-close");a.setAttribute("style",e.Lightbox.CLOSE_STYLE);a.innerHTML="\u00d7";this.contentPane.appendChild(a);return a},bindClose:function(){var a=this; window.addEventListener?(this.container().addEventListener("click",function(b){b.target===a.container()&&a.closeHandler.call(a)},!1),this.container().querySelector(".yad-lightbox-close").addEventListener("click",function(){a.closeHandler.call(a)}),window.addEventListener("keydown",function(b){27===b.keyCode&&a.closeHandler.call(a)},!1)):window.attachEvent&&(this.container().attachEvent("onclick",function(b){b.target===a.container()&&a.closeHandler.call(a)},!1),this.container().querySelector(".yad-lightbox-close").attachEvent("onclick", function(){a.closeHandler.call(a)}),window.attachEvent("onkeydown",function(b){27===b.keyCode&&a.closeHandler.call(a)},!1))},closeHandler:function(){this.hide()},container:function(){return this.containerDiv},exists:function(){return!!this.container()},setContent:function(a){this.lightboxContent=a}};e.Helper=e.Helper||{};e.Helper.Ajax={JSONPCallbacks:{},timeouts:{},AJAX_TIMEOUT:1E3,ajax:function(a,b,c,d,f){return e.Helper.Ajax.jsonp(a,b,c,d,f)},xhr:function(a,b,c,d,e){var f=new XMLHttpRequest;f.onreadystatechange= function(){4>f.readyState||200===f.status&&4===f.readyState&&c.call(e,f)};f.open("GET",a,!0);try{f.send("")}catch(h){"function"===typeof d&&d(h)}},jsonp:function(a,b,c,d,f){var g=(new Date).getTime(),h,k={},l;b&&b.publisher_url_params&&(h=b.publisher_url_params,delete b.publisher_url_params);b&&(a+=(-1<a.indexOf("?")?"&":"?")+e.Helper.Ajax.urlencode(b));if(h){for(l in h)if(h.hasOwnProperty(l))if("string"===typeof h[l]||"number"===typeof h[l]||"boolean"===typeof h[l])k[l]=h[l];else if("undefined"=== typeof h[l]||null===h[l])k[l]=null;a+=(-1<a.indexOf("?")?"&":"?")+"publisher_url_params="+encodeURIComponent(JSON.stringify(k))}a=a+(-1<a.indexOf("?")?"&":"?")+"callback="+("YADJSONPCallbacks.receiveCallback_"+g);e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]=function(a){window.clearTimeout(e.Helper.Ajax.timeouts[g]);a&&a.error&&d?d.call(f,a):a&&a.error?console.error("JSONP called returned an error, but there was no handler provided."):c&&c.call(f,a);delete e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+ g]};b=setTimeout(function(){e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]=function(){delete e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]};d&&d.call(f,{error:!0,isTimeout:!0})},e.Helper.Ajax.AJAX_TIMEOUT);e.Helper.Ajax.timeouts[g]=b;e.Helper.Ajax.addScript(a)},createElement:function(a){return f.createElement(a)},addScript:function(a,b,c){var d=e.Helper.Ajax.createElement("script"),m=f.getElementsByTagName("head")[0],g=!1;d.type="text/javascript";d.src=a;b&&(d.onload=d.onreadystatechange= function(){g||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(g=!0,d.onload=d.onreadystatechange=null,b.call(c))});m.insertBefore(d,m.firstChild)},urlencode:function(a,b){var c=[],d,f,g;for(d in a)if(a.hasOwnProperty(d))switch(f=b&&a instanceof Array?b+"[]":b?b+"["+d+"]":d,g=a[d],typeof g){case "object":g instanceof Array&&!(0<g.length)||c.push(e.Helper.Ajax.urlencode(g,f));break;default:c.push(encodeURIComponent(f)+"="+encodeURIComponent(g))}return c.join("&")},generateRequestID:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(a){var b=16*Math.random()|0;return("x"===a?b:b&3|8).toString(16)})}};window.YADJSONPCallbacks=window.YADJSONPCallbacks||e.Helper.Ajax.JSONPCallbacks;e.Bootstrap.IFRAME_DOMAIN="https://s.yimg.com";e.Bootstrap.LOG_PATH="//syndication.streamads.yahoo.com/na_stream_brewer/error/v1";e.Bootstrap.IFRAME_URL=e.Bootstrap.IFRAME_DOMAIN+"/uq/syndication/yad-iframe.82bbc70.html";e.Lightbox.ABOUT_IFRAME_URL=e.Bootstrap.IFRAME_DOMAIN+"/uq/syndication/yad-about.html";if("undefined"===typeof window.yad|| !window.yad.initialized){var t="undefined"!==typeof window.yad&&"undefined"!==typeof window.yad.q?window.yad.q:[],q=[],p={},s={};window.yad=function(a,b,c){b=b||{};var d=b.debug&&window.console&&window.console.error,m=null,g=window.location&&window.location.pathname+window.location.search;g?(s[g]||(s[g]=e.Helper.Ajax.generateRequestID()),g=s[g]):g=e.Helper.Ajax.generateRequestID();try{"undefined"===typeof p[a]&&(p[a]=0);b.element||(b.element=f.querySelectorAll(".YAD-"+a)[p[a]]);b.element||(b.element= f.querySelectorAll(".YAD")[q.length]);if(!b.element)throw new e.Error("Element with index #"+q.length+" not found");b.id=window.yad.i;b.pageviewID=g;m=new e.Bootstrap(a,b,c);q.push(m);p[a]+=1;window.yad.i++}catch(h){m&&m.hide();try{e.Helper.Ajax.ajax(e.Bootstrap.LOG_PATH,{exception:h.message,type:"Bootstrap",cid:a,pvid:g,url:window.location&&window.location.href})}catch(k){d&&window.console.error("YAD: Unable to send following message to log due to "+k.message)}if(d)if(h instanceof e.Error)window.console.error("YAD: "+ h.message);else throw h;}};window.yad.initialized=!0;window.yad.i=1;for(var m;t&&(m=t.shift());)"string"===typeof m[0]?window.yad(m[0],m[1]):(m[0]instanceof Array||m[0]instanceof Object)&&window.yad(m[0][0],m[0][1],m[1])}e.VERSION="82bbc70"})();
/** * grunt-webfont: fontforge engine * * @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py * @author Artem Sapegin (http://sapegin.me) */ module.exports = function(o, allDone) { 'use strict'; var fs = require('fs'); var path = require('path'); var temp = require('temp'); var async = require('async'); var glob = require('glob'); var exec = require('exec'); var chalk = require('chalk'); var _ = require('lodash'); var logger = o.logger || require('winston'); var wf = require('../util/util'); // Copy source files to temporary directory var tempDir = temp.mkdirSync(); o.files.forEach(function(file) { fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file)); }); // Run Fontforge var args = [ 'fontforge', '-script', path.join(__dirname, 'fontforge/generate.py') ]; var proc = exec(args, function(err, out, code) { if (err instanceof Error && err.code === 'ENOENT') { return error('fontforge not found. Please install fontforge and all other requirements.'); } else if (err) { if (err instanceof Error) { return error(err.message); } // Skip some fontforge output such as copyrights. Show warnings only when no font files was created // or in verbose mode. var success = !!generatedFontFiles(); var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/; var lines = err.split('\n'); var warn = []; lines.forEach(function(line) { if (!line.match(notError) && !success) { warn.push(line); } else { logger.verbose(chalk.grey('fontforge: ') + line); } }); if (warn.length) { return error(warn.join('\n')); } } // Trim fontforge result var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, ''); // Parse json var result; try { result = JSON.parse(json); } catch (e) { return error('Webfont did not receive a proper JSON result.\n' + e + '\n' + out); } allDone({ fontName: path.basename(result.file) }); }); // Send JSON with params if (!proc) return; var params = _.extend(o, { inputDir: tempDir }); proc.stdin.write(JSON.stringify(params)); proc.stdin.end(); function generatedFontFiles() { return glob.sync(path.join(o.dest, o.fontBaseName + wf.fontFileMask)); } function error() { logger.error.apply(null, arguments); allDone(false); return false; } };
'use strict'; var fs = require('fs'), path = require('path'); // path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux // path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/ // path.parse('/home/user/dir/file.txt') // returns // { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } var walk = function(dir, done){ var results = {}; fs.readdir(dir, function(err, list){ if (err) { return done(err); } var pending = list.length; if (!pending) { return done(null, results); } list.forEach(function(layer){ var target = path.resolve(dir, layer); fs.stat(target, function(err, stat){ if (stat && stat.isDirectory()) { console.log(layer); results[layer] = []; walk(target, function(err, file){ console.log(file); if (!--pending) { done(null, results); } }); } else { var file = path.basename(target); if (file[0] === '_') { // results[layer][].push(file); null; } if (!--pending) { done(null, results); } } }); }); }); }; var walking = function(config, done){ var results = {}; var pending = config.layers.length; config.layers.forEach(function(layer){ results[layer] = []; if (!pending) { return done(null, results); } fs.readdir(config.src.scss + '/' + layer, function(err, files){ if (err) { return 'error #1'; } files.forEach(function(file){ if (file[0] !== '.') { if (file[0] !== '_') { results[layer].push(file); } else { results[layer].push(file.slice(1, -5)); } } }); }); if (pending === 1) { done(null, results); } else { --pending; } }); }; var layers = function(dir){ var results = walk(dir, function(err, results){ if (err) { throw err; } results = JSON.stringify(results, null, 4); console.log(results); fs.writeFile('guide/app.json', results); return results; }); } module.exports = layers;
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }
var _ = require('../../util') var handlers = { text: require('./text'), radio: require('./radio'), select: require('./select'), checkbox: require('./checkbox') } module.exports = { priority: 800, twoWay: true, handlers: handlers, /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number * - TODO: more types may be supplied as a plugin */ bind: function () { // friendly warning... this.checkFilters() if (this.hasRead && !this.hasWrite) { process.env.NODE_ENV !== 'production' && _.warn( 'It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.' ) } var el = this.el var tag = el.tagName var handler if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text } else if (tag === 'SELECT') { handler = handlers.select } else if (tag === 'TEXTAREA') { handler = handlers.text } else { process.env.NODE_ENV !== 'production' && _.warn( 'v-model does not support element type: ' + tag ) return } handler.bind.call(this) this.update = handler.update this.unbind = handler.unbind }, /** * Check read/write filter stats. */ checkFilters: function () { var filters = this.filters if (!filters) return var i = filters.length while (i--) { var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name) if (typeof filter === 'function' || filter.read) { this.hasRead = true } if (filter.write) { this.hasWrite = true } } } }
var classes = [ { "name": "Hal\\Report\\Html\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "renderPage", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTrend", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 1, "nbMethodsPublic": 3, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 360, "vocabulary": 90, "volume": 2337.07, "difficulty": 12.54, "effort": 29298.84, "level": 0.08, "bugs": 0.78, "time": 1628, "intelligentContent": 186.42, "number_operators": 103, "number_operands": 257, "number_operators_unique": 8, "number_operands_unique": 82, "cloc": 30, "loc": 151, "lloc": 124, "mi": 60.71, "mIwoC": 28.86, "commentWeight": 31.85, "kanDefect": 1.36, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.68, "relativeSystemComplexity": 81.68, "totalStructuralComplexity": 324, "totalDataComplexity": 2.7, "totalSystemComplexity": 326.7, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Violations\\Xml\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "DOMDocument" ], "lcom": 1, "length": 96, "vocabulary": 40, "volume": 510.91, "difficulty": 5.71, "effort": 2919.46, "level": 0.18, "bugs": 0.17, "time": 162, "intelligentContent": 89.41, "number_operators": 16, "number_operands": 80, "number_operators_unique": 5, "number_operands_unique": 35, "cloc": 15, "loc": 61, "lloc": 47, "mi": 78.36, "mIwoC": 43.62, "commentWeight": 34.74, "kanDefect": 0.75, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.23, "relativeSystemComplexity": 100.23, "totalStructuralComplexity": 200, "totalDataComplexity": 0.45, "totalSystemComplexity": 200.45, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Cli\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 168, "vocabulary": 68, "volume": 1022.69, "difficulty": 7.75, "effort": 7921.69, "level": 0.13, "bugs": 0.34, "time": 440, "intelligentContent": 132.03, "number_operators": 33, "number_operands": 135, "number_operators_unique": 7, "number_operands_unique": 61, "cloc": 14, "loc": 105, "lloc": 85, "mi": 62.43, "mIwoC": 35.63, "commentWeight": 26.8, "kanDefect": 1.03, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 36.36, "totalStructuralComplexity": 72, "totalDataComplexity": 0.71, "totalSystemComplexity": 72.71, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Consolidated", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAvg", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getSum", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getClasses", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFiles", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getProject", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 6, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 5, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 181, "vocabulary": 53, "volume": 1036.75, "difficulty": 10.5, "effort": 10885.91, "level": 0.1, "bugs": 0.35, "time": 605, "intelligentContent": 98.74, "number_operators": 43, "number_operands": 138, "number_operators_unique": 7, "number_operands_unique": 46, "cloc": 37, "loc": 123, "lloc": 86, "mi": 73.03, "mIwoC": 35.47, "commentWeight": 37.55, "kanDefect": 1.67, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.29, "relativeSystemComplexity": 10.29, "totalStructuralComplexity": 54, "totalDataComplexity": 7.75, "totalSystemComplexity": 61.75, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\InterfaceMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\ClassMetric" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FunctionMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 2, "instability": 0.33, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FileMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Metrics", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "jsonSerialize", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "JsonSerializable" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 25, "loc": 51, "lloc": 26, "mi": 101.39, "mIwoC": 57.18, "commentWeight": 44.21, "kanDefect": 0.15, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.4, "relativeSystemComplexity": 10.4, "totalStructuralComplexity": 45, "totalDataComplexity": 7, "totalSystemComplexity": 52, "pageRank": 0.02, "afferentCoupling": 18, "efferentCoupling": 1, "instability": 0.05, "numberOfUnitTests": 12, "violations": {} }, { "name": "Hal\\Metric\\ProjectMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Helper\\RoleOfMethodDetector", "interface": false, "methods": [ { "name": "detects", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [], "lcom": 1, "length": 52, "vocabulary": 21, "volume": 228.4, "difficulty": 8.75, "effort": 1998.5, "level": 0.11, "bugs": 0.08, "time": 111, "intelligentContent": 26.1, "number_operators": 17, "number_operands": 35, "number_operators_unique": 7, "number_operands_unique": 14, "cloc": 15, "loc": 44, "lloc": 29, "mi": 90.35, "mIwoC": 51.05, "commentWeight": 39.31, "kanDefect": 0.66, "relativeStructuralComplexity": 0, "relativeDataComplexity": 6, "relativeSystemComplexity": 6, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 10, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "LogicException", "LogicException", "LogicException", "LogicException", "LogicException" ], "lcom": 1, "length": 111, "vocabulary": 36, "volume": 573.86, "difficulty": 10.14, "effort": 5820.6, "level": 0.1, "bugs": 0.19, "time": 323, "intelligentContent": 56.58, "number_operators": 40, "number_operands": 71, "number_operators_unique": 8, "number_operands_unique": 28, "cloc": 31, "loc": 77, "lloc": 46, "mi": 84.67, "mIwoC": 43.07, "commentWeight": 41.61, "kanDefect": 0.78, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 9, "instability": 0.9, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 20, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 102, "vocabulary": 25, "volume": 473.67, "difficulty": 14.97, "effort": 7091.94, "level": 0.07, "bugs": 0.16, "time": 394, "intelligentContent": 31.64, "number_operators": 25, "number_operands": 77, "number_operators_unique": 7, "number_operands_unique": 18, "cloc": 27, "loc": 102, "lloc": 75, "mi": 73.44, "mIwoC": 37.67, "commentWeight": 35.77, "kanDefect": 2.66, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 2, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 218, "vocabulary": 50, "volume": 1230.36, "difficulty": 11.97, "effort": 14721.41, "level": 0.08, "bugs": 0.41, "time": 818, "intelligentContent": 102.83, "number_operators": 71, "number_operands": 147, "number_operators_unique": 7, "number_operands_unique": 43, "cloc": 29, "loc": 88, "lloc": 59, "mi": 78.03, "mIwoC": 39.2, "commentWeight": 38.83, "kanDefect": 0.57, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\LengthVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 5, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 1, "length": 80, "vocabulary": 25, "volume": 371.51, "difficulty": 7.75, "effort": 2879.19, "level": 0.13, "bugs": 0.12, "time": 160, "intelligentContent": 47.94, "number_operators": 18, "number_operands": 62, "number_operators_unique": 5, "number_operands_unique": 20, "cloc": 20, "loc": 55, "lloc": 36, "mi": 87.59, "mIwoC": 47.38, "commentWeight": 40.21, "kanDefect": 0.59, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 50, "vocabulary": 21, "volume": 219.62, "difficulty": 7, "effort": 1537.31, "level": 0.14, "bugs": 0.07, "time": 85, "intelligentContent": 31.37, "number_operators": 15, "number_operands": 35, "number_operators_unique": 6, "number_operands_unique": 15, "cloc": 15, "loc": 48, "lloc": 33, "mi": 88.3, "mIwoC": 50.21, "commentWeight": 38.09, "kanDefect": 0.44, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 68, "vocabulary": 19, "volume": 288.86, "difficulty": 18.91, "effort": 5462.06, "level": 0.05, "bugs": 0.1, "time": 303, "intelligentContent": 15.28, "number_operators": 16, "number_operands": 52, "number_operators_unique": 8, "number_operands_unique": 11, "cloc": 27, "loc": 80, "lloc": 53, "mi": 83.79, "mIwoC": 44.62, "commentWeight": 39.17, "kanDefect": 1.04, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 18, "totalDataComplexity": 1, "totalSystemComplexity": 19, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 3, "instability": 0.6, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\ClassEnumVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\InterfaceMetric", "Hal\\Metric\\ClassMetric", "Hal\\Metric\\Helper\\RoleOfMethodDetector", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 113, "vocabulary": 35, "volume": 579.61, "difficulty": 12.59, "effort": 7298.78, "level": 0.08, "bugs": 0.19, "time": 405, "intelligentContent": 46.03, "number_operators": 28, "number_operands": 85, "number_operators_unique": 8, "number_operands_unique": 27, "cloc": 8, "loc": 73, "lloc": 65, "mi": 64.56, "mIwoC": 40.03, "commentWeight": 24.53, "kanDefect": 1.09, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.13, "relativeSystemComplexity": 49.13, "totalStructuralComplexity": 98, "totalDataComplexity": 0.25, "totalSystemComplexity": 98.25, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 11, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 98, "vocabulary": 27, "volume": 465.98, "difficulty": 8.3, "effort": 3865.51, "level": 0.12, "bugs": 0.16, "time": 215, "intelligentContent": 56.17, "number_operators": 25, "number_operands": 73, "number_operators_unique": 5, "number_operands_unique": 22, "cloc": 23, "loc": 63, "lloc": 40, "mi": 86.09, "mIwoC": 45.83, "commentWeight": 40.26, "kanDefect": 0.74, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverse", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 111, "vocabulary": 23, "volume": 502.12, "difficulty": 20.53, "effort": 10310.1, "level": 0.05, "bugs": 0.17, "time": 573, "intelligentContent": 24.45, "number_operators": 34, "number_operands": 77, "number_operators_unique": 8, "number_operands_unique": 15, "cloc": 27, "loc": 89, "lloc": 62, "mi": 78.59, "mIwoC": 40.91, "commentWeight": 37.67, "kanDefect": 1.47, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 81.5, "totalStructuralComplexity": 243, "totalDataComplexity": 1.5, "totalSystemComplexity": 244.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 8, "instability": 0.89, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\System\\Changes\\GitChanges", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "doesThisFileShouldBeCounted", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Metric\\Metrics", "Hal\\Application\\Config\\ConfigException", "DateTime", "Hal\\Metric\\ProjectMetric", "Hal\\Metric\\FileMetric" ], "lcom": 1, "length": 256, "vocabulary": 49, "volume": 1437.37, "difficulty": 16.17, "effort": 23237.41, "level": 0.06, "bugs": 0.48, "time": 1291, "intelligentContent": 88.91, "number_operators": 62, "number_operands": 194, "number_operators_unique": 7, "number_operands_unique": 42, "cloc": 36, "loc": 142, "lloc": 106, "mi": 66.99, "mIwoC": 31.83, "commentWeight": 35.17, "kanDefect": 1.82, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.54, "relativeSystemComplexity": 49.54, "totalStructuralComplexity": 147, "totalDataComplexity": 1.63, "totalSystemComplexity": 148.63, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 6, "instability": 0.86, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\PageRank", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculatePageRank", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 12, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 136, "vocabulary": 40, "volume": 723.78, "difficulty": 24.31, "effort": 17598.63, "level": 0.04, "bugs": 0.24, "time": 978, "intelligentContent": 29.77, "number_operators": 35, "number_operands": 101, "number_operators_unique": 13, "number_operands_unique": 27, "cloc": 20, "loc": 75, "lloc": 55, "mi": 76.27, "mIwoC": 40.4, "commentWeight": 35.87, "kanDefect": 2.13, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 16.5, "totalStructuralComplexity": 32, "totalDataComplexity": 1, "totalSystemComplexity": 33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\Coupling", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 84, "vocabulary": 23, "volume": 379.98, "difficulty": 11.12, "effort": 4224.47, "level": 0.09, "bugs": 0.13, "time": 235, "intelligentContent": 34.18, "number_operators": 21, "number_operands": 63, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 12, "loc": 56, "lloc": 44, "mi": 77.06, "mIwoC": 44.2, "commentWeight": 32.86, "kanDefect": 1.56, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.09, "relativeSystemComplexity": 100.09, "totalStructuralComplexity": 100, "totalDataComplexity": 0.09, "totalSystemComplexity": 100.09, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\ClassMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Ast\\NodeTraverser", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverseArray", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "PhpParser\\NodeTraverser", "parent" ], "lcom": 1, "length": 93, "vocabulary": 19, "volume": 395.06, "difficulty": 17.79, "effort": 7028.73, "level": 0.06, "bugs": 0.13, "time": 390, "intelligentContent": 22.2, "number_operators": 32, "number_operands": 61, "number_operators_unique": 7, "number_operands_unique": 12, "cloc": 5, "loc": 65, "lloc": 60, "mi": 63.05, "mIwoC": 42.22, "commentWeight": 20.83, "kanDefect": 1.63, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.75, "relativeSystemComplexity": 25.75, "totalStructuralComplexity": 50, "totalDataComplexity": 1.5, "totalSystemComplexity": 51.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\CliOutput", "interface": false, "methods": [ { "name": "writeln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "write", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "err", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clearln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setQuietMode", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 2, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 2, "length": 30, "vocabulary": 11, "volume": 103.78, "difficulty": 6.29, "effort": 652.35, "level": 0.16, "bugs": 0.03, "time": 36, "intelligentContent": 16.51, "number_operators": 8, "number_operands": 22, "number_operators_unique": 4, "number_operands_unique": 7, "cloc": 25, "loc": 54, "lloc": 31, "mi": 96.55, "mIwoC": 53.08, "commentWeight": 43.47, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.93, "relativeSystemComplexity": 5.93, "totalStructuralComplexity": 20, "totalDataComplexity": 9.67, "totalSystemComplexity": 29.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\ProgressBar", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "start", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "advance", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "hasAnsi", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 1, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 1, "length": 66, "vocabulary": 29, "volume": 320.63, "difficulty": 12.83, "effort": 4114.71, "level": 0.08, "bugs": 0.11, "time": 229, "intelligentContent": 24.98, "number_operators": 24, "number_operands": 42, "number_operators_unique": 11, "number_operands_unique": 18, "cloc": 40, "loc": 83, "lloc": 43, "mi": 90.27, "mIwoC": 46.28, "commentWeight": 43.99, "kanDefect": 0.36, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.6, "relativeSystemComplexity": 9.6, "totalStructuralComplexity": 45, "totalDataComplexity": 3, "totalSystemComplexity": 48, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Issue\\Issuer", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "onError", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "enable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "disable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "terminate", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "log", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 8, "nbMethodsPrivate": 2, "nbMethodsPublic": 6, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Component\\Output\\Output", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 3, "length": 123, "vocabulary": 49, "volume": 690.61, "difficulty": 6.77, "effort": 4673.66, "level": 0.15, "bugs": 0.23, "time": 260, "intelligentContent": 102.05, "number_operators": 26, "number_operands": 97, "number_operators_unique": 6, "number_operands_unique": 43, "cloc": 44, "loc": 152, "lloc": 95, "mi": 73.05, "mIwoC": 36.04, "commentWeight": 37.01, "kanDefect": 0.89, "relativeStructuralComplexity": 16, "relativeDataComplexity": 1.48, "relativeSystemComplexity": 17.48, "totalStructuralComplexity": 128, "totalDataComplexity": 11.8, "totalSystemComplexity": 139.8, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\Edge", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFrom", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTo", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 16, "vocabulary": 6, "volume": 41.36, "difficulty": 2.75, "effort": 113.74, "level": 0.36, "bugs": 0.01, "time": 6, "intelligentContent": 15.04, "number_operators": 5, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 47, "lloc": 24, "mi": 102.62, "mIwoC": 58.44, "commentWeight": 44.19, "kanDefect": 0.15, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 2.75, "totalStructuralComplexity": 4, "totalDataComplexity": 7, "totalSystemComplexity": 11, "pageRank": 0.37, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Component\\Tree\\Node", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getKey", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAdjacents", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getData", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setData", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 7, "nbMethods": 3, "nbMethodsPrivate": 0, "nbMethodsPublic": 3, "nbMethodsGetter": 3, "nbMethodsSetters": 1, "ccn": 4, "externals": [ "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 47, "vocabulary": 9, "volume": 148.99, "difficulty": 12.4, "effort": 1847.43, "level": 0.08, "bugs": 0.05, "time": 103, "intelligentContent": 12.02, "number_operators": 16, "number_operands": 31, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 40, "loc": 89, "lloc": 49, "mi": 90.46, "mIwoC": 47.38, "commentWeight": 43.08, "kanDefect": 0.52, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.64, "relativeSystemComplexity": 10.64, "totalStructuralComplexity": 63, "totalDataComplexity": 11.5, "totalSystemComplexity": 74.5, "pageRank": 0.35, "afferentCoupling": 13, "efferentCoupling": 1, "instability": 0.07, "numberOfUnitTests": 42, "violations": {} }, { "name": "Hal\\Component\\Tree\\Graph", "interface": false, "methods": [ { "name": "insert", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 6, "nbMethodsPrivate": 0, "nbMethodsPublic": 6, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Countable", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 67, "vocabulary": 16, "volume": 268, "difficulty": 8.5, "effort": 2278, "level": 0.12, "bugs": 0.09, "time": 127, "intelligentContent": 31.53, "number_operators": 16, "number_operands": 51, "number_operators_unique": 4, "number_operands_unique": 12, "cloc": 35, "loc": 94, "lloc": 59, "mi": 84.1, "mIwoC": 43.56, "commentWeight": 40.53, "kanDefect": 0.82, "relativeStructuralComplexity": 36, "relativeDataComplexity": 1.23, "relativeSystemComplexity": 37.23, "totalStructuralComplexity": 288, "totalDataComplexity": 9.86, "totalSystemComplexity": 297.86, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 8, "instability": 0.73, "numberOfUnitTests": 10, "violations": {} }, { "name": "Hal\\Component\\Tree\\Operator\\CycleDetector", "interface": false, "methods": [ { "name": "isCyclic", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "detectCycle", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 64, "vocabulary": 12, "volume": 229.44, "difficulty": 14.29, "effort": 3277.68, "level": 0.07, "bugs": 0.08, "time": 182, "intelligentContent": 16.06, "number_operators": 24, "number_operands": 40, "number_operators_unique": 5, "number_operands_unique": 7, "cloc": 23, "loc": 64, "lloc": 41, "mi": 87.12, "mIwoC": 47.08, "commentWeight": 40.04, "kanDefect": 1.12, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.79, "relativeSystemComplexity": 36.79, "totalStructuralComplexity": 72, "totalDataComplexity": 1.57, "totalSystemComplexity": 73.57, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 4, "violations": {} }, { "name": "Hal\\Component\\Tree\\GraphException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "LogicException" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\HashMap", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 0, "nbMethodsPublic": 5, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Countable", "IteratorAggregate", "Hal\\Component\\Tree\\Node", "ArrayIterator" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 21, "loc": 47, "lloc": 26, "mi": 100.19, "mIwoC": 57.18, "commentWeight": 43.01, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.87, "relativeSystemComplexity": 5.87, "totalStructuralComplexity": 20, "totalDataComplexity": 9.33, "totalSystemComplexity": 29.33, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 4, "instability": 1, "numberOfUnitTests": 3, "violations": {} }, { "name": "Hal\\Component\\File\\Finder", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fetch", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "RecursiveDirectoryIterator", "RecursiveIteratorIterator", "RegexIterator" ], "lcom": 1, "length": 64, "vocabulary": 25, "volume": 297.21, "difficulty": 4.38, "effort": 1302.05, "level": 0.23, "bugs": 0.1, "time": 72, "intelligentContent": 67.84, "number_operators": 18, "number_operands": 46, "number_operators_unique": 4, "number_operands_unique": 21, "cloc": 35, "loc": 68, "lloc": 33, "mi": 93.84, "mIwoC": 49.02, "commentWeight": 44.82, "kanDefect": 0.68, "relativeStructuralComplexity": 0, "relativeDataComplexity": 3, "relativeSystemComplexity": 3, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Violations", "interface": false, "methods": [ { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "add", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "__toString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "IteratorAggregate", "Countable", "ArrayIterator", "Hal\\Violation\\Violation" ], "lcom": 1, "length": 20, "vocabulary": 9, "volume": 63.4, "difficulty": 5.2, "effort": 329.67, "level": 0.19, "bugs": 0.02, "time": 18, "intelligentContent": 12.19, "number_operators": 7, "number_operands": 13, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 19, "loc": 44, "lloc": 25, "mi": 99.17, "mIwoC": 56.62, "commentWeight": 42.55, "kanDefect": 0.38, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.63, "relativeSystemComplexity": 2.63, "totalStructuralComplexity": 4, "totalDataComplexity": 6.5, "totalSystemComplexity": 10.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\Blob", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 47, "vocabulary": 19, "volume": 199.65, "difficulty": 4.27, "effort": 851.85, "level": 0.23, "bugs": 0.07, "time": 47, "intelligentContent": 46.79, "number_operators": 15, "number_operands": 32, "number_operators_unique": 4, "number_operands_unique": 15, "cloc": 12, "loc": 56, "lloc": 42, "mi": 80.54, "mIwoC": 47.68, "commentWeight": 32.86, "kanDefect": 0.5, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooComplexCode", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 15, "volume": 109.39, "difficulty": 3.45, "effort": 377.9, "level": 0.29, "bugs": 0.04, "time": 21, "intelligentContent": 31.67, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 46, "lloc": 32, "mi": 88.05, "mIwoC": 52.49, "commentWeight": 35.56, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooDependent", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 14, "volume": 106.61, "difficulty": 3.8, "effort": 405.1, "level": 0.26, "bugs": 0.04, "time": 23, "intelligentContent": 28.05, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 10, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.73, "mIwoC": 52.87, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooLong", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 27, "vocabulary": 15, "volume": 105.49, "difficulty": 3.45, "effort": 364.41, "level": 0.29, "bugs": 0.04, "time": 20, "intelligentContent": 30.54, "number_operators": 8, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.77, "mIwoC": 52.9, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\ProbablyBugged", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 31, "vocabulary": 17, "volume": 126.71, "difficulty": 3.23, "effort": 409.38, "level": 0.31, "bugs": 0.04, "time": 23, "intelligentContent": 39.22, "number_operators": 10, "number_operands": 21, "number_operators_unique": 4, "number_operands_unique": 13, "cloc": 13, "loc": 48, "lloc": 34, "mi": 87.55, "mIwoC": 51.46, "commentWeight": 36.08, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\ViolationParser", "interface": false, "methods": [ { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Violation\\Class_\\Blob", "Hal\\Violation\\Class_\\TooComplexCode", "Hal\\Violation\\Class_\\ProbablyBugged", "Hal\\Violation\\Class_\\TooLong", "Hal\\Violation\\Class_\\TooDependent", "Hal\\Violation\\Violations" ], "lcom": 1, "length": 13, "vocabulary": 7, "volume": 36.5, "difficulty": 2.2, "effort": 80.29, "level": 0.45, "bugs": 0.01, "time": 4, "intelligentContent": 16.59, "number_operators": 2, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 5, "cloc": 4, "loc": 19, "lloc": 15, "mi": 95.62, "mIwoC": 63, "commentWeight": 32.62, "kanDefect": 0.61, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 9, "totalDataComplexity": 0.5, "totalSystemComplexity": 9.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Analyze", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Component\\Issue\\Issuer", "Hal\\Metric\\Metrics", "PhpParser\\ParserFactory", "Hal\\Component\\Ast\\NodeTraverser", "PhpParser\\NodeVisitor\\NameResolver", "Hal\\Metric\\Class_\\ClassEnumVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "Hal\\Metric\\Class_\\Text\\LengthVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "Hal\\Component\\Output\\ProgressBar", "Hal\\Metric\\System\\Coupling\\PageRank", "Hal\\Metric\\System\\Coupling\\Coupling", "Hal\\Metric\\System\\Changes\\GitChanges", "Hal\\Metric\\System\\UnitTesting\\UnitTesting" ], "lcom": 1, "length": 88, "vocabulary": 21, "volume": 386.52, "difficulty": 6.25, "effort": 2415.77, "level": 0.16, "bugs": 0.13, "time": 134, "intelligentContent": 61.84, "number_operators": 13, "number_operands": 75, "number_operators_unique": 3, "number_operands_unique": 18, "cloc": 27, "loc": 86, "lloc": 59, "mi": 81.14, "mIwoC": 42.99, "commentWeight": 38.15, "kanDefect": 0.38, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 100.36, "totalStructuralComplexity": 200, "totalDataComplexity": 0.73, "totalSystemComplexity": 200.73, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 22, "instability": 0.96, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Application", "interface": false, "methods": [ { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Component\\Output\\CliOutput", "Hal\\Component\\Issue\\Issuer", "Hal\\Application\\Config\\Parser", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Component\\File\\Finder", "Hal\\Application\\Analyze", "Hal\\Violation\\ViolationParser", "Hal\\Report\\Cli\\Reporter", "Hal\\Report\\Html\\Reporter", "Hal\\Report\\Violations\\Xml\\Reporter" ], "lcom": 1, "length": 71, "vocabulary": 23, "volume": 321.17, "difficulty": 4.5, "effort": 1445.28, "level": 0.22, "bugs": 0.11, "time": 80, "intelligentContent": 71.37, "number_operators": 11, "number_operands": 60, "number_operators_unique": 3, "number_operands_unique": 20, "cloc": 13, "loc": 55, "lloc": 43, "mi": 80.74, "mIwoC": 46.55, "commentWeight": 34.2, "kanDefect": 0.36, "relativeStructuralComplexity": 144, "relativeDataComplexity": 0.08, "relativeSystemComplexity": 144.08, "totalStructuralComplexity": 144, "totalDataComplexity": 0.08, "totalSystemComplexity": 144.08, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 12, "instability": 1, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Validator", "interface": false, "methods": [ { "name": "validate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "help", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException" ], "lcom": 2, "length": 57, "vocabulary": 23, "volume": 257.84, "difficulty": 8.12, "effort": 2093.08, "level": 0.12, "bugs": 0.09, "time": 116, "intelligentContent": 31.76, "number_operators": 11, "number_operands": 46, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 15, "loc": 81, "lloc": 54, "mi": 75.17, "mIwoC": 44.25, "commentWeight": 30.92, "kanDefect": 0.96, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.38, "relativeSystemComplexity": 9.38, "totalStructuralComplexity": 18, "totalDataComplexity": 0.75, "totalSystemComplexity": 18.75, "pageRank": 0, "afferentCoupling": 3, "efferentCoupling": 4, "instability": 0.57, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\ConfigException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Exception" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 1, "instability": 0.2, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Parser", "interface": false, "methods": [ { "name": "parse", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config" ], "lcom": 1, "length": 67, "vocabulary": 23, "volume": 303.08, "difficulty": 9.18, "effort": 2781.19, "level": 0.11, "bugs": 0.1, "time": 155, "intelligentContent": 33.03, "number_operators": 15, "number_operands": 52, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 3, "loc": 36, "lloc": 33, "mi": 70.05, "mIwoC": 48.42, "commentWeight": 21.62, "kanDefect": 0.96, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.5, "relativeSystemComplexity": 2.5, "totalStructuralComplexity": 1, "totalDataComplexity": 1.5, "totalSystemComplexity": 2.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Application\\Config\\Config", "interface": false, "methods": [ { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fromArray", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 2, "externals": [], "lcom": 1, "length": 29, "vocabulary": 6, "volume": 74.96, "difficulty": 5.75, "effort": 431.04, "level": 0.17, "bugs": 0.02, "time": 24, "intelligentContent": 13.04, "number_operators": 6, "number_operands": 23, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 52, "lloc": 29, "mi": 97.58, "mIwoC": 54.7, "commentWeight": 42.87, "kanDefect": 0.38, "relativeStructuralComplexity": 4, "relativeDataComplexity": 2, "relativeSystemComplexity": 6, "totalStructuralComplexity": 20, "totalDataComplexity": 10, "totalSystemComplexity": 30, "pageRank": 0.01, "afferentCoupling": 7, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 0, "violations": {} }, { "name": "MyVisitor", "interface": false, "methods": [ { "name": "__construct", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 1, "externals": [ "PhpParser\\NodeVisitorAbstract", "PhpParser\\Node" ], "lcom": 1, "length": 7, "vocabulary": 4, "volume": 14, "difficulty": 1, "effort": 14, "level": 1, "bugs": 0, "time": 1, "intelligentContent": 14, "number_operators": 1, "number_operands": 6, "number_operators_unique": 1, "number_operands_unique": 3, "cloc": 13, "loc": 26, "lloc": 13, "mi": 112, "mIwoC": 67.54, "commentWeight": 44.46, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 1, "relativeSystemComplexity": 1, "totalStructuralComplexity": 0, "totalDataComplexity": 2, "totalSystemComplexity": 2, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 0, "violations": {} } ]
(function() { 'use strict'; var jhiAlert = { template: '<div class="alerts" ng-cloak="">' + '<div ng-repeat="alert in $ctrl.alerts" ng-class="[alert.position, {\'toast\': alert.toast}]">' + '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close($ctrl.alerts)"><pre ng-bind-html="alert.msg"></pre></uib-alert>' + '</div>' + '</div>', controller: jhiAlertController }; angular .module('noctemApp') .component('jhiAlert', jhiAlert); jhiAlertController.$inject = ['$scope', 'AlertService']; function jhiAlertController($scope, AlertService) { var vm = this; vm.alerts = AlertService.get(); $scope.$on('$destroy', function () { vm.alerts = []; }); } })();
const test = require('tape') const Queue = require('./Queue') test('peek on empty queue', assert => { const queue = new Queue() assert.strictEqual(queue.peek(), null) assert.end() }) test('enqueue items to the queue', assert => { const queue = new Queue() queue.enqueue('foo') queue.enqueue('bar') assert.equal(queue.length, 2) assert.equal(queue.peek(), 'foo') assert.end() }) test('dequeue items from the queue', assert => { const queue = new Queue() queue.enqueue('A') queue.enqueue('B') queue.enqueue('C') assert.equal(queue.dequeue(), 'A') assert.equal(queue.dequeue(), 'B') assert.equal(queue.dequeue(), 'C') assert.end() }) test('create queue from array', assert => { const queue = new Queue(['A', 'B', 'C']) assert.equal(queue.peek(), 'A') assert.equal(queue.dequeue(), 'A') assert.equal(queue.dequeue(), 'B') assert.equal(queue.dequeue(), 'C') assert.end() }) test('throws error when trying to dequeue empty queue', assert => { const queue = new Queue() assert.throws(() => queue.dequeue(), RangeError) assert.end() })
var EVENTS, ProxyClient, _r, bindSocketSubscriber, getSystemAddresses, io, mazehallGridRegister; _r = require('kefir'); io = require('socket.io-client'); EVENTS = require('./events'); ProxyClient = function(server, hosts) { server.on('listening', function() { return bindSocketSubscriber(server, hosts); }); return this; }; bindSocketSubscriber = function(server, hosts) { var socket; socket = io.connect(process.env.MAZEHALL_PROXY_MASTER || 'ws://localhost:3300/proxy'); socket.on(EVENTS.HELLO, function() { return mazehallGridRegister(server, socket, hosts); }); socket.on(EVENTS.MESSAGE, function(x) { return console.log('proxy-message: ' + x); }); socket.on(EVENTS.ERROR, function(err) { return console.error(err); }); socket.on('connect_timeout', function() { return console.log('proxy-connection: timeout'); }); socket.on('reconnect_failed', function() { return console.log('proxy-connection: couldn’t reconnect within reconnectionAttempts'); }); }; module.exports = ProxyClient; /* helper */ getSystemAddresses = function() { var address, addresses, interfaces, k, k2, os; os = require('os'); interfaces = os.networkInterfaces(); addresses = []; for (k in interfaces) { for (k2 in interfaces[k]) { address = interfaces[k][k2]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } return addresses; }; mazehallGridRegister = function(server, socket, hosts) { var addresses, port; port = server.address().port; addresses = getSystemAddresses(); hosts = hosts || ['localhost']; if (!Array.isArray(hosts)) { hosts = [hosts]; } return hosts.forEach(function(host) { var msg; msg = { target: host, port: port, addresses: addresses }; return socket.emit(EVENTS.REGISTER, msg); }); };
var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; item["No"] = index; item["Sales"] = order._id.sales; item["Januari"] = order.jan.toFixed(2); item["Februari"] = order.feb.toFixed(2); item["Maret"] = order.mar.toFixed(2); item["April"] = order.apr.toFixed(2); item["Mei"] = order.mei.toFixed(2); item["Juni"] = order.jun.toFixed(2); item["Juli"] = order.jul.toFixed(2); item["Agustus"] = order.agu.toFixed(2); item["September"] = order.sep.toFixed(2); item["Oktober"] = order.okt.toFixed(2); item["November"] = order.nov.toFixed(2); item["Desember"] = order.des.toFixed(2); item["Total"] = order.totalOrder.toFixed(2); data.push(item); } var options = { "No": "number", "Sales": "string", "Januari": "string", "Februari": "string", "Maret": "string", "April": "string", "Mei": "string", "Juni": "string", "Juli": "string", "Agustus": "string", "September": "string", "Oktober": "string", "November": "string", "Desember": "string", "Total": "string", }; response.xls(`Sales Monthly Report.xlsx`, data, options); } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; /* SUKSES var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; if(!query.page){ query.page=1; }if(!query.size){ query.size=20; } manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; var firstname = ""; var lastname = ""; if (order.firstname) firstname = order.firstname; if (order.lastname) lastname = order.lastname; item["No"] = index; item["Nomor Sales Contract"] = order.salesContractNo; item["Tanggal Surat Order Produksi"] = moment(new Date(order._createdDate)).format(dateFormat); item["Nomor Surat Order Produksi"] = order.orderNo; item["Jenis Order"] = order.orderType; item["Jenis Proses"] = order.processType; item["Buyer"] = order.buyer; item["Tipe Buyer"] = order.buyerType; item["Jumlah Order"] = order.orderQuantity; item["Satuan"] = order.uom; item["Acuan Warna / Desain"] = order.colorTemplate; item["Warna Yang Diminta"] = order.colorRequest; item["Jenis Warna"] = order.colorType; item["Jumlah"] = order.quantity; item["Satuan Detail"] = order.uomDetail; item["Tanggal Delivery"] = moment(new Date(order.deliveryDate)).format(dateFormat); item["Staff Penjualan"] = `${firstname} ${lastname}`; item["Status"] = order.status; item["Detail"] = order.detail; data.push(item); } var options = { "No": "number", "Nomor Sales Contract": "string", "Tanggal Surat Order Produksi": "string", "Nomor Surat Order Produksi": "string", "Jenis Order": "string", "Jenis Proses": "string", "Buyer": "string", "Tipe Buyer": "string", "Jumlah Order": "number", "Satuan": "string", "Acuan Warna / Desain": "string", "Warna Yang Diminta": "string", "Jenis Warna": "string", "Jumlah": "number", "Satuan Detail": "string", "Tanggal Delivery": "string", "Staff Penjualan": "string", "Status": "string", "Detail": "string" }; response.xls(`Sales Monthly Report.xlsx`, data, options); // } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; */
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z' }) ); };
define(['./alasqlportfoliodividenddata', './monthstaticvalues', './bankdatadividend', './dateperiod'], function(alasqlportfoliodividenddata, monthstaticvalues, bankdatadividend, dateperiod) { var gridData = []; var gridId; var months = monthstaticvalues.getMonthWithLettersValues(); var currentMonth = new Date().getMonth(); var selectedYear = new Date().getFullYear(); function setId(fieldId) { gridId = fieldId; } function setData(year) { selectedYear = year; var result = alasqlportfoliodividenddata.getPortfolioDividends(selectedYear); var data = []; var id = 0; result.forEach(function(entry) { if(entry == null) return; var månad = months[entry.Månad -1]; var land = entry.Land == null ? "x" : entry.Land.toLowerCase(); data.push({ Id: id, Name : entry.Värdepapper, Antal : entry.Antal, Typ: entry.Typ, Månad: månad, Utdelningsdatum : entry.Utdelningsdag, Utdelningsbelopp : entry.UtdelningaktieValuta, Utdelningtotal: entry.Belopp, Valuta: entry.Valuta, ValutaKurs: entry.ValutaKurs, Land: land, UtdelningDeklarerad: entry.UtdelningDeklarerad, Utv: entry.Utv }); id++; }); gridData = data; } function onDataBound(e) { var columns = e.sender.columns; var dataItems = e.sender.dataSource.view(); var today = new Date().toISOString(); for (var j = 0; j < dataItems.length; j++) { if(dataItems[j].items == null) return; for (var i = 0; i < dataItems[j].items.length; i++) { var utdelningsdatum = new Date(dataItems[j].items[i].get("Utdelningsdatum")).toISOString(); var utdelningdeklarerad = dataItems[j].items[i].get("UtdelningDeklarerad"); var row = e.sender.tbody.find("[data-uid='" + dataItems[j].items[i].uid + "']"); if(utdelningsdatum <= today) row.addClass("grid-ok-row"); if(utdelningdeklarerad == "N") row.addClass("grid-yellow-row"); } } } function load() { var today = new Date().toISOString().slice(0, 10); var grid = $(gridId).kendoGrid({ toolbar: ["excel", "pdf"], excel: { fileName: "förväntade_utdelningar" + "_" + today + ".xlsx", filterable: true }, pdf: { fileName: "förväntade_utdelningar" + "_" + today + ".pdf", allPages: true, avoidLinks: true, paperSize: "A4", margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" }, landscape: true, repeatHeaders: true, scale: 0.8 }, theme: "bootstrap", dataBound: onDataBound, dataSource: { data: gridData, schema: { model: { fields: { Name: { type: "string" }, Antal: { type: "number" }, Typ: { type: "string" }, Utdelningsdatum: { type: "date" }, Utdelningsbelopp: { type: "string" }, Utdelningtotal: { type: "number"}, Land: {type: "string" }, ValutaKurs: { type: "string"}, Valuta: {type: "string" } } } }, group: { field: "Månad", dir: "asc", aggregates: [ { field: "Månad", aggregate: "sum" }, { field: "Name", aggregate: "count" }, { field: "Utdelningtotal", aggregate: "sum"} ] }, aggregate: [ { field: "Månad", aggregate: "sum" }, { field: "Name", aggregate: "count" }, { field: "Utdelningtotal", aggregate: "sum" } ], sort: ({ field: "Utdelningsdatum", dir: "asc" }), pageSize: gridData.length }, scrollable: true, sortable: true, filterable: true, groupable: true, pageable: false, columns: [ { field: "Månad", groupHeaderTemplate: "#= value.substring(2, value.length) #", hidden: true }, { field: "UtdelningDeklarerad", hidden: true }, { field: "Name", title: "Värdepapper", template: "<div class='gridportfolio-country-picture' style='background-image: url(/styles/images/#:data.Land#.png);'></div><div class='gridportfolio-country-name'>#: Name #</div>", width: "150px", aggregates: ["count"], footerTemplate: "Totalt antal förväntade utdelningar: #=count# st", groupFooterTemplate: gridNameGroupFooterTemplate }, { field: "Utdelningsdatum", title: "Utd/Handl. utan utd", format: "{0:yyyy-MM-dd}", width: "75px" }, { field: "Typ", title: "Typ", width: "70px" }, { field: "Antal", title: "Antal", format: "{0} st", width: "40px" }, { field: "Utdelningsbelopp", title: "Utdelning/aktie", width: "60px" }, { title: "Utv.", template: '<span class="#= gridPortfolioDividendDivChangeClass(data) #"></span>', width: "15px" }, { field: "Utdelningtotal", title: "Belopp", width: "110px", format: "{0:n2} kr", aggregates: ["sum"], footerTemplate: gridUtdelningtotalFooterTemplate, groupFooterTemplate: gridUtdelningtotalGroupFooterTemplate }, { title: "", template: '<span class="k-icon k-i-info" style="#= gridPortfolioDividendInfoVisibility(data) #"></span>', width: "15px" } ], excelExport: function(e) { var sheet = e.workbook.sheets[0]; for (var i = 0; i < sheet.columns.length; i++) { sheet.columns[i].width = getExcelColumnWidth(i); } } }).data("kendoGrid"); grid.thead.kendoTooltip({ filter: "th", content: function (e) { var target = e.target; return $(target).text(); } }); addTooltipForColumnFxInfo(grid, gridId); addTooltipForColumnUtvInfo(grid, gridId); } function addTooltipForColumnUtvInfo(grid, gridId) { $(gridId).kendoTooltip({ show: function(e){ if(this.content.text().length > 1){ this.content.parent().css("visibility", "visible"); } }, hide:function(e){ this.content.parent().css("visibility", "hidden"); }, filter: "td:nth-child(9)", position: "left", width: 200, content: function(e) { var dataItem = grid.dataItem(e.target.closest("tr")); if(dataItem == null || e.target[0].parentElement.className == "k-group-footer" || dataItem.Utv == 0) return ""; var content = "Utdelningsutveckling jmf fg utdelning: " + dataItem.Utv.replace('.', ',') + " %"; return content } }).data("kendoTooltip"); } function addTooltipForColumnFxInfo(grid, gridId) { $(gridId).kendoTooltip({ show: function(e){ if(this.content.text().length > 1){ this.content.parent().css("visibility", "visible"); } }, hide:function(e){ this.content.parent().css("visibility", "hidden"); }, filter: "td:nth-child(11)", position: "left", width: 200, content: function(e) { var dataItem = grid.dataItem(e.target.closest("tr")); if(dataItem == null || dataItem.ValutaKurs <= 1 || e.target[0].parentElement.className == "k-group-footer") return ""; var content = "Förväntat belopp beräknat med " + dataItem.Valuta + " växelkurs: " + (dataItem.ValutaKurs).replace(".", ",") + "kr"; return content } }).data("kendoTooltip"); } window.gridPortfolioDividendDivChangeClass = function gridPortfolioDividendDivChangeClass(data) { if(data.Utv == 0 || data.Utv == null) return "hidden"; else if(data.Utv > 0) return "k-icon k-i-arrow-up"; else return "k-icon k-i-arrow-down"; } window.gridPortfolioDividendInfoVisibility = function gridPortfolioDividendInfoVisibility(data) { return data.ValutaKurs > 1 ? "" : "display: none;"; } function getExcelColumnWidth(index) { var columnWidth = 150; switch(index) { case 0: // Månad columnWidth = 80; break; case 1: // Värdepapper columnWidth = 220; break; case 2: // Datum columnWidth = 80; break; case 3: // Typ columnWidth = 130; break; case 4: // Antal columnWidth = 70; break; case 5: // Utdelning/aktie columnWidth = 120; break; case 6: // Belopp columnWidth = 260; break; default: columnWidth = 150; } return columnWidth; } function gridNameGroupFooterTemplate(e) { var groupNameValue = e.Månad.sum; if(typeof e.Name.group !== 'undefined') groupNameValue = e.Name.group.value; var groupMonthValue = months.indexOf(groupNameValue); if(currentMonth <= groupMonthValue) { return "Antal förväntade utdelningar: " + e.Name.count + " st"; } else { return "Antal erhållna utdelningar: " + e.Name.count + " st"; } } function gridUtdelningtotalFooterTemplate(e) { var startPeriod = dateperiod.getStartOfYear((selectedYear -1)); var endPeriod = dateperiod.getEndOfYear((selectedYear -1)); var isTaxChecked = $('#checkboxTax').is(":checked"); var selectedYearTotalNumeric = e.Utdelningtotal.sum; var selectedYearTotal = kendo.toString(selectedYearTotalNumeric, 'n2') + " kr"; var lastYearTotalNumeric = bankdatadividend.getTotalDividend(startPeriod, endPeriod, isTaxChecked); var lastYearTotal = kendo.toString(lastYearTotalNumeric, 'n2') + " kr"; var growthValueNumeric = calculateGrowthChange(selectedYearTotalNumeric, lastYearTotalNumeric); var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%"; var spanChange = buildSpanChangeArrow(selectedYearTotalNumeric, lastYearTotalNumeric); return "Totalt förväntat belopp: " + selectedYearTotal + " " + spanChange + growthValue + " (" + lastYearTotal + ")"; } function gridUtdelningtotalGroupFooterTemplate(e) { var groupNameValue = e.Månad.sum; if(typeof e.Name.group !== 'undefined') groupNameValue = e.Name.group.value; var groupMonthValue = months.indexOf(groupNameValue); var isTaxChecked = $('#checkboxTax').is(":checked"); var lastYearValueNumeric = bankdatadividend.getDividendMonthSumBelopp((selectedYear -1), (groupMonthValue +1), isTaxChecked); var selectedYearValueNumeric = e.Utdelningtotal.sum; var lastYearValue = kendo.toString(lastYearValueNumeric, 'n2') + " kr"; var selectedYearValue = kendo.toString(selectedYearValueNumeric, 'n2') + " kr"; var monthName = groupNameValue.substring(3, groupNameValue.length).toLowerCase(); var spanChange = buildSpanChangeArrow(selectedYearValueNumeric, lastYearValueNumeric); var growthValueNumeric = calculateGrowthChange(selectedYearValueNumeric, lastYearValueNumeric); var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%"; if(months.includes(groupNameValue)) { if(currentMonth <= groupMonthValue) { return "Förväntat belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } else { return "Erhållet belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } } else { return "Förväntat belopp " + groupNameValue + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } } function buildSpanChangeArrow(current, last) { var spanArrowClass = current > last ? "k-i-arrow-up" : "k-i-arrow-down"; var titleText = current > last ? "To the moon" : "Back to earth"; return "<span class='k-icon " + spanArrowClass + "' title='" + titleText + "'></span>"; } function calculateGrowthChange(current, last) { if(last == 0) return 0; var changeValue = current - last; return ((changeValue / last) * 100).toFixed(2); } return { setId: setId, setData: setData, load: load }; });
/* eslint-disable global-require */ // polyfills and vendors if (!window._babelPolyfill) { require('babel-polyfill') }
const iNaturalistAPI = require( "../inaturalist_api" ); const ControlledTerm = require( "../models/controlled_term" ); const Observation = require( "../models/observation" ); const Project = require( "../models/project" ); const Taxon = require( "../models/taxon" ); const User = require( "../models/user" ); const observations = class observations { static create( params, options ) { return iNaturalistAPI.post( "observations", params, options ) .then( Observation.typifyInstanceResponse ); } static update( params, options ) { return iNaturalistAPI.put( "observations/:id", params, options ) .then( Observation.typifyInstanceResponse ); } static delete( params, options ) { return iNaturalistAPI.delete( "observations/:id", params, options ); } static fave( params, options ) { return observations.vote( params, options ); } static unfave( params, options ) { return observations.unvote( params, options ); } static vote( params, options ) { let endpoint = "votes/vote/observation/:id"; if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { endpoint = "observations/:id/vote"; } return iNaturalistAPI.post( endpoint, params, options ) .then( Observation.typifyInstanceResponse ); } static unvote( params, options ) { let endpoint = "votes/unvote/observation/:id"; if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { endpoint = "observations/:id/vote"; } return iNaturalistAPI.delete( endpoint, params, options ); } static subscribe( params, options ) { if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { return iNaturalistAPI.put( "observations/:id/subscription", params, options ); } return iNaturalistAPI.post( "subscriptions/Observation/:id/subscribe", params, options ); } static review( params, options ) { const p = Object.assign( { }, params ); p.reviewed = "true"; return iNaturalistAPI.post( "observations/:id/review", p, options ); } static unreview( params, options ) { const p = Object.assign( { }, params ); return iNaturalistAPI.delete( "observations/:id/review", p, options ); } static qualityMetrics( params, options ) { return iNaturalistAPI.get( "observations/:id/quality_metrics", params, options ); } static setQualityMetric( params, options ) { return iNaturalistAPI.post( "observations/:id/quality/:metric", params, options ); } static deleteQualityMetric( params, options ) { return iNaturalistAPI.delete( "observations/:id/quality/:metric", params, options ); } static fetch( ids, params ) { return iNaturalistAPI.fetch( "observations", ids, params ) .then( Observation.typifyResultsResponse ); } static search( params, opts = { } ) { return iNaturalistAPI.get( "observations", params, { ...opts, useAuth: true } ) .then( Observation.typifyResultsResponse ); } static identifiers( params ) { return iNaturalistAPI.get( "observations/identifiers", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { user: new User( r.user ) } ) ) ); } return response; } ); } static observers( params ) { return iNaturalistAPI.get( "observations/observers", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { user: new User( r.user ) } ) ) ); } return response; } ); } static speciesCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/species_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static iconicTaxaCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/iconic_taxa_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static iconicTaxaSpeciesCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/iconic_taxa_species_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static popularFieldValues( params ) { return iNaturalistAPI.get( "observations/popular_field_values", params ) .then( response => { if ( response.results ) { response.results = response.results.map( res => { const r = Object.assign( { }, res ); r.controlled_attribute = new ControlledTerm( r.controlled_attribute ); r.controlled_value = new ControlledTerm( r.controlled_value ); return r; } ); } return response; } ); } static umbrellaProjectStats( params ) { return iNaturalistAPI.get( "observations/umbrella_project_stats", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { project: new Project( r.project ) } ) ) ); } return response; } ); } static histogram( params ) { return iNaturalistAPI.get( "observations/histogram", params ); } static qualityGrades( params ) { return iNaturalistAPI.get( "observations/quality_grades", params ); } static subscriptions( params, options ) { return iNaturalistAPI.get( "observations/:id/subscriptions", params, iNaturalistAPI.optionsUseAuth( options ) ); } static taxonSummary( params ) { return iNaturalistAPI.get( "observations/:id/taxon_summary", params ); } static updates( params, options ) { return iNaturalistAPI.get( "observations/updates", params, iNaturalistAPI.optionsUseAuth( options ) ); } static viewedUpdates( params, options ) { return iNaturalistAPI.put( "observations/:id/viewed_updates", params, iNaturalistAPI.optionsUseAuth( options ) ); } static identificationCategories( params ) { return iNaturalistAPI.get( "observations/identification_categories", params ); } static taxonomy( params ) { return iNaturalistAPI.get( "observations/taxonomy", params ) .then( Taxon.typifyResultsResponse ); } static similarSpecies( params, opts ) { const options = Object.assign( { }, opts || { } ); options.useAuth = true; return iNaturalistAPI.get( "observations/similar_species", params, options ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static taxa( params ) { return iNaturalistAPI.get( "observations/taxa", params ); } }; module.exports = observations;
/** * @author Adam Meadows <[email protected]> * @copyright 2015 Adam Meadows. All rights reserved. */ 'use strict'; /* eslint-disable max-nested-callbacks */ let $ = require('jquery'); let main = require('aiw-ui'); describe('main', () => { let $container; beforeEach(() => { $container = $('<div/>'); main.render($container[0]); }); it('renders template', () => { expect($('.main p', $container)).toHaveText('This is my first webpack project!'); }); });
import {Sample} from './sample' import {context} from './init_audio' let instanceIndex = 0 export class SampleOscillator extends Sample{ constructor(sampleData, event){ super(sampleData, event) this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}` if(this.sampleData === -1){ // create dummy source this.source = { start(){}, stop(){}, connect(){}, } }else{ // @TODO add type 'custom' => PeriodicWave let type = this.sampleData.type this.source = context.createOscillator() switch(type){ case 'sine': case 'square': case 'sawtooth': case 'triangle': this.source.type = type break default: this.source.type = 'square' } this.source.frequency.value = event.frequency } this.output = context.createGain() this.volume = event.data2 / 127 this.output.gain.value = this.volume this.source.connect(this.output) //this.output.connect(context.destination) } }
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.markdown_wiki = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
import { Client } from 'discord.js'; import { isFunction, isRegExp, isString } from 'lodash/lang'; import CommandRegistry from '../command/CommandRegistry'; import Dispatcher from './dispatcher/Dispatcher'; import ServiceContainer from './services/ServiceContainer'; /** * @external {ClientOptions} https://discord.js.org/#/docs/main/stable/typedef/ClientOptions */ /** * @desc The Ghastly client. * @extends Client */ export default class Ghastly extends Client { /** * Constructor. * @param {ClientOptions} options - The options for the client. * @param {PrefixType} options.prefix - The prefix for the client's dispatcher. * If a function is provided, it is given a received `Message` as an argument * and must return a `boolean` indicating if it passes the filter. * @throws {TypeError} Thrown if any option is of the wrong type. */ constructor(options) { const { prefix, ...rest } = options; if (!isString(prefix) && !isRegExp(prefix) && !isFunction(prefix)) { throw new TypeError('Expected prefix to be a string, RegExp or function.'); } super(rest); /** * The command registry for the client. * @type {CommandRegistry} */ this.commands = new CommandRegistry(); /** * The client's service container. * @type {ServiceContainer} */ this.services = new ServiceContainer(); /** * The client's dispatcher. * @type {Dispatcher} * @private */ this.dispatcher = new Dispatcher({ client: this, prefix }); } }
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb // This code moves your data from NeDB to MongoDB // You will first need to create the MongoDB connection in your /routes/config.json file // You then need to ensure your MongoDB Database has been created. // ** IMPORTANT ** // There are no duplication checks in place. Please only run this script once. // ** IMPORTANT ** const Nedb = require('nedb'); const mongodb = require('mongodb'); const async = require('async'); const path = require('path'); const common = require('../routes/common'); const config = common.read_config(); let ndb; // check for DB config if(!config.settings.database.connection_string){ console.log('No MongoDB configured. Please see README.md for help'); process.exit(1); } // Connect to the MongoDB database mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => { if(err){ console.log('Couldn\'t connect to the Mongo database'); console.log(err); process.exit(1); } console.log('Connected to: ' + config.settings.database.connection_string); console.log(''); insertKB(mdb, (KBerr, report) => { insertUsers(mdb, (Usererr, report) => { if(KBerr || Usererr){ console.log('There was an error upgrading to MongoDB. Check the console output'); }else{ console.log('MongoDB upgrade completed successfully'); process.exit(); } }); }); }); function insertKB(db, callback){ const collection = db.collection('kb'); console.log(path.join(__dirname, 'kb.db')); ndb = new Nedb(path.join(__dirname, 'kb.db')); ndb.loadDatabase((err) => { if(err){ console.error('Error while loading the data from the NeDB database'); console.error(err); process.exit(1); } ndb.find({}, (err, docs) => { if(docs.length === 0){ console.error('The NeDB database contains no data, no work required'); console.error('You should probably check the NeDB datafile path though!'); }else{ console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database'); console.log(''); } console.log('Inserting articles into MongoDB...'); async.each(docs, (doc, cb) => { console.log('Article inserted: ' + doc.kb_title); // check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking. if(!doc.kb_permalink || doc.kb_permalink === ''){ doc.kb_permalink = doc._id; } // delete the old ID and let MongoDB generate new ones delete doc._id; collection.insert(doc, (err) => { return cb(err); }); }, (err) => { if(err){ console.log('An error happened while inserting data'); callback(err, null); }else{ console.log('All articles successfully inserted'); console.log(''); callback(null, 'All articles successfully inserted'); } }); }); }); }; function insertUsers(db, callback){ const collection = db.collection('users'); ndb = new Nedb(path.join(__dirname, 'users.db')); ndb.loadDatabase((err) => { if(err){ console.error('Error while loading the data from the NeDB database'); console.error(err); process.exit(1); } ndb.find({}, (err, docs) => { if(docs.length === 0){ console.error('The NeDB database contains no data, no work required'); console.error('You should probably check the NeDB datafile path though!'); }else{ console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database'); console.log(''); } console.log('Inserting users into MongoDB...'); async.each(docs, (doc, cb) => { console.log('User inserted: ' + doc.user_email); // delete the old ID and let MongoDB generate new ones delete doc._id; collection.insert(doc, (err) => { return cb(err); }); }, (err) => { if(err){ console.error('An error happened while inserting user data'); callback(err, null); }else{ console.log('All users successfully inserted'); console.log(''); callback(null, 'All users successfully inserted'); } }); }); }); };
var React = require('react'), cx = require('classnames'), constants = require('./constants'); var Preloader = React.createClass({ propTypes: { size: React.PropTypes.oneOf(constants.SCALES), active: React.PropTypes.bool, colors: React.PropTypes.array }, getDefaultProps() { return { active: true, colors: ['blue', 'red', 'yellow', 'green'] }; }, render() { var classes = { 'preloader-wrapper': true, active: this.props.active }; if (this.props.size) { classes[this.props.size] = true; } return ( <div className={cx(this.props.className, classes)}> {this.props.colors.map(color => { var spinnerClasses = { 'spinner-layer': true }; spinnerClasses['spinner-' + color] = true; return ( <div className={cx(spinnerClasses)}> <div className="circle-clipper left"> <div className="circle"></div> </div><div className="gap-patch"> <div className="circle"></div> </div><div className="circle-clipper right"> <div className="circle"></div> </div> </div> ); })} </div> ); } }); module.exports = Preloader;
let userDao = require('../dao/userDao'), articleDao = require('../dao/articleDao'), commentDao = require('../dao/commentDao'), starDao = require('../dao/starDao'), messageDao = require('../dao/messageDao'), voteDao = require('../dao/voteDao'), settings = require('../config/settings'), tools = require('../config/tools'), jwt = require("jsonwebtoken"), moment = require("moment"), request = require('request'), crypto = require('crypto'), //crypto 是 Node.js 的一个核心模块,我们用它生成散列值来加密密码 sha1 = crypto.createHash('sha1'); module.exports = app => { function getAccToken(req, res) { // let options = { // uri: "https://api.weixin.qq.com/cgi-bin/token", // method: "get", // json: true, // qs: { // grant_type: "client_credential", // appid: "wx7b739a344a69a410", // secret: "9296286bb73ac0391d2eaf2b668c668a" // } // }; if (tools.isBlank(req.body.grant_type) || tools.isBlank(req.body.appid) || tools.isBlank(req.body.secret) || tools.isBlank(req.body.url)) { res.json({ code: 500, msg: '缺少参数' }) return; } let options = { uri: "https://api.weixin.qq.com/cgi-bin/token", method: "get", json: true, qs: { grant_type: req.body.grant_type, appid: req.body.appid, secret: req.body.secret } }; function callback(error, response, data) { if (!error && response.statusCode == 200 && tools.isNotBlank(data) && tools.isNotBlank(data.access_token)) { getTicket(req, res, data.access_token); } else { res.json({ code: 500, msg: '获取access_token失败', data: data }) } } request(options, callback); } function getTicket(req, res, access_token) { let options = { uri: "https://api.weixin.qq.com/cgi-bin/ticket/getticket", method: "get", json: true, qs: { access_token: access_token, type: "jsapi" } }; function callback(error, response, data) { if (!error && response.statusCode == 200 && tools.isNotBlank(data) && data.errcode == 0 && tools.isNotBlank(data.ticket)) { getSignature(req, res, access_token, data.ticket); } else { res.json({ code: 500, msg: '获取ticket失败', data: data }) } } request(options, callback); } function getSignature(req, res, access_token, ticket) { let jsapi_ticket = ticket, nonceStr = tools.randomWord(false, 32), timestamp = parseInt((new Date().getTime())/1000), url = req.body.url; let str = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}` let signature = sha1.update(str).digest('hex'); res.json({ code: 200, msg: 'ok', ob: { accessToken: access_token, timestamp: timestamp, nonceStr: nonceStr, signature: signature } }) } //检查收到的参数确认是否来自微信调用 function checkSignature(req) { let signature = req.query.signature, timestamp = req.query.timestamp, nonce = req.query.timestamp; let arr = ['yourToken', timestamp, nonce]; let str = arr.sort().join(''); let sig = sha1.update(str).digest('hex'); if (sig === signature) { return true; } else { return false; } } //给微信调用 app.get('/forWechat', (req, res, next) => { if (tools.isBlank(req.query.signature) || tools.isBlank(req.query.timestamp) || tools.isBlank(req.query.nonce) || tools.isBlank(req.query.echostr) || checkSignature(req)) { next(); } else { res.send(req.query.echostr); } }); //获取微信签名 app.post('/getAccToken', (req, res, next) => { getAccToken(req, res); }); app.get('/login', (req, res, next) => { let user = { id: '5902bc7cd7e7550ab6203037', name: 'name', level: '初级', avatar: 'http://image.beekka.com/blog/2014/bg2014051201.png' } let authToken = jwt.sign({ user: user, exp: moment().add('days', 30).valueOf(), }, settings.jwtSecret); res.json({ code: 200, msg: 'ok', token: authToken }); }); app.get('/w', (req, res, next) => { res.json({ code: 200, msg: 'ok', user: req.users }); }); //添加用户 app.get('/addUser', (req, res, next) => { userDao.addUser(req, res, next) }); //获取用户 app.get('/getUser', (req, res, next) => { userDao.getUser(req, res, next) }); //删除用户 app.get('/removeUser', (req, res, next) => { userDao.removeUser(req, res, next) }); //发表文章 app.post('/addArticle', (req, res, next) => { articleDao.addArticle(req, res, next) }); //删除文章 app.get('/removeArticle', (req, res, next) => { articleDao.removeArticle(req, res, next) }); //更新文章 -- 暂时不做 // app.get('/updateArticle', (req, res, next) => { // articleDao.updateArticle(req, res, next) // }); //获取文章详情 app.get('/article', (req, res, next) => { articleDao.getArticle(req, res, next) }); //获取文章列表 app.get('/articleList', (req, res, next) => { articleDao.getArticleList(req, res, next) }); //获取精选文章 app.get('/handpickList', (req, res, next) => { articleDao.getHandpickList(req, res, next) }); //根据类型获取文章 app.get('/articleListByType', (req, res, next) => { articleDao.getArticleListByType(req, res, next) }); //获取用户文章 app.get('/articleListByUser', (req, res, next) => { articleDao.getArticleListByUser(req, res, next) }); //获取收藏的文章 app.get('/articleListByCollection', (req, res, next) => { articleDao.getArticleListByCollection(req, res, next) }); //收藏 app.post('/addCollection', (req, res, next) => { articleDao.addArticleCollections(req, res, next) }); //取消收藏 app.get('/removeCollection', (req, res, next) => { articleDao.removeArticleCollections(req, res, next) }); //发表评论 app.post('/addComment', (req, res, next) => { commentDao.addComment(req, res, next) }); //删除评论 app.get('/removeComment', (req, res, next) => { commentDao.removeComment(req, res, next) }); //评论列表 app.get('/commentList', (req, res, next) => { commentDao.getCommentList(req, res, next) }); //消息列表 app.get('/message', (req, res, next) => { messageDao.getMessageList(req, res, next) }); //点赞 app.post('/addStar', (req, res, next) => { starDao.addStar(req, res, next) }); //取消赞 app.get('/removeStar', (req, res, next) => { starDao.removeStar(req, res, next) }); //赞列表 app.get('/starList', (req, res, next) => { starDao.getStarList(req, res, next) }); //他人信息 app.get('/otherInfo', (req, res, next) => { userDao.getOtherInfo(req, res, next) }); //自己信息 app.get('/selfInfo', (req, res, next) => { userDao.getUserInfo(req, res, next) }); //添加投票 app.post('/addVote', (req, res, next) => { voteDao.addVote(req, res, next) }); //确定投票 app.post('/commitVote', (req, res, next) => { voteDao.commitVote(req, res, next) }); //获取投票详情 app.get('/vote', (req, res, next) => { voteDao.getVote(req, res, next) }); //获取投票列表 app.get('/voteList', (req, res, next) => { voteDao.getVoteList(req, res, next) }); //已投票用户列表 app.get('/voteUserList', (req, res, next) => { voteDao.getVoteUserList(req, res, next) }); //获取顶部3条,1条投票2条精选 app.get('/getTopList', (req, res, next) => { articleDao.getTopList(req, res, next) }); }
/* @flow */ import * as React from 'react'; import cn from 'classnames'; import { StyleClasses } from '../theme/styleClasses'; type Props = { // An optional inline-style to apply to the overlay. style: ?Object, // An optional css className to apply. className: ?string, // Boolean if this divider should be inset relative to it's container inset: ?boolean, // Boolean if the divider should be vertical instead of horizontal. vertical: ?boolean, }; const BASE_ELEMENT = StyleClasses.DIVIDER; /** * The divider component will pass all other props such as style or * event listeners on to the component. */ class Divider extends React.PureComponent<Props, *> { props: Props; render() { const { className, inset, vertical, ...props } = this.props; const Component = vertical ? 'div' : 'hr'; return ( <Component {...props} className={cn( BASE_ELEMENT, { 'boldrui-divider__vertical': vertical, 'boldrui-divider__inset': inset, }, className, )} /> ); } } export default Divider;
var windowHeight = $(window).height(); var menuBarHeight = $('#codeplayer-menubar').height(); $('.codeplayer-code-container').css('height', (windowHeight - menuBarHeight) + 'px'); $('.codeplayer-toogle').click(function() { $(this).toggleClass('codeplayer-selected'); var codeContainerDiv = '#codeplayer-' + $(this).html() + '-container'; $(codeContainerDiv).toggle(); var showingDivs = $('.codeplayer-code-container').filter(function() { return $((this)).css('display') != 'none'; }).length; var divWidthPercentage = 100 / showingDivs; $('.codeplayer-code-container').css('width', divWidthPercentage + '%'); }); $('#codeplayer-runbuttondiv').click(function() { var iframeContent = '<style>' + $('#codeplayer-cssCode').val() + '</style>' + $('#codeplayer-htmlCode').val(); $('#codeplayer-iframe').contents().find('html').html(iframeContent); document.getElementById('codeplayer-iframe').contentWindow. eval($('#codeplayer-jsCode').val()) });
var randomBytes = require('mz/crypto').randomBytes; module.exports = function* trace(next) { this.id = yield randomBytes(24); var ctx = this; var req = this.req; var res = this.res; // request start this.trace('time.start'); // request end req.once('end', this.trace.bind(this, 'time.end')); // response headers var writeHead = res.writeHead; res.writeHead = function () { ctx.trace('time.headers'); return writeHead.apply(this, arguments); } // response finish res.once('finish', this.trace.bind(this, 'time.finish')); yield* next; }
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.getItem('selectedPlatform')); $ctrl.selectedPackage = JSON.parse(localStorage.getItem('selectedPackage')); if (StepsService.currentStep < StepsService.REGISTER) { $location.path('/package'); } else { _init(); } function _init () { $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { console.groupCollapsed('Formulário Enviado'); console.log('Formulário de registro', $ctrl.registerForm); console.log('Plano Selecionado', $ctrl.selectedPackage); console.log('Plataforma Selecionada', $ctrl.selectedPlatform); console.groupEnd(); }; }; }; })();
'use strict'; function fixImports() { let editor = atom.workspace.getActiveTextEditor() if (editor) { // fixImports(editor) // editor.selectLinesContainingCursors() } } module.exports = { fixImports, };
var $iterators = require('./es6.array.iterator') , redefine = require('./_redefine') , global = require('./_global') , hide = require('./_hide') , Iterators = require('./_iterators') , wks = require('./_wks') , CORRECT_SYMBOL = require('./_correct-symbol') , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array; require('./_').each.call(( 'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' + 'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList' ).split(','), function(NAME){ var Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators){ if(!CORRECT_SYMBOL || !proto[key])redefine(proto, key, $iterators[key], true); } } });
/** * Copyright (c) 2014 Famous Industries, Inc. * * 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. * * @license MIT */ /** * HeaderFooterLayout * ------------------ * * HeaderFooterLayout is a layout which will arrange three renderables * into a header and footer area of defined size and a content area * of flexible size. * * In this example we create a basic HeaderFooterLayout and define a * size for the header and footer */ define(function(require, exports, module) { var Engine = require('famous/core/Engine'); var Surface = require('famous/core/Surface'); var Modifier = require('famous/core/Modifier'); var StateModifier = require('famous/modifiers/StateModifier'); var Transform = require('famous/core/Transform'); var HeaderFooterLayout = require('famous/views/HeaderFooterLayout'); var Easing = require('famous/transitions/Easing'); var RenderController = require("famous/views/RenderController"); var MenuView = require('./views/MenuView'); var PlayHeaderView = require('./views/PlayHeaderView'); var PlayBodyView = require('./views/PlayBodyView'); var PlayFooterView = require('./views/PlayFooterView'); var Transitionable = require('famous/transitions/Transitionable'); var SpringTransition = require('famous/transitions/SpringTransition'); Transitionable.registerMethod('spring', SpringTransition); var mainContext = Engine.createContext(); var layout = new HeaderFooterLayout({ headerSize: 50, footerSize: 50 }); layout.header.add(PlayHeaderView); //position to the center var bodyRenderController = new RenderController(); layout.content.add(bodyRenderController); var bodySurfaces = []; bodySurfaces.push(PlayBodyView); bodySurfaces.push(MenuView); bodyRenderController.show(bodySurfaces[0]); PlayBodyView.eventHandler.on('seekToPosition', function(data) { PlayHeaderView.setIsPlaying(false); }); PlayBodyView.eventHandler.on('finishedSpeaking', function(data) { PlayHeaderView.setIsPlaying(true); }); var togglemenu = false; PlayHeaderView.eventHandler.on('showMenu', function(data) { bodySurfaces[1].toggle(); togglemenu = !togglemenu; if (togglemenu) { bodyRenderController.show(bodySurfaces[1]); } else { bodyRenderController.show(bodySurfaces[0]); } }); PlayHeaderView.eventHandler.on('shouldFlipViews', function(data) { PlayBodyView.flip(); }); PlayHeaderView.eventHandler.on('shouldPlay', function(data) { PlayBodyView.play(); }); PlayHeaderView.eventHandler.on('toTop', function(data) { PlayBodyView.scrollTo(0); }); MenuView.eventHandler.on('changeContent', function(title) { PlayHeaderView.setTitle(title); PlayHeaderView.setIsPlaying(true); PlayHeaderView.showMenu(); PlayBodyView.switchContent(title); }); layout.footer.add(PlayFooterView); mainContext.add(layout); });
import React, { Component, PropTypes } from 'react'; import Select from 'react-select'; import { omit } from 'lodash'; import classNames from 'classnames'; import styles from './styles.scss'; import chevronIcon from '../../../assets/images/icons/chevron-down.svg'; export const THEMES = { OLD: 'old', INTERNAL: 'internal' }; export default class SelectField extends Component { static propTypes = { theme: PropTypes.string, label: PropTypes.string, error: PropTypes.string, className: PropTypes.string, }; static defaultProps = { theme: THEMES.OLD, }; constructor(props, context) { super(props, context); this.renderArrow = ::this.renderArrow; } renderArrow() { return ( <div className={styles.selectArrow}> <img src={chevronIcon} alt="chevron" /> </div> ); } renderOption(option, i) { return ( <div key={i} className={styles.selectFieldOption}>{option.label}</div> ); } renderLabel() { const labelStyles = classNames(styles.selectLabel, { [styles.selectLabelInvalid]: this.props.error }); return this.props.label ? ( <div className={labelStyles}>{this.props.label}</div> ) : null; } renderError() { return this.props.error ? ( <div className={styles.selectFieldError}> {this.props.error} </div> ) : null; } renderSelectField() { const selectStyles = classNames(styles.selectField, { [styles.selectFieldInvalid]: this.props.error }); const props = omit(this.props, ['error', 'label']); return ( <div className={selectStyles}> <Select {...props} arrowRenderer={this.renderArrow} optionRenderer={this.renderOption} /> {this.renderError()} </div> ); } render() { const selectStyles = classNames(styles.select, this.props.className, { [styles.selectOld]: this.props.theme === THEMES.OLD, [styles.selectInternal]: this.props.theme === THEMES.INTERNAL, }); return ( <div className={selectStyles}> {this.renderLabel()} {this.renderSelectField()} </div> ); } }
Notify = function(text, callback, close_callback, style) { var time = '10000'; var $container = $('#notifications'); var icon = '<i class="fa fa-info-circle "></i>'; if (typeof style == 'undefined' ) style = 'warning' var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>'); $('<a>',{ text: '×', class: 'close', style: 'padding-left: 10px;', href: '#', click: function(e){ e.preventDefault() close_callback && close_callback() remove_notice() } }).prependTo(html) $container.prepend(html) html.removeClass('hide').hide().fadeIn('slow') function remove_notice() { html.stop().fadeOut('slow').remove() } var timer = setInterval(remove_notice, time); $(html).hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(remove_notice, time); }); html.on('click', function () { clearInterval(timer) callback && callback() remove_notice() }); }
import React from 'react'; import Link from 'gatsby-link'; import { BlogPostContent, BlogPostContainer, TagList } from '../utils/styles'; import { arrayReducer } from '../utils/helpers.js'; export default function TagsPage({ data }) { const { edges: posts } = data.allMarkdownRemark; const categoryArray = arrayReducer(posts, 'category'); const categoryLinks = categoryArray.map((category, index) => { return ( <li className="category-item" key={index}> <Link className='category-list-link' to={`/categories/${category}`} key={index}>{category}</Link> </li> ) }); return ( <BlogPostContainer> <BlogPostContent> <h2>Categories</h2> <TagList className='categories-list'>{categoryLinks}</TagList> </BlogPostContent> </BlogPostContainer> ); } export const query = graphql` query CategoryPage { allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { totalCount edges { node { frontmatter { category } } } } } `;
/* -*- javascript -*- */ "use strict"; import {StageComponent} from 'aurelia-testing'; import {bootstrap} from 'aurelia-bootstrapper'; import {LogManager} from 'aurelia-framework'; import {ConsoleAppender} from 'aurelia-logging-console'; import {customMatchers} from '../helpers'; describe('ui-icon', () => { let component, logger; beforeAll(() => { jasmine.addMatchers( customMatchers ); logger = LogManager.getLogger( 'ui-icon-spec' ); }); beforeEach(() => { component = StageComponent.withResources('src/elements/ui-icon'); }); afterEach(() => { component.dispose(); }); describe( 'as a custom attribute', () => { it( 'adds semantic classes when bound', done => { component. inView(` <i ui-icon="name: cloud"></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'cloud', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'has a reasonable name default', done => { component. inView(` <i ui-icon></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'help', 'circle', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a size class when one is set', done => { component. inView(` <i ui-icon="name: cloud; size: huge"></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'huge', 'cloud', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a color class when one is set', done => { component. inView(` <i ui-icon="name: user; color: red">Erase History</i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'red', 'user', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a disabled class when it is set', done => { component. inView(` <i ui-icon="disabled: true">Eject!</i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'disabled', 'icon' ); }). then( done ). catch( done.fail ); }); }); describe( 'as a custom element', () => { it( 'uses the icon name', done => { component. inView(` <ui-icon name="cloud"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'cloud' ); }). then( done ). catch( done.fail ); }); it( 'support multiple names', done => { component. inView(` <ui-icon name="circular inverted users"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'circular', 'inverted', 'users' ); }). then( done ). catch( done.fail ); }); it( 'has a reasonable default name', done => { component. inView(` <ui-icon></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'help', 'circle' ); }). then( done ). catch( done.fail ); }); it( 'adds a size class when one is set', done => { component. inView(` <ui-icon size="huge"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'huge' ); }). then( done ). catch( done.fail ); }); it( 'adds a color class when one is set', done => { component. inView(` <ui-icon color="red"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'red' ); }). then( done ). catch( done.fail ); }); it( 'adds a disabled class when it is set', done => { component. inView(` <ui-icon disabled="true"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'disabled' ); }). then( done ). catch( done.fail ); }); }); });
// // This software is released under the 3-clause BSD license. // // Copyright (c) 2015, Xin Chen <[email protected]> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /******************************************************************************* * 1) MidiPlayer.js. ******************************************************************************/ /** * MidiPlayer class. Used to play midi by javascript, without any plugin. * Requires a HTML5 browser: firefox, chrome, safari, opera, IE10+. * * The other 5 js files are from [2][3], which is a demo of [1]: * [1] http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/ * [2] http://jsspeccy.zxdemo.org/jasmid/ * [3] https://github.com/gasman/jasmid * * Modification is done to audio.js: * - added function fireEventEnded(). * - added 'ended' event firing when generator.finished is true. * - move 'context' outside function AudioPlayer, so in chrome it won't have this error * when you loop the play: * Failed to construct 'AudioContext': number of hardware contexts reached maximum (6) * * Github site: https://github.com/chenx/MidiPlayer * * @by: X. Chen * @Create on: 4/1/2015 * @Last modified: 4/3/2015 */ if (typeof (MidiPlayer) == 'undefined') { /** * Constructor of MidiPlayer class. * @param midi MIDI file path. * @param target Target html element that this MIDI player is attached to. * @param loop Optinoal. Whether loop the play. Value is true/false, default is false. * @param maxLoop Optional. max number of loops to play when loop is true. * Negative or 0 means infinite. Default is 1. * @param end_callback Optional. Callback function when MIDI ends. * @author X. Chen. April 2015. */ var MidiPlayer = function(midi, target, loop, maxLoop, end_callback) { this.midi = midi; this.target = document.getElementById(target); this.loop = (typeof (loop) == 'undefined') ? false : loop; if (! loop) { this.max_loop_ct = 1; } else { this.max_loop_ct = (typeof (maxLoop) == 'undefined') ? 1 : (maxLoop <= 0 ? 0 : maxLoop); } this.end_callback = (typeof (end_callback) == 'function') ? end_callback : null; this.debug_div = null; this.midiFile = null; this.synth = null; this.replayer = null; this.audio = null; this.ct = 0; // loop counter. this.started = false; // state of play: started/stopped. this.listener_added = false; } MidiPlayer.prototype.setDebugDiv = function(debug_div_id) { this.debug_div = (typeof (debug_div_id) == 'undefined') ? null : document.getElementById(debug_div_id); } MidiPlayer.prototype.debug = function(msg) { if (this.debug_div) { this.debug_div.innerHTML += msg + '<br/>'; } } MidiPlayer.prototype.stop = function() { this.started = false; this.ct = 0; if (this.audio) { this.audio.stop(); this.audio = null; } if (this.max_loop_ct > 0) { if (this.end_callback) { this.end_callback(); } } } MidiPlayer.prototype.play = function() { if (this.started) { this.stop(); //return; } this.started = true; var o = this.target; var _this = this; // must be 'var', otherwise _this is public, and causes problem. var file = this.midi; var loop = this.loop; if (window.addEventListener) { // Should not add more than one listener after first call, otherwise o has more // and more listeners attached, and will fire n events the n-th time calling play. if (! this.listener_added) { this.listener_added = true; if (o) { // If o does not exist, don't add listener. o.addEventListener('ended', function() { // addEventListener not work for IE8. //alert('ended'); if (_this.max_loop_ct <= 0 || (++ _this.ct) < _this.max_loop_ct) { _this.replayer = Replayer(_this.midiFile, _this.synth); _this.audio = AudioPlayer(_this.replayer, o, loop); _this.debug( file + ': loop ' + (1 +_this.ct) ); } else if (_this.max_loop_ct > 0) { _this.stop(); } }, false); } } } else if (window.attachEvent) { // IE don't work anyway. //document.getElementById('music').attachEvent( // 'onclick', function(e) { alert('IE end'); }, true); } loadRemote(file, function(data) { if (_this.ct == 0) { _this.midiFile = MidiFile(data); _this.synth = Synth(44100); } _this.replayer = Replayer(_this.midiFile, _this.synth); _this.audio = AudioPlayer(_this.replayer, o, loop); _this.debug( file + ': loop ' + (1 + _this.ct) ); //alert(_this.audio.type); // webkit for firefox, chrome; flash for opera/safari. }); } // This function is modified from [2] by adding support for IE. See: // http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie // https://code.google.com/p/jsdap/source/browse/trunk/?r=64 // // However, IE8 and before do not support HTML5 Audio tag so this still will not work. // See: http://www.impressivewebs.com/html5-support-ie9/ // // A private function, defined by 'var'. // Original definition in [2] is: function loadRemote(path, callback) { var loadRemote = function(path, callback) { var fetch = new XMLHttpRequest(); fetch.open('GET', path); if (fetch.overrideMimeType) { fetch.overrideMimeType("text/plain; charset=x-user-defined"); // for non-IE. } else { fetch.setRequestHeader('Accept-Charset', 'x-user-defined'); // for IE. } fetch.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { // munge response into a binary string if (IE_HACK) { // for IE. var t = BinaryToArray(fetch.responseBody).toArray(); var ff = []; var mx = t.length; var scc= String.fromCharCode; for (var z = 0; z < mx; z++) { // t[z] here is equivalent to 't.charCodeAt(z) & 255' below. // e.g., t[z] is 238, below t.charCodeAt[z] is 63470. 63470 & 255 = 238. // But IE8 has no Audio element, so can't play anyway, // and will report this error in audio.js: 'Audio' is undefined. ff[z] = scc(t[z]); } callback(ff.join("")); } else { // for non-IE. var t = this.responseText || "" ; var ff = []; var mx = t.length; var scc= String.fromCharCode; for (var z = 0; z < mx; z++) { ff[z] = scc(t.charCodeAt(z) & 255); } callback(ff.join("")); } } } fetch.send(); } // Now expand definition of MidiPlayer to include the other 6 files below. // So comment out the line below, and add the back curly bracket at the end of file. //} // (previous) end of: if (typeof (MidiPlayer) == 'undefined') /******************************************************************************* * 2) vbscript.js ******************************************************************************/ /** * Convert binary string to array. * * See: * [1] http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie * [2] https://code.google.com/p/jsdap/source/browse/trunk/?r=64 */ var IE_HACK = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)); if (IE_HACK) { //alert('IE hack'); document.write('<script type="text/vbscript">\n\ Function BinaryToArray(Binary)\n\ Dim i\n\ ReDim byteArray(LenB(Binary))\n\ For i = 1 To LenB(Binary)\n\ byteArray(i-1) = AscB(MidB(Binary, i, 1))\n\ Next\n\ BinaryToArray = byteArray\n\ End Function\n\ </script>'); } /******************************************************************************* * Files 3) to 7) below are by: * Matt Westcott <[email protected]> - @gasmanic - http://matt.west.co.tt/ * See: * - http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/ * - http://jsspeccy.zxdemo.org/jasmid/ * - https://github.com/gasman/jasmid ******************************************************************************/ /******************************************************************************* * 3) audio.js. ******************************************************************************/ var sampleRate = 44100; /* hard-coded in Flash player */ var context = null // XC. // Note this may cause name conflict. So be careful of variable name "context". // // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually // Added by XC. // function fireEventEnded(target) { if (! target) return; if (document.createEvent) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("ended", false, true); target.dispatchEvent(evt); } else if (document.createEventObject) { // IE before version 9 var myEvent = document.createEventObject(); target.fireEvent('onclick', myEvent); } } //function AudioPlayer(generator, opts) { function AudioPlayer(generator, targetElement, opts) { if (!opts) opts = {}; var latency = opts.latency || 1; var checkInterval = latency * 100 /* in ms */ var audioElement = new Audio(); var webkitAudio = window.AudioContext || window.webkitAudioContext; var requestStop = false; if (audioElement.mozSetup) { audioElement.mozSetup(2, sampleRate); /* channels, sample rate */ var buffer = []; /* data generated but not yet written */ var minBufferLength = latency * 2 * sampleRate; /* refill buffer when there are only this many elements remaining */ var bufferFillLength = Math.floor(latency * sampleRate); function checkBuffer() { if (requestStop) return; // no more data feed after request stop. xc. if (buffer.length) { var written = audioElement.mozWriteAudio(buffer); buffer = buffer.slice(written); } if (buffer.length < minBufferLength && !generator.finished) { buffer = buffer.concat(generator.generate(bufferFillLength)); } if (!requestStop && (!generator.finished || buffer.length)) { setTimeout(checkBuffer, checkInterval); } if (!requestStop && generator.finished) { fireEventEnded(targetElement); // xc. } } checkBuffer(); return { 'type': 'Firefox Audio', 'stop': function() { requestStop = true; } } } else if (webkitAudio) { // Uses Webkit Web Audio API if available // chrome stops after 5 invocation. XC. Error is: // Failed to construct 'AudioContext': number of hardware contexts reached maximum (6) //var context = new webkitAudio(); if (! context) context = new webkitAudio(); // fixed by this. XC. sampleRate = context.sampleRate; var channelCount = 2; var bufferSize = 4096*4; // Higher for less gitches, lower for less latency var node = context.createScriptProcessor(bufferSize, 0, channelCount); node.onaudioprocess = function(e) { process(e) }; function process(e) { if (generator.finished) { node.disconnect(); //alert('done: ' + targetElement); // xc. fireEventEnded(targetElement); // xc. return; } var dataLeft = e.outputBuffer.getChannelData(0); var dataRight = e.outputBuffer.getChannelData(1); var generate = generator.generate(bufferSize); for (var i = 0; i < bufferSize; ++i) { dataLeft[i] = generate[i*2]; dataRight[i] = generate[i*2+1]; } } // start node.connect(context.destination); return { 'stop': function() { // pause node.disconnect(); requestStop = true; }, 'type': 'Webkit Audio' } } else { // Fall back to creating flash player var c = document.createElement('div'); c.innerHTML = '<embed type="application/x-shockwave-flash" id="da-swf" src="da.swf" width="8" height="8" allowScriptAccess="always" style="position: fixed; left:-10px;" />'; document.body.appendChild(c); var swf = document.getElementById('da-swf'); var minBufferDuration = latency * 1000; /* refill buffer when there are only this many ms remaining */ var bufferFillLength = latency * sampleRate; function write(data) { var out = new Array(data.length); for (var i = data.length-1; i != 0; i--) { out[i] = Math.floor(data[i]*32768); } return swf.write(out.join(' ')); } function checkBuffer() { if (requestStop) return; // no more data feed after request stop. xc. if (swf.bufferedDuration() < minBufferDuration) { write(generator.generate(bufferFillLength)); }; if (!requestStop && !generator.finished) setTimeout(checkBuffer, checkInterval); if (!requestStop && generator.finished) fireEventEnded(targetElement); // xc. } function checkReady() { if (swf.write) { checkBuffer(); } else { setTimeout(checkReady, 10); } } checkReady(); return { 'stop': function() { swf.stop(); requestStop = true; }, 'bufferedDuration': function() { return swf.bufferedDuration(); }, 'type': 'Flash Audio' } } } /******************************************************************************* * 4) midifile.js ******************************************************************************/ /** * Class to parse the .mid file format. Depends on stream.js. */ function MidiFile(data) { function readChunk(stream) { var id = stream.read(4); var length = stream.readInt32(); return { 'id': id, 'length': length, 'data': stream.read(length) }; } var lastEventTypeByte; function readEvent(stream) { var event = {}; event.deltaTime = stream.readVarInt(); var eventTypeByte = stream.readInt8(); if ((eventTypeByte & 0xf0) == 0xf0) { /* system / meta event */ if (eventTypeByte == 0xff) { /* meta event */ event.type = 'meta'; var subtypeByte = stream.readInt8(); var length = stream.readVarInt(); switch(subtypeByte) { case 0x00: event.subtype = 'sequenceNumber'; if (length != 2) throw "Expected length for sequenceNumber event is 2, got " + length; event.number = stream.readInt16(); return event; case 0x01: event.subtype = 'text'; event.text = stream.read(length); return event; case 0x02: event.subtype = 'copyrightNotice'; event.text = stream.read(length); return event; case 0x03: event.subtype = 'trackName'; event.text = stream.read(length); return event; case 0x04: event.subtype = 'instrumentName'; event.text = stream.read(length); return event; case 0x05: event.subtype = 'lyrics'; event.text = stream.read(length); return event; case 0x06: event.subtype = 'marker'; event.text = stream.read(length); return event; case 0x07: event.subtype = 'cuePoint'; event.text = stream.read(length); return event; case 0x20: event.subtype = 'midiChannelPrefix'; if (length != 1) throw "Expected length for midiChannelPrefix event is 1, got " + length; event.channel = stream.readInt8(); return event; case 0x2f: event.subtype = 'endOfTrack'; if (length != 0) throw "Expected length for endOfTrack event is 0, got " + length; return event; case 0x51: event.subtype = 'setTempo'; if (length != 3) throw "Expected length for setTempo event is 3, got " + length; event.microsecondsPerBeat = ( (stream.readInt8() << 16) + (stream.readInt8() << 8) + stream.readInt8() ) return event; case 0x54: event.subtype = 'smpteOffset'; if (length != 5) throw "Expected length for smpteOffset event is 5, got " + length; var hourByte = stream.readInt8(); event.frameRate = { 0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30 }[hourByte & 0x60]; event.hour = hourByte & 0x1f; event.min = stream.readInt8(); event.sec = stream.readInt8(); event.frame = stream.readInt8(); event.subframe = stream.readInt8(); return event; case 0x58: event.subtype = 'timeSignature'; if (length != 4) throw "Expected length for timeSignature event is 4, got " + length; event.numerator = stream.readInt8(); event.denominator = Math.pow(2, stream.readInt8()); event.metronome = stream.readInt8(); event.thirtyseconds = stream.readInt8(); return event; case 0x59: event.subtype = 'keySignature'; if (length != 2) throw "Expected length for keySignature event is 2, got " + length; event.key = stream.readInt8(true); event.scale = stream.readInt8(); return event; case 0x7f: event.subtype = 'sequencerSpecific'; event.data = stream.read(length); return event; default: // console.log("Unrecognised meta event subtype: " + subtypeByte); event.subtype = 'unknown' event.data = stream.read(length); return event; } event.data = stream.read(length); return event; } else if (eventTypeByte == 0xf0) { event.type = 'sysEx'; var length = stream.readVarInt(); event.data = stream.read(length); return event; } else if (eventTypeByte == 0xf7) { event.type = 'dividedSysEx'; var length = stream.readVarInt(); event.data = stream.read(length); return event; } else { throw "Unrecognised MIDI event type byte: " + eventTypeByte; } } else { /* channel event */ var param1; if ((eventTypeByte & 0x80) == 0) { /* running status - reuse lastEventTypeByte as the event type. eventTypeByte is actually the first parameter */ param1 = eventTypeByte; eventTypeByte = lastEventTypeByte; } else { param1 = stream.readInt8(); lastEventTypeByte = eventTypeByte; } var eventType = eventTypeByte >> 4; event.channel = eventTypeByte & 0x0f; event.type = 'channel'; switch (eventType) { case 0x08: event.subtype = 'noteOff'; event.noteNumber = param1; event.velocity = stream.readInt8(); return event; case 0x09: event.noteNumber = param1; event.velocity = stream.readInt8(); if (event.velocity == 0) { event.subtype = 'noteOff'; } else { event.subtype = 'noteOn'; } return event; case 0x0a: event.subtype = 'noteAftertouch'; event.noteNumber = param1; event.amount = stream.readInt8(); return event; case 0x0b: event.subtype = 'controller'; event.controllerType = param1; event.value = stream.readInt8(); return event; case 0x0c: event.subtype = 'programChange'; event.programNumber = param1; return event; case 0x0d: event.subtype = 'channelAftertouch'; event.amount = param1; return event; case 0x0e: event.subtype = 'pitchBend'; event.value = param1 + (stream.readInt8() << 7); return event; default: throw "Unrecognised MIDI event type: " + eventType /* console.log("Unrecognised MIDI event type: " + eventType); stream.readInt8(); event.subtype = 'unknown'; return event; */ } } } stream = Stream(data); var headerChunk = readChunk(stream); if (headerChunk.id != 'MThd' || headerChunk.length != 6) { throw "Bad .mid file - header not found"; } var headerStream = Stream(headerChunk.data); var formatType = headerStream.readInt16(); var trackCount = headerStream.readInt16(); var timeDivision = headerStream.readInt16(); if (timeDivision & 0x8000) { throw "Expressing time division in SMTPE frames is not supported yet" } else { ticksPerBeat = timeDivision; } var header = { 'formatType': formatType, 'trackCount': trackCount, 'ticksPerBeat': ticksPerBeat } var tracks = []; for (var i = 0; i < header.trackCount; i++) { tracks[i] = []; var trackChunk = readChunk(stream); if (trackChunk.id != 'MTrk') { throw "Unexpected chunk - expected MTrk, got "+ trackChunk.id; } var trackStream = Stream(trackChunk.data); while (!trackStream.eof()) { var event = readEvent(trackStream); tracks[i].push(event); //console.log(event); } } return { 'header': header, 'tracks': tracks } } /******************************************************************************* * 5) replayer.js ******************************************************************************/ function Replayer(midiFile, synth) { var trackStates = []; var beatsPerMinute = 120; var ticksPerBeat = midiFile.header.ticksPerBeat; var channelCount = 16; for (var i = 0; i < midiFile.tracks.length; i++) { trackStates[i] = { 'nextEventIndex': 0, 'ticksToNextEvent': ( midiFile.tracks[i].length ? midiFile.tracks[i][0].deltaTime : null ) }; } function Channel() { var generatorsByNote = {}; var currentProgram = PianoProgram; function noteOn(note, velocity) { if (generatorsByNote[note] && !generatorsByNote[note].released) { /* playing same note before releasing the last one. BOO */ generatorsByNote[note].noteOff(); /* TODO: check whether we ought to be passing a velocity in */ } generator = currentProgram.createNote(note, velocity); synth.addGenerator(generator); generatorsByNote[note] = generator; } function noteOff(note, velocity) { if (generatorsByNote[note] && !generatorsByNote[note].released) { generatorsByNote[note].noteOff(velocity); } } function setProgram(programNumber) { currentProgram = PROGRAMS[programNumber] || PianoProgram; } return { 'noteOn': noteOn, 'noteOff': noteOff, 'setProgram': setProgram } } var channels = []; for (var i = 0; i < channelCount; i++) { channels[i] = Channel(); } var nextEventInfo; var samplesToNextEvent = 0; function getNextEvent() { var ticksToNextEvent = null; var nextEventTrack = null; var nextEventIndex = null; for (var i = 0; i < trackStates.length; i++) { if ( trackStates[i].ticksToNextEvent != null && (ticksToNextEvent == null || trackStates[i].ticksToNextEvent < ticksToNextEvent) ) { ticksToNextEvent = trackStates[i].ticksToNextEvent; nextEventTrack = i; nextEventIndex = trackStates[i].nextEventIndex; } } if (nextEventTrack != null) { /* consume event from that track */ var nextEvent = midiFile.tracks[nextEventTrack][nextEventIndex]; if (midiFile.tracks[nextEventTrack][nextEventIndex + 1]) { trackStates[nextEventTrack].ticksToNextEvent += midiFile.tracks[nextEventTrack][nextEventIndex + 1].deltaTime; } else { trackStates[nextEventTrack].ticksToNextEvent = null; } trackStates[nextEventTrack].nextEventIndex += 1; /* advance timings on all tracks by ticksToNextEvent */ for (var i = 0; i < trackStates.length; i++) { if (trackStates[i].ticksToNextEvent != null) { trackStates[i].ticksToNextEvent -= ticksToNextEvent } } nextEventInfo = { 'ticksToEvent': ticksToNextEvent, 'event': nextEvent, 'track': nextEventTrack } var beatsToNextEvent = ticksToNextEvent / ticksPerBeat; var secondsToNextEvent = beatsToNextEvent / (beatsPerMinute / 60); samplesToNextEvent += secondsToNextEvent * synth.sampleRate; } else { nextEventInfo = null; samplesToNextEvent = null; self.finished = true; } } getNextEvent(); function generate(samples) { var data = new Array(samples*2); var samplesRemaining = samples; var dataOffset = 0; while (true) { if (samplesToNextEvent != null && samplesToNextEvent <= samplesRemaining) { /* generate samplesToNextEvent samples, process event and repeat */ var samplesToGenerate = Math.ceil(samplesToNextEvent); if (samplesToGenerate > 0) { synth.generateIntoBuffer(samplesToGenerate, data, dataOffset); dataOffset += samplesToGenerate * 2; samplesRemaining -= samplesToGenerate; samplesToNextEvent -= samplesToGenerate; } handleEvent(); getNextEvent(); } else { /* generate samples to end of buffer */ if (samplesRemaining > 0) { synth.generateIntoBuffer(samplesRemaining, data, dataOffset); samplesToNextEvent -= samplesRemaining; } break; } } return data; } function handleEvent() { var event = nextEventInfo.event; switch (event.type) { case 'meta': switch (event.subtype) { case 'setTempo': beatsPerMinute = 60000000 / event.microsecondsPerBeat } break; case 'channel': switch (event.subtype) { case 'noteOn': channels[event.channel].noteOn(event.noteNumber, event.velocity); break; case 'noteOff': channels[event.channel].noteOff(event.noteNumber, event.velocity); break; case 'programChange': //console.log('program change to ' + event.programNumber); channels[event.channel].setProgram(event.programNumber); break; } break; } } function replay(audio) { console.log('replay'); audio.write(generate(44100)); setTimeout(function() {replay(audio)}, 10); } var self = { 'replay': replay, 'generate': generate, 'finished': false } return self; } /******************************************************************************* * 6) stream.js ******************************************************************************/ /** * Wrapper for accessing strings through sequential reads. */ function Stream(str) { var position = 0; function read(length) { var result = str.substr(position, length); position += length; return result; } /* read a big-endian 32-bit integer */ function readInt32() { var result = ( (str.charCodeAt(position) << 24) + (str.charCodeAt(position + 1) << 16) + (str.charCodeAt(position + 2) << 8) + str.charCodeAt(position + 3)); position += 4; return result; } /* read a big-endian 16-bit integer */ function readInt16() { var result = ( (str.charCodeAt(position) << 8) + str.charCodeAt(position + 1)); position += 2; return result; } /* read an 8-bit integer */ function readInt8(signed) { var result = str.charCodeAt(position); if (signed && result > 127) result -= 256; position += 1; return result; } function eof() { return position >= str.length; } /* read a MIDI-style variable-length integer (big-endian value in groups of 7 bits, with top bit set to signify that another byte follows) */ function readVarInt() { var result = 0; while (true) { var b = readInt8(); if (b & 0x80) { result += (b & 0x7f); result <<= 7; } else { /* b is the last byte */ return result + b; } } } return { 'eof': eof, 'read': read, 'readInt32': readInt32, 'readInt16': readInt16, 'readInt8': readInt8, 'readVarInt': readVarInt } } /******************************************************************************* * 7) synth.js ******************************************************************************/ function SineGenerator(freq) { var self = {'alive': true}; var period = sampleRate / freq; var t = 0; self.generate = function(buf, offset, count) { for (; count; count--) { var phase = t / period; var result = Math.sin(phase * 2 * Math.PI); buf[offset++] += result; buf[offset++] += result; t++; } } return self; } function SquareGenerator(freq, phase) { var self = {'alive': true}; var period = sampleRate / freq; var t = 0; self.generate = function(buf, offset, count) { for (; count; count--) { var result = ( (t / period) % 1 > phase ? 1 : -1); buf[offset++] += result; buf[offset++] += result; t++; } } return self; } function ADSRGenerator(child, attackAmplitude, sustainAmplitude, attackTimeS, decayTimeS, releaseTimeS) { var self = {'alive': true} var attackTime = sampleRate * attackTimeS; var decayTime = sampleRate * (attackTimeS + decayTimeS); var decayRate = (attackAmplitude - sustainAmplitude) / (decayTime - attackTime); var releaseTime = null; /* not known yet */ var endTime = null; /* not known yet */ var releaseRate = sustainAmplitude / (sampleRate * releaseTimeS); var t = 0; self.noteOff = function() { if (self.released) return; releaseTime = t; self.released = true; endTime = releaseTime + sampleRate * releaseTimeS; } self.generate = function(buf, offset, count) { if (!self.alive) return; var input = new Array(count * 2); for (var i = 0; i < count*2; i++) { input[i] = 0; } child.generate(input, 0, count); childOffset = 0; while(count) { if (releaseTime != null) { if (t < endTime) { /* release */ while(count && t < endTime) { var ampl = sustainAmplitude - releaseRate * (t - releaseTime); buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else { /* dead */ self.alive = false; return; } } else if (t < attackTime) { /* attack */ while(count && t < attackTime) { var ampl = attackAmplitude * t / attackTime; buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else if (t < decayTime) { /* decay */ while(count && t < decayTime) { var ampl = attackAmplitude - decayRate * (t - attackTime); buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else { /* sustain */ while(count) { buf[offset++] += input[childOffset++] * sustainAmplitude; buf[offset++] += input[childOffset++] * sustainAmplitude; t++; count--; } } } } return self; } function midiToFrequency(note) { return 440 * Math.pow(2, (note-69)/12); } PianoProgram = { 'attackAmplitude': 0.2, 'sustainAmplitude': 0.1, 'attackTime': 0.02, 'decayTime': 0.3, 'releaseTime': 0.02, 'createNote': function(note, velocity) { var frequency = midiToFrequency(note); return ADSRGenerator( SineGenerator(frequency), this.attackAmplitude * (velocity / 128), this.sustainAmplitude * (velocity / 128), this.attackTime, this.decayTime, this.releaseTime ); } } StringProgram = { 'createNote': function(note, velocity) { var frequency = midiToFrequency(note); return ADSRGenerator( SineGenerator(frequency), 0.5 * (velocity / 128), 0.2 * (velocity / 128), 0.4, 0.8, 0.4 ); } } PROGRAMS = { 41: StringProgram, 42: StringProgram, 43: StringProgram, 44: StringProgram, 45: StringProgram, 46: StringProgram, 47: StringProgram, 49: StringProgram, 50: StringProgram }; function Synth(sampleRate) { var generators = []; function addGenerator(generator) { generators.push(generator); } function generate(samples) { var data = new Array(samples*2); generateIntoBuffer(samples, data, 0); return data; } function generateIntoBuffer(samplesToGenerate, buffer, offset) { for (var i = offset; i < offset + samplesToGenerate * 2; i++) { buffer[i] = 0; } for (var i = generators.length - 1; i >= 0; i--) { generators[i].generate(buffer, offset, samplesToGenerate); if (!generators[i].alive) generators.splice(i, 1); } } return { 'sampleRate': sampleRate, 'addGenerator': addGenerator, 'generate': generate, 'generateIntoBuffer': generateIntoBuffer } } } // end of: if (typeof (MidiPlayer) == 'undefined')
import uglify from 'rollup-plugin-uglify' import buble from 'rollup-plugin-buble' export default { entry: 'js/index.js', dest: 'public/bundle.js', format: 'iife', plugins: [buble(), uglify()], }
function filterSinceSync(d) { var isValid = typeof d === 'number' || d instanceof Number || d instanceof Date; if (!isValid) { throw new Error('expected since option to be a date or a number'); } return file.stat && file.stat.mtime > d; }; module.exports = filterSinceSync;
var expect = require('chai').expect; var sinon = require('sinon'); var ColumnShifter = require('component/grid/projection/column-shifter'); var Base = require('component/grid/projection/base'); var Response = require('component/grid/model/response'); describe('projection ColumnShifter', function () { it('update should run normal', function () { var model = new ColumnShifter(); var originalData = new Base(); originalData.data = new Response({ columns: { name: { name: 'hello', property: 'name' }, id: { id: '007', property: 'id' }, }, select: ['name', 'id'], }); originalData.pipe(model); expect(model.data.get('select')[0]).to.be.equal('column.skip.less'); expect(model.data.get('select')[3]).to.be.equal('column.skip.more'); }); it('thClick should run normal', function () { var model = new ColumnShifter(); model.get = sinon.stub().returns(1); sinon.spy(model, 'set'); model.thClick({}, { column: { $metadata: { enabled: true } }, property: 'column.skip.less', }); expect(model.set.calledWith({ 'column.skip': 0 })).to.be.true; }); });
'use strict'; let TimeseriesShowController = function($scope, $controller, $timeout, NpolarApiSecurity, NpolarTranslate, npdcAppConfig, Timeseries, TimeseriesModel, TimeseriesCitation, google, Sparkline) { 'ngInject'; let ctrl = this; ctrl.authors = (t) => { return t.authors.map(a => { return { name: a['@id']}; }); }; // @todo NpolarLinkModel? ctrl.collection_link = (links,hreflang='en') => { return links.find(l => l.rel === 'collection' && l.hreflang === hreflang); }; $controller("NpolarBaseController", {$scope: $scope}); $scope.resource = Timeseries; let chartElement = Sparkline.getElement(); if (chartElement) { chartElement.innerHTML = ''; } $scope.show().$promise.then(timeseries => { $scope.data = timeseries.data; $scope.data_not_null = timeseries.data.filter(t => t.value !== undefined); // Create facet-style links with counts to timeseries with all of the same keywords... if (!$scope.keywords && timeseries.keywords && timeseries.keywords.length > 0) { $scope.keywords = {}; let keywords = TimeseriesModel.keywords(timeseries); ['en', 'no'].forEach(l => { let k = keywords[l]; let href = $scope.resource.uiBase+`?filter-keywords.@value=${ k.join(',') }`; let link = { keywords: keywords[l], count: 0, href }; Timeseries.feed({"filter-keywords.@value": k.join(','), facets: 'keywords,species,locations.placename', limit: 0}).$promise.then((r) => { link.count = r.feed.opensearch.totalResults; // All keywords // Count for all keywords + species if (timeseries.species) { let f = r.feed.facets.find(f => f.hasOwnProperty('species')); if (f && f.species) { let c = f.species.find(f => f.term === timeseries.species); link.count_keywords_and_species = c.count; } } // Count for first all keywords + placename[0] if (timeseries.locations && timeseries.locations.length > 0) { let f = r.feed.facets.find(f => f.hasOwnProperty('locations.placename')); if (f && f['locations.placename']) { let c = f['locations.placename'].find(f => f.term === timeseries.locations[0].placename); link.count_keywords_and_placename = c.count; } } $scope.keywords[l] = link; }, (e) => { $scope.keywords[l] = link; }); }); } $scope.citation = (t) => { if (!t) { return; } return TimeseriesCitation.citation(timeseries); }; // Create graph if ($scope.data && $scope.data.length > 0) { $timeout(function(){ $scope.sparkline = true; let sparkline = timeseries.data.map(d => [d.value]); google.setOnLoadCallback(Sparkline.draw(sparkline)); }); } // Count number of timeseries belonging to the same collection if (timeseries.links && timeseries.links.length > 0) { ['en', 'nb'].forEach(l => { if (!$scope.collection || !$scope.collection[l]) { let link = ctrl.collection_link(timeseries.links, l); if (link && link.href) { let query = {"filter-links.href": link.href, limit: 0 }; Timeseries.feed(query).$promise.then(r => { if (!$scope.collection) { $scope.collection = {}; } $scope.collection[l] = { href: $scope.resource.uiBase+`?filter-links.href=${link.href}`, title: link.title, count: r.feed.opensearch.totalResults }; }); } } }); } }); }; module.exports = TimeseriesShowController;
var should = require('should'); var npg = require('../core/npg').npg; var config = require('./_test_config_npg'); var request = ({body: {phrase: "111"}}); describe('NPG w/ config', function () { it('should using fixed key', function () { config.useFixedKey.should.be.ok; }); it('should return correct answer', function () { npg("111",config.key1,config.key2).should.eql({ md5: '747207ac', b64: '!QWOwMWY3AjM3QzN' }) }) });
/** * LICENSE : MIT */ "use strict"; (function (mod) { if (typeof exports == "object" && typeof module == "object") { mod(require("codemirror")); } else if (typeof define == "function" && define.amd) { define(["codemirror"], mod); } else { mod(CodeMirror); } })(function (CodeMirror) { "use strict"; CodeMirror.commands.scrollSelectionToCenter = function (cm) { if (cm.getOption("disableInput")) { return CodeMirror.Pass; } var cursor = cm.getCursor('anchor'); var top = cm.charCoords({line: cursor.line, ch: 0}, "local").top; var halfWindowHeight = cm.getWrapperElement().offsetHeight / 2; var scrollTo = Math.round((top - halfWindowHeight)); cm.scrollTo(null, scrollTo); }; CodeMirror.defineOption("typewriterScrolling", false, function (cm, val, old) { if (old && old != CodeMirror.Init) { cm.off("changes", onChanges); } if (val) { cm.on("changes", onChanges); } }); function onChanges(cm, changes) { if (cm.getSelection().length !== 0) { return; } for (var i = 0, len = changes.length; i < len; i++) { var each = changes[i]; if (each.origin === '+input' || each.origin === '+delete') { cm.execCommand("scrollSelectionToCenter"); return; } } } });
/** * @name Evemit * @description Minimal and fast JavaScript event emitter for Node.js and front-end. * @author Nicolas Tallefourtane <[email protected]> * @link https://github.com/Nicolab/evemit * @license MIT https://github.com/Nicolab/evemit/blob/master/LICENSE */ ;(function() { 'use strict'; /** * Evemit * * @constructor * @api public */ function Evemit() { this.events = {}; } /** * Register a new event listener for a given event. * * @param {string} event Event name. * @param {function} fn Callback function (listener). * @param {*} [context] Context for function execution. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.on = function(event, fn, context) { if (!this.events[event]) { this.events[event] = []; } if(context) { fn._E_ctx = context; } this.events[event].push(fn); return this; }; /** * Add an event listener that's only called once. * * @param {string} event Event name. * @param {function} fn Callback function (listener). * @param {*} [context] Context for function execution. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.once = function(event, fn, context) { fn._E_once = true; return this.on(event, fn, context); }; /** * Emit an event to all registered event listeners. * * @param {string} event Event name. * @param {*} [...arg] One or more arguments to pass to the listeners. * @return {bool} Indication, `true` if at least one listener was executed, * otherwise returns `false`. * @api public */ Evemit.prototype.emit = function(event, arg1, arg2, arg3, arg4) { var fn, evs, args, aLn; if(!this.events[event]) { return false; } args = Array.prototype.slice.call(arguments, 1); aLn = args.length; evs = this.events[event]; for(var i = 0, ln = evs.length; i < ln; i++) { fn = evs[i]; if (fn._E_once) { this.off(event, fn); } // Function.apply() is a bit slower, so try to do without switch (aLn) { case 0: fn.call(fn._E_ctx); break; case 1: fn.call(fn._E_ctx, arg1); break; case 2: fn.call(fn._E_ctx, arg1, arg2); break; case 3: fn.call(fn._E_ctx, arg1, arg2, arg3); break; case 4: fn.call(fn._E_ctx, arg1, arg2, arg3, arg4); break; default: fn.apply(fn._E_ctx, args); } } return true; }; /** * Remove event listeners. * * @param {string} event The event to remove. * @param {function} fn The listener that we need to find. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.off = function(event, fn) { if (!this.events[event]) { return this; } for (var i = 0, ln = this.events[event].length; i < ln; i++) { if (this.events[event][i] === fn) { this.events[event][i] = null; delete this.events[event][i]; } } // re-index this.events[event] = this.events[event].filter(function(ltns) { return typeof ltns !== 'undefined'; }); return this; }; /** * Get a list of assigned event listeners. * * @param {string} [event] The events that should be listed. * If not provided, all listeners are returned. * Use the property `Evemit.events` if you want to get an object like * ``` * {event1: [array of listeners], event2: [array of listeners], ...} * ``` * * @return {array} * @api public */ Evemit.prototype.listeners = function(event) { var evs, ltns; if(event) { return this.events[event] || []; } evs = this.events; ltns = []; for(var ev in evs) { ltns = ltns.concat(evs[ev].valueOf()); } return ltns; }; /** * Expose Evemit * @type {Evemit} */ if(typeof module !== 'undefined' && module.exports) { module.exports = Evemit; } else { window.Evemit = Evemit; } })();
(function() { //########################################################################################################### var CND, Multimix, alert, badge, debug, dec, decG, echo, help, hex, hexG, info, isa, log, name, nameO, nameOG, rpr, type_of, types, urge, validate, warn, whisper; CND = require('cnd'); rpr = CND.rpr.bind(CND); badge = 'NCR'; log = CND.get_logger('plain', badge); info = CND.get_logger('info', badge); alert = CND.get_logger('alert', badge); debug = CND.get_logger('debug', badge); warn = CND.get_logger('warn', badge); urge = CND.get_logger('urge', badge); whisper = CND.get_logger('whisper', badge); help = CND.get_logger('help', badge); echo = CND.echo.bind(CND); //........................................................................................................... this._input_default = 'plain'; // @_input_default = 'ncr' // @_input_default = 'xncr' //........................................................................................................... Multimix = require('multimix006modern'); this.cloak = (require('./cloak')).new(); this._aggregate = null; this._ISL = require('interskiplist'); this.unicode_isl = (() => { var R, i, interval, len, ref; R = this._ISL.new(); this._ISL.add_index(R, 'rsg'); this._ISL.add_index(R, 'tag'); ref = require('../data/unicode-9.0.0-intervals.json'); for (i = 0, len = ref.length; i < len; i++) { interval = ref[i]; this._ISL.add(R, interval); } this._aggregate = this._ISL.aggregate.use(R); return R; })(); types = require('./types'); ({isa, validate, type_of} = types.export()); //=========================================================================================================== //----------------------------------------------------------------------------------------------------------- this._copy_library = function(input_default = 'plain') { /* TAINT makeshift method until we have something better; refer to `tests[ "(v2) create derivatives of NCR (2)" ]` for example usage */ var R, mix, reducers; reducers = { fallback: 'assign', fields: { unicode_isl: (values) => { return this._ISL.copy(this.unicode_isl); } } }; //......................................................................................................... mix = (require('multimix006modern')).mix.use(reducers); R = mix(this, { _input_default: input_default }); R._aggregate = R._ISL.aggregate.use(R.unicode_isl); //......................................................................................................... return R; }; //=========================================================================================================== // CLOAK //----------------------------------------------------------------------------------------------------------- this._XXX_escape_chrs = (text) => { return this.cloak.backslashed.hide(this.cloak.hide(text)); }; this._XXX_unescape_escape_chrs = (text) => { return this.cloak.reveal(this.cloak.backslashed.reveal(text)); }; this._XXX_remove_escaping_backslashes = (text) => { return this.cloak.backslashed.remove(text); }; //=========================================================================================================== // SPLIT TEXT INTO CHARACTERS //----------------------------------------------------------------------------------------------------------- this.chrs_from_esc_text = function(text, settings) { var R, chrs, i, is_escaped, len, part, parts; R = []; parts = text.split(/\\([^.])/); is_escaped = true; for (i = 0, len = parts.length; i < len; i++) { part = parts[i]; if (is_escaped = !is_escaped) { /* almost */ R.push(part); continue; } chrs = this.chrs_from_text(part, settings); if (chrs[chrs.length - 1] === '\\') { chrs.pop(); } R.splice(R.length, 0, ...chrs); } //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this.chrs_from_text = function(text, settings) { var input_mode, ref, splitter; if (text.length === 0) { return []; } //......................................................................................................... switch (input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default) { case 'plain': splitter = this._plain_splitter; break; case 'ncr': splitter = this._ncr_splitter; break; case 'xncr': splitter = this._xncr_splitter; break; default: throw new Error(`unknown input mode: ${rpr(input_mode)}`); } //......................................................................................................... return (text.split(splitter)).filter(function(element, idx) { return element.length !== 0; }); }; //----------------------------------------------------------------------------------------------------------- this._new_chunk = function(csg, rsg, chrs) { var R; R = { '~isa': 'NCR/chunk', 'csg': csg, 'rsg': rsg, // 'chrs': chrs 'text': chrs.join('') }; //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this.chunks_from_text = function(text, settings) { /* Given a `text` and `settings` (of which `csg` is irrelevant here), return a list of `NCR/chunk` objects (as returned by `NCR._new_chunk`) that describes stretches of characters with codepoints in the same 'range' (Unicode block). */ var R, chr, chrs, csg, description, i, last_csg, last_rsg, len, output_mode, ref, ref1, rsg, transform_output; R = []; if (text.length === 0) { return R; } last_csg = 'u'; last_rsg = null; chrs = []; //......................................................................................................... switch (output_mode = (ref = settings != null ? settings['output'] : void 0) != null ? ref : this._input_default) { case 'plain': transform_output = function(chr) { return chr; }; break; case 'html': transform_output = function(chr) { switch (chr) { case '&': return '&amp;'; case '<': return '&lt;'; case '>': return '&gt;'; default: return chr; } }; break; default: throw new Error(`unknown output mode: ${rpr(output_mode)}`); } ref1 = this.chrs_from_text(text, settings); //......................................................................................................... for (i = 0, len = ref1.length; i < len; i++) { chr = ref1[i]; description = this.analyze(chr, settings); ({csg, rsg} = description); chr = description[csg === 'u' ? 'chr' : 'ncr']; if (rsg !== last_rsg) { if (chrs.length > 0) { R.push(this._new_chunk(last_csg, last_rsg, chrs)); } last_csg = csg; last_rsg = rsg; chrs = []; } //....................................................................................................... chrs.push(transform_output(chr)); } if (chrs.length > 0) { //......................................................................................................... R.push(this._new_chunk(last_csg, last_rsg, chrs)); } return R; }; //----------------------------------------------------------------------------------------------------------- this.html_from_text = function(text, settings) { var R, chunk, chunks, i, input_mode, len, ref, ref1; R = []; //......................................................................................................... input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; chunks = this.chunks_from_text(text, { input: input_mode, output: 'html' }); for (i = 0, len = chunks.length; i < len; i++) { chunk = chunks[i]; R.push(`<span class="${(ref1 = chunk['rsg']) != null ? ref1 : chunk['csg']}">${chunk['text']}</span>`); } //......................................................................................................... return R.join(''); }; //=========================================================================================================== // CONVERTING TO CID //----------------------------------------------------------------------------------------------------------- this.cid_from_chr = function(chr, settings) { var input_mode, ref; input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; return (this._chr_csg_cid_from_chr(chr, input_mode))[2]; }; //----------------------------------------------------------------------------------------------------------- this.csg_cid_from_chr = function(chr, settings) { var input_mode, ref; input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; return (this._chr_csg_cid_from_chr(chr, input_mode)).slice(1); }; //----------------------------------------------------------------------------------------------------------- this._chr_csg_cid_from_chr = function(chr, input_mode) { /* thx to http://perldoc.perl.org/Encode/Unicode.html */ var cid, cid_dec, cid_hex, csg, first_chr, hi, lo, match, matcher; if (chr.length === 0) { /* Given a text with one or more characters, return the first character, its CSG, and its CID (as a non-negative integer). Additionally, an input mode may be given as either `plain`, `ncr`, or `xncr`. */ //......................................................................................................... throw new Error("unable to obtain CID from empty string"); } //......................................................................................................... if (input_mode == null) { input_mode = 'plain'; } switch (input_mode) { case 'plain': matcher = this._first_chr_matcher_plain; break; case 'ncr': matcher = this._first_chr_matcher_ncr; break; case 'xncr': matcher = this._first_chr_matcher_xncr; break; default: throw new Error(`unknown input mode: ${rpr(input_mode)}`); } //......................................................................................................... match = chr.match(matcher); if (match == null) { throw new Error(`illegal character sequence in ${rpr(chr)}`); } first_chr = match[0]; //......................................................................................................... switch (first_chr.length) { //....................................................................................................... case 1: return [first_chr, 'u', first_chr.charCodeAt(0)]; //....................................................................................................... case 2: hi = first_chr.charCodeAt(0); lo = first_chr.charCodeAt(1); cid = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; return [first_chr, 'u', cid]; default: //....................................................................................................... [chr, csg, cid_hex, cid_dec] = match; cid = cid_hex != null ? parseInt(cid_hex, 16) : parseInt(cid_dec, 10); if (csg.length === 0) { csg = 'u'; } return [first_chr, csg, cid]; } }; // #----------------------------------------------------------------------------------------------------------- // @cid_from_ncr = ( ) -> // #----------------------------------------------------------------------------------------------------------- // @cid_from_xncr = ( ) -> // #----------------------------------------------------------------------------------------------------------- // @cid_from_fncr = ( ) -> //=========================================================================================================== // CONVERTING FROM CID &c //----------------------------------------------------------------------------------------------------------- this.as_csg = function(cid_hint, O) { return (this._csg_cid_from_hint(cid_hint, O))[0]; }; this.as_cid = function(cid_hint, O) { return (this._csg_cid_from_hint(cid_hint, O))[1]; }; //........................................................................................................... this.as_chr = function(cid_hint, O) { return this._as_chr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_uchr = function(cid_hint, O) { return this._as_uchr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_fncr = function(cid_hint, O) { return this._as_fncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_sfncr = function(cid_hint, O) { return this._as_sfncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_xncr = function(cid_hint, O) { return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_ncr = function(cid_hint, O) { return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_rsg = function(cid_hint, O) { return this._as_rsg.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_range_name = function(cid_hint, O) { return this._as_range_name.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; //........................................................................................................... this.analyze = function(cid_hint, O) { return this._analyze.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; //----------------------------------------------------------------------------------------------------------- this._analyze = function(csg, cid) { var R, chr, ncr, xncr; if (csg === 'u') { chr = this._unicode_chr_from_cid(cid); ncr = xncr = this._as_xncr(csg, cid); } else { chr = this._as_xncr(csg, cid); xncr = this._as_xncr(csg, cid); ncr = this._as_xncr('u', cid); } //......................................................................................................... R = { '~isa': 'NCR/info', 'chr': chr, 'uchr': this._unicode_chr_from_cid(cid), 'csg': csg, 'cid': cid, 'fncr': this._as_fncr(csg, cid), 'sfncr': this._as_sfncr(csg, cid), 'ncr': ncr, 'xncr': xncr, 'rsg': this._as_rsg(csg, cid) }; //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this._as_chr = function(csg, cid) { if (csg === 'u') { return this._unicode_chr_from_cid(cid); } return (this._analyze(csg, cid))['chr']; }; //----------------------------------------------------------------------------------------------------------- this._as_uchr = function(csg, cid) { return this._unicode_chr_from_cid(cid); }; //----------------------------------------------------------------------------------------------------------- this._unicode_chr_from_cid = function(cid) { if (!((0x000000 <= cid && cid <= 0x10ffff))) { return null; } return String.fromCodePoint(cid); }; // ### thx to http://perldoc.perl.org/Encode/Unicode.html ### // hi = ( Math.floor ( cid - 0x10000 ) / 0x400 ) + 0xD800 // lo = ( cid - 0x10000 ) % 0x400 + 0xDC00 // return ( String.fromCharCode hi ) + ( String.fromCharCode lo ) //----------------------------------------------------------------------------------------------------------- this._as_fncr = function(csg, cid) { var ref, rsg; rsg = (ref = this._as_rsg(csg, cid)) != null ? ref : csg; return `${rsg}-${cid.toString(16)}`; }; //----------------------------------------------------------------------------------------------------------- this._as_sfncr = function(csg, cid) { return `${csg}-${cid.toString(16)}`; }; //----------------------------------------------------------------------------------------------------------- this._as_xncr = function(csg, cid) { if (csg === 'u' || (csg == null)) { csg = ''; } return `&${csg}#x${cid.toString(16)};`; }; //----------------------------------------------------------------------------------------------------------- this._as_rsg = function(csg, cid) { var ref; if (csg !== 'u') { return csg; } return (ref = (this._aggregate(cid))['rsg']) != null ? ref : csg; }; //----------------------------------------------------------------------------------------------------------- this._as_range_name = function(csg, cid) { var ref; if (csg !== 'u') { return this._as_rsg(csg, cid); } return (ref = (this._aggregate(cid))['block']) != null ? ref : this._as_rsg(csg, cid); }; //=========================================================================================================== // ANALYZE ARGUMENTS //----------------------------------------------------------------------------------------------------------- this._csg_cid_from_hint = function(cid_hint, settings) { var cid, csg, csg_of_cid_hint, csg_of_options, input_mode, type; /* This helper is used to derive the correct CSG and CID from arguments as accepted by the `as_*` family of methods, such as `NCR.as_fncr`, `NCR.as_rsg` and so on; its output may be directly applied to the respective namesake private method (`NCR._as_fncr`, `NCR._as_rsg` and so on). The method arguments should obey the following rules: * Methods may be called with one or two arguments; the first is known as the 'CID hint', the second as 'settings'. * The CID hint may be a number or a text; if it is a number, it is understood as a CID; if it is a text, its interpretation is subject to the `settings[ 'input' ]` setting. * Options must be an object with the optional members `input` and `csg`. * `settings[ 'input' ]` is *only* observed if the CID hint is a text; it governs which kinds of character references are recognized in the text. `input` may be one of `plain`, `ncr`, or `xncr`; it defaults to `plain` (no character references will be recognized). * `settings[ 'csg' ]` sets the character set sigil. If `csg` is set in the settings, then it will override whatever the outcome of `NCR.csg_cid_from_chr` w.r.t. CSG is—in other words, if you call `NCR.as_sfncr '&jzr#xe100', input: 'xncr', csg: 'u'`, you will get `u-e100`, with the numerically equivalent codepoint from the `u` (Unicode) character set. * Before CSG and CID are returned, they will be validated for plausibility. */ //......................................................................................................... switch (type = type_of(settings)) { case 'null': case 'undefined': csg_of_options = null; input_mode = null; break; case 'object': csg_of_options = settings['csg']; input_mode = settings['input']; break; default: throw new Error(`expected an object as second argument, got a ${type}`); } //......................................................................................................... switch (type = type_of(cid_hint)) { case 'float': csg_of_cid_hint = null; cid = cid_hint; break; case 'text': [csg_of_cid_hint, cid] = this.csg_cid_from_chr(cid_hint, { input: input_mode }); break; default: throw new Error(`expected a text or a number as first argument, got a ${type}`); } //......................................................................................................... if (csg_of_options != null) { csg = csg_of_options; } else if (csg_of_cid_hint != null) { csg = csg_of_cid_hint; } else { csg = 'u'; } //......................................................................................................... // @validate_is_csg csg this.validate_cid(csg, cid); return [csg, cid]; }; //=========================================================================================================== // PATTERNS //----------------------------------------------------------------------------------------------------------- // G: grouped // O: optional name = /(?:[a-z][a-z0-9]*)/.source; // nameG = ( /// ( (?: [a-z][a-z0-9]* ) | ) /// ).source nameO = /(?:(?:[a-z][a-z0-9]*)|)/.source; nameOG = /((?:[a-z][a-z0-9]*)|)/.source; hex = /(?:x[a-fA-F0-9]+)/.source; hexG = /(?:x([a-fA-F0-9]+))/.source; dec = /(?:[0-9]+)/.source; decG = /(?:([0-9]+))/.source; //........................................................................................................... this._csg_matcher = RegExp(`^${name}$`); this._ncr_matcher = RegExp(`(?:&\\#(?:${hex}|${dec});)`); this._xncr_matcher = RegExp(`(?:&${nameO}\\#(?:${hex}|${dec});)`); this._ncr_csg_cid_matcher = RegExp(`(?:&()\\#(?:${hexG}|${decG});)`); this._xncr_csg_cid_matcher = RegExp(`(?:&${nameOG}\\#(?:${hexG}|${decG});)`); //........................................................................................................... /* Matchers for surrogate sequences and non-surrogate, 'ordinary' characters: */ this._surrogate_matcher = /(?:[\ud800-\udbff][\udc00-\udfff])/; this._nonsurrogate_matcher = /[^\ud800-\udbff\udc00-\udfff]/; //........................................................................................................... /* Matchers for the first character of a string, in three modes (`plain`, `ncr`, `xncr`): */ this._first_chr_matcher_plain = RegExp(`^(?:${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._first_chr_matcher_ncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._ncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`); this._first_chr_matcher_xncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._xncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`); //........................................................................................................... this._plain_splitter = RegExp(`(${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._ncr_splitter = RegExp(`(${this._ncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._xncr_splitter = RegExp(`(${this._xncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); // #----------------------------------------------------------------------------------------------------------- // @cid_range_from_rsg = ( rsg ) -> // # [ csg, ... ] = rsg.split '-' // unless ( R = @_ranges_by_rsg[ rsg ] )? // throw new Error "unknown RSG: #{rpr rsg}" // return R // #----------------------------------------------------------------------------------------------------------- // @validate_is_csg = ( x ) -> // validate.text x // throw new Error "not a valid CSG: #{rpr x}" unless ( x.match @_csg_matcher )? // throw new Error "unknown CSG: #{rpr x}" unless @_names_and_ranges_by_csg[ x ]? // return null //----------------------------------------------------------------------------------------------------------- this.validate_cid = function(csg, cid) { validate.float(cid); if (cid !== Math.floor(cid)) { throw new Error(`expected an integer, got ${cid}`); } if (!(cid >= 0)) { throw new Error(`expected a positive integer, got ${cid}`); } if ((csg === 'u') && !((0x000000 <= cid && cid <= 0x10ffff))) { throw new Error(`expected an integer between 0x000000 and 0x10ffff, got 0x${cid.toString(16)}`); } return null; }; // #=========================================================================================================== // class @XXX_Ncr extends Multimix // @include @, { overwrite: true, } # instance methods // # @include @, { overwrite: false, } # instance methods // # @extend @, { overwrite: false, } # class methods // #--------------------------------------------------------------------------------------------------------- // constructor: ( input_default = 'plain' ) -> // super() // debug '^44443^', ( k for k of @ ) // return undefined }).call(this); //# sourceMappingURL=main.js.map
/** * Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). * * @example * this.demoTest = function (browser) { * browser.expect.element('body').to.have.property('className').equals('test-class'); * browser.expect.element('body').to.have.property('className').matches(/^something\ else/); * browser.expect.element('body').to.not.have.property('classList').equals('test-class'); * browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']); * browser.expect.element('body').to.have.property('classList').contain('class-two'); * }; * * @method property * @param {string} property The property name * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default. * @display .property(name) * @api expect.element */ const BaseAssertion = require('./_element-assertion.js'); class PropertyAssertion extends BaseAssertion { static get assertionType() { return BaseAssertion.AssertionType.METHOD; } init(property, msg) { super.init(); this.flag('attributeFlag', true); this.property = property; this.hasCustomMessage = typeof msg != 'undefined'; this.message = msg || 'Expected element <%s> to ' + (this.negate ? 'not have' : 'have') + ' dom property "' + property + '"'; this.start(); } executeCommand() { return this.executeProtocolAction('getElementProperty', [this.property]).then(result => { if (!this.transport.isResultSuccess(result) || result.value === null) { throw result; } return result; }).catch(result => { this.propertyNotFound(); return false; }); } onResultSuccess() { if (this.retries > 0 && this.negate) { return; } if (!this.hasCondition()) { this.passed = !this.negate; this.expected = this.negate ? 'not found' : 'found'; this.actual = 'found'; } this.addExpectedInMessagePart(); } propertyNotFound() { this.processFlags(); this.passed = this.hasCondition() ? false : this.negate; if (!this.passed && this.shouldRetry()) { this.scheduleRetry(); } else { this.addExpectedInMessagePart(); if (!this.hasCondition()) { //this.expected = this.negate ? 'not found' : 'found'; this.actual = 'not found'; } if (!this.negate) { this.messageParts.push(' - property was not found'); } this.done(); } } onResultFailed() { this.passed = false; } } module.exports = PropertyAssertion;
const rangeParser = require(`parse-numeric-range`) module.exports = language => { if (!language) { return `` } if (language.split(`{`).length > 1) { let [splitLanguage, ...options] = language.split(`{`) let highlightLines = [], numberLines = false, numberLinesStartAt // Options can be given in any order and are optional options.forEach(option => { option = option.slice(0, -1) // Test if the option is for line hightlighting if (rangeParser.parse(option).length > 0) { highlightLines = rangeParser.parse(option).filter(n => n > 0) } option = option.split(`:`) // Test if the option is for line numbering // Option must look like `numberLines: true` or `numberLines: <integer>` // Otherwise we disable line numbering if ( option.length === 2 && option[0] === `numberLines` && (option[1].trim() === `true` || Number.isInteger(parseInt(option[1].trim(), 10))) ) { numberLines = true numberLinesStartAt = option[1].trim() === `true` ? 1 : parseInt(option[1].trim(), 10) } }) return { splitLanguage, highlightLines, numberLines, numberLinesStartAt, } } return { splitLanguage: language } }
import ruleError from './ruleError' // Tags that have no associated components but are allowed even so const componentLessTags = [ 'mj-all', 'mj-class', 'mj-selector', 'mj-html-attribute', ] export default function validateTag(element, { components }) { const { tagName } = element if (componentLessTags.includes(tagName)) return null const Component = components[tagName] if (!Component) { return ruleError( `Element ${tagName} doesn't exist or is not registered`, element, ) } return null }
class dximagetransform_microsoft_crblinds_1 { constructor() { // short bands () {get} {set} this.bands = undefined; // int Capabilities () {get} this.Capabilities = undefined; // string Direction () {get} {set} this.Direction = undefined; // float Duration () {get} {set} this.Duration = undefined; // float Progress () {get} {set} this.Progress = undefined; // float StepResolution () {get} this.StepResolution = undefined; } } module.exports = dximagetransform_microsoft_crblinds_1;
'use strict'; var webpack = require('webpack'); var cfg = { entry: './src/main.jsx', output: { path: __dirname + '/dist', filename: 'main.js', }, externals: { yaspm: 'commonjs yaspm' }, target: process.env.NODE_ENV === 'web' ? 'web' : 'node-webkit', module: { loaders: [ { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader?includePaths[]=' + __dirname + '/src' }, { test: /\.(js|jsx)$/, loader: 'jsx-loader?harmony' } ] }, plugins: [ new webpack.DefinePlugin({ '__NODEWEBKIT__': process.env.NODE_ENV === 'nodewebkit', }) ] }; module.exports = cfg;
/** * Created by ff on 2016/10/25. */ require('./style.css'); var vm = avalon.define({ $id:'map' }) module.exports = vm;
'use strict'; const _ = require('lodash'); const path = require('path'); /** * Special settings for use with serverless-offline. */ module.exports = { prepareOfflineInvoke() { // Use service packaging for compile _.set(this.serverless, 'service.package.individually', false); return this.serverless.pluginManager.spawn('webpack:validate').then(() => { // Set offline location automatically if not set manually if (!this.options.location && !_.get(this.serverless, 'service.custom.serverless-offline.location')) { _.set( this.serverless, 'service.custom.serverless-offline.location', path.relative(this.serverless.config.servicePath, path.join(this.webpackOutputPath, 'service')) ); } return null; }); } };
let widget = document.getElementsByClassName('markdownx-widget')[0]; let element = document.getElementsByClassName('markdownx'); let element_divs = element[0].getElementsByTagName('div'); let div_editor = element_divs[0]; let div_preview = element_divs[1]; let navbar_bar = document.getElementsByClassName('markdownx-toolbar')[0].getElementsByTagName('li'); let btn_preview = navbar_bar[0]; let btn_fullscreen = navbar_bar[1]; var turn_active = function(element) { value = element.classname; classval = element.getAttribute('class'); if (value.indexOf('active') >= 0) { element.removeClass('active'); } else { value += 'active' } } var refresh_pretty = function() { // 每次有都需要重新渲染code PR.prettyPrint(); }; var enable_preview = function() { var class_btn_preview = btn_preview.getAttribute('class'); var index = class_btn_preview.indexOf('active'); if (index >= 0) { btn_preview.setAttribute('class', ''); div_editor.setAttribute('class', 'col-md-12 child-left'); div_preview.style.display = 'none'; } else { btn_preview.setAttribute('class', 'active'); div_editor.setAttribute('class', 'col-md-6 child-left'); div_preview.style.display = 'block'; } }; var enable_fullscreen = function() { var class_btn_fullscreen = btn_fullscreen.getAttribute('class'); var index = class_btn_fullscreen.indexOf('active'); if (index >= 0) { btn_fullscreen.setAttribute('class', ''); widget.setAttribute('class', 'markup-widget'); } else{ btn_fullscreen.setAttribute('class', 'active'); widget.setAttribute('class', 'markup-widget fullscreen'); } } Object.keys(element).map(key => element[key].addEventListener('markdownx.update', refresh_pretty) ); btn_preview.addEventListener('click', enable_preview); btn_fullscreen.addEventListener('click', enable_fullscreen);
module.exports = {}; var app_data = {}; function initCharts() { $(document).ready(function() { $.get(app_data.config.analytics_data_route, function(analytics_data) { data = analytics_data.data; max_val = analytics_data.highest_value; var parseDate = d3.time.format('%Y%m%d').parse; data.forEach(function(d) { d.date = parseDate(d.date); }); $('.sessions-value').html(formatAnalyticsValue((analytics_data.total_sessions).toString())); $('.views-value').html(formatAnalyticsValue((analytics_data.total_views).toString())); d3.select(window).on('resize', resize); loadCharts(); }, 'json'); }); } function loadChart(data, max_val, selector, graph_width, graph_height) { var margin = { top: 20, right: 0, bottom: 30, left: 50 }, width = graph_width - margin.left - margin.right, height = graph_height - margin.top - margin.bottom; var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); var color = d3.scale.category10(); var x_axis = d3.svg.axis().scale(x).orient('bottom'); //.tickFormat(d3.time.format('%m/%d/%y')); var y_axis = d3.svg.axis().scale(y).orient('left').ticks(6); var line = d3.svg.line() .interpolate('cardinal') .tension(0.8) .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.val); }); var line_gridline = d3.svg.line() .x(function(d) { return x(d[0]); }) .y(function(d) { return y(d[1]); }); var area = d3.svg.area() .interpolate('cardinal') .tension(0.8) .x(function(d) { return x(d.date); }) .y0(height) .y1(function(d) { return y(d.val); }); d3.select(selector + ' > svg').remove(); var svg = d3.select(selector).append('svg') .attr('viewBox', '0 0 ' + graph_width + ' ' + graph_height) .attr('perserveAspectRatio', 'xMinYMid') .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); color.domain([ 'sessions', 'views' ]); var analytics = color.domain().map(function(name) { return { name: name, values: data.map(function(d) { return {date: d.date, val: +d[name]}; }) }; }); var x_extent = d3.extent(data, function(d) { return d.date; }); x.domain(x_extent); y.domain([ d3.min(analytics, function(c) { return 0; }), d3.max(analytics, function(c) { return max_val; /*d3.max(c.values, function(v) { return v.val; });*/ }) ]); svg.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')') .call(x_axis); svg.append('g') .attr('class', 'y axis') .call(y_axis) .append('text') .style('text-anchor', 'end'); var gridline_data = []; svg.selectAll('.y.axis .tick').each(function(data) { var tick = d3.select(this); var transform = d3.transform(tick.attr('transform')).translate; if (data > 0) { gridline_data.push({ values: [[x_extent[0], transform[1]], [x_extent[1], transform[1]]] }); } }); gridline_data.forEach(function(data) { svg.append('line') .attr('class', 'gridline') .attr('x1', x(data.values[0][0])) .attr('x2', x(data.values[1][0])) .attr('y1', data.values[0][1]) .attr('y2', data.values[1][1]); }); var analytics_line = svg.selectAll('.analytics_line') .data(analytics) .enter().append('g') .attr('class', 'analytics_line'); analytics_line.append('path') .attr('class', 'line') .attr('d', function(d) { return line(d.values); }) .style('stroke', function(d) { return '#f2711c'; }); analytics_line.append('path') .attr('class', 'area') .attr('d', function(d) { return area(d.values); }) .style('fill', function(d) { return '#f2711c'; }); /*analytics.forEach(function(category) { category.values.forEach(function(item) { analytics_line.append('circle') .attr('class', 'dot') .attr('r', 4) .attr('cx', x(item.date)) .attr('cy', y(item.val)) .style('fill', '#f2711c'); }); });*/ } function formatAnalyticsValue(value) { var formatted_val = ''; var c = 1; for (var i=value.length-1; i>=0; i--) { formatted_val = (c++ % 3 == 0 && i > 0 ? ' ' : '') + value.substring(i, i+1) + formatted_val; } return formatted_val; } var aspect = 4; var chart = null; var data = null; var max_val = 0; var resize_timeout = -1; function resize() { if (resize_timeout != -1) clearTimeout(resize_timeout); resize_timeout = setTimeout(function() { resize_timeout = -1; loadCharts(); }, 1000); } function loadCharts() { if (data == null) return; var width = $('.analytics-graph').width(); var height = Math.max(200, $('.analytics-graph').width()/aspect); //prevents height to be smaller than 200px loadChart(data, max_val, '.analytics-graph', width, height); chart = $('.analytics-graph > svg'); } module.exports.init = function(trans, config) { app_data.trans = trans; app_data.config = config; $(document).ready(function() { initCharts(); }); };
const SpecReporter = require('jasmine-spec-reporter').SpecReporter; jasmine.getEnv().clearReporters(); // remove default reporter logs jasmine.getEnv().addReporter(new SpecReporter({ // add jasmine-spec-reporter spec: { displayPending: true, }, summary: { displayDuration: true, } }));
const webpack = require('atool-build/lib/webpack'); module.exports = function (webpackConfig, env) { webpackConfig.babel.plugins.push('transform-runtime'); webpackConfig.babel.plugins.push(['import', { libraryName: 'antd', style: 'css' // if true, use less }]); // Support hmr if (env === 'development') { webpackConfig.devtool = '#eval'; webpackConfig.babel.plugins.push('dva-hmr'); } else { webpackConfig.babel.plugins.push('dev-expression'); } // Don't extract common.js and common.css webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) { return !(plugin instanceof webpack.optimize.CommonsChunkPlugin); }); // Support CSS Modules // Parse all less files as css module. webpackConfig.module.loaders.forEach(function (loader, index) { if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) { loader.include = /node_modules/; loader.test = /\.less$/; } if (loader.test.toString() === '/\\.module\\.less$/') { loader.exclude = /node_modules/; loader.test = /\.less$/; } if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) { loader.include = /node_modules/; loader.test = /\.css$/; } if (loader.test.toString() === '/\\.module\\.css$/') { loader.exclude = /node_modules/; loader.test = /\.css$/; } }); return webpackConfig; };
'use strict'; describe('Controllers Tests ', function () { beforeEach(module('solrpressApp')); describe('SessionsController', function () { var $scope, SessionsService; beforeEach(inject(function ($rootScope, $controller, Sessions) { $scope = $rootScope.$new(); SessionsService = Sessions; $controller('SessionsController',{$scope:$scope, Sessions:SessionsService}); })); it('should invalidate session', function () { //GIVEN $scope.series = "123456789"; //SET SPY spyOn(SessionsService, 'delete'); //WHEN $scope.invalidate($scope.series); //THEN expect(SessionsService.delete).toHaveBeenCalled(); expect(SessionsService.delete).toHaveBeenCalledWith({series: "123456789"}, jasmine.any(Function), jasmine.any(Function)); //SIMULATE SUCCESS CALLBACK CALL FROM SERVICE SessionsService.delete.calls.mostRecent().args[1](); expect($scope.error).toBeNull(); expect($scope.success).toBe('OK'); }); }); });
Template.registerHelper("itemTypes", function() { return [ {label: i18n.t('choose'), value: ''}, {label: i18n.t('offer'), value: 'offer', icon: 'icon gift'}, {label: i18n.t('need'), value: 'need', icon: 'icon fire'}, {label: i18n.t('wish'), value: 'wish', icon: 'icon wizard'}, {label: i18n.t('idea'), value: 'idea', icon: 'icon cloud'} ] })
// -------------------------------------------------------------------------------------------------------------------- // // cloudfront-config.js - config for AWS CloudFront // // Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <[email protected]> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- var data2xml = require('data2xml')({ attrProp : '@', valProp : '#', }); // -------------------------------------------------------------------------------------------------------------------- function pathDistribution(options, args) { return '/' + this.version() + '/distribution'; } function pathDistributionId(options, args) { return '/' + this.version() + '/distribution/' + args.DistributionId; } function pathDistributionIdConfig(options, args) { return '/' + this.version() + '/distribution/' + args.DistributionId + '/config'; } function pathDistributionInvalidation(options, args) { return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation'; } function pathDistributionInvalidationId(options, args) { return '/' + this.version() + '/distribution/' + args.DistributionId + '/invalidation/' + args.InvalidationId; } function pathStreamingDistribution(options, args) { return '/' + this.version() + '/streaming-distribution'; } function pathStreamingDistributionId(options, args) { return '/' + this.version() + '/streaming-distribution/' + args.DistributionId; } function pathStreamingDistributionIdConfig(options, args) { return '/' + this.version() + '/streaming-distribution/' + args.DistributionId + '/config'; } function pathOai(options, args) { return '/' + this.version() + '/origin-access-identity/cloudfront'; } function pathOaiId(options, args) { return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId; } function pathOaiIdConfig(options, args) { return '/' + this.version() + '/origin-access-identity/cloudfront/' + args.OriginAccessId + '/config'; } function bodyDistributionConfig(options, args) { // create the XML var data = { '@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' }, }; if ( args.S3OriginDnsName ) { data.S3Origin = {}; data.S3Origin.DNSName = args.S3OriginDnsName; if ( args.S3OriginOriginAccessIdentity ) { data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity; } } if ( args.CustomOriginDnsName || args.CustomOriginOriginProtocolPolicy ) { data.CustomOrigin = {}; if ( args.CustomOriginDnsName ) { data.CustomOrigin.DNSName = args.CustomOriginDnsName; } if ( args.CustomOriginHttpPort ) { data.CustomOrigin.HTTPPort = args.CustomOriginHttpPort; } if ( args.CustomOriginHttpsPort ) { data.CustomOrigin.HTTPSPort = args.CustomOriginHttpsPort; } if ( args.CustomOriginOriginProtocolPolicy ) { data.CustomOrigin.OriginProtocolPolicy = args.CustomOriginOriginProtocolPolicy; } } data.CallerReference = args.CallerReference; if ( args.Cname ) { data.CNAME = args.Cname; } if ( args.Comment ) { data.Comment = args.Comment; } if ( args.DefaultRootObject ) { data.DefaultRootObject = args.DefaultRootObject; } data.Enabled = args.Enabled; if ( args.PriceClass ) { data.PriceClass = args.PriceClass; } if ( args.LoggingBucket ) { data.Logging = {}; data.Logging.Bucket = args.LoggingBucket; if ( args.LoggingPrefix ) { data.Logging.Prefix = args.LoggingPrefix; } } if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) { data.TrustedSigners = {}; if ( args.TrustedSignersSelf ) { data.TrustedSigners.Self = ''; } if ( args.TrustedSignersAwsAccountNumber ) { data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber; } } if ( args.RequiredProtocolsProtocol ) { data.RequiredProtocols = {}; data.RequiredProtocols.Protocol = args.RequiredProtocolsProtocol; } return data2xml('DistributionConfig', data); } function bodyStreamingDistributionConfig(options, args) { // create the XML var data = { '@' : { 'xmlns' : 'http://cloudfront.amazonaws.com/doc/2010-11-01/' }, }; if ( args.S3OriginDnsName ) { data.S3Origin = {}; data.S3Origin.DNSName = args.S3OriginDnsName; if ( args.S3OriginOriginAccessIdentity ) { data.S3Origin.OriginAccessIdentity = args.S3OriginOriginAccessIdentity; } } data.CallerReference = args.CallerReference; if ( args.Cname ) { data.CNAME = args.Cname; } if ( args.Comment ) { data.Comment = args.Comment; } data.Enabled = args.Enabled; if ( args.PriceClass ) { data.PriceClass = args.PriceClass; } if ( args.LoggingBucket ) { data.Logging = {}; data.Logging.Bucket = args.LoggingBucket; if ( args.LoggingPrefix ) { data.Logging.Prefix = args.LoggingPrefix; } } if ( args.TrustedSignersSelf || args.TrustedSignersAwsAccountNumber ) { data.TrustedSigners = {}; if ( args.TrustedSignersSelf ) { data.TrustedSigners.Self = ''; } if ( args.TrustedSignersAwsAccountNumber ) { data.TrustedSigners.AwsAccountNumber = args.TrustedSignersAwsAccountNumber; } } return data2xml('StreamingDistributionConfig', data); } function bodyOaiConfig(options, args) { var self = this; var data = { '@' : { xmlns : 'http://cloudfront.amazonaws.com/doc/2010-11-01/', }, CallerReference : args.CallerReference, }; if ( args.Comments ) { data.Comments = args.Comments; } return data2xml('CloudFrontOriginAccessIdentityConfig', data); } // -------------------------------------------------------------------------------------------------------------------- module.exports = { // Operations on Distributions CreateDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html', method : 'POST', path : pathDistribution, args : { // S3Origin Elements DnsName : { type : 'special', required : false, }, OriginAccessIdentity : { type : 'special', required : false, }, // CustomOrigin elements CustomOriginDnsName : { type : 'special', required : false, }, CustomOriginHttpPort : { type : 'special', required : false, }, CustomOriginHttpsPort : { type : 'special', required : false, }, CustomOriginOriginProtocolPolicy : { type : 'special', required : false, }, // other top level elements CallerReference : { type : 'special', required : true, }, Cname : { type : 'special', required : false, }, Comment : { type : 'special', required : false, }, Enabled : { type : 'special', required : true, }, DefaultRootObject : { type : 'special', required : true, }, // Logging Elements LoggingBucket : { type : 'special', required : false, }, LoggingPrefix : { type : 'special', required : false, }, // TrustedSigners Elements TrustedSignersSelf : { type : 'special', required : false, }, TrustedSignersAwsAccountNumber : { type : 'special', required : false, }, RequiredProtocols : { type : 'special', required : false, }, }, body : bodyDistributionConfig, statusCode: 201, }, ListDistributions : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListDistributions.html', path : pathDistribution, args : { Marker : { required : false, type : 'param', }, MaxItems : { required : false, type : 'param', }, }, }, GetDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetDistribution.html', path : pathDistributionId, args : { DistributionId : { required : true, type : 'special', }, }, }, GetDistributionConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetConfig.html', path : pathDistributionIdConfig, args : { DistributionId : { required : true, type : 'special', }, }, }, PutDistributionConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutConfig.html', method : 'PUT', path : pathDistributionIdConfig, args : { DistributionId : { required : true, type : 'special', }, IfMatch : { name : 'If-Match', required : true, type : 'header' }, // S3Origin Elements DnsName : { type : 'special', required : false, }, OriginAccessIdentity : { type : 'special', required : false, }, // CustomOrigin elements CustomOriginDnsName : { type : 'special', required : false, }, CustomOriginHttpPort : { type : 'special', required : false, }, CustomOriginHttpsPort : { type : 'special', required : false, }, CustomOriginOriginProtocolPolicy : { type : 'special', required : false, }, // other top level elements CallerReference : { type : 'special', required : true, }, Cname : { type : 'special', required : false, }, Comment : { type : 'special', required : false, }, Enabled : { type : 'special', required : true, }, PriceClass : { type : 'special', required : false, }, DefaultRootObject : { type : 'special', required : true, }, // Logging Elements LoggingBucket : { type : 'special', required : false, }, LoggingPrefix : { type : 'special', required : false, }, // TrustedSigners Elements TrustedSignersSelf : { type : 'special', required : false, }, TrustedSignersAwsAccountNumber : { type : 'special', required : false, }, RequiredProtocols : { type : 'special', required : false, }, }, body : bodyDistributionConfig, }, DeleteDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteDistribution.html', method : 'DELETE', path : pathDistributionId, args : { DistributionId : { required : true, type : 'special', }, IfMatch : { name : 'If-Match', required : true, type : 'header' }, }, statusCode : 204, }, // Operations on Streaming Distributions CreateStreamingDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateStreamingDistribution.html', method : 'POST', path : pathStreamingDistribution, args : { // S3Origin Elements S3OriginDnsName : { type : 'special', required : false, }, S3OriginOriginAccessIdentity : { type : 'special', required : false, }, // other top level elements CallerReference : { type : 'special', required : true, }, Cname : { type : 'special', required : false, }, Comment : { type : 'special', required : false, }, Enabled : { type : 'special', required : true, }, PriceClass : { type : 'special', required : false, }, // Logging Elements LoggingBucket : { type : 'special', required : false, }, LoggingPrefix : { type : 'special', required : false, }, // TrustedSigners Elements TrustedSignersSelf : { type : 'special', required : false, }, TrustedSignersAwsAccountNumber : { type : 'special', required : false, }, }, body : bodyStreamingDistributionConfig, }, ListStreamingDistributions : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListStreamingDistributions.html', path : pathStreamingDistribution, args : { Marker : { required : false, type : 'param', }, MaxItems : { required : false, type : 'param', }, }, }, GetStreamingDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistribution.html', path : pathStreamingDistributionId, args : { DistributionId : { required : true, type : 'special', }, }, }, GetStreamingDistributionConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistConfig.html', path : pathStreamingDistributionIdConfig, args : { DistributionId : { required : true, type : 'special', }, }, }, PutStreamingDistributionConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutStreamingDistConfig.html', method : 'PUT', path : pathStreamingDistributionIdConfig, args : { DistributionId : { required : true, type : 'special', }, IfMatch : { name : 'If-Match', required : true, type : 'header' }, // S3Origin Elements DnsName : { type : 'special', required : false, }, OriginAccessIdentity : { type : 'special', required : false, }, // other top level elements CallerReference : { type : 'special', required : true, }, Cname : { type : 'special', required : false, }, Comment : { type : 'special', required : false, }, Enabled : { type : 'special', required : true, }, // Logging Elements LoggingBucket : { type : 'special', required : false, }, LoggingPrefix : { type : 'special', required : false, }, // TrustedSigners Elements TrustedSignersSelf : { type : 'special', required : false, }, TrustedSignersAwsAccountNumber : { type : 'special', required : false, }, }, body : bodyStreamingDistributionConfig, }, DeleteStreamingDistribution : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteStreamingDistribution.html', method : 'DELETE', path : pathStreamingDistributionId, args : { DistributionId : { required : true, type : 'special', }, IfMatch : { name : 'If-Match', required : true, type : 'header' }, }, statusCode : 204, }, // Operations on Origin Access Identities CreateOai : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateOAI.html', method : 'POST', path : pathOai, args : { CallerReference : { required : true, type : 'special', }, Comment : { required : false, type : 'special', }, }, body : bodyOaiConfig, statusCode: 201, }, ListOais : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListOAIs.html', path : pathOai, args : { Marker : { required : false, type : 'param', }, MaxItems : { required : false, type : 'param', }, }, }, GetOai : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAI.html', path : pathOaiId, args : { OriginAccessId : { required : true, type : 'special', }, }, }, GetOaiConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetOAIConfig.html', path : pathOaiIdConfig, args : { OriginAccessId : { required : true, type : 'special', }, }, }, PutOaiConfig : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutOAIConfig.html', method : 'PUT', path : pathOai, args : { OriginAccessId : { required : true, type : 'special', }, CallerReference : { required : true, type : 'special', }, Comment : { required : false, type : 'special', }, }, body : bodyOaiConfig, }, DeleteOai : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteOAI.html', method : 'DELETE', path : pathOaiId, args : { OriginAccessId : { required : true, type : 'special', }, IfMatch : { name : 'If-Match', required : true, type : 'header' }, }, statusCode : 204, }, // Operations on Invalidations CreateInvalidation : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateInvalidation.html', method : 'POST', path : pathDistributionInvalidation, args : { DistributionId : { required : true, type : 'special', }, Path : { required : true, type : 'special', }, CallerReference : { required : false, type : 'special', }, }, body : function(options, args) { var self = this; var data = { Path : args.Path, }; if ( args.CallerReference ) { data.CallerReference = args.CallerReference; } return data2xml('InvalidationBatch', data); }, }, ListInvalidations : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html', path : pathDistributionInvalidation, args : { DistributionId : { required : true, type : 'special', }, Marker : { required : false, type : 'param', }, MaxItems : { required : false, type : 'param', }, }, }, GetInvalidation : { url : 'http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetInvalidation.html', path : pathDistributionInvalidationId, args : { DistributionId : { required : true, type : 'special', }, Marker : { required : false, type : 'param', }, MaxItems : { required : false, type : 'param', }, }, }, }; // --------------------------------------------------------------------------------------------------------------------
var GlobezGame = GlobezGame || {}; GlobezGame.Boot = function() {}; GlobezGame.Boot.prototype = { preload: function() { console.log("%cStarting Fish Vs Mines", "color:white; background:red"); this.load.image("loading", "assets/sprites/loading.png"); this.load.image("logo", "assets/sprites/logo.png"); }, create: function() { this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; // this.scale.setScreenSize(true); this.physics.startSystem(Phaser.Physics.ARCADE); this.state.start("Preload"); } } var GlobezGame = GlobezGame || {}; GlobezGame.Preload = function() {}; GlobezGame.Preload.prototype = { preload: function() { console.log("%cPreloading assets", "color:white; background:red") var loadingBar = this.add.sprite(160, 340, "loading"); loadingBar.anchor.setTo(0.5, 0.5); this.load.setPreloadSprite(loadingBar); var logo = this.add.sprite(160, 240, "logo"); logo.anchor.setTo(0.5, 0.5); this.load.image("background", "assets/sprites/background.png"); this.load.image("playbutton", "assets/sprites/playbutton.png"); this.load.image("gametitle_sealife", "assets/sprites/gametitle_sealife.png"); this.load.image("gametitle_vs", "assets/sprites/gametitle_vs.png"); this.load.image("gametitle_mines", "assets/sprites/gametitle_mines.png"); this.load.image("blackfade", "assets/sprites/blackfade.png"); this.load.image("bubble", "assets/sprites/bubble.png"); }, create: function() { this.state.start("GameTitle"); } } var GlobezGame = GlobezGame || {}; GlobezGame.GameTitle = function() { startGame = false; }; GlobezGame.GameTitle.prototype = { create: function() { console.log("%cStarting game title", "color:white; background:red"); this.add.image(0, 0, "background"); // var bubblesEmitter = this.add.emitter(160, 500, 50); bubblesEmitter.makeParticles("bubble"); bubblesEmitter.maxParticleScale = 0.6; bubblesEmitter.minParticleScale = 0.2; bubblesEmitter.setYSpeed(-30, -40); bubblesEmitter.setXSpeed(-3, 3); bubblesEmitter.gravity = 0; bubblesEmitter.width = 320; bubblesEmitter.minRotation = 0; bubblesEmitter.maxRotation = 40; bubblesEmitter.flow(15000, 2000) // var gameTitleSeaLife = this.add.image(160, 70, "gametitle_sealife"); gameTitleSeaLife.anchor.setTo(0.5, 0.5); gameTitleSeaLife.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1); var seaLifeTween = this.add.tween(gameTitleSeaLife); seaLifeTween.to({ angle: -gameTitleSeaLife.angle }, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true); // var gameTitleVs = this.add.image(190, 120, "gametitle_vs"); gameTitleVs.anchor.setTo(0.5, 0.5); gameTitleVs.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1); var vsTween = this.add.tween(gameTitleVs); vsTween.to({ angle: -gameTitleVs.angle }, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true); // var gameTitleMines = this.add.image(160, 160, "gametitle_mines"); gameTitleMines.anchor.setTo(0.5, 0.5); gameTitleMines.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1); var minesTween = this.add.tween(gameTitleMines); minesTween.to({ angle: -gameTitleMines.angle }, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true); // var playButton = this.add.button(160, 320, "playbutton", this.playTheGame, this) playButton.anchor.setTo(0.5, 0.5); playButton.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1); var playTween = this.add.tween(playButton); playTween.to({ angle: -playButton.angle }, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true); // var blackFade = this.add.sprite(0, 0, "blackfade"); var fadeTween = this.add.tween(blackFade); fadeTween.to({ alpha: 0 }, 2000, Phaser.Easing.Cubic.Out, true); }, playTheGame: function() { if (!startGame) { startGame = true alert("Start the game!!"); } } } var GlobezGame = GlobezGame || {}; GlobezGame.gameOptions = { gameWidth: 320, gameHeight: 480 } GlobezGame.game = new Phaser.Game(GlobezGame.gameOptions.gameWidth, GlobezGame.gameOptions.gameHeight, Phaser.CANVAS, ""); GlobezGame.game.state.add("Boot", GlobezGame.Boot); GlobezGame.game.state.add("Preload", GlobezGame.Preload); GlobezGame.game.state.add("GameTitle", GlobezGame.GameTitle); GlobezGame.game.state.start("Boot");
$("nav span").mouseenter(function(){$("nav").removeClass("closed")}),$("nav").mouseleave(function(){$("nav").addClass("closed")}),$("nav a").click(function(){var o=$(this).parent().index();console.log(o),$("html,body").animate({scrollTop:$(".section-container > section").eq(o).offset().top},500)}),$(window).scroll(function(){var o=$(window).scrollTop()+window.innerHeight,e=$(".keywords").offset().top,n=$("footer").offset().top;console.log(o-e),e>o||o>n?$(".arrow").removeClass("black"):$(".arrow").addClass("black")}),jQuery(document).ready(function(o){o(window).load(function(){o(".preloader").fadeOut("slow",function(){o(this).remove()})})}),function(){for(var o,e=function(){},n=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeline","timelineEnd","timeStamp","trace","warn"],i=n.length,t=window.console=window.console||{};i--;)o=n[i],t[o]||(t[o]=e)}();
'use strict'; describe('nothing', () => { it('should do nothing', () => { // }); });
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "pt-CH", identity: { language: "pt", territory: "CH" }, territory: "CH", numbers: { symbols: { decimal: ",", group: " ", list: ";", percentSign: "%", plusSign: "+", minusSign: "-", exponential: "E", superscriptingExponent: "×", perMille: "‰", infinity: "∞", nan: "NaN", timeSeparator: ":" }, decimal: { patterns: [ "n" ], groupSize: [ 3 ] }, scientific: { patterns: [ "nEn" ], groupSize: [] }, percent: { patterns: [ "n%" ], groupSize: [ 3 ] }, currency: { patterns: [ "n $" ], groupSize: [ 3 ], "unitPattern-count-one": "n $", "unitPattern-count-other": "n $" }, accounting: { patterns: [ "n $", "(n $)" ], groupSize: [ 3 ] }, currencies: { ADP: { displayName: "Peseta de Andorra", "displayName-count-one": "Peseta de Andorra", "displayName-count-other": "Pesetas de Andorra", symbol: "ADP" }, AED: { displayName: "Dirham dos Emirados Árabes Unidos", "displayName-count-one": "Dirham dos Emirados Árabes Unidos", "displayName-count-other": "Dirhams dos Emirados Árabes Unidos", symbol: "AED" }, AFA: { displayName: "Afeghani (1927–2002)", "displayName-count-one": "Afegane do Afeganistão (AFA)", "displayName-count-other": "Afeganes do Afeganistão (AFA)", symbol: "AFA" }, AFN: { displayName: "Afegani do Afeganistão", "displayName-count-one": "Afegani do Afeganistão", "displayName-count-other": "Afeganis do Afeganistão", symbol: "AFN" }, ALK: { displayName: "Lek Albanês (1946–1965)", "displayName-count-one": "Lek Albanês (1946–1965)", "displayName-count-other": "Leks Albaneses (1946–1965)" }, ALL: { displayName: "Lek albanês", "displayName-count-one": "Lek albanês", "displayName-count-other": "Leks albaneses", symbol: "ALL" }, AMD: { displayName: "Dram arménio", "displayName-count-one": "Dram arménio", "displayName-count-other": "Drams arménios", symbol: "AMD" }, ANG: { displayName: "Florim das Antilhas Holandesas", "displayName-count-one": "Florim das Antilhas Holandesas", "displayName-count-other": "Florins das Antilhas Holandesas", symbol: "ANG" }, AOA: { displayName: "Kwanza angolano", "displayName-count-one": "Kwanza angolano", "displayName-count-other": "Kwanzas angolanos", symbol: "AOA", "symbol-alt-narrow": "Kz" }, AOK: { displayName: "Cuanza angolano (1977–1990)", "displayName-count-one": "Kwanza angolano (AOK)", "displayName-count-other": "Kwanzas angolanos (AOK)", symbol: "AOK" }, AON: { displayName: "Novo cuanza angolano (1990–2000)", "displayName-count-one": "Novo kwanza angolano (AON)", "displayName-count-other": "Novos kwanzas angolanos (AON)", symbol: "AON" }, AOR: { displayName: "Cuanza angolano reajustado (1995–1999)", "displayName-count-one": "Kwanza angolano reajustado (AOR)", "displayName-count-other": "Kwanzas angolanos reajustados (AOR)", symbol: "AOR" }, ARA: { displayName: "Austral argentino", "displayName-count-one": "Austral argentino", "displayName-count-other": "Austrais argentinos", symbol: "ARA" }, ARL: { displayName: "Peso lei argentino (1970–1983)", "displayName-count-one": "Peso lei argentino (1970–1983)", "displayName-count-other": "Pesos lei argentinos (1970–1983)", symbol: "ARL" }, ARM: { displayName: "Peso argentino (1881–1970)", "displayName-count-one": "Peso argentino (1881–1970)", "displayName-count-other": "Pesos argentinos (1881–1970)", symbol: "ARM" }, ARP: { displayName: "Peso argentino (1983–1985)", "displayName-count-one": "Peso argentino (1983–1985)", "displayName-count-other": "Pesos argentinos (1983–1985)", symbol: "ARP" }, ARS: { displayName: "Peso argentino", "displayName-count-one": "Peso argentino", "displayName-count-other": "Pesos argentinos", symbol: "ARS", "symbol-alt-narrow": "$" }, ATS: { displayName: "Xelim austríaco", "displayName-count-one": "Schilling australiano", "displayName-count-other": "Schillings australianos", symbol: "ATS" }, AUD: { displayName: "Dólar australiano", "displayName-count-one": "Dólar australiano", "displayName-count-other": "Dólares australianos", symbol: "AU$", "symbol-alt-narrow": "$" }, AWG: { displayName: "Florim de Aruba", "displayName-count-one": "Florim de Aruba", "displayName-count-other": "Florins de Aruba", symbol: "AWG" }, AZM: { displayName: "Manat azerbaijano (1993–2006)", "displayName-count-one": "Manat do Azeibaijão (1993–2006)", "displayName-count-other": "Manats do Azeibaijão (1993–2006)", symbol: "AZM" }, AZN: { displayName: "Manat do Azerbaijão", "displayName-count-one": "Manat do Azerbaijão", "displayName-count-other": "Manats do Azerbaijão", symbol: "AZN" }, BAD: { displayName: "Dinar da Bósnia-Herzegóvina", "displayName-count-one": "Dinar da Bósnia Herzegovina", "displayName-count-other": "Dinares da Bósnia Herzegovina", symbol: "BAD" }, BAM: { displayName: "Marco bósnio-herzegóvino conversível", "displayName-count-one": "Marco bósnio-herzegóvino conversível", "displayName-count-other": "Marcos bósnio-herzegóvinos conversíveis", symbol: "BAM", "symbol-alt-narrow": "KM" }, BAN: { displayName: "Novo dinar da Bósnia-Herzegovina (1994–1997)", "displayName-count-one": "Novo dinar da Bósnia-Herzegovina", "displayName-count-other": "Novos dinares da Bósnia-Herzegovina", symbol: "BAN" }, BBD: { displayName: "Dólar barbadense", "displayName-count-one": "Dólar barbadense", "displayName-count-other": "Dólares barbadenses", symbol: "BBD", "symbol-alt-narrow": "$" }, BDT: { displayName: "Taka de Bangladesh", "displayName-count-one": "Taka de Bangladesh", "displayName-count-other": "Takas de Bangladesh", symbol: "BDT", "symbol-alt-narrow": "৳" }, BEC: { displayName: "Franco belga (convertível)", "displayName-count-one": "Franco belga (conversível)", "displayName-count-other": "Francos belgas (conversíveis)", symbol: "BEC" }, BEF: { displayName: "Franco belga", "displayName-count-one": "Franco belga", "displayName-count-other": "Francos belgas", symbol: "BEF" }, BEL: { displayName: "Franco belga (financeiro)", "displayName-count-one": "Franco belga (financeiro)", "displayName-count-other": "Francos belgas (financeiros)", symbol: "BEL" }, BGL: { displayName: "Lev forte búlgaro", "displayName-count-one": "Lev forte búlgaro", "displayName-count-other": "Levs fortes búlgaros", symbol: "BGL" }, BGM: { displayName: "Lev socialista búlgaro", "displayName-count-one": "Lev socialista búlgaro", "displayName-count-other": "Levs socialistas búlgaros", symbol: "BGM" }, BGN: { displayName: "Lev búlgaro", "displayName-count-one": "Lev búlgaro", "displayName-count-other": "Levs búlgaros", symbol: "BGN" }, BGO: { displayName: "Lev búlgaro (1879–1952)", "displayName-count-one": "Lev búlgaro (1879–1952)", "displayName-count-other": "Levs búlgaros (1879–1952)", symbol: "BGO" }, BHD: { displayName: "Dinar baremita", "displayName-count-one": "Dinar baremita", "displayName-count-other": "Dinares baremitas", symbol: "BHD" }, BIF: { displayName: "Franco burundiano", "displayName-count-one": "Franco burundiano", "displayName-count-other": "Francos burundianos", symbol: "BIF" }, BMD: { displayName: "Dólar bermudense", "displayName-count-one": "Dólar bermudense", "displayName-count-other": "Dólares bermudenses", symbol: "BMD", "symbol-alt-narrow": "$" }, BND: { displayName: "Dólar bruneíno", "displayName-count-one": "Dólar bruneíno", "displayName-count-other": "Dólares bruneínos", symbol: "BND", "symbol-alt-narrow": "$" }, BOB: { displayName: "Boliviano", "displayName-count-one": "Boliviano", "displayName-count-other": "Bolivianos", symbol: "BOB", "symbol-alt-narrow": "Bs" }, BOL: { displayName: "Boliviano (1863–1963)", "displayName-count-one": "Boliviano (1863–1963)", "displayName-count-other": "Bolivianos (1863–1963)", symbol: "BOL" }, BOP: { displayName: "Peso boliviano", "displayName-count-one": "Peso boliviano", "displayName-count-other": "Pesos bolivianos", symbol: "BOP" }, BOV: { displayName: "Mvdol boliviano", "displayName-count-one": "Mvdol boliviano", "displayName-count-other": "Mvdols bolivianos", symbol: "BOV" }, BRB: { displayName: "Cruzeiro novo brasileiro (1967–1986)", "displayName-count-one": "Cruzeiro novo brasileiro (BRB)", "displayName-count-other": "Cruzeiros novos brasileiros (BRB)", symbol: "BRB" }, BRC: { displayName: "Cruzado brasileiro (1986–1989)", "displayName-count-one": "Cruzado brasileiro", "displayName-count-other": "Cruzados brasileiros", symbol: "BRC" }, BRE: { displayName: "Cruzeiro brasileiro (1990–1993)", "displayName-count-one": "Cruzeiro brasileiro (BRE)", "displayName-count-other": "Cruzeiros brasileiros (BRE)", symbol: "BRE" }, BRL: { displayName: "Real brasileiro", "displayName-count-one": "Real brasileiro", "displayName-count-other": "Reais brasileiros", symbol: "R$", "symbol-alt-narrow": "R$" }, BRN: { displayName: "Cruzado novo brasileiro (1989–1990)", "displayName-count-one": "Cruzado novo brasileiro", "displayName-count-other": "Cruzados novos brasileiros", symbol: "BRN" }, BRR: { displayName: "Cruzeiro brasileiro (1993–1994)", "displayName-count-one": "Cruzeiro brasileiro", "displayName-count-other": "Cruzeiros brasileiros", symbol: "BRR" }, BRZ: { displayName: "Cruzeiro brasileiro (1942–1967)", "displayName-count-one": "Cruzeiro brasileiro antigo", "displayName-count-other": "Cruzeiros brasileiros antigos", symbol: "BRZ" }, BSD: { displayName: "Dólar das Bahamas", "displayName-count-one": "Dólar das Bahamas", "displayName-count-other": "Dólares das Bahamas", symbol: "BSD", "symbol-alt-narrow": "$" }, BTN: { displayName: "Ngultrum do Butão", "displayName-count-one": "Ngultrum do Butão", "displayName-count-other": "Ngultruns do Butão", symbol: "BTN" }, BUK: { displayName: "Kyat birmanês", "displayName-count-one": "Kyat burmês", "displayName-count-other": "Kyats burmeses", symbol: "BUK" }, BWP: { displayName: "Pula de Botswana", "displayName-count-one": "Pula de Botswana", "displayName-count-other": "Pulas de Botswana", symbol: "BWP", "symbol-alt-narrow": "P" }, BYB: { displayName: "Rublo novo bielorusso (1994–1999)", "displayName-count-one": "Novo rublo bielorusso (BYB)", "displayName-count-other": "Novos rublos bielorussos (BYB)", symbol: "BYB" }, BYN: { displayName: "Rublo bielorrusso", "displayName-count-one": "Rublo bielorrusso", "displayName-count-other": "Rublos bielorrussos", symbol: "BYN", "symbol-alt-narrow": "р." }, BYR: { displayName: "Rublo bielorrusso (2000–2016)", "displayName-count-one": "Rublo bielorrusso (2000–2016)", "displayName-count-other": "Rublos bielorrussos (2000–2016)", symbol: "BYR" }, BZD: { displayName: "Dólar belizense", "displayName-count-one": "Dólar belizense", "displayName-count-other": "Dólares belizenses", symbol: "BZD", "symbol-alt-narrow": "$" }, CAD: { displayName: "Dólar canadiano", "displayName-count-one": "Dólar canadiano", "displayName-count-other": "Dólares canadianos", symbol: "CA$", "symbol-alt-narrow": "$" }, CDF: { displayName: "Franco congolês", "displayName-count-one": "Franco congolês", "displayName-count-other": "Francos congoleses", symbol: "CDF" }, CHE: { displayName: "Euro WIR", "displayName-count-one": "Euro WIR", "displayName-count-other": "Euros WIR", symbol: "CHE" }, CHF: { displayName: "Franco suíço", "displayName-count-one": "Franco suíço", "displayName-count-other": "Francos suíços", symbol: "CHF" }, CHW: { displayName: "Franco WIR", "displayName-count-one": "Franco WIR", "displayName-count-other": "Francos WIR", symbol: "CHW" }, CLE: { displayName: "Escudo chileno", "displayName-count-one": "Escudo chileno", "displayName-count-other": "Escudos chilenos", symbol: "CLE" }, CLF: { displayName: "Unidades de Fomento chilenas", "displayName-count-one": "Unidade de fomento chilena", "displayName-count-other": "Unidades de fomento chilenas", symbol: "CLF" }, CLP: { displayName: "Peso chileno", "displayName-count-one": "Peso chileno", "displayName-count-other": "Pesos chilenos", symbol: "CLP", "symbol-alt-narrow": "$" }, CNX: { displayName: "Dólar do Banco Popular da China", "displayName-count-one": "Dólar do Banco Popular da China", "displayName-count-other": "Dólares do Banco Popular da China" }, CNY: { displayName: "Yuan chinês", "displayName-count-one": "Yuan chinês", "displayName-count-other": "Yuans chineses", symbol: "CN¥", "symbol-alt-narrow": "¥" }, COP: { displayName: "Peso colombiano", "displayName-count-one": "Peso colombiano", "displayName-count-other": "Pesos colombianos", symbol: "COP", "symbol-alt-narrow": "$" }, COU: { displayName: "Unidade de Valor Real", "displayName-count-one": "Unidade de valor real", "displayName-count-other": "Unidades de valor real", symbol: "COU" }, CRC: { displayName: "Colon costa-riquenho", "displayName-count-one": "Colon costa-riquenho", "displayName-count-other": "Colons costa-riquenhos", symbol: "CRC", "symbol-alt-narrow": "₡" }, CSD: { displayName: "Dinar sérvio (2002–2006)", "displayName-count-one": "Dinar antigo da Sérvia", "displayName-count-other": "Dinares antigos da Sérvia", symbol: "CSD" }, CSK: { displayName: "Coroa Forte checoslovaca", "displayName-count-one": "Coroa forte tchecoslovaca", "displayName-count-other": "Coroas fortes tchecoslovacas", symbol: "CSK" }, CUC: { displayName: "Peso cubano conversível", "displayName-count-one": "Peso cubano conversível", "displayName-count-other": "Pesos cubanos conversíveis", symbol: "CUC", "symbol-alt-narrow": "$" }, CUP: { displayName: "Peso cubano", "displayName-count-one": "Peso cubano", "displayName-count-other": "Pesos cubanos", symbol: "CUP", "symbol-alt-narrow": "$" }, CVE: { displayName: "Escudo cabo-verdiano", "displayName-count-one": "Escudo cabo-verdiano", "displayName-count-other": "Escudos cabo-verdianos", symbol: "CVE" }, CYP: { displayName: "Libra de Chipre", "displayName-count-one": "Libra cipriota", "displayName-count-other": "Libras cipriotas", symbol: "CYP" }, CZK: { displayName: "Coroa checa", "displayName-count-one": "Coroa checa", "displayName-count-other": "Coroas checas", symbol: "CZK", "symbol-alt-narrow": "Kč" }, DDM: { displayName: "Ostmark da Alemanha Oriental", "displayName-count-one": "Marco da Alemanha Oriental", "displayName-count-other": "Marcos da Alemanha Oriental", symbol: "DDM" }, DEM: { displayName: "Marco alemão", "displayName-count-one": "Marco alemão", "displayName-count-other": "Marcos alemães", symbol: "DEM" }, DJF: { displayName: "Franco jibutiano", "displayName-count-one": "Franco jibutiano", "displayName-count-other": "Francos jibutianos", symbol: "DJF" }, DKK: { displayName: "Coroa dinamarquesa", "displayName-count-one": "Coroa dinamarquesa", "displayName-count-other": "Coroas dinamarquesas", symbol: "DKK", "symbol-alt-narrow": "kr" }, DOP: { displayName: "Peso dominicano", "displayName-count-one": "Peso dominicano", "displayName-count-other": "Pesos dominicanos", symbol: "DOP", "symbol-alt-narrow": "$" }, DZD: { displayName: "Dinar argelino", "displayName-count-one": "Dinar argelino", "displayName-count-other": "Dinares argelinos", symbol: "DZD" }, ECS: { displayName: "Sucre equatoriano", "displayName-count-one": "Sucre equatoriano", "displayName-count-other": "Sucres equatorianos", symbol: "ECS" }, ECV: { displayName: "Unidad de Valor Constante (UVC) do Equador", "displayName-count-one": "Unidade de valor constante equatoriana (UVC)", "displayName-count-other": "Unidades de valor constante equatorianas (UVC)", symbol: "ECV" }, EEK: { displayName: "Coroa estoniana", "displayName-count-one": "Coroa estoniana", "displayName-count-other": "Coroas estonianas", symbol: "EEK" }, EGP: { displayName: "Libra egípcia", "displayName-count-one": "Libra egípcia", "displayName-count-other": "Libras egípcias", symbol: "EGP", "symbol-alt-narrow": "E£" }, ERN: { displayName: "Nakfa da Eritreia", "displayName-count-one": "Nakfa da Eritreia", "displayName-count-other": "Nakfas da Eritreia", symbol: "ERN" }, ESA: { displayName: "Peseta espanhola (conta A)", "displayName-count-one": "Peseta espanhola (conta A)", "displayName-count-other": "Pesetas espanholas (conta A)", symbol: "ESA" }, ESB: { displayName: "Peseta espanhola (conta conversível)", "displayName-count-one": "Peseta espanhola (conta conversível)", "displayName-count-other": "Pesetas espanholas (conta conversível)", symbol: "ESB" }, ESP: { displayName: "Peseta espanhola", "displayName-count-one": "Peseta espanhola", "displayName-count-other": "Pesetas espanholas", symbol: "ESP", "symbol-alt-narrow": "₧" }, ETB: { displayName: "Birr etíope", "displayName-count-one": "Birr etíope", "displayName-count-other": "Birrs etíopes", symbol: "ETB" }, EUR: { displayName: "Euro", "displayName-count-one": "Euro", "displayName-count-other": "Euros", symbol: "€", "symbol-alt-narrow": "€" }, FIM: { displayName: "Marca finlandesa", "displayName-count-one": "Marco finlandês", "displayName-count-other": "Marcos finlandeses", symbol: "FIM" }, FJD: { displayName: "Dólar de Fiji", "displayName-count-one": "Dólar de Fiji", "displayName-count-other": "Dólares de Fiji", symbol: "FJD", "symbol-alt-narrow": "$" }, FKP: { displayName: "Libra das Ilhas Falkland", "displayName-count-one": "Libra das Ilhas Falkland", "displayName-count-other": "Libras das Ilhas Falkland", symbol: "FKP", "symbol-alt-narrow": "£" }, FRF: { displayName: "Franco francês", "displayName-count-one": "Franco francês", "displayName-count-other": "Francos franceses", symbol: "FRF" }, GBP: { displayName: "Libra esterlina britânica", "displayName-count-one": "Libra esterlina britânica", "displayName-count-other": "Libras esterlinas britânicas", symbol: "£", "symbol-alt-narrow": "£" }, GEK: { displayName: "Cupom Lari georgiano", "displayName-count-one": "Kupon larit da Geórgia", "displayName-count-other": "Kupon larits da Geórgia", symbol: "GEK" }, GEL: { displayName: "Lari georgiano", "displayName-count-one": "Lari georgiano", "displayName-count-other": "Laris georgianos", symbol: "GEL", "symbol-alt-narrow": "₾", "symbol-alt-variant": "₾" }, GHC: { displayName: "Cedi de Gana (1979–2007)", "displayName-count-one": "Cedi de Gana (1979–2007)", "displayName-count-other": "Cedis de Gana (1979–2007)", symbol: "GHC" }, GHS: { displayName: "Cedi de Gana", "displayName-count-one": "Cedi de Gana", "displayName-count-other": "Cedis de Gana", symbol: "GHS" }, GIP: { displayName: "Libra de Gibraltar", "displayName-count-one": "Libra de Gibraltar", "displayName-count-other": "Libras de Gibraltar", symbol: "GIP", "symbol-alt-narrow": "£" }, GMD: { displayName: "Dalasi da Gâmbia", "displayName-count-one": "Dalasi da Gâmbia", "displayName-count-other": "Dalasis da Gâmbia", symbol: "GMD" }, GNF: { displayName: "Franco guineense", "displayName-count-one": "Franco guineense", "displayName-count-other": "Francos guineenses", symbol: "GNF", "symbol-alt-narrow": "FG" }, GNS: { displayName: "Syli da Guiné", "displayName-count-one": "Syli guineano", "displayName-count-other": "Sylis guineanos", symbol: "GNS" }, GQE: { displayName: "Ekwele da Guiné Equatorial", "displayName-count-one": "Ekwele da Guiné Equatorial", "displayName-count-other": "Ekweles da Guiné Equatorial", symbol: "GQE" }, GRD: { displayName: "Dracma grego", "displayName-count-one": "Dracma grego", "displayName-count-other": "Dracmas gregos", symbol: "GRD" }, GTQ: { displayName: "Quetzal da Guatemala", "displayName-count-one": "Quetzal da Guatemala", "displayName-count-other": "Quetzales da Guatemala", symbol: "GTQ", "symbol-alt-narrow": "Q" }, GWE: { displayName: "Escudo da Guiné Portuguesa", "displayName-count-one": "Escudo da Guiné Portuguesa", "displayName-count-other": "Escudos da Guinéa Portuguesa", symbol: "GWE" }, GWP: { displayName: "Peso da Guiné-Bissau", "displayName-count-one": "Peso de Guiné-Bissau", "displayName-count-other": "Pesos de Guiné-Bissau", symbol: "GWP" }, GYD: { displayName: "Dólar da Guiana", "displayName-count-one": "Dólar da Guiana", "displayName-count-other": "Dólares da Guiana", symbol: "GYD", "symbol-alt-narrow": "$" }, HKD: { displayName: "Dólar de Hong Kong", "displayName-count-one": "Dólar de Hong Kong", "displayName-count-other": "Dólares de Hong Kong", symbol: "HK$", "symbol-alt-narrow": "$" }, HNL: { displayName: "Lempira das Honduras", "displayName-count-one": "Lempira das Honduras", "displayName-count-other": "Lempiras das Honduras", symbol: "HNL", "symbol-alt-narrow": "L" }, HRD: { displayName: "Dinar croata", "displayName-count-one": "Dinar croata", "displayName-count-other": "Dinares croatas", symbol: "HRD" }, HRK: { displayName: "Kuna croata", "displayName-count-one": "Kuna croata", "displayName-count-other": "Kunas croatas", symbol: "HRK", "symbol-alt-narrow": "kn" }, HTG: { displayName: "Gourde haitiano", "displayName-count-one": "Gourde haitiano", "displayName-count-other": "Gourdes haitianos", symbol: "HTG" }, HUF: { displayName: "Forint húngaro", "displayName-count-one": "Forint húngaro", "displayName-count-other": "Forints húngaros", symbol: "HUF", "symbol-alt-narrow": "Ft" }, IDR: { displayName: "Rupia indonésia", "displayName-count-one": "Rupia indonésia", "displayName-count-other": "Rupias indonésias", symbol: "IDR", "symbol-alt-narrow": "Rp" }, IEP: { displayName: "Libra irlandesa", "displayName-count-one": "Libra irlandesa", "displayName-count-other": "Libras irlandesas", symbol: "IEP" }, ILP: { displayName: "Libra israelita", "displayName-count-one": "Libra israelita", "displayName-count-other": "Libras israelitas", symbol: "ILP" }, ILR: { displayName: "Sheqel antigo israelita", "displayName-count-one": "Sheqel antigo israelita", "displayName-count-other": "Sheqels antigos israelitas" }, ILS: { displayName: "Sheqel novo israelita", "displayName-count-one": "Sheqel novo israelita", "displayName-count-other": "Sheqels novos israelitas", symbol: "₪", "symbol-alt-narrow": "₪" }, INR: { displayName: "Rupia indiana", "displayName-count-one": "Rupia indiana", "displayName-count-other": "Rupias indianas", symbol: "₹", "symbol-alt-narrow": "₹" }, IQD: { displayName: "Dinar iraquiano", "displayName-count-one": "Dinar iraquiano", "displayName-count-other": "Dinares iraquianos", symbol: "IQD" }, IRR: { displayName: "Rial iraniano", "displayName-count-one": "Rial iraniano", "displayName-count-other": "Riais iranianos", symbol: "IRR" }, ISJ: { displayName: "Coroa antiga islandesa", "displayName-count-one": "Coroa antiga islandesa", "displayName-count-other": "Coroas antigas islandesas" }, ISK: { displayName: "Coroa islandesa", "displayName-count-one": "Coroa islandesa", "displayName-count-other": "Coroas islandesas", symbol: "ISK", "symbol-alt-narrow": "kr" }, ITL: { displayName: "Lira italiana", "displayName-count-one": "Lira italiana", "displayName-count-other": "Liras italianas", symbol: "ITL" }, JMD: { displayName: "Dólar jamaicano", "displayName-count-one": "Dólar jamaicano", "displayName-count-other": "Dólares jamaicanos", symbol: "JMD", "symbol-alt-narrow": "$" }, JOD: { displayName: "Dinar jordaniano", "displayName-count-one": "Dinar jordaniano", "displayName-count-other": "Dinares jordanianos", symbol: "JOD" }, JPY: { displayName: "Iene japonês", "displayName-count-one": "Iene japonês", "displayName-count-other": "Ienes japoneses", symbol: "JP¥", "symbol-alt-narrow": "¥" }, KES: { displayName: "Xelim queniano", "displayName-count-one": "Xelim queniano", "displayName-count-other": "Xelins quenianos", symbol: "KES" }, KGS: { displayName: "Som do Quirguistão", "displayName-count-one": "Som do Quirguistão", "displayName-count-other": "Sons do Quirguistão", symbol: "KGS" }, KHR: { displayName: "Riel cambojano", "displayName-count-one": "Riel cambojano", "displayName-count-other": "Rieles cambojanos", symbol: "KHR", "symbol-alt-narrow": "៛" }, KMF: { displayName: "Franco comoriano", "displayName-count-one": "Franco comoriano", "displayName-count-other": "Francos comorianos", symbol: "KMF", "symbol-alt-narrow": "CF" }, KPW: { displayName: "Won norte-coreano", "displayName-count-one": "Won norte-coreano", "displayName-count-other": "Wons norte-coreanos", symbol: "KPW", "symbol-alt-narrow": "₩" }, KRH: { displayName: "Hwan da Coreia do Sul (1953–1962)", "displayName-count-one": "Hwan da Coreia do Sul", "displayName-count-other": "Hwans da Coreia do Sul", symbol: "KRH" }, KRO: { displayName: "Won da Coreia do Sul (1945–1953)", "displayName-count-one": "Won antigo da Coreia do Sul", "displayName-count-other": "Wons antigos da Coreia do Sul", symbol: "KRO" }, KRW: { displayName: "Won sul-coreano", "displayName-count-one": "Won sul-coreano", "displayName-count-other": "Wons sul-coreanos", symbol: "₩", "symbol-alt-narrow": "₩" }, KWD: { displayName: "Dinar kuwaitiano", "displayName-count-one": "Dinar kuwaitiano", "displayName-count-other": "Dinares kuwaitianos", symbol: "KWD" }, KYD: { displayName: "Dólar das Ilhas Caimão", "displayName-count-one": "Dólar das Ilhas Caimão", "displayName-count-other": "Dólares das Ilhas Caimão", symbol: "KYD", "symbol-alt-narrow": "$" }, KZT: { displayName: "Tenge do Cazaquistão", "displayName-count-one": "Tenge do Cazaquistão", "displayName-count-other": "Tenges do Cazaquistão", symbol: "KZT", "symbol-alt-narrow": "₸" }, LAK: { displayName: "Kip de Laos", "displayName-count-one": "Kip de Laos", "displayName-count-other": "Kips de Laos", symbol: "LAK", "symbol-alt-narrow": "₭" }, LBP: { displayName: "Libra libanesa", "displayName-count-one": "Libra libanesa", "displayName-count-other": "Libras libanesas", symbol: "LBP", "symbol-alt-narrow": "L£" }, LKR: { displayName: "Rupia do Sri Lanka", "displayName-count-one": "Rupia do Sri Lanka", "displayName-count-other": "Rupias do Sri Lanka", symbol: "LKR", "symbol-alt-narrow": "Rs" }, LRD: { displayName: "Dólar liberiano", "displayName-count-one": "Dólar liberiano", "displayName-count-other": "Dólares liberianos", symbol: "LRD", "symbol-alt-narrow": "$" }, LSL: { displayName: "Loti do Lesoto", "displayName-count-one": "Loti do Lesoto", "displayName-count-other": "Lotis do Lesoto", symbol: "LSL" }, LTL: { displayName: "Litas da Lituânia", "displayName-count-one": "Litas da Lituânia", "displayName-count-other": "Litas da Lituânia", symbol: "LTL", "symbol-alt-narrow": "Lt" }, LTT: { displayName: "Talonas lituano", "displayName-count-one": "Talonas lituanas", "displayName-count-other": "Talonases lituanas", symbol: "LTT" }, LUC: { displayName: "Franco conversível de Luxemburgo", "displayName-count-one": "Franco conversível de Luxemburgo", "displayName-count-other": "Francos conversíveis de Luxemburgo", symbol: "LUC" }, LUF: { displayName: "Franco luxemburguês", "displayName-count-one": "Franco de Luxemburgo", "displayName-count-other": "Francos de Luxemburgo", symbol: "LUF" }, LUL: { displayName: "Franco financeiro de Luxemburgo", "displayName-count-one": "Franco financeiro de Luxemburgo", "displayName-count-other": "Francos financeiros de Luxemburgo", symbol: "LUL" }, LVL: { displayName: "Lats da Letónia", "displayName-count-one": "Lats da Letónia", "displayName-count-other": "Lats da Letónia", symbol: "LVL", "symbol-alt-narrow": "Ls" }, LVR: { displayName: "Rublo letão", "displayName-count-one": "Rublo da Letônia", "displayName-count-other": "Rublos da Letônia", symbol: "LVR" }, LYD: { displayName: "Dinar líbio", "displayName-count-one": "Dinar líbio", "displayName-count-other": "Dinares líbios", symbol: "LYD" }, MAD: { displayName: "Dirham marroquino", "displayName-count-one": "Dirham marroquino", "displayName-count-other": "Dirhams marroquinos", symbol: "MAD" }, MAF: { displayName: "Franco marroquino", "displayName-count-one": "Franco marroquino", "displayName-count-other": "Francos marroquinos", symbol: "MAF" }, MCF: { displayName: "Franco monegasco", "displayName-count-one": "Franco monegasco", "displayName-count-other": "Francos monegascos", symbol: "MCF" }, MDC: { displayName: "Cupon moldávio", "displayName-count-one": "Cupon moldávio", "displayName-count-other": "Cupon moldávio", symbol: "MDC" }, MDL: { displayName: "Leu moldavo", "displayName-count-one": "Leu moldavo", "displayName-count-other": "Lei moldavos", symbol: "MDL" }, MGA: { displayName: "Ariari de Madagáscar", "displayName-count-one": "Ariari de Madagáscar", "displayName-count-other": "Ariaris de Madagáscar", symbol: "MGA", "symbol-alt-narrow": "Ar" }, MGF: { displayName: "Franco de Madagascar", "displayName-count-one": "Franco de Madagascar", "displayName-count-other": "Francos de Madagascar", symbol: "MGF" }, MKD: { displayName: "Dinar macedónio", "displayName-count-one": "Dinar macedónio", "displayName-count-other": "Dinares macedónios", symbol: "MKD" }, MKN: { displayName: "Dinar macedônio (1992–1993)", "displayName-count-one": "Dinar macedônio (1992–1993)", "displayName-count-other": "Dinares macedônios (1992–1993)", symbol: "MKN" }, MLF: { displayName: "Franco de Mali", "displayName-count-one": "Franco de Mali", "displayName-count-other": "Francos de Mali", symbol: "MLF" }, MMK: { displayName: "Kyat de Mianmar", "displayName-count-one": "Kyat de Mianmar", "displayName-count-other": "Kyats de Mianmar", symbol: "MMK", "symbol-alt-narrow": "K" }, MNT: { displayName: "Tugrik da Mongólia", "displayName-count-one": "Tugrik da Mongólia", "displayName-count-other": "Tugriks da Mongólia", symbol: "MNT", "symbol-alt-narrow": "₮" }, MOP: { displayName: "Pataca de Macau", "displayName-count-one": "Pataca de Macau", "displayName-count-other": "Patacas de Macau", symbol: "MOP" }, MRO: { displayName: "Ouguiya da Mauritânia", "displayName-count-one": "Ouguiya da Mauritânia", "displayName-count-other": "Ouguiyas da Mauritânia", symbol: "MRO" }, MTL: { displayName: "Lira maltesa", "displayName-count-one": "Lira Maltesa", "displayName-count-other": "Liras maltesas", symbol: "MTL" }, MTP: { displayName: "Libra maltesa", "displayName-count-one": "Libra maltesa", "displayName-count-other": "Libras maltesas", symbol: "MTP" }, MUR: { displayName: "Rupia mauriciana", "displayName-count-one": "Rupia mauriciana", "displayName-count-other": "Rupias mauricianas", symbol: "MUR", "symbol-alt-narrow": "Rs" }, MVR: { displayName: "Rupia das Ilhas Maldivas", "displayName-count-one": "Rupia das Ilhas Maldivas", "displayName-count-other": "Rupias das Ilhas Maldivas", symbol: "MVR" }, MWK: { displayName: "Kwacha do Malawi", "displayName-count-one": "Kwacha do Malawi", "displayName-count-other": "Kwachas do Malawi", symbol: "MWK" }, MXN: { displayName: "Peso mexicano", "displayName-count-one": "Peso mexicano", "displayName-count-other": "Pesos mexicanos", symbol: "MX$", "symbol-alt-narrow": "$" }, MXP: { displayName: "Peso Plata mexicano (1861–1992)", "displayName-count-one": "Peso de prata mexicano (1861–1992)", "displayName-count-other": "Pesos de prata mexicanos (1861–1992)", symbol: "MXP" }, MXV: { displayName: "Unidad de Inversion (UDI) mexicana", "displayName-count-one": "Unidade de investimento mexicana (UDI)", "displayName-count-other": "Unidades de investimento mexicanas (UDI)", symbol: "MXV" }, MYR: { displayName: "Ringgit malaio", "displayName-count-one": "Ringgit malaio", "displayName-count-other": "Ringgits malaios", symbol: "MYR", "symbol-alt-narrow": "RM" }, MZE: { displayName: "Escudo de Moçambique", "displayName-count-one": "Escudo de Moçambique", "displayName-count-other": "Escudos de Moçambique", symbol: "MZE" }, MZM: { displayName: "Metical de Moçambique (1980–2006)", "displayName-count-one": "Metical antigo de Moçambique", "displayName-count-other": "Meticales antigos de Moçambique", symbol: "MZM" }, MZN: { displayName: "Metical de Moçambique", "displayName-count-one": "Metical de Moçambique", "displayName-count-other": "Meticales de Moçambique", symbol: "MZN" }, NAD: { displayName: "Dólar da Namíbia", "displayName-count-one": "Dólar da Namíbia", "displayName-count-other": "Dólares da Namíbia", symbol: "NAD", "symbol-alt-narrow": "$" }, NGN: { displayName: "Naira nigeriana", "displayName-count-one": "Naira nigeriana", "displayName-count-other": "Nairas nigerianas", symbol: "NGN", "symbol-alt-narrow": "₦" }, NIC: { displayName: "Córdoba nicaraguano (1988–1991)", "displayName-count-one": "Córdoba nicaraguano (1988–1991)", "displayName-count-other": "Córdobas nicaraguano (1988–1991)", symbol: "NIC" }, NIO: { displayName: "Córdoba nicaraguano", "displayName-count-one": "Córdoba nicaraguano", "displayName-count-other": "Córdoba nicaraguano", symbol: "NIO", "symbol-alt-narrow": "C$" }, NLG: { displayName: "Florim holandês", "displayName-count-one": "Florim holandês", "displayName-count-other": "Florins holandeses", symbol: "NLG" }, NOK: { displayName: "Coroa norueguesa", "displayName-count-one": "Coroa norueguesa", "displayName-count-other": "Coroas norueguesas", symbol: "NOK", "symbol-alt-narrow": "kr" }, NPR: { displayName: "Rupia nepalesa", "displayName-count-one": "Rupia nepalesa", "displayName-count-other": "Rupias nepalesas", symbol: "NPR", "symbol-alt-narrow": "Rs" }, NZD: { displayName: "Dólar neozelandês", "displayName-count-one": "Dólar neozelandês", "displayName-count-other": "Dólares neozelandeses", symbol: "NZ$", "symbol-alt-narrow": "$" }, OMR: { displayName: "Rial de Omã", "displayName-count-one": "Rial de Omã", "displayName-count-other": "Riais de Omã", symbol: "OMR" }, PAB: { displayName: "Balboa do Panamá", "displayName-count-one": "Balboa do Panamá", "displayName-count-other": "Balboas do Panamá", symbol: "PAB" }, PEI: { displayName: "Inti peruano", "displayName-count-one": "Inti peruano", "displayName-count-other": "Intis peruanos", symbol: "PEI" }, PEN: { displayName: "Sol peruano", "displayName-count-one": "Sol peruano", "displayName-count-other": "Soles peruanos", symbol: "PEN" }, PES: { displayName: "Sol peruano (1863–1965)", "displayName-count-one": "Sol peruano (1863–1965)", "displayName-count-other": "Soles peruanos (1863–1965)", symbol: "PES" }, PGK: { displayName: "Kina da Papua-Nova Guiné", "displayName-count-one": "Kina da Papua-Nova Guiné", "displayName-count-other": "Kinas da Papua-Nova Guiné", symbol: "PGK" }, PHP: { displayName: "Peso filipino", "displayName-count-one": "Peso filipino", "displayName-count-other": "Pesos filipinos", symbol: "PHP", "symbol-alt-narrow": "₱" }, PKR: { displayName: "Rupia paquistanesa", "displayName-count-one": "Rupia paquistanesa", "displayName-count-other": "Rupias paquistanesas", symbol: "PKR", "symbol-alt-narrow": "Rs" }, PLN: { displayName: "Zloti polaco", "displayName-count-one": "Zloti polaco", "displayName-count-other": "Zlotis polacos", symbol: "PLN", "symbol-alt-narrow": "zł" }, PLZ: { displayName: "Zloti polonês (1950–1995)", "displayName-count-one": "Zloti polonês (1950–1995)", "displayName-count-other": "Zlotis poloneses (1950–1995)", symbol: "PLZ" }, PTE: { displayName: "Escudo português", "displayName-count-one": "Escudo português", "displayName-count-other": "Escudos portugueses", symbol: "​", decimal: "$", group: "," }, PYG: { displayName: "Guarani paraguaio", "displayName-count-one": "Guarani paraguaio", "displayName-count-other": "Guaranis paraguaios", symbol: "PYG", "symbol-alt-narrow": "₲" }, QAR: { displayName: "Rial do Catar", "displayName-count-one": "Rial do Catar", "displayName-count-other": "Riais do Catar", symbol: "QAR" }, RHD: { displayName: "Dólar rodesiano", "displayName-count-one": "Dólar da Rodésia", "displayName-count-other": "Dólares da Rodésia", symbol: "RHD" }, ROL: { displayName: "Leu romeno (1952–2006)", "displayName-count-one": "Leu antigo da Romênia", "displayName-count-other": "Leus antigos da Romênia", symbol: "ROL" }, RON: { displayName: "Leu romeno", "displayName-count-one": "Leu romeno", "displayName-count-other": "Lei romenos", symbol: "RON", "symbol-alt-narrow": "L" }, RSD: { displayName: "Dinar sérvio", "displayName-count-one": "Dinar sérvio", "displayName-count-other": "Dinares sérvios", symbol: "RSD" }, RUB: { displayName: "Rublo russo", "displayName-count-one": "Rublo russo", "displayName-count-other": "Rublos russos", symbol: "RUB", "symbol-alt-narrow": "₽" }, RUR: { displayName: "Rublo russo (1991–1998)", "displayName-count-one": "Rublo russo (1991–1998)", "displayName-count-other": "Rublos russos (1991–1998)", symbol: "RUR", "symbol-alt-narrow": "р." }, RWF: { displayName: "Franco ruandês", "displayName-count-one": "Franco ruandês", "displayName-count-other": "Francos ruandeses", symbol: "RWF", "symbol-alt-narrow": "RF" }, SAR: { displayName: "Rial saudita", "displayName-count-one": "Rial saudita", "displayName-count-other": "Riais sauditas", symbol: "SAR" }, SBD: { displayName: "Dólar das Ilhas Salomão", "displayName-count-one": "Dólar das Ilhas Salomão", "displayName-count-other": "Dólares das Ilhas Salomão", symbol: "SBD", "symbol-alt-narrow": "$" }, SCR: { displayName: "Rupia seichelense", "displayName-count-one": "Rupia seichelense", "displayName-count-other": "Rupias seichelenses", symbol: "SCR" }, SDD: { displayName: "Dinar sudanês (1992–2007)", "displayName-count-one": "Dinar antigo do Sudão", "displayName-count-other": "Dinares antigos do Sudão", symbol: "SDD" }, SDG: { displayName: "Libra sudanesa", "displayName-count-one": "Libra sudanesa", "displayName-count-other": "Libras sudanesas", symbol: "SDG" }, SDP: { displayName: "Libra sudanesa (1957–1998)", "displayName-count-one": "Libra antiga sudanesa", "displayName-count-other": "Libras antigas sudanesas", symbol: "SDP" }, SEK: { displayName: "Coroa sueca", "displayName-count-one": "Coroa sueca", "displayName-count-other": "Coroas suecas", symbol: "SEK", "symbol-alt-narrow": "kr" }, SGD: { displayName: "Dólar de Singapura", "displayName-count-one": "Dólar de Singapura", "displayName-count-other": "Dólares de Singapura", symbol: "SGD", "symbol-alt-narrow": "$" }, SHP: { displayName: "Libra de Santa Helena", "displayName-count-one": "Libra de Santa Helena", "displayName-count-other": "Libras de Santa Helena", symbol: "SHP", "symbol-alt-narrow": "£" }, SIT: { displayName: "Tolar Bons esloveno", "displayName-count-one": "Tolar da Eslovênia", "displayName-count-other": "Tolares da Eslovênia", symbol: "SIT" }, SKK: { displayName: "Coroa eslovaca", "displayName-count-one": "Coroa eslovaca", "displayName-count-other": "Coroas eslovacas", symbol: "SKK" }, SLL: { displayName: "Leone de Serra Leoa", "displayName-count-one": "Leone de Serra Leoa", "displayName-count-other": "Leones de Serra Leoa", symbol: "SLL" }, SOS: { displayName: "Xelim somali", "displayName-count-one": "Xelim somali", "displayName-count-other": "Xelins somalis", symbol: "SOS" }, SRD: { displayName: "Dólar do Suriname", "displayName-count-one": "Dólar do Suriname", "displayName-count-other": "Dólares do Suriname", symbol: "SRD", "symbol-alt-narrow": "$" }, SRG: { displayName: "Florim do Suriname", "displayName-count-one": "Florim do Suriname", "displayName-count-other": "Florins do Suriname", symbol: "SRG" }, SSP: { displayName: "Libra sul-sudanesa", "displayName-count-one": "Libra sul-sudanesa", "displayName-count-other": "Libras sul-sudanesas", symbol: "SSP", "symbol-alt-narrow": "£" }, STD: { displayName: "Dobra de São Tomé e Príncipe", "displayName-count-one": "Dobra de São Tomé e Príncipe", "displayName-count-other": "Dobras de São Tomé e Príncipe", symbol: "STD", "symbol-alt-narrow": "Db" }, SUR: { displayName: "Rublo soviético", "displayName-count-one": "Rublo soviético", "displayName-count-other": "Rublos soviéticos", symbol: "SUR" }, SVC: { displayName: "Colom salvadorenho", "displayName-count-one": "Colon de El Salvador", "displayName-count-other": "Colons de El Salvador", symbol: "SVC" }, SYP: { displayName: "Libra síria", "displayName-count-one": "Libra síria", "displayName-count-other": "Libras sírias", symbol: "SYP", "symbol-alt-narrow": "£" }, SZL: { displayName: "Lilangeni da Suazilândia", "displayName-count-one": "Lilangeni da Suazilândia", "displayName-count-other": "Lilangenis da Suazilândia", symbol: "SZL" }, THB: { displayName: "Baht da Tailândia", "displayName-count-one": "Baht da Tailândia", "displayName-count-other": "Bahts da Tailândia", symbol: "฿", "symbol-alt-narrow": "฿" }, TJR: { displayName: "Rublo do Tadjiquistão", "displayName-count-one": "Rublo do Tajaquistão", "displayName-count-other": "Rublos do Tajaquistão", symbol: "TJR" }, TJS: { displayName: "Somoni do Tajaquistão", "displayName-count-one": "Somoni do Tajaquistão", "displayName-count-other": "Somonis do Tajaquistão", symbol: "TJS" }, TMM: { displayName: "Manat do Turcomenistão (1993–2009)", "displayName-count-one": "Manat do Turcomenistão (1993–2009)", "displayName-count-other": "Manats do Turcomenistão (1993–2009)", symbol: "TMM" }, TMT: { displayName: "Manat do Turquemenistão", "displayName-count-one": "Manat do Turquemenistão", "displayName-count-other": "Manats do Turquemenistão", symbol: "TMT" }, TND: { displayName: "Dinar tunisino", "displayName-count-one": "Dinar tunisino", "displayName-count-other": "Dinares tunisinos", symbol: "TND" }, TOP: { displayName: "Paʻanga de Tonga", "displayName-count-one": "Paʻanga de Tonga", "displayName-count-other": "Paʻangas de Tonga", symbol: "TOP", "symbol-alt-narrow": "T$" }, TPE: { displayName: "Escudo timorense", "displayName-count-one": "Escudo do Timor", "displayName-count-other": "Escudos do Timor", symbol: "TPE" }, TRL: { displayName: "Lira turca (1922–2005)", "displayName-count-one": "Lira turca antiga", "displayName-count-other": "Liras turcas antigas", symbol: "TRL" }, TRY: { displayName: "Lira turca", "displayName-count-one": "Lira turca", "displayName-count-other": "Liras turcas", symbol: "TRY", "symbol-alt-narrow": "₺", "symbol-alt-variant": "TL" }, TTD: { displayName: "Dólar de Trindade e Tobago", "displayName-count-one": "Dólar de Trindade e Tobago", "displayName-count-other": "Dólares de Trindade e Tobago", symbol: "TTD", "symbol-alt-narrow": "$" }, TWD: { displayName: "Novo dólar taiwanês", "displayName-count-one": "Novo dólar taiwanês", "displayName-count-other": "Novos dólares taiwaneses", symbol: "NT$", "symbol-alt-narrow": "NT$" }, TZS: { displayName: "Xelim tanzaniano", "displayName-count-one": "Xelim tanzaniano", "displayName-count-other": "Xelins tanzanianos", symbol: "TZS" }, UAH: { displayName: "Hryvnia da Ucrânia", "displayName-count-one": "Hryvnia da Ucrânia", "displayName-count-other": "Hryvnias da Ucrânia", symbol: "UAH", "symbol-alt-narrow": "₴" }, UAK: { displayName: "Karbovanetz ucraniano", "displayName-count-one": "Karbovanetz da Ucrânia", "displayName-count-other": "Karbovanetzs da Ucrânia", symbol: "UAK" }, UGS: { displayName: "Xelim ugandense (1966–1987)", "displayName-count-one": "Shilling de Uganda (1966–1987)", "displayName-count-other": "Shillings de Uganda (1966–1987)", symbol: "UGS" }, UGX: { displayName: "Xelim ugandense", "displayName-count-one": "Xelim ugandense", "displayName-count-other": "Xelins ugandenses", symbol: "UGX" }, USD: { displayName: "Dólar dos Estados Unidos", "displayName-count-one": "Dólar dos Estados Unidos", "displayName-count-other": "Dólares dos Estados Unidos", symbol: "US$", "symbol-alt-narrow": "$" }, USN: { displayName: "Dólar norte-americano (Dia seguinte)", "displayName-count-one": "Dólar americano (dia seguinte)", "displayName-count-other": "Dólares americanos (dia seguinte)", symbol: "USN" }, USS: { displayName: "Dólar norte-americano (Mesmo dia)", "displayName-count-one": "Dólar americano (mesmo dia)", "displayName-count-other": "Dólares americanos (mesmo dia)", symbol: "USS" }, UYI: { displayName: "Peso uruguaio en unidades indexadas", "displayName-count-one": "Peso uruguaio em unidades indexadas", "displayName-count-other": "Pesos uruguaios em unidades indexadas", symbol: "UYI" }, UYP: { displayName: "Peso uruguaio (1975–1993)", "displayName-count-one": "Peso uruguaio (1975–1993)", "displayName-count-other": "Pesos uruguaios (1975–1993)", symbol: "UYP" }, UYU: { displayName: "Peso uruguaio", "displayName-count-one": "Peso uruguaio", "displayName-count-other": "Pesos uruguaios", symbol: "UYU", "symbol-alt-narrow": "$" }, UZS: { displayName: "Som do Uzbequistão", "displayName-count-one": "Som do Uzbequistão", "displayName-count-other": "Sons do Uzbequistão", symbol: "UZS" }, VEB: { displayName: "Bolívar venezuelano (1871–2008)", "displayName-count-one": "Bolívar venezuelano (1871–2008)", "displayName-count-other": "Bolívares venezuelanos (1871–2008)", symbol: "VEB" }, VEF: { displayName: "Bolívar venezuelano", "displayName-count-one": "Bolívar venezuelano", "displayName-count-other": "Bolívares venezuelanos", symbol: "VEF", "symbol-alt-narrow": "Bs" }, VND: { displayName: "Dong vietnamita", "displayName-count-one": "Dong vietnamita", "displayName-count-other": "Dongs vietnamitas", symbol: "₫", "symbol-alt-narrow": "₫" }, VNN: { displayName: "Dong vietnamita (1978–1985)", "displayName-count-one": "Dong vietnamita (1978–1985)", "displayName-count-other": "Dong vietnamita (1978–1985)", symbol: "VNN" }, VUV: { displayName: "Vatu de Vanuatu", "displayName-count-one": "Vatu de Vanuatu", "displayName-count-other": "Vatus de Vanuatu", symbol: "VUV" }, WST: { displayName: "Tala samoano", "displayName-count-one": "Tala samoano", "displayName-count-other": "Talas samoanos", symbol: "WST" }, XAF: { displayName: "Franco CFA (BEAC)", "displayName-count-one": "Franco CFA (BEAC)", "displayName-count-other": "Francos CFA (BEAC)", symbol: "FCFA" }, XAG: { displayName: "Prata", "displayName-count-one": "Prata", "displayName-count-other": "Pratas", symbol: "XAG" }, XAU: { displayName: "Ouro", "displayName-count-one": "Ouro", "displayName-count-other": "Ouros", symbol: "XAU" }, XBA: { displayName: "Unidade Composta Europeia", "displayName-count-one": "Unidade de composição europeia", "displayName-count-other": "Unidades de composição europeias", symbol: "XBA" }, XBB: { displayName: "Unidade Monetária Europeia", "displayName-count-one": "Unidade monetária europeia", "displayName-count-other": "Unidades monetárias europeias", symbol: "XBB" }, XBC: { displayName: "Unidade de Conta Europeia (XBC)", "displayName-count-one": "Unidade europeia de conta (XBC)", "displayName-count-other": "Unidades europeias de conta (XBC)", symbol: "XBC" }, XBD: { displayName: "Unidade de Conta Europeia (XBD)", "displayName-count-one": "Unidade europeia de conta (XBD)", "displayName-count-other": "Unidades europeias de conta (XBD)", symbol: "XBD" }, XCD: { displayName: "Dólar das Caraíbas Orientais", "displayName-count-one": "Dólar das Caraíbas Orientais", "displayName-count-other": "Dólares das Caraíbas Orientais", symbol: "EC$", "symbol-alt-narrow": "$" }, XDR: { displayName: "Direitos Especiais de Giro", "displayName-count-one": "Direitos de desenho especiais", "displayName-count-other": "Direitos de desenho especiais", symbol: "XDR" }, XEU: { displayName: "Unidade de Moeda Europeia", "displayName-count-one": "Unidade de moeda europeia", "displayName-count-other": "Unidades de moedas europeias", symbol: "XEU" }, XFO: { displayName: "Franco-ouro francês", "displayName-count-one": "Franco de ouro francês", "displayName-count-other": "Francos de ouro franceses", symbol: "XFO" }, XFU: { displayName: "Franco UIC francês", "displayName-count-one": "Franco UIC francês", "displayName-count-other": "Francos UIC franceses", symbol: "XFU" }, XOF: { displayName: "Franco CFA (BCEAO)", "displayName-count-one": "Franco CFA (BCEAO)", "displayName-count-other": "Francos CFA (BCEAO)", symbol: "CFA" }, XPD: { displayName: "Paládio", "displayName-count-one": "Paládio", "displayName-count-other": "Paládios", symbol: "XPD" }, XPF: { displayName: "Franco CFP", "displayName-count-one": "Franco CFP", "displayName-count-other": "Francos CFP", symbol: "CFPF" }, XPT: { displayName: "Platina", "displayName-count-one": "Platina", "displayName-count-other": "Platinas", symbol: "XPT" }, XRE: { displayName: "Fundos RINET", "displayName-count-one": "Fundos RINET", "displayName-count-other": "Fundos RINET", symbol: "XRE" }, XSU: { displayName: "XSU", symbol: "XSU" }, XTS: { displayName: "Código de Moeda de Teste", "displayName-count-one": "Código de moeda de teste", "displayName-count-other": "Códigos de moeda de teste", symbol: "XTS" }, XUA: { displayName: "XUA", symbol: "XUA" }, XXX: { displayName: "Moeda desconhecida", "displayName-count-one": "(moeda desconhecida)", "displayName-count-other": "(moedas desconhecidas)", symbol: "XXX" }, YDD: { displayName: "Dinar iemenita", "displayName-count-one": "Dinar do Iêmen", "displayName-count-other": "Dinares do Iêmen", symbol: "YDD" }, YER: { displayName: "Rial iemenita", "displayName-count-one": "Rial iemenita", "displayName-count-other": "Riais iemenitas", symbol: "YER" }, YUD: { displayName: "Dinar forte iugoslavo (1966–1990)", "displayName-count-one": "Dinar forte iugoslavo", "displayName-count-other": "Dinares fortes iugoslavos", symbol: "YUD" }, YUM: { displayName: "Dinar noviy iugoslavo (1994–2002)", "displayName-count-one": "Dinar noviy da Iugoslávia", "displayName-count-other": "Dinares noviy da Iugoslávia", symbol: "YUM" }, YUN: { displayName: "Dinar conversível iugoslavo (1990–1992)", "displayName-count-one": "Dinar conversível da Iugoslávia", "displayName-count-other": "Dinares conversíveis da Iugoslávia", symbol: "YUN" }, YUR: { displayName: "Dinar reformado iugoslavo (1992–1993)", "displayName-count-one": "Dinar iugoslavo reformado", "displayName-count-other": "Dinares iugoslavos reformados", symbol: "YUR" }, ZAL: { displayName: "Rand sul-africano (financeiro)", "displayName-count-one": "Rand da África do Sul (financeiro)", "displayName-count-other": "Rands da África do Sul (financeiro)", symbol: "ZAL" }, ZAR: { displayName: "Rand sul-africano", "displayName-count-one": "Rand sul-africano", "displayName-count-other": "Rands sul-africanos", symbol: "ZAR", "symbol-alt-narrow": "R" }, ZMK: { displayName: "Kwacha zambiano (1968–2012)", "displayName-count-one": "Kwacha zambiano (1968–2012)", "displayName-count-other": "Kwachas zambianos (1968–2012)", symbol: "ZMK" }, ZMW: { displayName: "Kwacha zambiano", "displayName-count-one": "Kwacha zambiano", "displayName-count-other": "Kwachas zambianos", symbol: "ZMW", "symbol-alt-narrow": "ZK" }, ZRN: { displayName: "Zaire Novo zairense (1993–1998)", "displayName-count-one": "Novo zaire do Zaire", "displayName-count-other": "Novos zaires do Zaire", symbol: "ZRN" }, ZRZ: { displayName: "Zaire zairense (1971–1993)", "displayName-count-one": "Zaire do Zaire", "displayName-count-other": "Zaires do Zaire", symbol: "ZRZ" }, ZWD: { displayName: "Dólar do Zimbábue (1980–2008)", "displayName-count-one": "Dólar do Zimbábue", "displayName-count-other": "Dólares do Zimbábue", symbol: "ZWD" }, ZWL: { displayName: "Dólar do Zimbábue (2009)", "displayName-count-one": "Dólar do Zimbábue (2009)", "displayName-count-other": "Dólares do Zimbábue (2009)", symbol: "ZWL" }, ZWR: { displayName: "Dólar do Zimbábue (2008)", "displayName-count-one": "Dólar do Zimbábue (2008)", "displayName-count-other": "Dólares do Zimbábue (2008)", symbol: "ZWR" } }, localeCurrency: "CHF" }, calendar: { patterns: { d: "dd/MM/y", D: "EEEE, d 'de' MMMM 'de' y", m: "d/MM", M: "d 'de' MMMM", y: "MM/y", Y: "MMMM 'de' y", F: "EEEE, d 'de' MMMM 'de' y HH:mm:ss", g: "dd/MM/y HH:mm", G: "dd/MM/y HH:mm:ss", t: "HH:mm", T: "HH:mm:ss", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" }, dateTimeFormats: { full: "{1} 'às' {0}", long: "{1} 'às' {0}", medium: "{1}, {0}", short: "{1}, {0}", availableFormats: { d: "d", E: "ccc", Ed: "E, d", Ehm: "E, h:mm a", EHm: "E, HH:mm", Ehms: "E, h:mm:ss a", EHms: "E, HH:mm:ss", Gy: "y G", GyMMM: "MMM 'de' y G", GyMMMd: "d 'de' MMM 'de' y G", GyMMMEd: "E, d 'de' MMM 'de' y G", h: "h a", H: "HH", hm: "h:mm a", Hm: "HH:mm", hms: "h:mm:ss a", Hms: "HH:mm:ss", hmsv: "h:mm:ss a v", Hmsv: "HH:mm:ss v", hmv: "h:mm a v", Hmv: "HH:mm v", M: "L", Md: "dd/MM", MEd: "E, dd/MM", MMdd: "dd/MM", MMM: "LLL", MMMd: "d/MM", MMMEd: "E, d/MM", MMMMd: "d 'de' MMMM", MMMMEd: "ccc, d 'de' MMMM", "MMMMW-count-one": "W.'ª' 'semana' 'de' MMM", "MMMMW-count-other": "W.'ª' 'semana' 'de' MMM", ms: "mm:ss", y: "y", yM: "MM/y", yMd: "dd/MM/y", yMEd: "E, dd/MM/y", yMM: "MM/y", yMMM: "MM/y", yMMMd: "d/MM/y", yMMMEd: "E, d/MM/y", yMMMEEEEd: "EEEE, d/MM/y", yMMMM: "MMMM 'de' y", yMMMMd: "d 'de' MMMM 'de' y", yMMMMEd: "ccc, d 'de' MMMM 'de' y", yQQQ: "QQQQ 'de' y", yQQQQ: "QQQQ 'de' y", "yw-count-one": "w.'ª' 'semana' 'de' y", "yw-count-other": "w.'ª' 'semana' 'de' y" } }, timeFormats: { full: "HH:mm:ss zzzz", long: "HH:mm:ss z", medium: "HH:mm:ss", short: "HH:mm" }, dateFormats: { full: "EEEE, d 'de' MMMM 'de' y", long: "d 'de' MMMM 'de' y", medium: "dd/MM/y", short: "dd/MM/yy" }, days: { format: { abbreviated: [ "domingo", "segunda", "terça", "quarta", "quinta", "sexta", "sábado" ], narrow: [ "D", "S", "T", "Q", "Q", "S", "S" ], short: [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], wide: [ "domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado" ] }, "stand-alone": { abbreviated: [ "domingo", "segunda", "terça", "quarta", "quinta", "sexta", "sábado" ], narrow: [ "D", "S", "T", "Q", "Q", "S", "S" ], short: [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], wide: [ "domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado" ] } }, months: { format: { abbreviated: [ "jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez" ], narrow: [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], wide: [ "janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro" ] }, "stand-alone": { abbreviated: [ "jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez" ], narrow: [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], wide: [ "janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro" ] } }, quarters: { format: { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1.º trimestre", "2.º trimestre", "3.º trimestre", "4.º trimestre" ] }, "stand-alone": { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1.º trimestre", "2.º trimestre", "3.º trimestre", "4.º trimestre" ] } }, dayPeriods: { format: { abbreviated: { midnight: "meia-noite", am: "a.m.", noon: "meio-dia", pm: "p.m.", morning1: "da manhã", afternoon1: "da tarde", evening1: "da noite", night1: "da madrugada" }, narrow: { midnight: "meia-noite", am: "a.m.", noon: "meio-dia", pm: "p.m.", morning1: "manhã", afternoon1: "tarde", evening1: "noite", night1: "madrugada" }, wide: { midnight: "meia-noite", am: "da manhã", noon: "meio-dia", pm: "da tarde", morning1: "da manhã", afternoon1: "da tarde", evening1: "da noite", night1: "da madrugada" } }, "stand-alone": { abbreviated: { midnight: "meia-noite", am: "a.m.", noon: "meio-dia", pm: "p.m.", morning1: "manhã", afternoon1: "tarde", evening1: "noite", night1: "madrugada" }, narrow: { midnight: "meia-noite", am: "a.m.", noon: "meio-dia", pm: "p.m.", morning1: "manhã", afternoon1: "tarde", evening1: "noite", night1: "madrugada" }, wide: { midnight: "meia-noite", am: "manhã", noon: "meio-dia", pm: "tarde", morning1: "manhã", afternoon1: "tarde", evening1: "noite", night1: "madrugada" } } }, eras: { format: { wide: { 0: "antes de Cristo", 1: "depois de Cristo", "0-alt-variant": "antes da Era Comum", "1-alt-variant": "Era Comum" }, abbreviated: { 0: "a.C.", 1: "d.C.", "0-alt-variant": "a.E.C.", "1-alt-variant": "E.C." }, narrow: { 0: "a.C.", 1: "d.C.", "0-alt-variant": "a.E.C.", "1-alt-variant": "E.C." } } }, gmtFormat: "GMT{0}", gmtZeroFormat: "GMT", dateFields: { era: { wide: "era", short: "era", narrow: "era" }, year: { wide: "ano", short: "ano", narrow: "ano" }, quarter: { wide: "trimestre", short: "trim.", narrow: "trim." }, month: { wide: "mês", short: "mês", narrow: "mês" }, week: { wide: "semana", short: "sem.", narrow: "sem." }, weekOfMonth: { wide: "Week Of Month", short: "Week Of Month", narrow: "Week Of Month" }, day: { wide: "dia", short: "dia", narrow: "dia" }, dayOfYear: { wide: "Day Of Year", short: "Day Of Year", narrow: "Day Of Year" }, weekday: { wide: "dia da semana", short: "dia da semana", narrow: "dia da semana" }, weekdayOfMonth: { wide: "Weekday Of Month", short: "Weekday Of Month", narrow: "Weekday Of Month" }, dayperiod: { short: "AM/PM", wide: "AM/PM", narrow: "AM/PM" }, hour: { wide: "hora", short: "h", narrow: "h" }, minute: { wide: "minuto", short: "min", narrow: "min" }, second: { wide: "segundo", short: "s", narrow: "s" }, zone: { wide: "fuso horário", short: "fuso horário", narrow: "fuso horário" } } }, firstDay: 1, likelySubtags: { pt: "pt-Latn-BR" } });
define(function(require) { var Checker = require("checkers/controller/Checker"), GameBoard = require("checkers/controller/GameBoard"), GameSpace = require("checkers/controller/GameSpace"); var instance = null; function GameBoardUtil() { } var getInstance = function() { if (instance === null) { instance = new GameBoardUtil(); } return instance; } GameBoardUtil.prototype.getValidMoves = function(checker, gameBoard, posDir) { var validMoves = new Array(); $.merge(validMoves, this.getEmptySpaceMoves(checker, gameBoard, posDir)); $.merge(validMoves, this.getJumpMoves(checker, gameBoard, posDir)); return validMoves; } GameBoardUtil.prototype.getEmptySpaceMoves = function(checker, gameBoard, posDir) { var emptySpaceMoves = new Array(); var row = checker.getRow() + posDir; // Checks left move if (this.isValidMove(row, checker.getColumn() - 1)) { var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 1) if (gameSpace.isEmpty()) { emptySpaceMoves.push(gameSpace); } } // Checks right move if (this.isValidMove(row, checker.getColumn() + 1)) { var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 1); if (gameSpace.isEmpty()) { emptySpaceMoves.push(gameSpace); } } if (checker.isKing()) { var kRow = checker.getRow() - posDir; // Checks left move if (this.isValidMove(kRow, checker.getColumn() - 1)) { var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 1) if (gameSpace.isEmpty()) { emptySpaceMoves.push(gameSpace); } } // Checks right move if (this.isValidMove(kRow, checker.getColumn() + 1)) { var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 1); if (gameSpace.isEmpty()) { emptySpaceMoves.push(gameSpace); } } } return emptySpaceMoves; } GameBoardUtil.prototype.isValidMove = function(row, column) { if (row < 0 || row >= GameBoard.NUMSQUARES || column < 0 || column >= GameBoard.NUMSQUARES) { return false; } return true; } GameBoardUtil.prototype.getJumpMoves = function(checker, gameBoard, posDir) { var jumpMoves = new Array(); var row = checker.getRow() + posDir * 2; // Checks left jump move if (this.isValidMove(row, checker.getColumn() - 2)) { var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 2); if (gameSpace.isEmpty()) { var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() - 1); if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) { jumpMoves.push(gameSpace); } } } // Checks right jump move if (this.isValidMove(row, checker.getColumn() + 2)) { var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 2); if (gameSpace.isEmpty()) { var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() + 1); if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) { jumpMoves.push(gameSpace); } } } if (checker.isKing()) { // Checks left jump move var kRow = checker.getRow() - posDir * 2; if (this.isValidMove(kRow, checker.getColumn() - 2)) { var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 2); if (gameSpace.isEmpty()) { var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() - 1); if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) { jumpMoves.push(gameSpace); } } } // Checks right jump move if (this.isValidMove(kRow, checker.getColumn() + 2)) { var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 2); if (gameSpace.isEmpty()) { var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() + 1); if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) { jumpMoves.push(gameSpace); } } } } return jumpMoves; } return ({getInstance:getInstance}); });
import { LOCAL_STORAGE_REMOVE_ITEM, LOCAL_STORAGE_SET_ITEM } from './actionTypes' import createMiddleware from './middleware' describe('middleware', () => { let removeItem let setItem let middleware let next let store beforeEach(() => { removeItem = jest.fn() setItem = jest.fn() middleware = createMiddleware({ removeItem, setItem, }) next = jest.fn() store = { dispatch: jest.fn(), getState: jest.fn(), } }) it('calls next on dummy actionType', () => { const action = { type: 'dummyType', payload: { key: 'key', }, } middleware(store)(next)(action) expect(next.mock.calls.length).toBe(1) }) it(`calls removeItem on ${LOCAL_STORAGE_REMOVE_ITEM}`, () => { const action = { type: LOCAL_STORAGE_REMOVE_ITEM, payload: { key: 'key', }, } middleware(store)(next)(action) expect(removeItem.mock.calls.length).toBe(1) }) it(`calls removeItem on ${LOCAL_STORAGE_SET_ITEM}`, () => { const action = { type: LOCAL_STORAGE_SET_ITEM, payload: { key: 'key', value: 'value', }, } middleware(store)(next)(action) expect(setItem.mock.calls.length).toBe(1) }) })
jQuery.each(param_obj, function (index, value) { if (!isNaN(value)) { param_obj[index] = parseInt(value); } }); function Portfolio_Gallery_Full_Height(id) { var _this = this; _this.container = jQuery('#' + id + '.view-full-height'); _this.hasLoading = _this.container.data("show-loading") == "on"; _this.optionsBlock = _this.container.parent().find('div[id^="huge_it_portfolio_options_"]'); _this.filtersBlock = _this.container.parent().find('div[id^="huge_it_portfolio_filters_"]'); _this.content = _this.container.parent(); _this.element = _this.container.find('.portelement'); _this.defaultBlockHeight = param_obj.ht_view1_block_height; _this.defaultBlockWidth = param_obj.ht_view1_block_width; _this.optionSets = _this.optionsBlock.find('.option-set'); _this.optionLinks = _this.optionSets.find('a'); _this.sortBy = _this.optionsBlock.find('#sort-by'); _this.filterButton = _this.filtersBlock.find('ul li'); if (_this.container.data('show-center') == 'on' && ( ( !_this.content.hasClass('sortingActive') && !_this.content.hasClass('filteringActive') ) || ( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == 'top' ) || ( _this.optionsBlock.data('sorting-position') == 'top' && _this.filtersBlock.data('filtering-position') == '' ) || ( _this.optionsBlock.data('sorting-position') == '' && _this.filtersBlock.data('filtering-position') == 'top' ) )) { _this.isCentered = _this.container.data("show-center") == "on"; } _this.documentReady = function () { _this.container.hugeitmicro({ itemSelector: _this.element, masonry: { columnWidth: _this.defaultBlockWidth + 20 + param_obj.ht_view1_element_border_width * 2 }, masonryHorizontal: { rowHeight: 300 + 20 }, cellsByRow: { columnWidth: 300 + 20, rowHeight: 240 }, cellsByColumn: { columnWidth: 300 + 20, rowHeight: 240 }, getSortData: { symbol: function ($elem) { return $elem.attr('data-symbol'); }, category: function ($elem) { return $elem.attr('data-category'); }, number: function ($elem) { return parseInt($elem.find('.number').text(), 10); }, weight: function ($elem) { return parseFloat($elem.find('.weight').text().replace(/[\(\)]/g, '')); }, id: function ($elem) { return $elem.find('.id').text(); } } }); setInterval(function(){ _this.container.hugeitmicro('reLayout'); }); }; _this.manageLoading = function () { if (_this.hasLoading) { _this.container.css({'opacity': 1}); _this.optionsBlock.css({'opacity': 1}); _this.filtersBlock.css({'opacity': 1}); _this.content.find('div[id^="huge-it-container-loading-overlay_"]').css('display', 'none'); } }; _this.showCenter = function () { if (_this.isCentered) { var count = _this.element.length; var elementwidth = _this.defaultBlockWidth + 10 + param_obj.ht_view1_element_border_width * 2; var enterycontent = _this.content.width(); var whole = ~~(enterycontent / (elementwidth)); if (whole > count) whole = count; if (whole == 0) { return false; } else { var sectionwidth = whole * elementwidth + (whole - 1) * 20; } _this.container.width(sectionwidth).css({ "margin": "0px auto", "overflow": "hidden" }); console.log(elementwidth + " " + enterycontent + " " + whole + " " + sectionwidth); } }; _this.addEventListeners = function () { _this.optionLinks.on('click', _this.optionsClick); _this.optionsBlock.find('#shuffle a').on('click',_this.randomClick); _this.filterButton.on('click', _this.filtersClick); jQuery(window).resize(_this.resizeEvent); }; _this.resizeEvent = function(){ _this.container.hugeitmicro('reLayout'); _this.showCenter(); }; _this.optionsClick = function () { var $this = jQuery(this); if ($this.hasClass('selected')) { return false; } var $optionSet = $this.parents('.option-set'); $optionSet.find('.selected').removeClass('selected'); $this.addClass('selected'); var options = {}, key = $optionSet.attr('data-option-key'), value = $this.attr('data-option-value'); value = value === 'false' ? false : value; options[key] = value; if (key === 'layoutMode' && typeof changeLayoutMode === 'function') { changeLayoutMode($this, options) } else { _this.container.hugeitmicro(options); } return false; }; _this.randomClick = function () { _this.container.hugeitmicro('shuffle'); _this.sortBy.find('.selected').removeClass('selected'); _this.sortBy.find('[data-option-value="random"]').addClass('selected'); return false; }; _this.filtersClick = function () { _this.filterButton.each(function () { jQuery(this).removeClass('active'); }); jQuery(this).addClass('active'); // get filter value from option value var filterValue = jQuery(this).attr('rel'); // use filterFn if matches value _this.container.hugeitmicro({filter: filterValue}); }; _this.init = function () { _this.showCenter(); jQuery(window).load(_this.manageLoading); _this.documentReady(); _this.addEventListeners(); }; this.init(); } var portfolios = []; jQuery(document).ready(function () { jQuery(".huge_it_portfolio_container.view-full-height").each(function (i) { var id = jQuery(this).attr('id'); portfolios[i] = new Portfolio_Gallery_Full_Height(id); }); });
import s from './Callouts.css'; import React, { PropTypes } from 'react'; import numbro from 'numbro'; function diversityAtParityOrGreater(conf) { return conf.diversityPercentage >= 50; } function confFromCurrentYear(conf) { return conf.year == (new Date()).getFullYear(); } function diversityAccumulator(accumulator, conf) { return accumulator + conf.diversityPercentage; } function diversitySorter(confA, confB) { if (confA.diversityPercentage < confB.diversityPercentage) { return 1; } if (confA.diversityPercentage > confB.diversityPercentage) { return -1; } return 0; } class Callouts extends React.Component { constructor(props) { super(props); this.currentYearConfs = props.confs.filter(confFromCurrentYear); this.state = { confs: props.confs, bestPerformer: props.confs.sort(diversitySorter)[0], numberOfConfs: props.confs.length, numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater).length, averageDiversity: props.confs.reduce(diversityAccumulator, 0) / props.confs.length, averageDiversityCurrentYear: this.currentYearConfs.reduce(diversityAccumulator, 0) / this.currentYearConfs.length }; } render() { return ( <div className={s.container}> <div className="row"> <div className="col-sm-2"> <div className={s.title}>Conferences<br/>tracked</div> <div className={s.pop}>{this.state.numberOfConfs}</div> </div> <div className="col-sm-2"> <div className={s.title}>Best<br/>performer</div> <div className={s.body}><strong>{this.state.bestPerformer.name} ({this.state.bestPerformer.year})</strong><br/>{numbro(this.state.bestPerformer.diversityPercentage).format('0')}%</div> </div> <div className="col-sm-2"> <div className={s.title}>Biggest recent improver</div> <div className={s.body}><strong>1st Conf</strong><br/>+36%<br/>2016 -> 2017</div> </div> <div className="col-sm-2" id={s.nbrConfAtParity}> <div className={s.title}>#confs >= 50%<br/>diversity</div> <div className={s.pop}>{this.state.numberOfConfsAtParityOrGreater}</div> </div> <div className="col-sm-2"> <div className={s.title}>Average<br/>f:m%</div> <div className={s.pop}>{numbro(this.state.averageDiversity).format('0')}%</div> </div> <div className="col-sm-2"> <div className={s.title}>Average<br/>f:m% (2017)</div> <div className={s.pop}>{numbro(this.state.averageDiversityCurrentYear).format('0')}%</div> </div> </div> </div> ); } } export default Callouts;