code
stringlengths 2
1.05M
|
|---|
const path = require('path');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
content: './content.js',
insertVotes: './insertVotes.js',
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js',
},
};
|
"use strict";
/**
* @fileoverview events handling from central columns page
* @name Central columns
*
* @requires jQuery
*/
/**
* AJAX scripts for /database/central-columns
*
* Actions ajaxified here:
* Inline Edit and save of a result row
* Delete a row
* Multiple edit and delete option
*
*/
AJAX.registerTeardown('database/central_columns.js', function () {
$('.edit').off('click');
$('.edit_save_form').off('click');
$('.edit_cancel_form').off('click');
$('.del_row').off('click');
$(document).off('keyup', '.filter_rows');
$('.edit_cancel_form').off('click');
$('#table-select').off('change');
$('#column-select').off('change');
$('#add_col_div').find('>a').off('click');
$('#add_new').off('submit');
$('#multi_edit_central_columns').off('submit');
$('select.default_type').off('change');
$('button[name=\'delete_central_columns\']').off('click');
$('button[name=\'edit_central_columns\']').off('click');
});
AJAX.registerOnload('database/central_columns.js', function () {
$('#tableslistcontainer input,#tableslistcontainer select,#tableslistcontainer .default_value,#tableslistcontainer .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
$('#tableslistcontainer').find('.checkall_box').show();
if ($('#table_columns').find('tbody tr').length > 0) {
$('#table_columns').tablesorter({
headers: {
0: {
sorter: false
},
1: {
sorter: false
},
// hidden column
4: {
sorter: 'integer'
}
}
});
}
$('#tableslistcontainer').find('button[name="delete_central_columns"]').on('click', function (event) {
event.preventDefault();
var multiDeleteColumns = $('.checkall:checkbox:checked').serialize();
if (multiDeleteColumns === '') {
Functions.ajaxShowMessage(Messages.strRadioUnchecked);
return false;
}
Functions.ajaxShowMessage();
$('#del_col_name').val(multiDeleteColumns);
$('#del_form').trigger('submit');
});
$('#tableslistcontainer').find('button[name="edit_central_columns"]').on('click', function (event) {
event.preventDefault();
var editColumnList = $('.checkall:checkbox:checked').serialize();
if (editColumnList === '') {
Functions.ajaxShowMessage(Messages.strRadioUnchecked);
return false;
}
var argsep = CommonParams.get('arg_separator');
var editColumnData = editColumnList + '' + argsep + 'edit_central_columns_page=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + encodeURIComponent(CommonParams.get('db'));
Functions.ajaxShowMessage();
AJAX.source = $(this);
$.post('index.php?route=/database/central-columns', editColumnData, AJAX.responseHandler);
});
$('#multi_edit_central_columns').on('submit', function (event) {
event.preventDefault();
event.stopPropagation();
var argsep = CommonParams.get('arg_separator');
var multiColumnEditData = $('#multi_edit_central_columns').serialize() + argsep + 'multi_edit_central_column_save=true' + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'db=' + encodeURIComponent(CommonParams.get('db'));
Functions.ajaxShowMessage();
AJAX.source = $(this);
$.post('index.php?route=/database/central-columns', multiColumnEditData, AJAX.responseHandler);
});
$('#add_new').find('td').each(function () {
if ($(this).attr('name') !== 'undefined') {
$(this).find('input,select').first().attr('name', $(this).attr('name'));
}
});
$('#field_0_0').attr('required', 'required');
$('#add_new input[type="text"], #add_new input[type="number"], #add_new select').css({
'width': '10em',
'-moz-box-sizing': 'border-box'
});
window.scrollTo(0, 0);
$(document).on('keyup', '.filter_rows', function () {
// get the column names
var cols = $('th.column_heading').map(function () {
return $(this).text().trim();
}).get();
$.uiTableFilter($('#table_columns'), $(this).val(), cols, null, 'td span');
});
$('.edit').on('click', function () {
var rownum = $(this).parent().data('rownum');
$('#save_' + rownum).show();
$(this).hide();
$('#f_' + rownum + ' td span').hide();
$('#f_' + rownum + ' input, #f_' + rownum + ' select, #f_' + rownum + ' .open_enum_editor').show();
var attributeVal = $('#f_' + rownum + ' td[name=col_attribute] span').html();
$('#f_' + rownum + ' select[name=field_attribute\\[' + rownum + '\\] ] option[value="' + attributeVal + '"]').attr('selected', 'selected');
if ($('#f_' + rownum + ' .default_type').val() === 'USER_DEFINED') {
$('#f_' + rownum + ' .default_type').siblings('.default_value').show();
} else {
$('#f_' + rownum + ' .default_type').siblings('.default_value').hide();
}
});
$('.del_row').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
var $td = $(this);
var question = Messages.strDeleteCentralColumnWarning;
$td.confirm(question, null, function () {
var rownum = $td.data('rownum');
$('#del_col_name').val('selected_fld%5B%5D=' + $('#checkbox_row_' + rownum).val());
$('#del_form').trigger('submit');
});
});
$('.edit_cancel_form').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
var rownum = $(this).data('rownum');
$('#save_' + rownum).hide();
$('#edit_' + rownum).show();
$('#f_' + rownum + ' td span').show();
$('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_' + rownum + ' .default_value, #f_' + rownum + ' .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
});
$('.edit_save_form').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
var rownum = $(this).data('rownum');
$('#f_' + rownum + ' td').each(function () {
if ($(this).attr('name') !== 'undefined') {
$(this).find(':input[type!="hidden"],select').first().attr('name', $(this).attr('name'));
}
});
if ($('#f_' + rownum + ' .default_type').val() === 'USER_DEFINED') {
$('#f_' + rownum + ' .default_type').attr('name', 'col_default_sel');
} else {
$('#f_' + rownum + ' .default_value').attr('name', 'col_default_val');
}
var datastring = $('#f_' + rownum + ' :input').serialize();
$.ajax({
type: 'POST',
url: 'index.php?route=/database/central-columns',
data: datastring + CommonParams.get('arg_separator') + 'ajax_request=true',
dataType: 'json',
success: function success(data) {
if (data.message !== '1') {
Functions.ajaxShowMessage('<div class="alert alert-danger" role="alert">' + data.message + '</div>', false);
} else {
$('#f_' + rownum + ' td input[id=checkbox_row_' + rownum + ']').val($('#f_' + rownum + ' input[name=col_name]').val()).html();
$('#f_' + rownum + ' td[name=col_name] span').text($('#f_' + rownum + ' input[name=col_name]').val()).html();
$('#f_' + rownum + ' td[name=col_type] span').text($('#f_' + rownum + ' select[name=col_type]').val()).html();
$('#f_' + rownum + ' td[name=col_length] span').text($('#f_' + rownum + ' input[name=col_length]').val()).html();
$('#f_' + rownum + ' td[name=collation] span').text($('#f_' + rownum + ' select[name=collation]').val()).html();
$('#f_' + rownum + ' td[name=col_attribute] span').text($('#f_' + rownum + ' select[name=col_attribute]').val()).html();
$('#f_' + rownum + ' td[name=col_isNull] span').text($('#f_' + rownum + ' input[name=col_isNull]').is(':checked') ? 'Yes' : 'No').html();
$('#f_' + rownum + ' td[name=col_extra] span').text($('#f_' + rownum + ' input[name=col_extra]').is(':checked') ? 'auto_increment' : '').html();
$('#f_' + rownum + ' td[name=col_default] span').text($('#f_' + rownum + ' :input[name=col_default]').val()).html();
}
$('#save_' + rownum).hide();
$('#edit_' + rownum).show();
$('#f_' + rownum + ' td span').show();
$('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_' + rownum + ' .default_value, #f_' + rownum + ' .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
},
error: function error() {
Functions.ajaxShowMessage('<div class="alert alert-danger" role="alert">' + Messages.strErrorProcessingRequest + '</div>', false);
}
});
});
$('#table-select').on('change', function () {
var selectValue = $(this).val();
var defaultColumnSelect = $('#column-select').find('option').first();
var href = 'index.php?route=/database/central-columns/populate';
var params = {
'ajax_request': true,
'server': CommonParams.get('server'),
'db': CommonParams.get('db'),
'selectedTable': selectValue
};
$('#column-select').html('<option value="">' + Messages.strLoading + '</option>');
if (selectValue !== '') {
$.post(href, params, function (data) {
$('#column-select').empty().append(defaultColumnSelect);
$('#column-select').append(data.message);
});
}
});
$('#add_column').on('submit', function (e) {
var selectvalue = $('#column-select').val();
if (selectvalue === '') {
e.preventDefault();
e.stopPropagation();
}
});
$('#add_col_div').find('>a').on('click', function () {
$('#add_new').slideToggle('slow');
var $addColDivLinkSpan = $('#add_col_div').find('>a span');
if ($addColDivLinkSpan.html() === '+') {
$addColDivLinkSpan.html('-');
} else {
$addColDivLinkSpan.html('+');
}
});
$('#add_new').on('submit', function () {
$('#add_new').toggle();
});
$('#tableslistcontainer').find('select.default_type').on('change', function () {
if ($(this).val() === 'USER_DEFINED') {
$(this).siblings('.default_value').attr('name', 'col_default');
$(this).attr('name', 'col_default_sel');
} else {
$(this).attr('name', 'col_default');
$(this).siblings('.default_value').attr('name', 'col_default_val');
}
});
});
|
'use strict';
var React = window.React = require('react'),
attachFastClick = require('fastclick'),
House = require('./views/house'),
mountNode = document.getElementById('app');
var HouseApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
componentDidMount: function() {},
render: function() {
return (
<House id='1' />
);
}
});
React.render(<HouseApp />, mountNode);
attachFastClick(document.body);
|
import chai from 'chai'
import {startQuestionnaire} from '../../../helpers'
import GeographicMarkets from '../../../pages/surveys/ukis/geographic-markets.page.js'
import SignificantEvents from '../../../pages/surveys/ukis/significant-events.page.js'
import GeneralBusinessInformationCompleted from '../../../pages/surveys/ukis/general-business-information-completed.page.js'
import BusinessChanges from '../../../pages/surveys/ukis/business-changes.page.js'
import BusinessStrategyPracticesCompleted from '../../../pages/surveys/ukis/business-strategy-practices-completed.page.js'
import InternalInvestmentRD from '../../../pages/surveys/ukis/internal-investment-r-d.page.js'
import YearsInternalInvestmentRD from '../../../pages/surveys/ukis/years-internal-investment-r-d.page.js'
import ExpenditureInternalInvestmentRD from '../../../pages/surveys/ukis/expenditure-internal-investment-r-d.page.js'
import AcquisitionInternalInvestmentRD from '../../../pages/surveys/ukis/acquisition-internal-investment-r-d.page.js'
import AmountAcquisitionInternalInvestmentRD from '../../../pages/surveys/ukis/amount-acquisition-internal-investment-r-d.page.js'
import InvestmentAdvancedMachinery from '../../../pages/surveys/ukis/investment-advanced-machinery.page.js'
import InvestmentPurposesInnovation from '../../../pages/surveys/ukis/investment-purposes-innovation.page.js'
import AmountAcquisitionAdvancedMachinery from '../../../pages/surveys/ukis/amount-acquisition-advanced-machinery.page.js'
import InvestmentExistingKnowledgeInnovation from '../../../pages/surveys/ukis/investment-existing-knowledge-innovation.page.js'
import ExpenditureExisting2016 from '../../../pages/surveys/ukis/expenditure-existing-2016.page.js'
import InvestmentTrainingInnovative from '../../../pages/surveys/ukis/investment-training-innovative.page.js'
import ExpenditureTrainingInnovative2016 from '../../../pages/surveys/ukis/expenditure-training-innovative-2016.page.js'
import InvestmentDesignFutureInnovation from '../../../pages/surveys/ukis/investment-design-future-innovation.page.js'
import ExpenditureDesign2016 from '../../../pages/surveys/ukis/expenditure-design-2016.page.js'
import InvestmentIntroductionInnovations from '../../../pages/surveys/ukis/investment-introduction-innovations.page.js'
import InvestmentPurposesInnovation2 from '../../../pages/surveys/ukis/investment-purposes-innovation-2.page.js'
import ExpenditureIntroductionInnovations2016 from '../../../pages/surveys/ukis/expenditure-introduction-innovations-2016.page.js'
import InnovationInvestmentCompleted from '../../../pages/surveys/ukis/innovation-investment-completed.page.js'
import IntroducingSignificantlyImprovedGoods from '../../../pages/surveys/ukis/introducing-significantly-improved-goods.page.js'
import EntityDevelopedTheseGoods from '../../../pages/surveys/ukis/entity-developed-these-goods.page.js'
import IntroduceSignificantlyImprovement from '../../../pages/surveys/ukis/introduce-significantly-improvement.page.js'
import EntityMainlyDevelopedThese from '../../../pages/surveys/ukis/entity-mainly-developed-these.page.js'
import NewGoodsServicesInnovations from '../../../pages/surveys/ukis/new-goods-services-innovations.page.js'
import GoodsServicesInnovationsNew from '../../../pages/surveys/ukis/goods-services-innovations-new.page.js'
import PercentageTurnover2016 from '../../../pages/surveys/ukis/percentage-turnover-2016.page.js'
import GoodsAndServicesInnovationCompleted from '../../../pages/surveys/ukis/goods-and-services-innovation-completed.page.js'
import ProcessImproved from '../../../pages/surveys/ukis/process-improved.page.js'
import DevelopedProcesses from '../../../pages/surveys/ukis/developed-processes.page.js'
import ImprovedProcesses from '../../../pages/surveys/ukis/improved-processes.page.js'
import ProcessInnovationCompleted from '../../../pages/surveys/ukis/process-innovation-completed.page.js'
import ConstraintsInnovationActivities from '../../../pages/surveys/ukis/constraints-innovation-activities.page.js'
import ConstrainingInnovationEconomic from '../../../pages/surveys/ukis/constraining-innovation-economic.page.js'
import ConstrainingInnovationCosts from '../../../pages/surveys/ukis/constraining-innovation-costs.page.js'
import ConstrainingInnovationFinance from '../../../pages/surveys/ukis/constraining-innovation-finance.page.js'
import ConstrainingInnovationAvailableFinance from '../../../pages/surveys/ukis/constraining-innovation-available-finance.page.js'
import ConstrainingInnovationLackQualified from '../../../pages/surveys/ukis/constraining-innovation-lack-qualified.page.js'
import ConstrainingInnovationLackTechnology from '../../../pages/surveys/ukis/constraining-innovation-lack-technology.page.js'
import ConstrainingInnovationLackInformation from '../../../pages/surveys/ukis/constraining-innovation-lack-information.page.js'
import ConstrainingInnovationDominated from '../../../pages/surveys/ukis/constraining-innovation-dominated.page.js'
import ConstrainingInnovationUncertain from '../../../pages/surveys/ukis/constraining-innovation-uncertain.page.js'
import ConstrainingInnovationGovernment from '../../../pages/surveys/ukis/constraining-innovation-government.page.js'
import ConstrainingInnovationEu from '../../../pages/surveys/ukis/constraining-innovation-eu.page.js'
import ConstrainingInnovationReferendum from '../../../pages/surveys/ukis/constraining-innovation-referendum.page.js'
import ConstraintsOnInnovationCompleted from '../../../pages/surveys/ukis/constraints-on-innovation-completed.page.js'
import FactorsAffectingIncreasingRange from '../../../pages/surveys/ukis/factors-affecting-increasing-range.page.js'
import FactorsAffectingNewMarkets from '../../../pages/surveys/ukis/factors-affecting-new-markets.page.js'
import FactorsAffectingMarketShare from '../../../pages/surveys/ukis/factors-affecting-market-share.page.js'
import FactorsAffectingQuality from '../../../pages/surveys/ukis/factors-affecting-quality.page.js'
import FactorsAffectingFlexibility from '../../../pages/surveys/ukis/factors-affecting-flexibility.page.js'
import FactorsAffectingCapacity from '../../../pages/surveys/ukis/factors-affecting-capacity.page.js'
import FactorsAffectingValue from '../../../pages/surveys/ukis/factors-affecting-value.page.js'
import FactorsAffectingReducingCost from '../../../pages/surveys/ukis/factors-affecting-reducing-cost.page.js'
import FactorsAffectingHealthSafety from '../../../pages/surveys/ukis/factors-affecting-health-safety.page.js'
import FactorsAffectingEnvironmental from '../../../pages/surveys/ukis/factors-affecting-environmental.page.js'
import FactorsAffectingReplacing from '../../../pages/surveys/ukis/factors-affecting-replacing.page.js'
import FactorsAffectingRegulatory from '../../../pages/surveys/ukis/factors-affecting-regulatory.page.js'
import FactorsAffectingCompleted from '../../../pages/surveys/ukis/factors-affecting-completed.page.js'
import ImportancesInformationInnovation from '../../../pages/surveys/ukis/importances-information-innovation.page.js'
import ImportancesInformationSuppliers from '../../../pages/surveys/ukis/importances-information-suppliers.page.js'
import ImportancesInformationClient from '../../../pages/surveys/ukis/importances-information-client.page.js'
import ImportancesInformationPublicSector from '../../../pages/surveys/ukis/importances-information-public-sector.page.js'
import ImportancesInformationCompetitors from '../../../pages/surveys/ukis/importances-information-competitors.page.js'
import ImportancesInformationConsultants from '../../../pages/surveys/ukis/importances-information-consultants.page.js'
import ImportancesInformationUniversities from '../../../pages/surveys/ukis/importances-information-universities.page.js'
import ImportancesInformationGovernment from '../../../pages/surveys/ukis/importances-information-government.page.js'
import ImportancesInformationConferences from '../../../pages/surveys/ukis/importances-information-conferences.page.js'
import ImportancesInformationAssociations from '../../../pages/surveys/ukis/importances-information-associations.page.js'
import ImportancesInformationStandards from '../../../pages/surveys/ukis/importances-information-standards.page.js'
import ImportancesInformationPublications from '../../../pages/surveys/ukis/importances-information-publications.page.js'
import InformationNeededForInnovationCompleted from '../../../pages/surveys/ukis/information-needed-for-innovation-completed.page.js'
import CoOperationOtherBusinesses from '../../../pages/surveys/ukis/co-operation-other-businesses.page.js'
import CoOperationSuppliers from '../../../pages/surveys/ukis/co-operation-suppliers.page.js'
import CoOperationPrivateSector from '../../../pages/surveys/ukis/co-operation-private-sector.page.js'
import CoOperationPublicSector from '../../../pages/surveys/ukis/co-operation-public-sector.page.js'
import CoOperationCompetitors from '../../../pages/surveys/ukis/co-operation-competitors.page.js'
import CoOperationConsultants from '../../../pages/surveys/ukis/co-operation-consultants.page.js'
import CoOperationInstitutions from '../../../pages/surveys/ukis/co-operation-institutions.page.js'
import CoOperationGovernment from '../../../pages/surveys/ukis/co-operation-government.page.js'
import NotNecessaryPossible from '../../../pages/surveys/ukis/not-necessary-possible.page.js'
import InnovationsProtectedPatents from '../../../pages/surveys/ukis/innovations-protected-patents.page.js'
import InnovationsProtectedDesign from '../../../pages/surveys/ukis/innovations-protected-design.page.js'
import InnovationsProtectedCopyright from '../../../pages/surveys/ukis/innovations-protected-copyright.page.js'
import InnovationsProtectedTrademark from '../../../pages/surveys/ukis/innovations-protected-trademark.page.js'
import InnovationsProtectedLeadTime from '../../../pages/surveys/ukis/innovations-protected-lead-time.page.js'
import InnovationsProtectedServices from '../../../pages/surveys/ukis/innovations-protected-services.page.js'
import InnovationsProtectedSecrecy from '../../../pages/surveys/ukis/innovations-protected-secrecy.page.js'
import CoOperationOnInnovationCompleted from '../../../pages/surveys/ukis/co-operation-on-innovation-completed.page.js'
import PublicFinancialSupport from '../../../pages/surveys/ukis/public-financial-support.page.js'
import KindFinancialCentralGovernmentSupport from '../../../pages/surveys/ukis/kind-financial-central-government-support.page.js'
import PublicFinancialSupportForInnovationCompleted from '../../../pages/surveys/ukis/public-financial-support-for-innovation-completed.page.js'
import Turnover2014 from '../../../pages/surveys/ukis/turnover-2014.page.js'
import Turnover2016 from '../../../pages/surveys/ukis/turnover-2016.page.js'
import Exports2016 from '../../../pages/surveys/ukis/exports-2016.page.js'
import TurnoverAndExportsCompleted from '../../../pages/surveys/ukis/turnover-and-exports-completed.page.js'
import Employees2014 from '../../../pages/surveys/ukis/employees-2014.page.js'
import Employees2016 from '../../../pages/surveys/ukis/employees-2016.page.js'
import EmployeesQualifications2016 from '../../../pages/surveys/ukis/employees-qualifications-2016.page.js'
import EmployeesInHouseSkills from '../../../pages/surveys/ukis/employees-in-house-skills.page.js'
import EmployeesAndSkillsCompleted from '../../../pages/surveys/ukis/employees-and-skills-completed.page.js'
import AdditionalComments from '../../../pages/surveys/ukis/additional-comments.page.js'
import HowLong from '../../../pages/surveys/ukis/how-long.page.js'
import ApproachedTelephone from '../../../pages/surveys/ukis/approached-telephone.page.js'
import ReadyToSubmitCompleted from '../../../pages/surveys/ukis/ready-to-submit-completed.page.js'
import Navigation from '../../../pages/surveys/ukis/navigation.page.js'
const expect = chai.expect
describe('UKIS - Did you invest in training?', function() {
it('Given I am answering question 3.11 under 3. Innovation Investment block, When I select Yes as the response, Then I am routed to question 3.12', function() {
startQuestionnaire('1_0001.json')
Navigation.navigateToInnovationInvestment()
InternalInvestmentRD.clickInternalInvestmentRDAnswerYes().submit()
YearsInternalInvestmentRD.clickYearsInternalInvestmentRDAnswer2016().submit()
ExpenditureInternalInvestmentRD.setExpenditureInternalInvestmentRDAnswer(100).submit()
AcquisitionInternalInvestmentRD.clickAcquisitionInternalInvestmentRDAnswerNo().submit()
InvestmentAdvancedMachinery.clickInvestmentAdvancedMachineryAnswerYes().submit()
InvestmentPurposesInnovation.clickInvestmentPurposesInnovationAnswerAdvancedMachineryAndEquipment()
.clickInvestmentPurposesInnovationAnswerComputerHardware()
.clickInvestmentPurposesInnovationAnswerComputerSoftware()
.submit()
AmountAcquisitionAdvancedMachinery.setAmountAcquisitionAdvancedMachineryAnswer(99999).submit()
InvestmentExistingKnowledgeInnovation.clickInvestmentExistingKnowledgeInnovationAnswerNo().submit()
InvestmentTrainingInnovative.clickInvestmentTrainingInnovativeAnswerYes().submit()
expect(ExpenditureTrainingInnovative2016.isOpen()).to.equal(true, 'Expected to Navigate to Q: 3.12')
})
it('Given I am answering question 3.11 under 3. Innovation Investment block, When I select No as the response, Then I am routed to question 3.13', function() {
startQuestionnaire('1_0001.json')
Navigation.navigateToInnovationInvestment()
InternalInvestmentRD.clickInternalInvestmentRDAnswerYes().submit()
YearsInternalInvestmentRD.clickYearsInternalInvestmentRDAnswer2016().submit()
ExpenditureInternalInvestmentRD.setExpenditureInternalInvestmentRDAnswer(100).submit()
AcquisitionInternalInvestmentRD.clickAcquisitionInternalInvestmentRDAnswerNo().submit()
InvestmentAdvancedMachinery.clickInvestmentAdvancedMachineryAnswerYes().submit()
InvestmentPurposesInnovation.clickInvestmentPurposesInnovationAnswerAdvancedMachineryAndEquipment()
.clickInvestmentPurposesInnovationAnswerComputerHardware()
.clickInvestmentPurposesInnovationAnswerComputerSoftware()
.submit()
AmountAcquisitionAdvancedMachinery.setAmountAcquisitionAdvancedMachineryAnswer(99999).submit()
InvestmentExistingKnowledgeInnovation.clickInvestmentExistingKnowledgeInnovationAnswerNo().submit()
InvestmentTrainingInnovative.clickInvestmentTrainingInnovativeAnswerNo().submit()
expect(InvestmentDesignFutureInnovation.isOpen()).to.equal(true, 'Expected to Navigate to Q: 3.13')
})
it('Given I am answering question 3.11 under 3. Innovation Investment block, When no response is selected, Then I am routed to question 3.13', function() {
startQuestionnaire('1_0001.json')
Navigation.navigateToInnovationInvestment()
InternalInvestmentRD.clickInternalInvestmentRDAnswerYes().submit()
YearsInternalInvestmentRD.clickYearsInternalInvestmentRDAnswer2016().submit()
ExpenditureInternalInvestmentRD.setExpenditureInternalInvestmentRDAnswer(100).submit()
AcquisitionInternalInvestmentRD.clickAcquisitionInternalInvestmentRDAnswerNo().submit()
InvestmentAdvancedMachinery.clickInvestmentAdvancedMachineryAnswerYes().submit()
InvestmentPurposesInnovation.clickInvestmentPurposesInnovationAnswerAdvancedMachineryAndEquipment()
.clickInvestmentPurposesInnovationAnswerComputerHardware()
.clickInvestmentPurposesInnovationAnswerComputerSoftware()
.submit()
AmountAcquisitionAdvancedMachinery.setAmountAcquisitionAdvancedMachineryAnswer(99999).submit()
InvestmentExistingKnowledgeInnovation.clickInvestmentExistingKnowledgeInnovationAnswerNo().submit()
InvestmentTrainingInnovative.submit()
expect(InvestmentDesignFutureInnovation.isOpen()).to.equal(true, 'Expected to Navigate to Q: 3.13')
})
})
|
// ConfirmationModal
// ---------------------------------
//
// A simple modal for simple confirmation dialogs
BackboneBootstrapModals.ConfirmationModal = BackboneBootstrapModals.BaseModal.extend({
confirmationEvents: {
'click #confirmation-confirm-btn': 'onClickConfirm',
'keypress .modal-body': 'onKeyPress'
},
// Default set of BaseModal options for use as ConfirmationModal
headerViewOptions: function() {
return {
label: _.result(this, 'label'),
labelId: _.result(this, 'labelId'),
labelTagName: _.result(this, 'labelTagName'),
showClose: _.result(this, 'showClose')
};
},
bodyViewOptions: function() {
return {
text: _.result(this, 'text'),
textTagName: _.result(this, 'textTagName')
};
},
footerViewOptions: function() {
var buttons = [],
showCancel = _.result(this, 'showCancel');
if (showCancel === undefined || showCancel === true) {
buttons.push({
id: 'confirmation-cancel-btn',
className: 'btn '+ (_.result(this, 'cancelClassName') || 'btn-default'),
value: (_.result(this, 'cancelText') || 'Cancel'),
attributes: { 'data-dismiss': 'modal', 'aria-hidden': 'true' }
});
}
buttons.push({
id: 'confirmation-confirm-btn',
className: 'btn '+ (_.result(this, 'confirmClassName') || 'btn-primary'),
value: (_.result(this, 'confirmText') || 'Confirm')
});
return {
buttons: buttons
};
},
// properties to copy from options
confirmationProperties: [
'label',
'labelId',
'labelTagName',
'showClose',
'text',
'textTagName',
'confirmText',
'confirmClassName',
'cancelText',
'cancelClassName',
'showCancel',
'onConfirm',
'onCancel'
],
initialize: function(opts) {
var options = opts || {};
_.extend(this, _.pick(options, this.confirmationProperties));
},
// Override BaseModal hook to add additional default delegated events
getAdditionalEventsToDelegate: function() {
var eventHashes = BackboneBootstrapModals.BaseModal.prototype.getAdditionalEventsToDelegate.call(this);
return eventHashes.concat(this.confirmationEvents);
},
onKeyPress: function(e) {
// if the user presses the enter key
if (e.which === 13) {
e.preventDefault();
this.$('#confirmation-confirm-btn').click();
}
},
onClickConfirm: function(e) {
e.preventDefault();
e.currentTarget.disabled = true;
this.confirmProgress(e);
},
confirmProgress: function(e) {
this.isConfirmed = true;
// Execute the specified callback if it exists, then hide the modal.
// The modal will not be hidden if the callback returns false.
if (this.onConfirm) {
if (this.onConfirm(e) !== false) {
this.hide();
}
} else {
this.hide();
}
},
onHideBsModal: function() {
if (!this.isConfirmed) {
if (this.onCancel) {
this.onCancel();
}
}
BackboneBootstrapModals.BaseModal.prototype.onHideBsModal.call(this);
}
});
|
import Mirage from 'ember-cli-mirage';
export default Mirage.Factory.extend({
name: 'travis-web',
vcs_name: 'travis-web',
github_language: 'ruby',
active: true,
active_on_org: false,
email_subscribed: true,
migration_status: null,
owner_name: 'travis-ci',
owner: Object.freeze({
login: 'travis-ci',
}),
permissions: Object.freeze({
read: false,
activate: false,
deactivate: false,
star: false,
unstar: false,
create_request: false,
create_cron: false,
change_settings: false,
admin: false,
}),
customSshKey: Object.freeze({
description: 'Custom',
fingerprint: 'dd:cc:bb:aa',
type: 'custom'
}),
defaultSshKey: Object.freeze({
type: 'default',
fingerprint: 'aa:bb:cc:dd',
description: 'Default',
}),
slug: function () {
return `${this.owner.login}/${this.name}`;
},
afterCreate(repository, server) {
if (!repository.attrs.skipPermissions) {
// Creates permissions for first user in the database
// TODO: I'd like to remove it at some point as this is unexpected
// we should set up permissions as needed. Possibly whenever we fully
// switch to permissions from V3
const user = server.schema.users.all().models[0] || null;
server.create('permissions', { user, repository });
}
}
});
|
var PBSyntaxHighlighter = ( function() {
"use strict";
var sh;
/**
* Constructor
* @param {String} sh The SyntaxHighlighter
*/
function PBSyntaxHighlighter(sh) {
switch(sh) {
case "HIGHLIGHT" :
this.sh = HIGHLIGHT;
break;
case "PRETTIFY" :
this.sh = PRETTIFY;
break;
case "PRISM" :
this.sh = PRISM;
break;
case "SYNTAX_HIGHLIGHTER" :
this.sh = SYNTAX_HIGHLIGHTER;
break;
default :
this.sh = {
_type : "DEFAULT",
_cls : "",
_tag : 'pre'
}
break;
}
}
/**
* Sets the SyntaxHighlighter type
* @param {String} type The name of the SyntaxHighlighter
*/
PBSyntaxHighlighter.prototype.setType = function(type) {
this.sh._type = type;
};
/**
* Gets the SyntaxHighlighter type
* @return {String} The type of the SyntaxHighlighter
*/
PBSyntaxHighlighter.prototype.getType = function() {
return this.sh._type;
};
/**
* Sets the full class of the SH object
* @param {String} cls the class to add to the Object
*/
PBSyntaxHighlighter.prototype.setCls = function(cls) {
this.sh.cls = this.sh._cls + cls;
};
/**
* Gets the full class of the SH Object
* @return {String} the full class of the SH Object
*/
PBSyntaxHighlighter.prototype.getCls = function() {
return this.sh.cls;
};
/**
* Get the tag to insert into the pre tag
* @return {String} the tag to insert, pre otherwise
*/
PBSyntaxHighlighter.prototype.getTag = function() {
return this.sh._tag;
};
return PBSyntaxHighlighter;
})();
/**********************************/
/* SYNTAX HIGHLIGHTERS DEFINITION */
/**********************************/
var HIGHLIGHT = {
_type : "HIGHLIGHT",
_cls : "", // only show language (done in pbckcode.js)
_tag : 'code'
}
var PRETTIFY = {
_type : "PRETTIFY",
_cls : "prettyprint linenums lang-",
_tag : 'pre'
}
var PRISM = {
_type : "PRISM",
_cls : "language-",
_tag : 'code'
};
var SYNTAX_HIGHLIGHTER = {
_type : "SYNTAX_HIGHLIGHTER",
_cls : "brush: ",
_tag : 'pre'
}
|
System =
{
_cycle: null,
_startCycle: function()
{
this._cycle = setInterval("System.Queue.walk()",1);
},
_stopCycle: function()
{
clearInterval(this._cycle);
},
_initialize: function()
{
// start the cycle
this._startCycle();
// set the document monitor
document.onmousemove = System.Document._monitor;
},
attach: function()
/*
* Interface method shared by all subclasses.
* Used to attach an object to the queue.
* Ex. System.Behaviours.attach("elastic",args);
*/
{
try
{
// create an instance of object
var inst = eval("new this." + arguments[0]);
// what will be the argument object passed to object
var args = new Array();
// now add in any remaining argument values (all properties
// of 'arguments' >= [1] since [0] == method name
for(a=1; a < arguments.length; a++)
{
args[a-1] = arguments[a];
}
// call the instance constructor
eval("inst." + arguments[0] + "(args)");
// add it to the Queue
System.Queue.push(inst);
}
catch(e)
{
System.handleException(e,arguments);
}
},
register: function(scr)
{
try
{
// set prototype of new object to System
eval(scr + ".prototype = System");
// add new object to System collection
eval("this." + scr + " = new " + scr + "()");
// try to call constructor, if any
try
{
eval("this." + scr + "." + scr + "()");
} catch(e) {;}
/* Some System function are private, and are indicated by
* a leading underscore ("_"). To avoid any accidental
* collisions with extended instances calling private methods,
* override private methods by assigning null function to extended instance.
*/
for(p in System)
{
if(p.charAt(0) == "_")
{
eval("this." + scr + "." + p + " = new Function()");
}
}
}
catch(e)
{
this.handleException(e,arguments);
}
},
handleException: function(e,ar)
{
var cler = (ar.caller) ? ar.caller.callee : 'n/a';
var clee = ar.callee || 'n/a';
var err = '>> ' + e + '\n';
for(p in e)
{
err += '>> ' + p + ': ' + eval('e.'+p) + '\n';
}
alert('Callee ->\n' + clee + '\n\nCaller ->\n' + cler + '\n\nInfo -> '+err);
},
Document:
/*
* Interface to document and event data
*
*/
{
// private event data storage, exposed to document.methods
_eventInfo:
{
element: new Object(),
xPos: null,
yPos: null
},
// mousemove handler, bound in _initialize()
_monitor: function(e)
{
var ns = (e);
var ev = (ns) ? e : window.event;
// note that this function executes in the event scope, so
// we need to build a direct ref to System
var eInf = System.Document._eventInfo;
eInf.element = (ns) ? ev.target : ev.srcElement;
eInf.xPos = (ns) ? ev.pageX : ev.clientX;
eInf.yPos = (ns) ? ev.pageY : ev.clientY;
},
cursorX: function()
{
return(System.Document._eventInfo.xPos);
},
cursorY: function()
{
return(System.Document._eventInfo.yPos);
},
currentElement: function()
{
return(System.Document._eventInfo.element);
}
},
Queue:
{
_queue: new Array(),
push: function(ob)
{
var sOb = ob || new Object();
sOb.main = sOb.main || new Function();
this._queue.push(sOb);
},
kill: function(ref)
{
for(q=0; q<this._queue.length; q++)
{
if(this._queue[q] == ref)
{
this._queue.splice(q,1);
return(true);
}
}
return(false);
},
walk: function()
{
var instance = false;
// because the queue may be appended to during this routine, the terminal
// instruction of the start set is needed to flag termination of the run
var terminal = this._queue[this._queue.length-1];
while(instance = this._queue.shift())
{
try
{
// execute main routine of object and
// reintroduce to queue if main() returns true
instance.main() && this.push(instance);
}
catch(e)
{
// note that if an error occurs in instance.main() the instance
// is removed from the queue by force: ie. it will never get pushed
System.handleException(e,arguments);
}
// die if we've reached the end of the ORIGINAL queue
if(instance == terminal)
{
break;
}
}
}
},
XMLHTTP:
/*
* Interface to file loading functions
* Handles SOAP, .xml, and any accessible HTTP file
*
*/
{
loadHTTP: function(method,file,callback,SOAP)
{
/*
* Because data stream is loaded asynchronously, add a monitor to the queue,
* and let that object carry until its stream is completed.
*
*/
try
{
var ob = new this._handler();
ob.httpHandle.open(method,file,true);
ob.httpHandle.send(SOAP || null);
var monitor =
{
ref: ob.httpHandle,
callback: callback,
main: function()
{
if(this.ref.readyState == 4)
{
this.callback(this.ref.responseText);
return(false);
}
else
{
return(true);
}
}
};
System.Queue.push(monitor);
}
catch(e)
{
System.handleException(e,arguments);
}
},
loadXML: function(file,callback)
{
/*
* Because data stream is loaded asynchronously, add a monitor to the queue,
* and let that object carry until its stream is completed.
*
*/
try
{
var ob = new this._handler();
if(window.XMLHttpRequest)
{
ob.xmlHandle.open("GET",file,true);
ob.xmlHandle.send(null);
}
else
{
ob.xmlHandle.async = false;
ob.xmlHandle.load(file);
}
var monitor =
{
ref: ob.xmlHandle,
callback: callback,
main: function()
{
if(this.ref.readyState == 4)
{
var result = (window.XMLHttpRequest)
? this.ref.responseXML
: this.ref.documentElement;
this.callback(result);
return(false);
}
else
{
return(true);
}
}
};
System.Queue.push(monitor);
}
catch(e)
{
System.handleException(e,arguments);
}
},
serialize: function(obj)
{
try
{
// moz
var s = new XMLSerializer();
var ser = s.serializeToString(obj);
}
catch(e)
{
// ie
var ser = obj.xml;
}
return(ser);
},
_handler: function()
{
// mozilla
if(window.XMLHttpRequest)
{
this.httpHandle = new XMLHttpRequest();
this.xmlHandle = new XMLHttpRequest();
}
else
{
// create the Microsoft handle
var prefixes = ["MSXML4","MSXML3","MSXML2","MSXML","Microsoft"];
for (var i = 0; i < prefixes.length; i++)
{
try
{
http = new ActiveXObject(prefixes[i] + ".XmlHttp");
xml = new ActiveXObject(prefixes[i] + ".XmlDom");
this.httpHandle = http;
this.xmlHandle = xml;
break;
}
catch(ex) {;}
}
}
}
}
};
|
/*
* @Author: Matteo Zambon
* @Date: 2017-01-11 00:31:57
* @Last Modified by: Matteo Zambon
* @Last Modified time: 2017-01-11 00:39:42
*/
'use strict'
const routes = require('./routes')
module.exports = {
init: (app) => {
// const swagger = app.services.SwaggerService.stripe
},
addRoutes: app => {
const routerUtil = app.packs.router.util
app.config.routes = routerUtil.mergeRoutes(routes, app.config.routes)
}
}
|
export { default } from './DataUploadContainer';
|
module.exports = {
options: function(method, options, keys, stream) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!options || !options[key]) {
stream.emit('error', new Error('#' + method + ': options.' + key + ' was not provided.'));
stream.push(null);
return true;
}
}
return false;
}
};
|
// This THREEx helper makes it easy to handle the fullscreen API
// * it hides the prefix for each browser
// * it hides the little discrepencies of the various vendor API
// * at the time of this writing (nov 2011) it is available in
// [firefox nightly](http://blog.pearce.org.nz/2011/11/firefoxs-html-full-screen-api-enabled.html),
// [webkit nightly](http://peter.sh/2011/01/javascript-full-screen-api-navigation-timing-and-repeating-css-gradients/) and
// [chrome stable](http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API).
//
// # Code
//
/** @namespace */
var THREEx = THREEx || {};
THREEx.FullScreen = THREEx.FullScreen || {};
/**
* test if it is possible to have fullscreen
*
* @returns {Boolean} true if fullscreen API is available, false otherwise
*/
THREEx.FullScreen.available = function()
{
return this._hasWebkitFullScreen || this._hasMozFullScreen;
}
/**
* test if fullscreen is currently activated
*
* @returns {Boolean} true if fullscreen is currently activated, false otherwise
*/
THREEx.FullScreen.activated = function()
{
if( this._hasWebkitFullScreen ){
return document.webkitIsFullScreen;
}else if( this._hasMozFullScreen ){
return document.mozFullScreen;
}else{
console.assert(false);
}
}
/**
* Request fullscreen on a given element
* @param {DomElement} element to make fullscreen. optional. default to document.body
*/
THREEx.FullScreen.request = function(element)
{
element = element || document.body;
if( this._hasWebkitFullScreen ){
element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}else if( this._hasMozFullScreen ){
element.mozRequestFullScreen();
}else{
console.assert(false);
}
}
/**
* Cancel fullscreen
*/
THREEx.FullScreen.cancel = function()
{
if( this._hasWebkitFullScreen ){
document.webkitCancelFullScreen();
}else if( this._hasMozFullScreen ){
document.mozCancelFullScreen();
}else{
console.assert(false);
}
}
// internal functions to know which fullscreen API implementation is available
THREEx.FullScreen._hasWebkitFullScreen = 'webkitCancelFullScreen' in document ? true : false;
THREEx.FullScreen._hasMozFullScreen = 'mozCancelFullScreen' in document ? true : false;
/**
* Bind a key to renderer screenshot
*/
THREEx.FullScreen.bindKey = function(opts){
opts = opts || {};
var charCode = opts.charCode || 'f'.charCodeAt(0);
var dblclick = opts.dblclick !== undefined ? opts.dblclick : false;
var element = opts.element
var toggle = function(){
if( THREEx.FullScreen.activated() ){
THREEx.FullScreen.cancel();
}else{
THREEx.FullScreen.request(element);
}
}
// callback to handle keypress
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
var onKeyPress = __bind(function(event){
// return now if the KeyPress isnt for the proper charCode
if( event.which !== charCode ) return;
// toggle fullscreen
toggle();
}, this);
// listen to keypress
// NOTE: for firefox it seems mandatory to listen to document directly
document.addEventListener('keypress', onKeyPress, false);
// listen to dblclick
dblclick && document.addEventListener('dblclick', toggle, false);
return {
unbind : function(){
document.removeEventListener('keypress', onKeyPress, false);
dblclick && document.removeEventListener('dblclick', toggle, false);
}
};
}
|
import isEqual from "../is-equal"
import fromPolyline from "./index"
test("should get the corresponding path from the SVG polyline node", () => {
const node = document.createElement("polyline")
node.setAttribute("points", "0 0 100,100 150-150 5e-14-4")
const test = fromPolyline(node)
const expected = "M0 0L100 100L150 -150L5e-14 -4"
expect(isEqual(test, expected)).toBe(true)
})
|
const destDirProd = '';
const destDirDev = 'build/';
const isDev = process.argv[2] !== 'publish';
const destDir = isDev ? destDirDev : destDirProd;
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
dev: {
src: [ `${destDirDev}**` ],
filter: function(filepath) {
return filepath.split('\\').length > 1;
}
},
prod: [ `${destDirProd}app.js`, `${destDirProd}app.es5.js` ]
},
jade: {
compile: {
options: {
pretty: isDev,
data: {
debug: isDev,
}
},
src: [ 'src/views/*.jade' ],
dest: `${destDir}index.html`
},
},
less: {
compile: {
src: [ 'src/styles/*.less' ],
dest: `${destDir}app.css`
}
},
concat: {
js: {
src: [ 'src/js/namespace.js', 'src/js/**' ],
dest: `${destDir}app.js`
}
},
copy: {
libs: {
expand: true,
cwd: 'libs/',
src: '**',
dest: `${destDirDev}libs/`,
flatten: false
},
img: {
expand: true,
cwd: 'img/',
src: ['*.png', '*.gif'],
dest: `${destDirDev}img/`,
flatten: false
}
},
postcss: {
autopref: {
options: {
map: false,
processors: [
require('autoprefixer')({
browsers: ['last 2 versions']
})
]
},
src: `${destDir}*.css`
},
// This linting do work with syntax: require('postcss-less'),
// but stylelint complains about certain LESS syntax features,
// like mixins ( .a { .b } ).
// Having postcss-less for syntax does not really
// help, just removes the ressame "you are using CSS parser for LESS files"
// If "syntax: 'less', then some error occurs,
// Work OK with syntax: require('stylelint/node_modules/postcss-less), but
// removes ";" after mixins in "less" files, so the following lint will fail
lint: {
options: {
map: false,
syntax: require('stylelint/node_modules/postcss-less'),
processors: [
require('stylelint')({
extends: './node_modules/stylelint-config-standard/index.js',
rules: {
'at-rule-name-case': 'lower',
'length-zero-no-unit': true,
'indentation': 4,
'comment-empty-line-before': [ 'never', {
except: ['first-nested'],
ignore: ['stylelint-commands', 'after-comment'],
}],
'declaration-empty-line-before': null,
}
})
]
},
src: 'src/styles/**/*.less'
}
},
babel: {
options: {
sourceMap: false,
presets: ['es2015']
},
compile: {
src: `${destDir}app.js`,
dest: `${destDir}app.es5.js`
}
},
uglify: {
options: {
mangle: {
except: [
'ReadVis2', 'SGWM', 'firebase', 'app', 'window', 'document'
]
}
},
js: {
src: `${destDir}app.es5.js`,
dest: `${destDir}app.min.js`
}
},
jshint: {
files: [
'src/js/**/*.js'
],
options: {
// engorce
bitwise: true,
curly: true,
eqeqeq: true,
esversion: 6,
freeze: true,
funcscope: true,
globals: {
// module: true,
},
//latedef: 'nofunc',
newcap: true,
noarg: true,
nocomma: true,
//nonew: true,
shadow: false,
undef: true,
unused: 'vars',
varstmt: true,
// relax
boss: true,
loopfunc: true,
supernew: false,
//environments
browser: true,
devel: true,
}
},
eslint: {
files: [
'src/js/**/*.js'
],
options: {
extends: './node_modules/eslint/conf/eslint.json',
parserOptions: {
ecmaVersion: 6,
sourceType: 'script'
},
env: {
browser: true,
es6: true
},
rules: {
'comma-dangle': 'off'
},
globals: [
// browser
// 'document',
// 'console',
// 'window',
// 'setTimeout',
// 'clearTimeout',
// 'localStorage',
// 'arguments',
// 'Blob',
// 'Map',
// 'NodeFilter',
// libs
'firebase',
]
}
},
stylelint: {
options: {
syntax: '',
config: {
extends: 'stylelint-config-standard',
rules: {
'at-rule-name-case': 'lower',
'length-zero-no-unit': true,
'indentation': 4,
'comment-empty-line-before': [ 'never', {
except: ['first-nested'],
ignore: ['stylelint-commands', 'after-comment'],
}],
'declaration-empty-line-before': null,
}
}
},
src: 'src/styles/**/*.less'
},
});
grunt.loadNpmTasks( 'grunt-contrib-clean' );
grunt.loadNpmTasks( 'grunt-contrib-jade' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-concat' );
grunt.loadNpmTasks( 'grunt-postcss' );
grunt.loadNpmTasks( 'grunt-babel' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-eslint' );
grunt.loadNpmTasks( 'grunt-stylelint' );
grunt.registerTask( 'default', [ 'jade', 'less', 'concat', 'copy', 'postcss:autopref' ] );
grunt.registerTask( 'rebuild', [ 'clean:dev', 'jade', 'less', 'concat', 'copy', 'postcss:autopref' ] );
grunt.registerTask( 'publish', [ 'jade', 'less', 'concat', 'postcss:autopref', 'babel', 'uglify', 'clean:prod' ] );
grunt.registerTask( 'compile', [ 'jshint' ] );
grunt.registerTask( 'compile2', [ 'eslint', 'stylelint' ] );
};
|
function solution(A) {
var sum = 0;
var i;
var len = A.length;
for (i = 0; i < len; i++) {
sum += A[i];
}
return (len+1) / 2 * (len+2) - sum;
}
|
import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { childrenUtils, customPropTypes, getElementType, getUnhandledProps } from '../../lib'
/**
* A message can contain a content.
*/
function MessageContent(props) {
const { children, className, content } = props
const classes = cx('content', className)
const rest = getUnhandledProps(MessageContent, props)
const ElementType = getElementType(MessageContent, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
MessageContent.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default MessageContent
|
import React, {Component} from 'react';
import Nav from '../components/layout/Nav.js';
import Footer from '../components/layout/Footer.js';
import Header from '../components/layout/Header.js';
import Gramventures from '../components/layout/Gramventures.js';
import Voting from '../components/layout/Voting.js';
import Votebrief from '../components/layout/Votebrief.js';
import Vote from '../components/layout/Vote.js';
import Closed from '../components/layout/Closed.js';
import Closedbrief from '../components/layout/Closedbrief.js';
import Applybrief from '../components/layout/Applybrief.js';
import Apply from '../components/layout/Apply.js';
import Login from '../components/layout/Login.js';
import Signup from '../components/layout/Signup.js';
import Profile from '../components/layout/Profile.js';
export default class Layout extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
<Footer />
</div>
)
}
}
|
//backyard 1
/*!
* coloursave v3 (130919)
*/
/**
* Posílátko pro libovolný element, který umožňuje držet uživatelem zadávaný obsah.
* Pošle při defocus/změně jeho obsah s´případně s kontextem na definované API URL.
* S tím, že automaticky mění barvu podle stavu odesílání.
*
* All class="coloursave" must have `name' defined.
* class="required" is possible and if empty the colour of its parent is defined by .colourSaveHighlight
* Therefore it is recommended to contain the element and its neighborhood into a <span/> or <div/> container to prevent other text being highlighted.
* Only `a' and `button' elements must have `id' defined. And its value is passed in data-coloursave-arg. data-parent may be used for these two elements, as well.
*
* URL of the API may either be defined globally by `var apiUrlColoursave'
* or may be modified on element level in data attribute coloursave-api
*
* When the value of element is changed by user, this script POSTs following parameters:
action:api_update //constant. API should deal with CRUD (create-read-update-delete) operations. The coloursave script handles just the UPDATE.
api_arg:{"relation_task":"Umí Telefónica kombinovaný SMS+MMS kanál? A co když lidé odpoví MMS? Smlouva?\n....\nJak to vypada s STK deploymentem?"} //name of the element and its value
api_context:{"project_id":3,"person_id":15,"relation_id":15} //optional information set in the data attribute coloursave-context. Equals to null if not set. @TODO - anebo nepošle nic?
eid:92 //if not set in data attribute eid, it is equal to zero
*
* If parent element should be disabled instead of the changed element, put parent's id into data attribute parent
*
* If the API response contain "error":"Anything to alert to the user." , then the string is alert()ed.
*/
/**
* @TODO 1 - přepsat tak, aby funkce nebyly v konfliktu s původním kódem a refaktorovat ve Stakan1
*
*/
'use strict';
//TBD: Use single quote instead of double quotes.
/**
* Init
*/
var apiUrlErrorLog = 'http://free.t-mobile.cz/check13stage/api/v1/error_log/';
//var relativePathToBackyardJs = 'lib/backyard/deploy/backyard/js';
var relativePathToBackyardJs = '../deploy/backyard/js';
var localisationString = new Array();
localisationString['fill_in_red'] = 'Vyplňte červené pole'; // @TODO - customize někde v config
localisationString["sent_to_server"] = 'Odesláno na server';// @TODO - customize někde v config
if(typeof(apiUrlColoursave) === 'undefined') var apiUrlColoursave = relativePathToBackyardJs + '/' + 'dummy.json';
/**
* /Init
*/
/* NOTE:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
*/
//used only in "proximity"/"visible" scope, i.e. may be reused without remorse
var tempArg;
var tempSelector;
var tempObject;
var tempEid;
var tempContext;
var tempSelectParent;
var tempURL;
var tempApiUrl;
var temp2;
$(document).ready(function() {
/*
if (typeof(my_error_log) != "function"){
// jQuery
$.getScript(relativePathToBackyardJs + '/' +'debug.js', function() //or the relative path to the calling html is needed??
{
// script is now loaded and executed.
// put your dependent JS here.
});
}
if (typeof(gi) != "function"){ //@TODO - když skript natáhnu takto, tak gi níže na "tempObject[tempSelector]=gi(tempSelector);" není definováno
// jQuery
$.getScript(relativePathToBackyardJs + '/' + 'basic.js', function() //or the relative path to the calling html is needed??
{});
}
*/
$('a.coloursave, button.coloursave').bind('click', function(e){//(e){
//console.log(e.type);//debug
if($(this).attr('id') === undefined){
my_error_log('Error: pls add id to this element.',3);
alert('Error: pls add id to this element.');
return false;
}
tempSelector=$(this).attr('id');
if($('#' + tempSelector).data('coloursave-arg')){
tempArg = $('#' + tempSelector).data('coloursave-arg');
} else {
my_error_log(tempSelector + ' has no argument',2);
return false;
}
console.log(tempArg);
tempSelectParent = '#' + tempSelector;
if($('#' + tempSelector).data('parent')){
tempSelectParent = '#' + $('#' + tempSelector).data('parent');
//console.log('slide ' + tempSelectParent + ' parent of ' + tempSelector + ' disabled');
}
if($('#' + tempSelector).data('coloursave-context')){
temp2 = JSON.stringify($('#' + tempSelector).data('coloursave-context'));
//console.log(temp2);
if(IsJsonString(temp2)){
tempContext=temp2;
} else {
my_error_log(tempSelector + ' has invalid context. JSON expected. Received:' + temp2,3);
}
}
//for eventId analytics
tempEid=0;
if($(this).data('eid'))tempEid=$(this).data('eid');
tempApiUrl = apiUrlColoursave;
if($('#' + tempSelector).data('coloursave-api')){
tempApiUrl=$('#' + tempSelector).data('coloursave-api');
}
colourSubmitForm(
{action: 'api_update', api_arg: tempArg, api_context: tempContext, eid: tempEid}, //parameters,
tempApiUrl, //apiUrl,
null, //urlDone,
tempSelectParent, //currentTarget,
null //callback
);
//není voláno z form//return false;//The return false is blocking the default form submit action.
});
$('select.coloursave, input[type="radio"].coloursave').change(function(){
tempSelector=$(this).attr('name');
//console.log("TS:" + tempSelector);
if(tempSelector === undefined){
alert('Pls add name to this element');
}
tempObject = new Object;
tempObject[tempSelector]=gi(tempSelector);
tempArg=JSON.stringify(tempObject);
tempSelectParent = null;
tempURL = null;
if(tempSelector == 'owner_language'){
tempURL = document.location.href;//refresh to change the locale language by server page generation
}
if($('[name=' + tempSelector + ']').is('select')){
if($('[name=' + tempSelector + ']').data('parent')){
tempSelectParent = '#' + $('[name=' + tempSelector + ']').data('parent');
//console.log('slide ' + tempSelectParent + ' parent of ' + tempSelector + ' disabled');
} else {
my_error_log('For ' + tempSelector + ' parent expected',3);
}
}
if($('[name=' + tempSelector + ']').is('input[type="radio"]')){
if(typeof $('[name=' + tempSelector + ']').checkboxradio === 'function'){
$('[name=' + tempSelector + ']').checkboxradio();//http://www.qlambda.com/2012/06/jqm-refresh-jquery-mobile-select-menu.html
$('[name=' + tempSelector + ']').checkboxradio('disable');
} else {
$('[name=' + tempSelector + ']').attr('disabled',true);//.removeAttr("disabled");
}
//console.log('checkbox ' + tempSelector + ' disabled');
} else if($('[name=' + tempSelector + ']').is('input')){
$('[name=' + tempSelector + ']').textinput();//http://www.qlambda.com/2012/06/jqm-refresh-jquery-mobile-select-menu.html
$('[name=' + tempSelector + ']').textinput('disable');
//console.log('textinput ' + tempSelector + ' disabled');
}
if($('[name=' + tempSelector + ']').data('coloursave-context')){
temp2 = JSON.stringify($('[name=' + tempSelector + ']').data('coloursave-context'));
//console.log(temp2);
if(IsJsonString(temp2)){
tempContext=temp2;
} else {
my_error_log(tempSelector + ' has invalid context. JSON expected. Received:' + temp2,3);
}
}
tempApiUrl = apiUrlColoursave;
if($('[name=' + tempSelector + ']').data('coloursave-api')){
tempApiUrl=$('[name=' + tempSelector + ']').data('coloursave-api');
}
colourSubmitForm(
{action: 'api_update', api_arg: tempArg},
tempApiUrl,
tempURL,
tempSelectParent,
function(tmp){
//console.log(tempSelector + ' ' + tmp + ' callbacked');
return function() {
//console.log("i = " + tmp);
if($('[name=' + tmp + ']').is('input[type="radio"]')){
if(typeof $('[name=' + tmp + ']').checkboxradio === 'function'){
$('[name=' + tmp + ']').checkboxradio('enable');
} else {
$('[name=' + tmp + ']').removeAttr("disabled");
}
}
else if($('[name=' + tempSelector + ']').is('input')){$('[name=' + tempSelector + ']').textinput('enable');}
};
}(tempSelector)
);
//není voláno z form//return false;//The return false is blocking the default form submit action.
});
});//$(document).ready(function() {
$(document).on(
"focusin", //"keydown focusin", function (e) .. keydown vždy přemaže placeholder
'textarea.coloursave, input[type="text"].coloursave, input[type="date"].coloursave, input[type="email"].coloursave, input[type="tel"].coloursave',
function (e)
{
$(this).css("color", "red");
if($(this).val() != ""){
$(this).attr("placeholder", $(this).val());
}
});
$(document).on(
"focusout", //keyup píše každé písmeno
'textarea.coloursave, input[type="text"].coloursave, input[type="date"].coloursave, input[type="email"].coloursave, input[type="tel"].coloursave',
function (e)
{
var isFormValid = true;
if($(this).hasClass("required")){
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("colourSaveHighlight");//@TODO 3 - možná bude potřeba jít přes selector v parents
if(isFormValid)$(this).focus();//focus na prvni
isFormValid = false;
} else {
$(this).parent().removeClass("colourSaveHighlight");//@TODO 3 - možná bude potřeba jít přes selector v parents
}
};
if (!isFormValid) {
alert(localisationString['fill_in_red']);
return isFormValid;
}
if($(this).attr("placeholder") != $(this).val()){
$(this).css("color", "green");
tempSelector=$(this).attr('name');
//console.log("TS:" + tempSelector);
if(tempSelector === undefined){
alert('Pls add name to this element');
}
tempObject = new Object;
tempObject[tempSelector]=gi(tempSelector);
tempArg=JSON.stringify(tempObject);
//console.log(tempArg);
if($('[name=' + tempSelector + ']').data('coloursave-context')){
temp2 = JSON.stringify($('[name=' + tempSelector + ']').data('coloursave-context'));
//console.log(temp2);
if(IsJsonString(temp2)){
tempContext=temp2;
} else {
my_error_log(tempSelector + ' has invalid context. JSON expected. Received:' + temp2,3);
}
}
/* //@TODO tempContext dle sumbit api .. lze nějak precall?
tempObject = new Object;
if(projectId)tempObject['project_id']=projectId;
if(personId)tempObject['person_id']=personId;
if(relationId)tempObject['relation_id']=relationId;
tempContext=JSON.stringify(tempObject);
*/
//for eventId analytics
tempEid=0;
if($(this).data('eid'))tempEid=$(this).data('eid');
tempApiUrl = apiUrlColoursave;
if($('[name=' + tempSelector + ']').data('coloursave-api')){
tempApiUrl=$('[name=' + tempSelector + ']').data('coloursave-api');
}
//console.log(tempArg);
colourSubmitForm(
{action: 'api_update', api_arg: tempArg, api_context: tempContext, eid: tempEid},//@TODO - kam submit?
tempApiUrl,
null, //urlDone - no redirect
null, //currentTarget - not needed for this type of input element
//function(){$('[name=' + tempSelector + ']').css('color', 'black');}//this was wrong - see below how it is done right
function(tmp){
//console.log(tempSelector + ' ' + tmp + ' callbacked');
return function() {
//console.log("i = " + tmp);
$('[name=' + tmp + ']').css('color', 'black');
};
}(tempSelector)
);
} else {
$(this).css("color", "black");//black is expected to be default //@TODO načíst do proměnné barvu a vrátit pak původní
}
});
/**
* needs localisationString['sent_to_server']
*/
/**
* //migration script
* function submitStakanForm(parameters,url,currentTarget,callback){
* return colourSubmitForm(parameters,'',url,currentTarget,callback){
* }
*/
function colourSubmitForm(parameters,apiUrl,urlDone,currentTarget,callback){
if(apiUrl == null){
apiUrl = '';//this page
}
var descriptionId = '';
if(currentTarget){
//console.log('will hide ' + currentTarget);
descriptionId = currentTarget.substring(1) + '-wait';
if($('#'+descriptionId).length == 0){//na iPhone někdy zdvojovalo přidanou description
var newDetail = document.createElement('div');
newDetail.setAttribute('id', descriptionId);
var newContent = document.createTextNode(localisationString['sent_to_server']);//debug.. + ' (1) ' + descriptionId + ' ' + tempM1 + ' ' + Math.floor((Math.random()*100)+200));//debug.. + ' ' + dump(parameters) + ' ' + dump(currentTarget));
newDetail.appendChild(newContent);
$(currentTarget).before(newDetail);
$(currentTarget).fadeOut('slow');//deactivate currentTarget ... to enable .removeAttr('disabled');
} else {
my_error_log("Double vclick on " + descriptionId,3, apiUrlErrorLog);
return false;
}
}
//debug//console.log(parameters);
var jqxhr = $.ajax( {
url: apiUrl,
type: 'POST',
data: parameters,
dataType: 'json'
} )
.fail(function(error){
if(error.responseText){//contains the response
my_error_log('failed json reply: ' + error.responseText,2, apiUrlErrorLog);
alert("Error received");//@TODO 2 - vylepšit
} else {//user probably tries to navigate away before it is finished
my_error_log('no reply acquired',2, apiUrlErrorLog);
//@TODO 2 improve this//alert("Continue without server confirmation");//You are so fast.
}
if(descriptionId){$('#'+descriptionId).fadeOut('slow',
function(){$('#'+descriptionId).remove();
if(currentTarget)$(currentTarget).fadeIn('slow');}
)} else if(currentTarget)$(currentTarget).fadeIn('slow');//hide info about server & reactivate currentTarget
})
.done(function(msg) {
if(!(msg.error === undefined)){alert(msg.error);}//pak změnit na json a toto vrátit
if(descriptionId){$('#'+descriptionId).fadeOut('slow',
function(){$('#'+descriptionId).remove();
if(currentTarget)$(currentTarget).fadeIn('slow');}
)} else if(currentTarget)$(currentTarget).fadeIn('slow');//hide info about server & reactivate currentTarget
typeof callback == "function" && callback();
if(urlDone != null){
window.location.href=urlDone; //http://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript
}}
);
return true;
}
//@TODO 4 - submitStakanForm(parameters,url)
// sanitize parameters
// Dat info, ze poslu .. Misto sending buttonu
// Poslat
// Dat info, vyckejte .. Misto sending buttonu
// OnSuccess: redirect; // dat button zpet? Nebo tam priste bude automaticky
|
import {routes} from "./routes/dashboard-routes";
require('./bootstrap');
require('es6-promise').polyfill();
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
import VueRouter from 'vue-router';
import MainPage from './components/newsfeed/MainPage.vue'
Vue.use(BootstrapVue);
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes,
})
new Vue({
el: '#app',
router,
components:{
MainPage
}
});
|
/* eslint-disable no-console */
const chalk = require('chalk');
const ip = require('ip');
const divider = chalk.gray('\n-----------------------------------');
/**
* Logger middleware, you can customize it to make messages more personal
*/
const logger = {
// Called whenever there's an error on the server we want to print
error: (err) => {
console.error(chalk.red(err));
},
// Called when express.js app starts on given port w/o errors
appStarted: (port, host, tunnelStarted) => {
console.log(`Server started ! ${chalk.green('✓')}`);
// If the tunnel started, log that and the URL it's available at
if (tunnelStarted) {
console.log(`Tunnel initialised ${chalk.green('✓')}`);
}
console.log(`
${chalk.bold('Access URLs:')}${divider}
Localhost: ${chalk.magenta(`http://${host}:${port}`)}
LAN: ${chalk.magenta(`http://${ip.address()}:${port}`) +
(tunnelStarted ? `\n Proxy: ${chalk.magenta(tunnelStarted)}` : '')}${divider}
${chalk.blue(`Press ${chalk.italic('CTRL-C')} to stop`)}
`);
},
};
module.exports = logger;
|
const { assert, skip, test, module: describe } = require('qunit');
const { GPU } = require('../../src');
describe('issue #130');
function typedArrays(mode) {
const gpu = new GPU({ mode });
const kernel = gpu.createKernel(function(changes) {
return changes[this.thread.y][this.thread.x];
})
.setOutput([2, 1]);
const values = [new Float32Array(2)];
values[0][0] = 0;
values[0][1] = 0;
const result = kernel(values);
assert.equal(result[0][0], 0);
assert.equal(result[0][1], 0);
gpu.destroy();
}
test("Issue #130 - typed array auto", () => {
typedArrays(null);
});
test("Issue #130 - typed array gpu", () => {
typedArrays('gpu');
});
(GPU.isWebGLSupported ? test : skip)("Issue #130 - typed array webgl", () => {
typedArrays('webgl');
});
(GPU.isWebGL2Supported ? test : skip)("Issue #130 - typed array webgl2", () => {
typedArrays('webgl2');
});
(GPU.isHeadlessGLSupported ? test : skip)("Issue #130 - typed array headlessgl", () => {
typedArrays('headlessgl');
});
test("Issue #130 - typed array cpu", () => {
typedArrays('cpu');
});
|
function Paint (container, settings) {
this.eventHandlers = {};
this.settings = this.utils.merge(this.utils.copy(settings), this.defaultSettings);
this.container = container;
this.boundingBoxList = [];
this.scale = [1, 1]; // Used for horizontal and vertical mirror
this.rotation = 0; // Rotation in degrees
this.frames = []; // The frames that will be displayed
// Contains objects of the form: {leftTop: [0,0], width: 500, height: 100, shift: 200, opacity: 0.4}
this.addCanvas(container);
this.resize();
this.controlContainer = container.appendChild(document.createElement("div"));
this.controlContainer.className = "control-container";
this.controls = new Controls(this.controlContainer, this.createControlArray());
this.addCoordDom(container);
// Set tool values
this.changeTool("brush");
this.setColor(new tinycolor());
this.changeToolSize(5, true);
$(this.controls.byName["tool-color"].input).spectrum("set", this.current_color);
this.localDrawings = [];
this.paths = {};
this.localUserPaths = [];
// Drawings that have not yet finalized
// The server still has to write them to image
// They could still be undone
this.publicdrawings = [];
this.altPressed = false;
window.addEventListener("resize", this.resize.bind(this));
window.addEventListener("keypress", this.keypress.bind(this));
window.addEventListener("keydown", this.keydown.bind(this));
window.addEventListener("keyup", this.keyup.bind(this));
window.addEventListener('wheel', this.wheel.bind(this));
//introJs().setOptions({ 'tooltipPosition': 'auto', 'showProgress': true }).start();
}
Paint.prototype.MAX_RANDOM_COORDS = 1048576;
Paint.prototype.FIX_CANVAS_PIXEL_SIZE = 0;
Paint.prototype.PATH_PRECISION = 1000;
Paint.prototype.MIN_PATH_WIDTH = 1.001;
Paint.prototype.defaultSettings = {
maxSize: 100,
maxLineLength: 200
};
Paint.prototype.defaultShortcuts = {
};
// Redraws everything taking into account mirroring and rotation
Paint.prototype.redrawAll = function redrawAll () {
for (var k = 0; k < this.canvasArray.length; k++) {
var ctx = this.canvasArray[k].getContext("2d");
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.setTransform(
this.scale[0], 0, 0,
this.scale[1], this.canvasArray[k].width / 2, this.canvasArray[k].height / 2
);
ctx.rotate(this.rotation * Math.PI / 180);
ctx.translate(-this.canvasArray[k].width / 2, -this.canvasArray[k].height / 2);
}
this.background.redrawOnce();
this.public.redrawOnce();
this.local.redrawOnce();
this.redrawPaths();
this.redrawFrames();
};
Paint.prototype.setHorizontalMirror = function setHorizontalMirror (value) {
this.scale[0] = value ? -1 : 1;
this.redrawAll();
this.dispatchEvent({
type: "canvaschange",
rotation: this.rotation,
scale: this.scale
});
};
Paint.prototype.setVerticalMirror = function setVerticalMirror (value) {
this.scale[1] = value ? -1 : 1;
this.redrawAll();
this.dispatchEvent({
type: "canvaschange",
rotation: this.rotation,
scale: this.scale
});
};
Paint.prototype.setRotation = function setRotation (value) {
this.rotation = value % 360;
this.redrawAll();
this.dispatchEvent({
type: "canvaschange",
rotation: this.rotation,
scale: this.scale
});
};
Paint.prototype.addCanvas = function addCanvas (container) {
// The background pngs
var backgroundC = container.appendChild(this.createCanvas("background"));
backgroundC.oncontextmenu = function() {
return false;
}
// The things that have been drawn and we already know the order of
// but have yet to be finalized
var publicC = container.appendChild(this.createCanvas("public"));
publicC.oncontextmenu = function() {
return false;
}
// This canvas is used to display parts of the background and public
// The use case is to display the previous frames in an animation
var frameC = container.appendChild(this.createCanvas("frames"));
frameC.oncontextmenu = function() {
return false;
}
// The things we drew but the server hasn't confirmed yet
var localC = container.appendChild(this.createCanvas("local"));
localC.oncontextmenu = function() {
return false;
}
// Canvas for things like cursor that should always be at the top
var effectC = container.appendChild(this.createCanvas("effect"));
effectC.oncontextmenu = function() {
return false;
}
var backgroundCtx = backgroundC.getContext("2d");
backgroundCtx.mozImageSmoothingEnabled = false;
backgroundCtx.webkitImageSmoothingEnabled = false;
backgroundCtx.msImageSmoothingEnabled = false;
backgroundCtx.imageSmoothingEnabled = false;
this.background = new TiledCanvas(backgroundC);
this.public = new TiledCanvas(publicC);
this.local = new TiledCanvas(localC);
this.public.requestUserChunk = function requestPublicUserChunk (cx, cy, callback) {
// We actually dont have background chunks, but we have to make sure
// the background canvas requests background images when we get
// drawings for that chunk so that no race condition happens when we
// finalize all the drawings
callback();
this.background.requestChunk(cx, cy);
}.bind(this);
this.public.beforeUnloadChunk = function beforeUnloadChunk (cx, cy) {
if((this.public.canBeUnloaded(cx, cy) || (this.public.chunks[cx] && this.public.chunks[cx][cy] == "empty")) &&
(this.background.canBeUnloaded(cx, cy) || (this.background.chunks[cx] && this.background.chunks[cx][cy] == "empty"))) {
console.log("Unloading chunk", cx, cy);
delete this.background.chunks[cx][cy];
delete this.public.chunks[cx][cy];
return true;
}
return false;
}.bind(this);
this.background.beforeUnloadChunk = this.public.beforeUnloadChunk;
this.effectsCanvas = effectC;
this.effectsCanvasCtx = effectC.getContext("2d");
effectC.addEventListener("touchstart", this.exectool.bind(this));
effectC.addEventListener("touchmove", this.exectool.bind(this));
effectC.addEventListener("touchend", this.exectool.bind(this));
effectC.addEventListener("pointerdown", this.exectool.bind(this));
effectC.addEventListener("pointermove", this.exectool.bind(this));
effectC.addEventListener("pointerup", this.exectool.bind(this));
effectC.addEventListener("pointerout", this.exectool.bind(this));
this.canvasArray = [backgroundC, publicC, frameC, localC, effectC];
// Used as the point where new canvasses should be added
// This way effectC stays on top
this.lastCanvas = localC;
// The paths are still being drawn, they are on top of everything else
this.pathCanvas = this.newCanvasOnTop("paths");
this.pathContext = this.pathCanvas.getContext("2d");
this.framesContext = frameC.getContext("2d");
};
Paint.prototype.addCoordDom = function addCoordDom (container) {
this.coordDiv = container.appendChild(document.createElement("div"));
this.coordDiv.className = "mouse-coords";
this.coordDiv.setAttribute("data-intro", "Here you can jump to any coordinates you would like to see. The random button brings you to a random location.");
this.coordDiv.appendChild(document.createTextNode("x:"));
var xInput = this.coordDiv.appendChild(document.createElement("input"));
this.coordDiv.appendChild(document.createTextNode("y:"));
var yInput = this.coordDiv.appendChild(document.createElement("input"));
xInput.type = "number";
yInput.type = "number";
xInput.min = -this.MAX_RANDOM_COORDS;
yInput.min = -this.MAX_RANDOM_COORDS;
xInput.max = this.MAX_RANDOM_COORDS;
yInput.max = this.MAX_RANDOM_COORDS;
xInput.addEventListener("input", function (event) {
this.goto(parseInt(event.target.value) - this.canvasArray[0].width / this.public.zoom / 2 || 0, this.public.leftTopY);
}.bind(this));
yInput.addEventListener("input", function (event) {
this.goto(this.public.leftTopX, parseInt(event.target.value) - this.canvasArray[0].height / this.public.zoom / 2 || 0);
}.bind(this));
var randomButton = this.coordDiv.appendChild(document.createElement("div"));
randomButton.className = "control-button random-button";
var randomButtonImage = randomButton.appendChild(document.createElement("img"));
randomButtonImage.src = "images/icons/randomlocation.png";
randomButtonImage.alt = "Jump to random location";
randomButtonImage.title = "Jump to random location";
randomButton.addEventListener("click", function () {
var maxCoords = this.MAX_RANDOM_COORDS;
this.goto(Math.random() * maxCoords * 2 - maxCoords, Math.random() * maxCoords * 2 - maxCoords);
}.bind(this));
};
Paint.prototype.setMouseCoords = function setMouseCoords (x, y) {
// Assume first input is x, second is y
var xSet = false;
for (var k = 0; k < this.coordDiv.children.length; k++) {
if (this.coordDiv.children[k].type == "number") {
this.coordDiv.children[k].value = xSet ? y.toFixed() : x.toFixed();
if (xSet) return;
xSet = true;
}
}
};
Paint.prototype.newCanvasOnTop = function newCanvasOnTop (name) {
var canvas = this.createCanvas(name || "foreign");
// Insert the canvas behind the current last canvas
this.lastCanvas.parentNode.insertBefore(canvas, this.lastCanvas.nextSibling);
// Put it as new canvas, put it in the canvasarray and return
this.lastCanvas = canvas;
this.canvasArray.push(canvas);
// Set the coords
canvas.leftTopX = this.public.leftTopX;
canvas.leftTopY = this.public.leftTopY;
// Invalidate canvas size
this.resize();
return canvas;
};
// Resets the paint (background, position, paths, ...)
Paint.prototype.clear = function clear () {
this.public.clearAll();
this.background.clearAll();
this.local.clearAll();
this.paths = {};
this.localUserPaths = [];
this.publicdrawings = [];
this.goto(0, 0);
};
Paint.prototype.goto = function goto (worldX, worldY) {
if (typeof worldX !== "number") console.warn("worldX in goto was not a number!");
if (typeof worldY !== "number") console.warn("worldY in goto was not a number!");
if (worldX !== worldX) console.warn("worldX was NaN");
if (worldY !== worldY) console.warn("worldY was NaN");
// Move both local and public tiledcanvas and set all canvas leftTopX/Y properties
this.background.goto(worldX, worldY);
this.local.goto(worldX, worldY);
this.public.goto(worldX, worldY);
for (var k = 0; k < this.canvasArray.length; k++) {
this.canvasArray[k].leftTopX = this.public.leftTopX;
this.canvasArray[k].leftTopY = this.public.leftTopY;
}
this.redrawPaths();
this.redrawFrames();
this.dispatchEvent({
type: "move",
leftTopX: worldX,
leftTopY: worldY
});
};
Paint.prototype.finalizeAll = function finalizeAll (amountToKeep) {
this.drawDrawings("background", this.publicdrawings.slice(0, this.publicdrawings.length - (amountToKeep || 0)));
this.publicdrawings.splice(0, this.publicdrawings.length - (amountToKeep || 0));
this.public.clearAll();
this.drawDrawings("public", this.publicdrawings);
};
Paint.prototype.createCanvas = function createCanvas (name) {
var canvas = document.createElement("canvas");
canvas.className = "paint-canvas paint-canvas-" + name;
return canvas;
};
// Invalidate the canvas size
Paint.prototype.resize = function resize () {
for (var cKey = 0; cKey < this.canvasArray.length; cKey++) {
this.canvasArray[cKey].width = this.canvasArray[cKey].offsetWidth;
this.canvasArray[cKey].height = this.canvasArray[cKey].offsetHeight;
}
this.public.reinitializeImageSmoothing();
this.background.reinitializeImageSmoothing();
this.local.reinitializeImageSmoothing();
this.redrawAll();
for (var k = 0; k < this.boundingBoxList.length; k++) {
this.boundingBoxList[k].boundingBoxCache = this.boundingBoxList[k].getBoundingClientRect();
}
};
Paint.prototype.keypress = function keypress (event) {
var key = event.keyCode || event.which;
if (event.target == document.body) {
//console.log("Keypress", event);
if (key == 99) {
//console.log("Pressed C, toggling color selector.");
$(this.controls.byName["tool-color"].input).spectrum("toggle");
}
if (key > 47 && key < 58) {
var number = key - 48;
this.setColor(tinycolor(this.current_color.toRgb()).setAlpha(number / 9));
}
if (key == 91 || key == 44 || key == 45 || key == 219
|| key == 186 || key == 96)
this.changeToolSize(--this.current_size, true);
if (key == 93 || key == 46 || key == 221
|| key == 187 || key == 43 || key == 61)
this.changeToolSize(++this.current_size, true);
//r
if (key == 114)
this.setRotation(this.rotation + 1);
//e
if (key == 101)
this.setRotation(this.rotation - 1);
if (key == 109)
this.setHorizontalMirror(this.scale[0] == 1);
if (key == 107)
this.setVerticalMirror(this.scale[1] == 1);
var toolShortcuts = {
98: "brush",
103: "grab",
108: "line",
112: "picker",
116: "text",
118: "picker",
122: "zoom"
};
if (toolShortcuts[key]) {
console.log("Switching tool to " + toolShortcuts[key]);
this.changeTool(toolShortcuts[key]);
}
}
};
Paint.prototype.keydown = function keydown (event) {
var key = event.keyCode || event.which;
if (event.target == document.body) {
//console.log("Keydown", event);
if (key == 27) {
this.setRotation(0);
this.setHorizontalMirror(false);
this.setVerticalMirror(false);
}
if (this.current_tool !== "grab" && key == 32) {
this.previous_tool = this.current_tool;
this.changeTool("grab");
}
if (this.current_tool !== "picker" && key == 18) {
this.previous_tool = this.current_tool;
this.changeTool("picker");
this.altPressed = true;
}
if (event.ctrlKey && event.keyCode == 90) {
this.undo();
event.preventDefault();
}
}
};
Paint.prototype.keyup = function keyup (event) {
var key = event.keyCode || event.which;
if (event.target == document.body) {
//console.log("Keyup", event);
if (this.current_tool == "grab" && key == 32 && this.previous_tool) {
this.changeTool(this.previous_tool);
}
if (this.current_tool == "picker" && key == 18 && this.previous_tool) {
this.changeTool(this.previous_tool);
this.altPressed = false;
}
}
};
Paint.prototype.wheel = function wheel (event) { // <---- new function
if (this.altPressed) {
//console.log("Wheel", event);
if (event.deltaY < 0){
//scrolling up
this.zoom(1.1);
}
if (event.deltaY > 0){
//scrolling down
this.zoom(1 / 1.1);
}
}
};
// From, to: [x, y]
// Returns a data url of the background + public layer
// Returns a canvas if returnCanvas is true
Paint.prototype.exportImage = function exportImage (from, to, returnCanvas) {
var canvas = document.createElement("canvas");
canvas.width = Math.abs(from[0] - to[0]);
canvas.height = Math.abs(from[1] - to[1]);
this.background.drawToCanvas(canvas, from, to);
this.public.drawToCanvas(canvas, from, to);
if (returnCanvas) return canvas;
return canvas.toDataURL();
};
Paint.prototype.redrawLocalDrawings = function redrawLocalDrawings () {
this.redrawLocals();
};
// Shedule for the paths to be redrawn in the next frame
Paint.prototype.redrawPaths = function redrawPaths () {
if (this.redrawPathsTimeout) return;
this.redrawPathsTimeout = requestAnimationFrame(this._redrawPaths.bind(this));
};
// Shedule for the frames to be redrawn in the next frame
Paint.prototype.redrawFrames = function redrawFrames () {
if (this.redrawFramesTimeout) return;
this.redrawFramesTimeout = requestAnimationFrame(this._redrawFrames.bind(this));
};
Paint.prototype._redrawFrames = function _redrawFrames () {
if (this._framesHaveBeenDrawn) {
this.framesContext.clearRect(0, 0, this.framesContext.canvas.width, this.framesContext.canvas.height);
this._framesHaveBeenDrawn = false;
}
delete this.redrawFramesTimeout;
for (var k = 0; k < this.frames.length; k++) {
this.drawFrame(this.frames[k], this.framesContext);
this._framesHaveBeenDrawn = true;
}
};
Paint.prototype.drawFrame = function drawFrame (frame, framesContext) {
// TODO: Optimization possibility: only draw frames that are in vision
if (frame.disabled) return;
var to = [frame.leftTop[0] + frame.width, frame.leftTop[1] + frame.height];
var frameCanvas = this.exportImage(frame.leftTop, to, true);
var relativeX = frame.leftTop[0] - this.public.leftTopX + frame.shift;
var relativeY = frame.leftTop[1] - this.public.leftTopY;
framesContext.globalAlpha = frame.opacity;
framesContext.drawImage(frameCanvas, relativeX * this.public.zoom, relativeY * this.public.zoom, frameCanvas.width * this.public.zoom, frameCanvas.height * this.public.zoom);
};
Paint.prototype._redrawPaths = function _redrawPaths () {
this.pathContext.clearRect(0, 0, this.pathContext.canvas.width, this.pathContext.canvas.height);
delete this.redrawPathsTimeout;
for (var pathId in this.paths) {
this.drawPath(this.paths[pathId]);
}
for (var pathId = 0; pathId < this.localUserPaths.length; pathId++) {
this.drawPath(this.localUserPaths[pathId]);
}
};
Paint.prototype.drawPathTiledCanvas = function drawPathTiledCanvas (path, ctx, tiledCanvas) {
var minX = path.points[0][0],
minY = path.points[0][1],
maxX = path.points[0][0],
maxY = path.points[0][1];
// Start on the first point
ctx.beginPath();
ctx.moveTo(path.points[0][0], path.points[0][1] + this.FIX_CANVAS_PIXEL_SIZE); // Might not be necessary
// Connect a line between all points
for (var pointId = 1; pointId < path.points.length; pointId++) {
ctx.lineTo(path.points[pointId][0], path.points[pointId][1] + this.FIX_CANVAS_PIXEL_SIZE); // Might not be necessary
minX = Math.min(path.points[pointId][0], minX);
minY = Math.min(path.points[pointId][1], minY);
maxX = Math.max(path.points[pointId][0], maxX);
maxY = Math.max(path.points[pointId][1], maxY);
}
ctx.strokeStyle = path.color.toRgbString();
ctx.lineWidth = path.size; // Might not be necessary
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.stroke();
tiledCanvas.drawingRegion(minX, minY, maxX, maxY, path.size);
tiledCanvas.execute();
if (tiledCanvas == this.public || tiledCanvas == this.background)
this.redrawFrames();
};
Paint.prototype.drawPath = function drawPath (path, ctx, tiledCanvas) {
var ctx = ctx || this.pathContext;
if (!path.points || !path.points[0]) return;
if (tiledCanvas) {
this.drawPathTiledCanvas(path, ctx, tiledCanvas);
return;
}
// Start on the first point
ctx.beginPath();
var x = path.points[0][0] - this.public.leftTopX,
y = path.points[0][1] - this.public.leftTopY;
ctx.moveTo(x * this.public.zoom, y * this.public.zoom + this.FIX_CANVAS_PIXEL_SIZE);
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
// Connect a line between all points
for (var pointId = 1; pointId < path.points.length; pointId++) {
var x = path.points[pointId][0] - this.public.leftTopX,
y = path.points[pointId][1] - this.public.leftTopY;
ctx.lineTo(x * this.public.zoom, y * this.public.zoom + this.FIX_CANVAS_PIXEL_SIZE);
if (x < minX) minX = x;
if (x > maxX) maxX = x;
}
if (path.color.type == "gradient") {
var lastX = path.points[path.points.length - 1][0];
var lastY = path.points[path.points.length - 1][1];
var gradient = ctx.createLinearGradient(minX, 0,
maxX, 0);
for (var k = 0; k < path.color.length; k++) {
gradient.addColorStop(path.color[k].pos, path.color[k].color);
}
ctx.strokeStyle = gradient;
} else {
path.color = tinycolor(path.color);
ctx.strokeStyle = path.color.toRgbString();
}
ctx.lineWidth = path.size * this.public.zoom;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.stroke();
};
Paint.prototype.redrawLocals = function redrawLocals (noclear) {
// Force the redrawing of locals in this frame
this.local.clearAll();
this.localDrawings.forEach(this.drawDrawing.bind(this, "local"));
this.local.redrawOnce();
}
Paint.prototype.removeLocalDrawing = function removeLocalDrawing (drawing) {
var index = this.localDrawings.indexOf(drawing);
this.localDrawings.splice(index, 1);
this.redrawLocalDrawings();
};
// From, to: [0, 0]
// frames: number of frames
Paint.prototype.addFrame = function addFrame (from, to, frames, opacity) {
var width = Math.abs(from[0] - to[0]);
this.frames.push({
leftTop: [Math.min(from[0], to[0]), Math.min(from[1], to[1])],
width: width,
height: Math.abs(from[1] - to[1]),
shift: width / frames,
opacity: opacity
});
this.redrawFrames();
};
Paint.prototype.addPublicDrawings = function addPublicDrawings (drawings) {
for (var k = 0; k < drawings.length; k++) this.addPublicDrawing(drawings[k]);
};
Paint.prototype.addPublicDrawing = function addPublicDrawing (drawing) {
this.publicdrawings.push(drawing);
this.drawDrawing("public", drawing);
this.redrawFrames();
};
Paint.prototype.undodrawings = function undodrawings (socketid, all) {
for (var k = this.publicdrawings.length - 1; k >= 0; k--) {
if (this.publicdrawings[k].id == socketid || this.publicdrawings[k].socketid == socketid) {
this.publicdrawings.splice(k, 1);
if (!all) break;
}
}
this.public.clearAll();
this.drawDrawings("public", this.publicdrawings);
this.redrawFrames();
};
Paint.prototype.undo = function undo () {
this.dispatchEvent({
type: "undo"
});
};
Paint.prototype.addPath = function addPath (id, props) {
this.paths[id] = props;
this.paths[id].points = this.paths[id].points || [];
this.redrawPaths();
this.redrawFrames();
};
Paint.prototype.addPathPoint = function addPathPoint (id, point) {
if (!this.paths[id]) {
console.error("Path ", id, " not known. Can't add point.");
return;
}
this.paths[id].points.push(point);
this.redrawPaths();
this.redrawFrames();
};
Paint.prototype.generateGrid = function generateGrid (leftTop, squares, sqwidth, sqheight, gutter) {
for (var k = 0; k < squares; k++) {
var localLeftTop = [leftTop[0] + k * sqwidth + k * gutter, leftTop[1]];
this.addUserPath();
this.addUserPathPoint(localLeftTop);
this.addUserPathPoint([localLeftTop[0] + sqwidth, localLeftTop[1]]);
this.addUserPathPoint([localLeftTop[0] + sqwidth, localLeftTop[1] + sqheight]);
this.addUserPathPoint([localLeftTop[0] , localLeftTop[1] + sqheight]);
this.addUserPathPoint(localLeftTop);
this.endUserPath();
}
};
Paint.prototype.previewGrid = function previewGrid (leftTop, squares, sqwidth, sqheight, gutter) {
var context = this.effectsCanvasCtx;
context.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
var x = (leftTop[0] - this.public.leftTopX) * this.public.zoom,
y = (leftTop[1] - this.public.leftTopY) * this.public.zoom;
context.setLineDash([]); // overwrite the selection tool line dash effect
for (var k = 0; k < squares; k++) {
var localLeftTop = [x + k * sqwidth * this.public.zoom + k * gutter * this.public.zoom, y];
context.beginPath();
context.rect(localLeftTop[0], localLeftTop[1], sqwidth * this.public.zoom, sqheight * this.public.zoom);
context.lineWidth = this.current_size * this.public.zoom;
context.strokeStyle = this.current_color.toRgbString();
context.stroke();
}
};
// Draw the given path on the public layer and remove it
Paint.prototype.finalizePath = function finalizePath (id) {
if (!this.paths[id]) {
return;
}
this.drawPath(this.paths[id], this.public.context, this.public);
this.publicdrawings.push(this.paths[id]);
this.removePath(id);
};
Paint.prototype.removePath = function removePath (id) {
delete this.paths[id];
this.redrawPaths();
};
// Remove the given point of the given path
// Returns true if removed, false if not
Paint.prototype.removePathPoint = function removePathPoint (id, point) {
for (var k = this.paths.points.length - 1; k >= 0; k++) {
if (this.paths.points[k] == point) {
this.paths.points.splice(k, 1);
this.redrawPaths();
return true;
}
}
return false;
};
// Function that should be called when a new drawing is added
// because of a user interaction. Calls the userdrawing event
Paint.prototype.addUserDrawing = function addUserDrawing (drawing) {
this.drawDrawing("local", drawing);
this.localDrawings.push(drawing);
this.dispatchEvent({
type: "userdrawing",
drawing: drawing,
removeDrawing: this.removeLocalDrawing.bind(this, drawing)
});
};
// Functions for the current user path (user path = path we are drawing)
Paint.prototype.addUserPath = function addUserPath () {
this.localUserPaths.push({
type: "path",
color: this.current_color,
size: this.current_size
});
this.dispatchEvent({
type: "startuserpath",
props: this.localUserPaths[this.localUserPaths.length - 1]
});
};
Paint.prototype.addUserPathPoint = function dispatchPathPoint (point) {
var lastPath = this.localUserPaths[this.localUserPaths.length - 1];
lastPath.points = lastPath.points || [];
lastPath.points.push(point);
this.dispatchEvent({
type: "userpathpoint",
point: point,
removePathPoint: this.removeUserPathPoint.bind(this, lastPath, point)
});
this.redrawPaths();
};
Paint.prototype.endUserPath = function endUserPath () {
var lastPath = this.localUserPaths[this.localUserPaths.length - 1];
if (typeof lastPath === 'undefined')
return;
this.dispatchEvent({
type: "enduserpath",
removePath: this.removeUserPath.bind(this, lastPath)
});
};
Paint.prototype.removeUserPathPoint = function removeUserPathPoint (path, point) {
for (var k = 0; k < path.points.length; k++) {
if (path.points[k] == point) {
path.points.splice(k, 1);
return;
}
}
};
Paint.prototype.removeUserPath = function removeUserPath (path, finalize, id) {
path.socketid = id;
this.publicdrawings.push(path);
for (var k = 0; k < this.localUserPaths.length; k++) {
if (this.localUserPaths[k] == path) {
if (finalize)
this.drawPath(path, this.public.context, this.public);
this.localUserPaths.splice(k, 1);
this.redrawPaths();
return true;
}
}
return false;
};
// Put the drawings on the given layer ('background', 'public', 'local', 'effects')
// This function forces a redraw after the drawings have been added
Paint.prototype.drawDrawings = function drawDrawings (layer, drawings) {
for (var dKey = 0; dKey < drawings.length; dKey++) {
if (typeof this.drawFunctions[drawings[dKey].type] == "function")
this.drawFunctions[drawings[dKey].type].call(this, this[layer].context, drawings[dKey], this[layer]);
else if (drawings[dKey].points)
this.drawFunctions.path.call(this, this[layer].context, drawings[dKey], this[layer]);
else
console.error("Unkown drawing", drawings[dKey]);
}
this[layer].redrawOnce();
};
// Put the drawing on the given layer ('background', 'public', 'local', 'effects')
// This function only redraws at the next browser drawframe
Paint.prototype.drawDrawing = function drawDrawing (layer, drawing) {
this.drawFunctions[drawing.type].call(this, this[layer].context, drawing, this[layer]);
this[layer].redrawOnce();
};
// User interaction on the canvas
Paint.prototype.exectool = function exectool (event) {
// Don't do the default stuff
if (event && typeof event.preventDefault == "function")
event.preventDefault();
// Don't use PointerEvent's touch system. it's not fully functional
if( event.pointerType == "touch" && event.__proto__.toString() == "[object PointerEvent]" )
return;
if (typeof this.tools[this.current_tool] == "function") {
if (event.button === 2 && event.altKey) { // right click
this.tools["change_size"](this, event);
}
else
this.tools[this.current_tool](this, event);
}
if (typeof event == "object") {
var coords = this.getCoords(event);
coords = this.scaledCoords(coords, event);
coords[0] = this.local.leftTopX + (coords[0] / this.local.zoom);
coords[1] = this.local.leftTopY + (coords[1] / this.local.zoom);
this.setMouseCoords(coords[0], coords[1]);
}
if (document.activeElement && document.activeElement !== this.textToolInput)
document.activeElement.blur();
};
Paint.prototype.changeTool = function changeTool (tool) {
this.exectool("remove");
this.current_tool = tool;
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
for (var name in this.controls.byName)
this.controls.byName[name].input.classList.remove("paint-selected-tool");
this.controls.byName[tool].input.classList.add("paint-selected-tool");
this.exectool("setup");
};
Paint.prototype._changeColor = function _changeColor (color) {
this.current_color = tinycolor(color);
this.currentColorMode = "color";
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
};
// Change gradient coming from the gradientcreator
Paint.prototype._changeGradient = function _changeGradient (event) {
this.current_color = event.stops;
this.current_color.type = "gradient";
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
};
Paint.prototype.changeToolSize = function changeToolSize (size, setinput) {
if (this.brushing) return;
if (size > this.settings.maxSize) size = this.settings.maxSize;
if (size <= 1) size = this.MIN_PATH_WIDTH;
if (size == 2.001) size = 2;
this.current_size = parseFloat(size);
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
if (setinput) {
this.controls.byName["tool-size"].input.value = size;
this.controls.byName["tool-size"].integerOutput.textContent = (size==this.MIN_PATH_WIDTH) ? '1' : size; // display 1 instead of min path size fraction
}
if (this.lastMovePoint) {
var context = this.effectsCanvasCtx;
context.beginPath();
context.arc(this.lastMovePoint[0], this.lastMovePoint[1], (this.current_size * this.local.zoom) / 2, 0, 2 * Math.PI, true);
context.fillStyle = this.current_color.toRgbString();
context.fill();
}
};
Paint.prototype.setColor = function setColor (color) {
if (this.brushing) return;
console.log(this.brushing);
this._changeColor(color);
$(this.controls.byName["tool-color"].input).spectrum("set", this.current_color);
};
Paint.prototype.createControlArray = function createControlArray () {
return [{
name: "grab",
type: "button",
image: "images/icons/grab.png",
title: "Change tool to grab",
value: "grab",
action: this.changeTool.bind(this),
data: {
intro: "You can use this tool to move around."
}
}, {
name: "line",
type: "button",
image: "images/icons/line.png",
title: "Change tool to line",
value: "line",
action: this.changeTool.bind(this),
data: {
intro: "With this tool you can make a line, the next one is a normal brush. You can also put text."
}
}, {
name: "brush",
type: "button",
image: "images/icons/brush.png",
title: "Change tool to brush",
value: "brush",
action: this.changeTool.bind(this)
}, {
name: "text",
type: "button",
image: "images/icons/text.png",
title: "Change tool to text",
value: "text",
action: this.changeTool.bind(this)
}, {
name: "picker",
type: "button",
image: "images/icons/picker.png",
title: "Change tool to picker",
value: "picker",
action: this.changeTool.bind(this),
data: {
intro: "Click on the canvas and your color will be changed to that value."
}
}, {
name: "zoom",
type: "button",
image: "images/icons/zoom.png",
title: "Change tool to zoom",
value: "zoom",
action: this.changeTool.bind(this),
data: {
intro: "Click and drag to zoom in to whatever is inside the box."
}
}, {
name: "select",
type: "button",
image: "images/icons/select.png",
title: "Change tool to select",
value: "select",
action: this.changeTool.bind(this),
data: {
intro: "Click and drag to select an area."
}
}, {
name: "undo",
type: "button",
image: "images/icons/undo.png",
title: "Undo drawing",
action: this.undo.bind(this),
data: {
intro: "Made a mistake? No worry just click here!"
}
}, /*{
name: "block",
type: "button",
image: "images/icons/block.png",
title: "Change tool to block",
value: "block",
action: this.changeTool.bind(this)
},*/ {
name: "tool-size",
type: "integer",
range: true,
text: "Tool size",
min: 1,
max: this.defaultSettings.maxSize,
value: 5,
title: "Change the size of the tool",
action: this.changeToolSize.bind(this),
data: {
intro: "This changes your brush, line and text size."
}
}, {
name: "zoom-in",
type: "button",
image: "images/icons/zoomin.png",
title: "Zoom in",
value: 1.2,
action: this.zoom.bind(this),
data: {
intro: "These buttons allow you to zoom in or out of the center. Respectivly zoom in, reset zoom and zoom out."
}
}, {
name: "zoom-reset",
type: "button",
image: "images/icons/zoomreset.png",
title: "Reset zoom",
value: 1,
action: this.zoomAbsolute.bind(this)
}, {
name: "zoom-out",
type: "button",
image: "images/icons/zoomout.png",
title: "Zoom out",
value: 1 / 1.2,
action: this.zoom.bind(this)
}, {
name: "tool-color",
type: "color",
text: "Tool color",
value: "#FFFFFF",
title: "Change the color of the tool",
action: this._changeColor.bind(this)
}/*, {
name: "gradient",
type: "gradient",
action: this._changeGradient.bind(this)
}*/];
};
Paint.prototype.zoom = function zoom (zoomFactor) {
this.zoomAbsolute(this.public.zoom * zoomFactor);
};
Paint.prototype.zoomToPoint = function zoomToPoint(zoomFactor, pointX, pointY){
if((zoomFactor>0.98)&&(zoomFactor<1.02)) zoomFactor=1
var currentMiddleX = this.public.leftTopX + this.canvasArray[0].width / this.public.zoom / 2;
var currentMiddleY = this.public.leftTopY + this.canvasArray[0].height / this.public.zoom / 2;
//currentMiddleX -= pointX / this.public.zoom;
//currentMiddleY -= pointY / this.public.zoom;
var newX = pointX / zoomFactor - this.canvasArray[0].width / zoomFactor / 2;
var newY = pointY / zoomFactor - this.canvasArray[0].height / zoomFactor / 2;
if(zoomFactor==1){
newX=Math.round(newX)
newY=Math.round(newY)
}
this.public.absoluteZoom(zoomFactor);
this.background.absoluteZoom(zoomFactor);
this.local.absoluteZoom(zoomFactor);
console.log(newX,newY);
this.goto(newX, newY);
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
this.redrawPaths();
this.redrawFrames();
}
Paint.prototype.zoomAbsolute = function zoomAbsolute (zoomFactor) {
if((zoomFactor>0.98)&&(zoomFactor<1.02)) zoomFactor=1
var currentMiddleX = this.public.leftTopX + this.canvasArray[0].width / this.public.zoom / 2;
var currentMiddleY = this.public.leftTopY + this.canvasArray[0].height / this.public.zoom / 2;
var newX = currentMiddleX - this.canvasArray[0].width / zoomFactor / 2;
var newY = currentMiddleY - this.canvasArray[0].height / zoomFactor / 2;
if(zoomFactor==1){
newX=Math.round(newX)
newY=Math.round(newY)
}
this.public.absoluteZoom(zoomFactor);
this.background.absoluteZoom(zoomFactor);
this.local.absoluteZoom(zoomFactor);
this.goto(newX, newY);
this.effectsCanvasCtx.clearRect(0, 0, this.effectsCanvas.width, this.effectsCanvas.height);
this.redrawPaths();
this.redrawFrames();
};
// Get the coordinates of the event relative to the upper left corner of the target element
Paint.prototype.getCoords = function getCoords (event) {
// If there is no clientX/Y (meaning no mouse event) and there are no changed touches
// meaning no touch event, then we can't get the coords relative to the target element
// for this event
if ((typeof event.clientX !== "number" && (!event.changedTouches || !event.changedTouches[0])) ||
(typeof event.clientY !== "number" && (!event.changedTouches || !event.changedTouches[0])))
return [0, 0];
// Return the coordinates relative to the target element
var clientX = (typeof event.clientX === 'number') ? event.clientX : event.changedTouches[0].clientX,
clientY = (typeof event.clientY === 'number') ? event.clientY : event.changedTouches[0].clientY,
target = event.target || document.elementFromPoint(clientX, clientY);
if (this.boundingBoxList.indexOf(target) == -1)
this.boundingBoxList.push(target);
target.boundingBoxCache = target.boundingBoxCache || target.getBoundingClientRect();
var relativeX = clientX - target.boundingBoxCache.left,
relativeY = clientY - target.boundingBoxCache.top;
return [relativeX, relativeY];
};
// TODO: Fix rotation and mirror
Paint.prototype.getColorAt = function getColorAt (point) {
for (var cKey = 0; cKey < this.canvasArray.length; cKey++) {
this.tempPixelCtx.drawImage(this.canvasArray[cKey], point[0], point[1], 1, 1, 0, 0, 1, 1);
}
var pixel = this.tempPixelCtx.getImageData(0, 0, 1, 1).data;
return tinycolor(this.rgbToHex(pixel[0], pixel[1], pixel[2]));
};
Paint.prototype.scaledCoords = function scaledCoords (point, event) {
var newPoint = [point[0], point[1]];
var target = event.target || document.elementFromPoint(point[0], point[1]);
if (this.rotation !== 0 || this.scale[0] !== 1 || this.scale[1] !== 1) {
newPoint[0] -= target.offsetWidth / 2;
newPoint[1] -= target.offsetHeight / 2;
newPoint[0] *= this.scale[0];
newPoint[1] *= this.scale[1];
var oldX = newPoint[0];
var cos = Math.cos(-this.rotation * Math.PI / 180);
var sin = Math.sin(-this.rotation * Math.PI / 180);
newPoint[0] = newPoint[0] * cos - newPoint[1] * sin;
newPoint[1] = oldX * sin + newPoint[1] * cos;
newPoint[0] += target.offsetWidth / 2;
newPoint[1] += target.offsetHeight / 2;
}
return newPoint;
};
Paint.prototype.rgbToHex = function rgbToHex (r, g, b) {
var hex = ((r << 16) | (g << 8) | b).toString(16);
return "#" + ("000000" + hex).slice(-6);
};
Paint.prototype.tempPixelCtx = document.createElement("canvas").getContext("2d");
// Tools, called on events
Paint.prototype.tools = {
zoom: function zoom (paint, event) {
if (event == "remove") {
delete paint.lastZoomPoint;
paint.effectsCanvas.style.cursor = "";
if (typeof paint.effectsCanvasCtx.setLineDash == "function")
paint.effectsCanvasCtx.setLineDash([]);
return;
}
paint.effectsCanvas.style.cursor = "zoom-in";
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
if ((event.type == "pointerdown" || event.type == "touchstart") && !paint.lastZoomPoint) {
paint.lastZoomPoint = scaledCoords;
paint.lastZoomPointAlt = scaledCoords;
}
if (event.type == "pointerup" || event.type == "touchend") {
// If mouseup is on the same point as mousedown we switch behaviour by making
// a box between two clicks instead of dragging the box around
delete paint.lastZoomPoint;
/*
if (paint.lastZoomPoint[0] == scaledCoords[0] && paint.lastZoomPoint[1] == scaledCoords[1]) {
return;
}
var x1 = Math.round(paint.local.leftTopX + (paint.lastZoomPoint[0] / paint.local.zoom));
var y1 = Math.round(paint.local.leftTopY + (paint.lastZoomPoint[1] / paint.local.zoom));
var x2 = Math.round(paint.local.leftTopX + (scaledCoords[0] / paint.local.zoom));
var y2 = Math.round(paint.local.leftTopY + (scaledCoords[1] / paint.local.zoom));
var minX = Math.min(x1, x2);
var minY = Math.min(y1, y2);
var width = Math.abs(x1 - x2);
var height = Math.abs(y1 - y2);
var zoom = Math.min(paint.canvasArray[0].width / width,
paint.canvasArray[1].height / height);
var extraWidth = (paint.canvasArray[0].width - zoom * width) / 2;
var extraHeight = (paint.canvasArray[1].height - zoom * height) / 2;
// Set the zoom to the least zoom that we require
paint.zoomAbsolute(zoom);
// Goto the top left corner
paint.goto(minX - extraWidth / zoom, minY - extraHeight / zoom);
delete paint.lastZoomPoint;
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
*/
}
if ((event.type == "pointermove" || event.type == "touchmove") && paint.lastZoomPoint) {
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
var x1 = scaledCoords[0];
var y1 = scaledCoords[1];
var x2 = paint.lastZoomPoint[0];
var y2 = paint.lastZoomPoint[1];
var x3 = paint.lastZoomPointAlt[0];
var y3 = paint.lastZoomPointAlt[1];
var minX = Math.min(x1, x2);
var minY = Math.min(y1, y2);
var width = x1 - x2;
var height = Math.abs(y1 - y2);
var context = paint.effectsCanvasCtx;
context.beginPath();
if (typeof context.setLineDash == "function")
context.setLineDash([6]);
context.rect(x2, y2, width, 1);
context.lineWidth = 3;
context.strokeStyle = "red";
context.stroke();
scale = x1 - x3;
zoomFactor = 1.1;
if(scale < 0) { // zoom out
paint.zoomAbsolute(paint.public.zoom * ( 1 / zoomFactor ));
} else if (scale > 0) {//zoom in
paint.zoomAbsolute(paint.public.zoom * ( zoomFactor ));
}
paint.lastZoomPointAlt = scaledCoords;
}
},
select: function select (paint, event) {
if (event == "remove") {
delete paint.lastSelectPoint;
paint.effectsCanvas.style.cursor = "";
if (typeof paint.effectsCanvasCtx.setLineDash == "function")
paint.effectsCanvasCtx.setLineDash([]);
return;
}
paint.effectsCanvas.style.cursor = "cell";
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
if ((event.type == "pointerdown" || event.type == "touchstart") && !paint.lastSelectPoint) {
paint.lastSelectPoint = scaledCoords;
}
if (event.type == "pointerup" || event.type == "touchend") {
// If mouseup is on the same point as mousedown we switch behaviour by making
// a box between two clicks instead of dragging the box around
if (paint.lastSelectPoint[0] == scaledCoords[0] && paint.lastSelectPoint[1] == scaledCoords[1]) {
return;
}
var x1 = Math.round(paint.local.leftTopX + (paint.lastSelectPoint[0] / paint.local.zoom));
var y1 = Math.round(paint.local.leftTopY + (paint.lastSelectPoint[1] / paint.local.zoom));
var x2 = Math.round(paint.local.leftTopX + (scaledCoords[0] / paint.local.zoom));
var y2 = Math.round(paint.local.leftTopY + (scaledCoords[1] / paint.local.zoom));
paint.dispatchEvent({
type: "select",
from: [x1, y1],
to: [x2, y2]
});
delete paint.lastSelectPoint;
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
}
if ((event.type == "pointermove" || event.type == "touchmove") && paint.lastSelectPoint) {
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
var x1 = scaledCoords[0];
var y1 = scaledCoords[1];
var x2 = paint.lastSelectPoint[0];
var y2 = paint.lastSelectPoint[1];
var minX = Math.min(x1, x2);
var minY = Math.min(y1, y2);
var width = Math.abs(x1 - x2);
var height = Math.abs(y1 - y2);
var context = paint.effectsCanvasCtx;
context.beginPath();
if (typeof context.setLineDash == "function")
context.setLineDash([4]);
context.rect(minX, minY, width, height);
context.lineWidth = 2;
context.strokeStyle = "darkgray";
context.stroke();
}
},
grab: function grab (paint, event) {
// Tool canceled or deselected
if (event == "remove" || event.type == "pointerup" || event.type == "touchend" || event.type === 'pointerout') {
delete paint.lastGrabCoords;
paint.effectsCanvas.style.cursor = "";
return;
}
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
// First time we grab?
if (!paint.lastGrabCoords) {
// If this is just a mousemove we are just moving
// our mouse without holding the button down
if (event.type == "pointerdown" || event.type == "touchstart") {
paint.lastGrabCoords = scaledCoords;
paint.effectsCanvas.style.cursor = "move";
}
}
if ((event.type == "pointermove" || event.type == "touchmove") && paint.lastGrabCoords) {
// How much should the drawings be moved
var relativeMotionX = paint.lastGrabCoords[0] - scaledCoords[0],
relativeMotionY = paint.lastGrabCoords[1] - scaledCoords[1];
paint.goto(paint.local.leftTopX + (relativeMotionX / paint.local.zoom), paint.local.leftTopY + (relativeMotionY / paint.local.zoom));
// Update last grab position
paint.lastGrabCoords = scaledCoords;
}
},
line: function line (paint, event) {
if (event == "remove") {
delete paint.lastLinePoint;
paint.effectsCanvas.style.cursor = "";
return;
}
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
if ((event.type == "pointerdown" || event.type == "touchstart") && !paint.lastLinePoint) {
paint.lastLinePoint = scaledCoords;
}
if (event.type == "pointerup" || event.type == "touchend") {
// If mouseup is on the same point as mousedown we switch behaviour by making
// a line between two clicks instead of dragging
if (paint.lastLinePoint[0] == scaledCoords[0] && paint.lastLinePoint[1] == scaledCoords[1]) {
return;
}
paint.addUserDrawing({
type: "line",
x: Math.round((paint.local.leftTopX + (paint.lastLinePoint[0] / paint.local.zoom)) * paint.PATH_PRECISION)/ paint.PATH_PRECISION,
y: Math.round((paint.local.leftTopY + (paint.lastLinePoint[1] / paint.local.zoom)) * paint.PATH_PRECISION) / paint.PATH_PRECISION,
x1: Math.round((paint.local.leftTopX + (scaledCoords[0] / paint.local.zoom)) * paint.PATH_PRECISION) / paint.PATH_PRECISION,
y1: Math.round((paint.local.leftTopY + (scaledCoords[1] / paint.local.zoom)) * paint.PATH_PRECISION) / paint.PATH_PRECISION,
size: paint.current_size,
color: paint.current_color
});
delete paint.lastLinePoint;
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
}
if ((event.type == "pointermove" || event.type == "touchmove") && paint.lastLinePoint) {
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
// TODO refactor this to use drawFunctions
var context = paint.effectsCanvasCtx;
context.beginPath();
context.arc(paint.lastLinePoint[0], paint.lastLinePoint[1], (paint.current_size * paint.local.zoom) / 2, 0, 2 * Math.PI, true);
context.fillStyle = paint.current_color.toRgbString();
context.fill();
context.beginPath();
context.moveTo(paint.lastLinePoint[0], paint.lastLinePoint[1]);
context.lineTo(scaledCoords[0], scaledCoords[1]);
context.strokeStyle = paint.current_color.toRgbString();
context.lineWidth = paint.current_size * paint.local.zoom ;
context.stroke();
context.beginPath();
context.arc(scaledCoords[0], scaledCoords[1], (paint.current_size * paint.local.zoom) / 2, 0, 2 * Math.PI, true);
context.fillStyle = paint.current_color.toRgbString();
context.fill();
}
},
brush: function brush (paint, event, type) {
//console.log(event, event.pointerType, event.x, event.y);
if (event == "remove") {
delete paint.lastMovePoint;
delete paint.lockcolor;
delete paint.brushing;
return;
}
paint.lastMovePoint = paint.lastMovePoint || [0, 0];
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
if (event.type == "pointerdown" || event.type == "touchstart") {
paint.brushing = true;
paint.addUserPath();
// Clear the previous mouse dot
paint.effectsCanvasCtx.clearRect(paint.lastMovePoint[0] - paint.current_size * paint.local.zoom * 2, paint.lastMovePoint[1] - paint.current_size * paint.local.zoom * 2, paint.current_size * paint.local.zoom * 4, paint.current_size * paint.local.zoom * 4);
//chrome bug hotfix
paint.lastPointerDownType = event.pointerType;
// so we dont mix pointer types
// recreate case: enable windows ink
// 1. move mouse to left side of canvas
// 2. move pen to right side of canvas
// 3. move mouse again and it will jump to left side where it was left
// bug:
// 1. everytime pointerdown is fired with pointerType == "pen"
// the proceeding pointermove is always pointerType == "mouse"
// 2. this causes a sudden jolting line to the position where the mouse was last moved
// and where the pen currently is.
}
if ( event.type == "pointerup" || event.type == "pointerout" || event.type == "touchend") {
paint.endUserPath();
paint.brushing = false;
//delete paint.lastPointerDownType;
//console.log("endpathing");
}
if (event.type == "pointermove" || event.type == "touchmove") {
// If we are brushing we don't need to draw a preview
if (!this.brushing) {
// Clear the previous mouse dot
paint.effectsCanvasCtx.clearRect(paint.lastMovePoint[0] - paint.current_size * paint.local.zoom * 2, paint.lastMovePoint[1] - paint.current_size * paint.local.zoom * 2, paint.current_size * paint.local.zoom * 4, paint.current_size * paint.local.zoom * 4);
// Draw the current mouse position
var context = paint.effectsCanvasCtx;
context.beginPath();
context.arc(scaledCoords[0], scaledCoords[1], (paint.current_size * paint.local.zoom) / 2, 0, 2 * Math.PI, true);
if (paint.current_color.type == "gradient") {
if (!paint.current_color[0]) {
context.fillStyle = "black";
} else {
context.fillStyle = paint.current_color[0].color.toRgbString();
}
} else {
context.fillStyle = paint.current_color.toRgbString();
}
context.fill();
// Save the last move point for efficient clearing
paint.lastMovePoint[0] = scaledCoords[0];
paint.lastMovePoint[1] = scaledCoords[1];
}
// If the last brush point is set we are currently drawing
if (paint.brushing && paint.lastPointerDownType == event.pointerType) {
paint.addUserPathPoint([Math.round((paint.local.leftTopX + (scaledCoords[0] / paint.local.zoom)) * paint.PATH_PRECISION) / paint.PATH_PRECISION,
Math.round((paint.local.leftTopY + (scaledCoords[1] / paint.local.zoom)) * paint.PATH_PRECISION) / paint.PATH_PRECISION]);
}
}
},
picker: function picker (paint, event) {
if (event == "remove") {
delete paint.picking;
paint.effectsCanvas.style.cursor = "";
return;
}
if (event.button === 2){//right click
return;
}
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
if ((event.type == "pointerdown" || event.type == "touchstart") && !paint.picking) {
paint.picking = true;
paint.setColor(paint.getColorAt(targetCoords).setAlpha(paint.current_color.getAlpha()));
paint.effectsCanvas.style.cursor = "crosshair";
}
if (event.type == "pointerup" || event.type == "touchend") {
delete paint.picking;
paint.effectsCanvas.style.cursor = "";
}
if (event.type == "pointermove" || event.type == "touchmove") {
if (paint.picking)
paint.setColor(paint.getColorAt(targetCoords).setAlpha(paint.current_color.getAlpha()));
}
},
block: function block (paint, event) {
this.brush(paint, event, "block");
},
text: function text (paint, event) {
if (event == "remove") {
// Remove lastmove data
delete paint.lastMovePoint;
delete paint.lastToolText;
// Remove the text tool from dom and paint object
paint.textToolInput && paint.container.removeChild(paint.textToolInput);
delete paint.textToolInput;
return;
}
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
// Create an input for the text if one doesn't exist
if (!paint.textToolInput) {
paint.textToolInput = document.createElement("input");
paint.textToolInput.className = "paint-texttool";
paint.textToolInput.placeholder = "Type some text";
paint.container.appendChild(paint.textToolInput);
paint.textToolInput.addEventListener("input", function () {
this.exectool("redraw");
}.bind(paint));
}
paint.textToolInput.focus();
if ((event.type == "pointerup" || event.type == "touchend") && paint.textToolInput.value) {
paint.addUserDrawing({
type: "text",
text: paint.textToolInput.value.slice(0, 256) || "",
x: Math.round(paint.local.leftTopX + (scaledCoords[0] / paint.local.zoom)),
y: Math.round(paint.local.leftTopY + (scaledCoords[1] / paint.local.zoom)),
size: paint.current_size,
color: paint.current_color
});
paint.textToolInput.value = "";
}
if (event.type == "pointermove" || event.type == "touchmove") {
paint.lastMovePoint = paint.lastMovePoint || [0, 0];
paint.effectsCanvasCtx.font = paint.current_size * paint.local.zoom + "px Verdana, Geneva, sans-serif";
// Remove the old text and draw the new one (use half height margin)
paint.effectsCanvasCtx.clearRect(paint.lastMovePoint[0],
paint.lastMovePoint[1] - (paint.current_size * paint.local.zoom * 1.5),
paint.effectsCanvasCtx.measureText(paint.lastToolText).width,
paint.current_size * paint.local.zoom * 2);
paint.effectsCanvasCtx.fillStyle = paint.current_color.toRgbString();
paint.effectsCanvasCtx.fillText(paint.textToolInput.value.slice(0, 256), scaledCoords[0], scaledCoords[1]);
paint.lastToolText = paint.textToolInput.value.slice(0, 256);
paint.lastMovePoint = scaledCoords;
}
if (event == "redraw") {
paint.effectsCanvasCtx.font = paint.current_size * paint.local.zoom + "px Verdana, Geneva, sans-serif";
// Remove the old text and draw the new one (use half height margin)
paint.effectsCanvasCtx.clearRect(paint.lastMovePoint[0],
paint.lastMovePoint[1] - (paint.current_size * paint.local.zoom * 1.5),
paint.effectsCanvasCtx.measureText(paint.lastToolText).width,
paint.current_size * paint.local.zoom * 2);
paint.effectsCanvasCtx.fillStyle = paint.current_color.toRgbString();
paint.effectsCanvasCtx.fillText(paint.textToolInput.value.slice(0, 256), paint.lastMovePoint[0], paint.lastMovePoint[1]);
paint.lastToolText = paint.textToolInput.value.slice(0, 256);
}
},
change_size: function change_size (paint, event) {
// Get the coordinates relative to the canvas
var targetCoords = paint.getCoords(event);
var scaledCoords = paint.scaledCoords(targetCoords, event);
if ((event.type == "pointerdown" || event.type == "touchstart") && !paint.lastChangeSizePoint) {
paint.lastChangeSizePoint = scaledCoords;
paint.lastChangeSizePointAlt = scaledCoords;
//console.log("down");
}
if (event.type == "pointerup" || event.type == "touchend") {
delete paint.lastChangeSizePoint;
}
if ((event.type == "pointermove" || event.type == "touchmove") && paint.lastChangeSizePoint) {
var x1 = scaledCoords[0];
var y1 = scaledCoords[1];
var x3 = paint.lastChangeSizePointAlt[0];
var y3 = paint.lastChangeSizePointAlt[1];
var delta = x1 - x3;
if (delta < 0) { // mouse move left
paint.changeToolSize(--paint.current_size, true);
} else if (delta > 0) {
paint.changeToolSize(++paint.current_size, true);
}
paint.lastChangeSizePointAlt = scaledCoords;
// Clear the previous mouse dot
paint.effectsCanvasCtx.clearRect(0, 0, paint.effectsCanvas.width, paint.effectsCanvas.height);
// Draw the current mouse position
var context = paint.effectsCanvasCtx;
context.beginPath();
context.arc(paint.lastChangeSizePoint[0], paint.lastChangeSizePoint[1], (paint.current_size * paint.local.zoom) / 2, 0, 2 * Math.PI, true);
if (paint.current_color.type == "gradient") {
if (!paint.current_color[0]) {
context.fillStyle = "black";
} else {
context.fillStyle = paint.current_color[0].color.toRgbString();
}
} else {
context.fillStyle = paint.current_color.toRgbString();
}
context.fill();
}
}
};
// Drawfunctions
// this = current paint
Paint.prototype.drawFunctions = {
brush: function (context, drawing, tiledCanvas) {
context.beginPath();
context.arc(drawing.x, drawing.y, drawing.size, 0, 2 * Math.PI, true);
context.fillStyle = drawing.color.toRgbString();
context.fill();
if (tiledCanvas) {
tiledCanvas.drawingRegion(drawing.x, drawing.y, drawing.x, drawing.y, drawing.size);
tiledCanvas.executeNoRedraw();
}
},
block: function (context, drawing, tiledCanvas) {
context.fillStyle = drawing.color.toRgbString();
context.fillRect(drawing.x, drawing.y, drawing.size, drawing.size);
if (tiledCanvas) {
tiledCanvas.drawingRegion(drawing.x, drawing.y, drawing.x, drawing.y, drawing.size);
tiledCanvas.executeNoRedraw();
}
},
line: function (context, drawing, tiledCanvas) {
context.beginPath();
context.moveTo(drawing.x, drawing.y + this.FIX_CANVAS_PIXEL_SIZE);
context.lineTo(drawing.x1, drawing.y1 + this.FIX_CANVAS_PIXEL_SIZE);
context.strokeStyle = drawing.color.toRgbString();
context.lineWidth = drawing.size;
context.lineCap = "round";
context.stroke();
if (tiledCanvas) {
tiledCanvas.drawingRegion(drawing.x, drawing.y, drawing.x1, drawing.y1, drawing.size);
tiledCanvas.executeNoRedraw();
}
},
path: function (context, drawing, tiledCanvas) {
this.drawPath(drawing, context, tiledCanvas);
},
text: function (context, drawing, tiledCanvas) {
context.font = drawing.size + "px Verdana, Geneva, sans-serif";
context.fillStyle = drawing.color.toRgbString();
context.fillText(drawing.text, drawing.x, drawing.y);
if (tiledCanvas) {
// Context can't be used because it's a tiledCanvas context
// and that doesnt have a meastureText function that actually returns
// valid data, so we need to create a hidden context
var hiddenContext = document.createElement("canvas").getContext("2d");
hiddenContext.font = drawing.size + "pt Verdana, Geneva, sans-serif";
var textWidth = hiddenContext.measureText(drawing.text).width;
tiledCanvas.drawingRegion(drawing.x, drawing.y - drawing.size, drawing.x + textWidth, drawing.y, drawing.size);
tiledCanvas.executeNoRedraw();
}
}
};
Paint.prototype.utils = {
copy: function (object) {
// Returns a deep copy of the object
var copied_object = {};
for (var key in object) {
if (typeof object[key] == "object") {
copied_object[key] = this.copy(object[key]);
} else {
copied_object[key] = object[key];
}
}
return copied_object;
},
merge: function (targetobject, object) {
// All undefined keys from targetobject will be filled
// by those of object (goes deep)
if (typeof targetobject != "object") {
targetobject = {};
}
for (var key in object) {
if (typeof object[key] == "object") {
targetobject[key] = this.merge(targetobject[key], object[key]);
} else if (typeof targetobject[key] == "undefined") {
targetobject[key] = object[key];
}
}
return targetobject;
},
sqDistance: function sqDistance (point1, point2) {
var xDist = point1[0] - point2[0];
var yDist = point1[1] - point2[1];
return xDist * xDist + yDist * yDist;
}
};
/**
* Event dispatcher
* License mit
* https://github.com/mrdoob/eventdispatcher.js
* @author mrdoob / http://mrdoob.com/
*/
var EventDispatcher = function () {}
EventDispatcher.prototype = {
constructor: EventDispatcher,
apply: function ( object ) {
object.addEventListener = EventDispatcher.prototype.addEventListener;
object.hasEventListener = EventDispatcher.prototype.hasEventListener;
object.removeEventListener = EventDispatcher.prototype.removeEventListener;
object.dispatchEvent = EventDispatcher.prototype.dispatchEvent;
},
addEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) this._listeners = {};
var listeners = this._listeners;
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
},
hasEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) return false;
var listeners = this._listeners;
if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
return true;
}
return false;
},
removeEventListener: function ( type, listener ) {
if ( this._listeners === undefined ) return;
var listeners = this._listeners;
var listenerArray = listeners[ type ];
if ( listenerArray !== undefined ) {
var index = listenerArray.indexOf( listener );
if ( index !== - 1 ) {
listenerArray.splice( index, 1 );
}
}
},
dispatchEvent: function ( event ) {
if ( this._listeners === undefined ) return;
var listeners = this._listeners;
var listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
var array = [];
var length = listenerArray.length;
for ( var i = 0; i < length; i ++ ) {
array[ i ] = listenerArray[ i ];
}
for ( var i = 0; i < length; i ++ ) {
array[ i ].call( this, event );
}
}
}
};
EventDispatcher.prototype.apply(Paint.prototype);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map'
//npm i --save react-sparklines@1.6.0
class WeatherList extends Component {
renderWeather(cityData){
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressure = cityData.list.map(weather => weather.main.pressure);
const humidity = cityData.list.map(weather => weather.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key = {name}>
<td><GoogleMap lon={lon} lat={lat} /> </td>
<td><Chart data={temps} color="orange" units="°C" /></td>
<td><Chart data={pressure} color="green" units="hPa" /></td>
<td><Chart data={humidity} color="black" units= "%" /></td>
</tr>
)
}
render () {
return (
<table className = "table table-hover">
<thead>
<tr>
<th> City </th>
<th> Temperature (°C) </th>
<th> Pressure (hPa) </th>
<th> Humidity (%) </th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
)};
}
function mapStateToProps (state){
return { weather: state.weather};
}
export default connect (mapStateToProps)(WeatherList);
|
/**
* A set of functions that can be deployed to transcribe audio files to speech
*
* Note: these examples are overly verbose for demonstration purposes.
* A real application should not use console.log this liberally.
*/
'use strict';
const storage = require('@google-cloud/storage');
const speech = require('@google-cloud/speech')();
const datastore = require('@google-cloud/datastore')();
const translate = require('@google-cloud/translate')();
/**
* Handles changes to a cloud storage bucket item.
*
* @param {object} event The event that triggered this function
* @returns {Promise}
*/
exports.storageHandler = (event) => {
const obj = event.data;
console.log('Handling event for object:', obj);
if (obj.resourceState === 'not_exists') {
console.log('Object has been deleted, nothing to do:', obj.name);
return Promise.resolve();
}
if (!obj.bucket) {
throw new Error('Bucket is missing from event data');
}
if (!obj.name) {
throw new Error('Object name is missing from event data');
}
const uri = 'gs://' + obj.bucket + '/' + obj.name;
const meta = obj.metadata || {};
// Use object metadata to specify language and audio encoding parameters
// Note: gsutil often removes camelCase from meta parameters during upload
// so check languageCode and languagecode
const language = meta.languageCode || meta.languagecode || obj.contentLanguage || 'en-US';
const sampleRate = parseInt(meta.sampleRateHertz || meta.sampleratehertz || '16000');
const encoding = meta.encoding || 'LINEAR16';
const params = {
encoding: encoding,
languageCode: language,
sampleRateHertz: sampleRate
};
return processStorageObject(uri, params)
.then((transcript) => {
console.log('Transcript:', transcript);
const newLanguage = 'es';
return translate.translate(transcript, newLanguage)
.then((translation) => {
console.log('Translation: ', translation);
const key = datastore.key('transcript');
const record = {
key: key,
data: {
transcript: transcript,
translation: translation,
ts: Date.now()
}
};
return datastore.save(record)
.then(() => {
console.log('Saved record:', record);
});
});
})
.catch((err) => {
console.error('Caught an error:', err);
});
};
/**
* Given an uri for an object in Cloud Storage, and any known parameters, invoke
* the Cloud Speech API and transcribe the audio.
*
* @param {string} uri The URI of object in Cloud Storage; e.g. gs://bucket/name
* @param {object} params A set of parameters to use when trying to transcribe audio.
* @returns {Promise} A promise that encapsulates the transcribed audio
*/
function processStorageObject(uri, params) {
console.log('Handling storage bucket object, uri:', uri, 'with params:', params);
const apiParams = Object.create(params);
apiParams.verbose = true;
apiParams.maxAlternatives = 1;
return speech.startRecognition(uri, apiParams)
.then((data) => {
console.log('Start recognition returned:', data);
const operation = data[0];
// Return a promise to get the results when complete
return operation.promise();
})
.then((data) => {
console.log('Operation has finished:', data);
return data[0]
.map((result) => {
console.log('Confidence:', result.confidence, ', Transcript:', result.transcript);
return result.transcript;
})
.reduce((accumulator, element) => '' + accumulator + element, '');
});
};
|
/**
* @function spawnProcess
*/
'use strict'
const childProcess = require('child_process')
/** @lends spawnProcess */
async function spawnProcess (bin, args, options = {}) {
const {
suppressOut = false
} = options
return new Promise((resolve, reject) => {
const spawned = childProcess.spawn(bin, args, options)
if (!suppressOut) {
spawned.stdout.pipe(process.stdout)
spawned.stderr.pipe(process.stderr)
}
spawned.on('exit', function (exitCode) {
let err = exitCode === 0 ? null : new Error(`Exit with code: ${exitCode}`)
err ? reject(err) : resolve()
})
return spawned
})
}
module.exports = spawnProcess
|
"use strict";
var path = require('path'),
exec = require('child_process').exec;
module.exports = function (grunt) {
grunt.registerTask('data-download', '1. Download data from iana.org/time-zones.', function (version) {
version = version || 'latest';
var done = this.async(),
src = 'ftp://ftp.iana.org/tz/tzdata-latest.tar.gz',
curl = path.resolve('temp/curl', version, 'data.tar.gz'),
dest = path.resolve('temp/download', version);
if (version !== 'latest') {
src = 'http://www.iana.org/time-zones/repository/releases/tzdata' + version + '.tar.gz';
}
grunt.file.mkdir(path.dirname(curl));
grunt.file.mkdir(dest);
grunt.log.ok('Downloading ' + src);
exec('curl ' + src + ' -o ' + curl + ' && cd ' + dest + ' && gzip -dc ' + curl + ' | tar -xf -', function (err) {
if (err) { throw err; }
grunt.log.ok('Downloaded ' + src);
done();
});
});
};
|
'use strict'
function createLoggerKeyword (opts) {
const { provider, seller, path } = opts
let keyword = `${provider}_${seller}`
if (path) keyword += `_${path}`
return keyword
}
module.exports = createLoggerKeyword
|
Oshinko.when( /^I empty the text field "([^\"]+)"$/ , function (window, captures) {
Oshinko.target.delay(1);
var field = UIQuery.firstKindWithName("textFields", captures[0]);
field.setValue("");
// tap somewhere to "end editing"
window.tap();
});
|
export default {
prefix: false,
/**
* 短信发送驱动
*/
drivers: {
test: {
label: 'Test',
type: 'alaska-sms-test'
}
},
/**
* 短信签名,例如 【脉冲软件】
*/
sign: ''
};
|
const initialState = [
{
id: '1',
title: 'ReactJS for dummies',
description: 'Great book to start learning React.',
count: 2,
},
{
id: '2',
title: 'JavaScript to the rescue',
description: 'Want to know more advanced stuff about JS, must read ;)!',
count: 3,
},
{
id: '3',
title: 'NodeJS for the win',
description: 'Everything about NodeJS.',
count: 4,
},
];
const books = (state = {
items: initialState,
}, action) => {
switch (action.type) {
case 'ADD_COUNT': {
const newItems = state.items.map(item => {
let newCount = item.count;
if (item.id === action.item.id) {
newCount++;
}
return Object.assign(item, { count: newCount });
});
return Object.assign({}, state.items, {
items: newItems,
});
}
default:
return state;
}
};
export default { books };
|
const _ = require('underscore');
const DrawCard = require('../../../drawcard.js');
class OldWyk extends DrawCard {
setupCardAbilities() {
this.reaction({
when: {
onChallenge: (event, challenge) => (
challenge.attackingPlayer === this.controller &&
challenge.challengeType === 'power' &&
!this.kneeled
)
},
handler: () => {
this.controller.kneelCard(this);
var card = _.last(this.controller.deadPile.filter(c => c.hasTrait('Drowned God')));
if(!card) {
this.game.addMessage('{0} finds no character in their dead pile to put into play with {1}', this.controller, this);
return;
}
this.controller.playCard(card, true, true);
this.game.currentChallenge.addAttacker(card);
this.game.addMessage('{0} uses {1} to put into play {2} as an attacker from their dead pile', this.controller, this, card);
this.untilEndOfChallenge(ability => ({
match: card,
effect: ability.effects.returnToHandOrDeckBottom()
}));
}
});
}
}
OldWyk.code = '05028';
module.exports = OldWyk;
|
/**
* Created by jtun02 on 15/4/22.
*/
var Q = (function() {
var qs = (location.search.length > 0 ? decodeURIComponent(location.search.substring(1)) : '');
var args = {};
var items = qs.split('&');
var item = null,
key = null,
value = null;
for (var i = 0; i < items.length; i ++) {
item = items[i].split('=');
key = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
args[key] = value;
}
return args;
})();
//常用
var commons = {
//正则
Regexp : {},
//实用方法 Practical Method
PraMethod: {},
TempMethod: {}
};
//手机号码正则表达式
commons.Regexp.mRep = /^0?(13[0-9]|15[0123456789]|17[0-9]|18[0123456789]|14[57])[0-9]{8}$/;
commons.Regexp.eRep = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
commons.Regexp.ticket = /^[1-9]\d*$/;
//分页
commons.PraMethod.pagination = function(arr, count) {
var result = [];
var i;
var len = arr.length;
var num = Math.ceil(len / count);
for(i = 0; i < num; i++)
{
var child = [];
var next = i +1;
if(next*count < len)
{
child = arr.slice(i*count,next*count);
}
else
{
child = arr.slice(i*count,arr.length);
}
result.push(child);
if(child.length == 0)
{
break;
}
}
return result;
};
//函数
commons.PraMethod.isFunction = function(callback) {
if (Object.prototype.toString.call(callback).slice(8, -1) == 'Function') {
return true;
}
return false;
};
//微信浏览器
commons.PraMethod.isWeichatBro = function() {
var device = navigator.userAgent.toLowerCase();
if (/mobile/.test(device) && /micromessenger/.test(device)) {
return true;
}
return false;
};
//移动浏览器
commons.PraMethod.isMobileBro = function () {
var device = navigator.userAgent.toLowerCase();
if (device.indexOf('mobile') === -1) {
return false;
}
return true;
};
//分享到微博
/**
*
* @param sns : sina or tencent
* @param para {title:String(分享title), desc:String(分享内容), url:String(分享地址), pic:String(图片地址)}
* @constructor
*/
commons.PraMethod.shareToWeibo = function(sns, para) {
var _pre = sns == 'sina' ?
'http://v.t.sina.com.cn/share/share.php?searchPic=false&' :
'http://v.t.qq.com/share/share.php?';
var link = _pre + 'title=' +
_e(para.title) +
_e(para.desc) +
'&url=' + _e(para.url) +
(sns == 'sina' ?
'&content=utf-8&sourceUrl=' + _e(para.url) + '&pic=' + _e(para.picurl) :
'&pic=' + _e(para.picurl));
window.open(link, 'newwindow','height=400,width=400,top=100,left=100');
function _e(t) {
return encodeURIComponent(t)
}
};
//浏览器种类
commons.PraMethod.transitionEvent = function() {
var t;
var el = document.createElement('fakeelement');
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
};
var animations = {
'animation':'animationend',
'OAnimation':'oAnimationEnd',
'MozAnimation':'animationend',
'WebkitAnimation':'webkitAnimationEnd'
};
var e = {};
for(t in transitions){
if( el.style[t] !== undefined ){
e.tr = transitions[t];
}
}
for(t in animations) {
if (el.style[t] !== undefined) {
e.ani = animations[t];
}
}
return e;
};
//local storage
commons.PraMethod.localStorage = function(key, obj) {
var l = window.localStorage;
if (typeof key != 'string') {
throw new Error('wrong key !!!');
}
if (obj !== undefined && obj !== null) {
l.removeItem(key);
if (obj === true) {
return;
}
if (typeof obj != 'object') {
l.setItem(key, obj);
} else {
l.setItem(key, JSON.stringify(obj));
}
}
else {
var ls = undefined;
try {
ls = JSON.parse(l.getItem(key));
} catch (err) {
ls = l.getItem(key);
}
return ls;
}
};
/**
*
* @param range :jquery|zepto
* @param onloading :function
* @param onfinishload :function
* @constructor
*/
//页面加载loading
commons.PraMethod.ImgLoader = function(range, onloading, onfinishload) {
this.total = 0;
this.imgs = [];
this.current = 0;
this.range = range || $('body');
this.onloading = onloading;
this.onfinishload = onfinishload;
};
commons.PraMethod.ImgLoader.prototype.init = function() {
var self = this;
function imgload() {
if (self.current == self.total) {
typeof self.onfinishload == 'function' && self.onfinishload();
return;
}
if (self.current > self.total) return;
typeof self.onloading == 'function' && self.onloading(self.current, self.total);
}
self.range.find('img').each(function() {
var i = new Image();
i.src = $(this).attr('src');
if (/(.jpg|.png|.gif)/gi.test(i.src)) {
self.imgs.push(i);
}
});
self.total = self.imgs.length;
self.imgs.forEach(function(item, index, array) {
if (item.complete) {
self.current += 1;
imgload();
}
else {
item.onload = function(e) {
self.current += 1;
imgload();
};
item.onerror = function() {
self.current += 1;
imgload();
throw new Error(item.src + ' was not found');
};
}
});
};
//身份证号验证
commons.PraMethod.IDvf = function(_n) {
var _nx = ('7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2').split('-');
var _an = _n.split('');
var _vf = ('1-0-X-9-8-7-6-5-4-3-2').split('-');
var _sum = 0;
var _r = /^(\d{17}(\d|X|x))$/;
if (_n.length != 18) {
return false;
}
if (!_r.test(_n)) {
return false;
}
for (var i = 0; i < _nx.length; i++) {
_sum += _nx[i]*_an[i];
}
if (_an[17].toUpperCase() == _vf[_sum%11]) {
return true;
}
return false;
};
//base64
commons.PraMethod.base64 = (function() {
var base64 = {};
base64.map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
base64.decode = function(s){
s += '';
var len = s.length;
if((len === 0) || (len % 4 !== 0)){
return s;
}
var pads = 0;
if(s.charAt(len - 1) === base64.map[64]){
pads++;
if(s.charAt(len - 2) === base64.map[64]){
pads++;
}
len -= 4;
}
var i, b, map = base64.map, x = [];
for(i = 0; i < len; i += 4){
b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i + 1)) << 12) | (map.indexOf(s.charAt(i + 2)) << 6) | map.indexOf(s.charAt(i + 3));
x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff, b & 0xff));
}
switch(pads){
case 1:
b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12) | (map.indexOf(s.charAt(i)) << 6);
x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff));
break;
case 2:
b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12);
x.push(String.fromCharCode(b >> 16));
break;
}
return unescape(x.join(''));
};
base64.encode = function(s){
if(!s){
return;
}
s += '';
if(s.length === 0){
return s;
}
s = escape(s);
var i, b, x = [], map = base64.map, padchar = map[64];
var len = s.length - s.length % 3;
for(i = 0; i < len; i += 3){
b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i+1) << 8) | s.charCodeAt(i+2);
x.push(map.charAt(b >> 18));
x.push(map.charAt((b >> 12) & 0x3f));
x.push(map.charAt((b >> 6) & 0x3f));
x.push(map.charAt(b & 0x3f));
}
switch(s.length - len){
case 1:
b = s.charCodeAt(i) << 16;
x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + padchar + padchar);
break;
case 2:
b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i + 1) << 8);
x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + map.charAt((b >> 6) & 0x3f) + padchar);
break;
}
return x.join('');
};
return base64;
})();
commons.PraMethod.Base64 = function () {
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
this.encode = function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
}
// public method for decoding
this.decode = function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
// private method for UTF-8 encoding
var _utf8_encode = function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
// private method for UTF-8 decoding
var _utf8_decode = function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
commons.TempMethod.imgLayout = function(ele) {
var imgs = document.querySelectorAll(ele);
[].forEach.call(imgs, function(img, index, array) {
if (img.complete) {
console.log('complete');
ol(img);
} else {
img.onload = function() {
console.log('load');
ol(img);
}
}
});
function ol(img) {
img.removeAttribute('width');
img.removeAttribute('height');
var nh = img.naturalHeight,
nw = img.naturalWidth;
if (nh > nw) {
$(img).attr('width','100%')
} else {
$(img).attr('height','100%');
}
}
};
|
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* 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 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 THE
* COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* 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 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 THE
* COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
*/
/*
* jQuery css bezier animation support -- Jonah Fox
* version 0.0.1
* Released under the MIT license.
*/
/*
var path = $.path.bezier({
start: {x:10, y:10, angle: 20, length: 0.3},
end: {x:20, y:30, angle: -20, length: 0.2}
})
$("myobj").animate({path: path}, duration)
*/
;(function($){
$.path = {};
var V = {
rotate: function(p, degrees) {
var radians = degrees * Math.PI / 180,
c = Math.cos(radians),
s = Math.sin(radians);
return [c*p[0] - s*p[1], s*p[0] + c*p[1]];
},
scale: function(p, n) {
return [n*p[0], n*p[1]];
},
add: function(a, b) {
return [a[0]+b[0], a[1]+b[1]];
},
minus: function(a, b) {
return [a[0]-b[0], a[1]-b[1]];
}
};
$.path.bezier = function( params, rotate ) {
params.start = $.extend( {angle: 0, length: 0.3333}, params.start );
params.end = $.extend( {angle: 0, length: 0.3333}, params.end );
this.p1 = [params.start.x, params.start.y];
this.p4 = [params.end.x, params.end.y];
var v14 = V.minus( this.p4, this.p1 ),
v12 = V.scale( v14, params.start.length ),
v41 = V.scale( v14, -1 ),
v43 = V.scale( v41, params.end.length );
v12 = V.rotate( v12, params.start.angle );
this.p2 = V.add( this.p1, v12 );
v43 = V.rotate(v43, params.end.angle );
this.p3 = V.add( this.p4, v43 );
this.f1 = function(t) { return (t*t*t); };
this.f2 = function(t) { return (3*t*t*(1-t)); };
this.f3 = function(t) { return (3*t*(1-t)*(1-t)); };
this.f4 = function(t) { return ((1-t)*(1-t)*(1-t)); };
/* p from 0 to 1 */
this.css = function(p) {
var f1 = this.f1(p), f2 = this.f2(p), f3 = this.f3(p), f4=this.f4(p), css = {};
if (rotate) {
css.prevX = this.x;
css.prevY = this.y;
}
css.x = this.x = ( this.p1[0]*f1 + this.p2[0]*f2 +this.p3[0]*f3 + this.p4[0]*f4 +.5 )|0;
css.y = this.y = ( this.p1[1]*f1 + this.p2[1]*f2 +this.p3[1]*f3 + this.p4[1]*f4 +.5 )|0;
css.left = css.x + "px";
css.top = css.y + "px";
return css;
};
};
$.path.arc = function(params, rotate) {
for ( var i in params ) {
this[i] = params[i];
}
this.dir = this.dir || 1;
while ( this.start > this.end && this.dir > 0 ) {
this.start -= 360;
}
while ( this.start < this.end && this.dir < 0 ) {
this.start += 360;
}
this.css = function(p) {
var a = ( this.start * (p ) + this.end * (1-(p )) ) * Math.PI / 180,
css = {};
if (rotate) {
css.prevX = this.x;
css.prevY = this.y;
}
css.x = this.x = ( Math.sin(a) * this.radius + this.center[0] +.5 )|0;
css.y = this.y = ( Math.cos(a) * this.radius + this.center[1] +.5 )|0;
css.left = css.x + "px";
css.top = css.y + "px";
return css;
};
};
$.fx.step.path = function(fx) {
var css = fx.end.css( 1 - fx.pos );
if ( css.prevX != null ) {
$.cssHooks.transform.set( fx.elem, "rotate(" + Math.atan2(css.prevY - css.y, css.prevX - css.x) + ")" );
}
fx.elem.style.top = css.top;
fx.elem.style.left = css.left;
};
})(jQuery);
|
var searchData=
[
['initial',['initial',['../struct_score.html#a5d149221823e63acce30b844db826c68',1,'Score']]],
['intromenu',['IntroMenu',['../class_intro_menu.html',1,'IntroMenu'],['../class_intro_menu.html#ae34d394e4b9c966f44edb891c567a879',1,'IntroMenu::IntroMenu()']]],
['intromenu_2ecpp',['intromenu.cpp',['../intromenu_8cpp.html',1,'']]],
['intromenu_2eh',['intromenu.h',['../intromenu_8h.html',1,'']]],
['intromessage',['intromessage',['../classintromessage.html',1,'intromessage'],['../classintromessage.html#aabdd5763f78f38cb924a56ccb250ffa9',1,'intromessage::intromessage()']]],
['intromessage_2ecpp',['intromessage.cpp',['../intromessage_8cpp.html',1,'']]],
['intromessage_2eh',['intromessage.h',['../intromessage_8h.html',1,'']]]
];
|
'use strict';
angular.module('copayApp.controllers').controller('topUpController', function($scope, $log, $state, $timeout, $ionicHistory, $ionicConfig, lodash, popupService, profileService, ongoingProcess, walletService, configService, platformInfo, bitpayService, bitpayCardService, payproService, bwcError, txFormatService, sendMaxService, gettextCatalog) {
$scope.isCordova = platformInfo.isCordova;
var coin = 'btcz';
var cardId;
var useSendMax;
var amount;
var currency;
var createdTx;
var message;
var configWallet = configService.getSync().wallet;
var _resetValues = function() {
$scope.totalAmountStr = $scope.amount = $scope.invoiceFee = $scope.networkFee = $scope.totalAmount = $scope.wallet = null;
createdTx = message = null;
};
var showErrorAndBack = function(title, msg) {
title = title || gettextCatalog.getString('Error');
$scope.sendStatus = '';
$log.error(msg);
msg = msg.errors ? msg.errors[0].message : msg;
popupService.showAlert(title, msg, function() {
$ionicHistory.goBack();
});
};
var showError = function(title, msg, cb) {
cb = cb || function() {};
title = title || gettextCatalog.getString('Error');
$scope.sendStatus = '';
$log.error(msg);
msg = msg.errors ? msg.errors[0].message : msg;
popupService.showAlert(title, msg, cb);
};
var satToFiat = function(sat, cb) {
txFormatService.toFiat(coin, sat, $scope.currencyIsoCode, function(value) {
return cb(value);
});
};
var publishAndSign = function (wallet, txp, onSendStatusChange, cb) {
if (!wallet.canSign() && !wallet.isPrivKeyExternal()) {
var err = gettextCatalog.getString('No signing proposal: No private key');
$log.info(err);
return cb(err);
}
walletService.publishAndSign(wallet, txp, function(err, txp) {
if (err) return cb(err);
return cb(null, txp);
}, onSendStatusChange);
};
var statusChangeHandler = function (processName, showName, isOn) {
$log.debug('statusChangeHandler: ', processName, showName, isOn);
if (processName == 'topup' && !isOn) {
$scope.sendStatus = 'success';
$timeout(function() {
$scope.$digest();
}, 100);
} else if (showName) {
$scope.sendStatus = showName;
}
};
var setTotalAmount = function(amountSat, invoiceFeeSat, networkFeeSat) {
satToFiat(amountSat, function(a) {
$scope.amount = Number(a);
satToFiat(invoiceFeeSat, function(i) {
$scope.invoiceFee = Number(i);
satToFiat(networkFeeSat, function(n) {
$scope.networkFee = Number(n);
$scope.totalAmount = $scope.amount + $scope.invoiceFee + $scope.networkFee;
$timeout(function() {
$scope.$digest();
});
});
});
});
};
var createInvoice = function(data, cb) {
bitpayCardService.topUp(cardId, data, function(err, invoiceId) {
if (err) {
return cb({
title: gettextCatalog.getString('Could not create the invoice'),
message: err
});
}
bitpayCardService.getInvoice(invoiceId, function(err, inv) {
if (err) {
return cb({
title: gettextCatalog.getString('Could not get the invoice'),
message: err
});
}
return cb(null, inv);
});
});
};
var createTx = function(wallet, invoice, message, cb) {
var payProUrl = (invoice && invoice.paymentUrls) ? invoice.paymentUrls.BIP73 : null;
if (!payProUrl) {
return cb({
title: gettextCatalog.getString('Error in Payment Protocol'),
message: gettextCatalog.getString('Invalid URL')
});
}
var outputs = [];
var toAddress = invoice.bitcoinAddress;
var amountSat = parseInt((invoice.btczDue * 100000000).toFixed(0)); // BTCZ to Satoshi
outputs.push({
'toAddress': toAddress,
'amount': amountSat,
'message': message
});
var txp = {
toAddress: toAddress,
amount: amountSat,
outputs: outputs,
message: message,
payProUrl: payProUrl,
excludeUnconfirmedUtxos: configWallet.spendUnconfirmed ? false : true,
feeLevel: configWallet.settings.feeLevel || 'normal'
};
walletService.createTx(wallet, txp, function(err, ctxp) {
if (err) {
return cb({
title: gettextCatalog.getString('Could not create transaction'),
message: bwcError.msg(err)
});
}
return cb(null, ctxp);
});
};
var calculateAmount = function(wallet, cb) {
// Global variables defined beforeEnter
var a = amount;
var c = currency;
if (useSendMax) {
sendMaxService.getInfo(wallet, function(err, maxValues) {
if (err) {
return cb({
title: null,
message: err
})
}
if (maxValues.amount == 0) {
return cb({message: gettextCatalog.getString('Insufficient funds for fee')});
}
var maxAmountBtc = Number((maxValues.amount / 100000000).toFixed(8));
createInvoice({amount: maxAmountBtc, currency: 'BTCZ'}, function(err, inv) {
if (err) return cb(err);
var invoiceFeeSat = parseInt((inv.buyerPaidBtcMinerFee * 100000000).toFixed());
var newAmountSat = maxValues.amount - invoiceFeeSat;
if (newAmountSat <= 0) {
return cb({message: gettextCatalog.getString('Insufficient funds for fee')});
}
return cb(null, newAmountSat, 'sat');
});
});
} else {
return cb(null, a, c);
}
};
var initializeTopUp = function(wallet, parsedAmount) {
$scope.amountUnitStr = parsedAmount.amountUnitStr;
var dataSrc = {
amount: parsedAmount.amount,
currency: parsedAmount.currency
};
ongoingProcess.set('loadingTxInfo', true);
createInvoice(dataSrc, function(err, invoice) {
if (err) {
ongoingProcess.set('loadingTxInfo', false);
showErrorAndBack(err.title, err.message);
return;
}
// Sometimes API does not return this element;
invoice['buyerPaidBtcMinerFee'] = invoice.buyerPaidBtcMinerFee || 0;
var invoiceFeeSat = (invoice.buyerPaidBtcMinerFee * 100000000).toFixed();
message = gettextCatalog.getString("Top up {{amountStr}} to debit card ({{cardLastNumber}})", {
amountStr: $scope.amountUnitStr,
cardLastNumber: $scope.lastFourDigits
});
createTx(wallet, invoice, message, function(err, ctxp) {
ongoingProcess.set('loadingTxInfo', false);
if (err) {
_resetValues();
showError(err.title, err.message);
return;
}
// Save TX in memory
createdTx = ctxp;
$scope.totalAmountStr = txFormatService.formatAmountStr(coin, ctxp.amount);
setTotalAmount(parsedAmount.amountSat, invoiceFeeSat, ctxp.fee);
});
});
};
$scope.$on("$ionicView.beforeLeave", function(event, data) {
$ionicConfig.views.swipeBackEnabled(true);
});
$scope.$on("$ionicView.enter", function(event, data) {
$ionicConfig.views.swipeBackEnabled(false);
});
$scope.$on("$ionicView.beforeEnter", function(event, data) {
cardId = data.stateParams.id;
useSendMax = data.stateParams.useSendMax;
amount = data.stateParams.amount;
currency = data.stateParams.currency;
bitpayCardService.get({ cardId: cardId, noRefresh: true }, function(err, card) {
if (err) {
showErrorAndBack(null, err);
return;
}
bitpayCardService.setCurrencySymbol(card[0]);
$scope.lastFourDigits = card[0].lastFourDigits;
$scope.currencySymbol = card[0].currencySymbol;
$scope.currencyIsoCode = card[0].currency;
$scope.wallets = profileService.getWallets({
onlyComplete: true,
network: bitpayService.getEnvironment().network,
hasFunds: true,
coin: coin
});
if (lodash.isEmpty($scope.wallets)) {
showErrorAndBack(null, gettextCatalog.getString('No wallets available'));
return;
}
bitpayCardService.getRates($scope.currencyIsoCode, function(err, r) {
if (err) $log.error(err);
$scope.rate = r.rate;
});
$scope.onWalletSelect($scope.wallets[0]); // Default first wallet
});
});
$scope.topUpConfirm = function() {
if (!createdTx) {
showError(null, gettextCatalog.getString('Transaction has not been created'));
return;
}
var title = gettextCatalog.getString('Confirm');
var okText = gettextCatalog.getString('OK');
var cancelText = gettextCatalog.getString('Cancel');
popupService.showConfirm(title, message, okText, cancelText, function(ok) {
if (!ok) {
$scope.sendStatus = '';
return;
}
ongoingProcess.set('topup', true, statusChangeHandler);
publishAndSign($scope.wallet, createdTx, function() {}, function(err, txSent) {
if (err) {
_resetValues();
ongoingProcess.set('topup', false, statusChangeHandler);
showError(gettextCatalog.getString('Could not send transaction'), err);
return;
}
ongoingProcess.set('topup', false, statusChangeHandler);
});
});
};
$scope.showWalletSelector = function() {
$scope.walletSelectorTitle = gettextCatalog.getString('From');
$scope.showWallets = true;
};
$scope.onWalletSelect = function(wallet) {
$scope.wallet = wallet;
ongoingProcess.set('retrievingInputs', true);
calculateAmount(wallet, function(err, a, c) {
ongoingProcess.set('retrievingInputs', false);
if (err) {
_resetValues();
showError(err.title, err.message, function() {
$scope.showWalletSelector();
});
return;
}
var parsedAmount = txFormatService.parseAmount(coin, a, c);
initializeTopUp(wallet, parsedAmount);
});
};
$scope.goBackHome = function() {
$scope.sendStatus = '';
$ionicHistory.nextViewOptions({
disableAnimate: true,
historyRoot: true
});
$ionicHistory.clearHistory();
$state.go('tabs.home').then(function() {
$state.transitionTo('tabs.bitpayCard', {id: cardId});
});
};
});
|
var config = require("./config.json");
var currentSong, newSong, currentAlbum;
const http = require("http");
const LastFmNode = require("lastfm").LastFmNode;
const Discord = require("discord.js");
const client = new Discord.Client();
var lastfm = new LastFmNode({
api_key: config.api_key
});
function stoppedPlaying(){
console.log("stopped playing.");
client.user.setGame(0);
currentAlbum = 0;
if(config.changeAvatar){
client.user.setAvatar(config.defaultAvatar);
}
}
var trackStream = lastfm.stream(config.username);
trackStream.on("nowPlaying", function(track) {
if(track.name && track.artist["#text"]){
//console.log(track);
if(track["@attr"]){
newSong = track.artist["#text"] + " - " + track.name;
if (newSong != currentSong) {
if (currentAlbum != track.album["#text"]){
if(track.image[0]["#text"] && config.changeAvatar){
console.log("playing album: "+track.album["#text"]);
client.user.setAvatar(track.image[track.image.length-1]["#text"]);
currentAlbum = track.album["#text"];
}
}
console.info("currently playing:", newSong);
client.user.setGame("♫ "+newSong);
currentSong = newSong;
}
}else{
stoppedPlaying();
}
}
});
trackStream.on("stoppedPlaying", function(track) {
stoppedPlaying();
});
trackStream.on("error", function(err) {
console.log("something went wrong: ",err);
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.username}!`);
trackStream.start();
});
// Script for exiting the process is from https://frankl.in/code/before-exit-scripts-in-node-js
let preExit = [];
// Add pre-exit script
preExit.push(code => {
console.log('Whoa! Exit code %d, cleaning up...', code);
stoppedPlaying();
});
// Catch CTRL+C
process.on('SIGINT', () => {
console.log('\nCTRL+C...');
stoppedPlaying();
process.exit(0);
});
// Catch uncaught exception
process.on('uncaughtException', err => {
console.dir(err, {
depth: null
});
stoppedPlaying();
process.exit(1);
});
console.log('Bot on, hit CTRL+C to exit :)');
client.login(config.token);
|
version https://git-lfs.github.com/spec/v1
oid sha256:5a29985b06bccf704a9d8245673a80448eaaf090ff55eb16c3bbe8b3152286dd
size 292
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var mocha = require('gulp-mocha');
var browserify = require('gulp-browserify');
var derequire = require('gulp-derequire');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var http = require('http');
var BrowserStackTunnel = require('browserstacktunnel-wrapper');
var config = require('./test/config');
gulp.task('default', ['build']);
gulp.task('build', function() {
return gulp
.src('./index.js')
.pipe(browserify({standalone: 'SolidusAssetsProxy'}))
.pipe(derequire())
.pipe(rename('solidus-assets-proxy.js'))
.pipe(gulp.dest('./build'));
});
gulp.task('test', function(callback) {
runSequence(
['build-browser-test', 'start-test-server', 'start-browserstack-tunnel'],
'run-node-test',
'run-browser-test',
function() {
runSequence(
['stop-test-server', 'stop-browserstack-tunnel'],
callback);
}
);
});
gulp.task('node-test', function(callback) {
runSequence(
'start-test-server',
'run-node-test',
function() {
runSequence(
'stop-test-server',
callback);
}
);
});
gulp.task('browser-test', function(callback) {
runSequence(
['build-browser-test', 'start-test-server', 'start-browserstack-tunnel'],
'run-browser-test',
function() {
runSequence(
['stop-test-server', 'stop-browserstack-tunnel'],
callback);
}
);
});
gulp.task('test-server', function(callback) {
runSequence(
['build-browser-test', 'start-test-server'],
callback);
});
// TASKS
gulp.task('build-browser-test', function() {
return gulp
.src('./test/test.js')
.pipe(browserify())
.pipe(gulp.dest('./test/browser'));
});
var test_server;
gulp.task('start-test-server', function(callback) {
test_server = http
.createServer(config.routes)
.listen(config.port, function() {
gutil.log('Test server started on', gutil.colors.green(config.host));
gutil.log('Run manual tests on', gutil.colors.green(config.host + '/test/browser/test.html'));
callback();
});
});
gulp.task('stop-test-server', function(callback) {
test_server.close(callback);
});
var browserstack_tunnel;
gulp.task('start-browserstack-tunnel', function(callback) {
var port = 3000;
browserstack_tunnel = new BrowserStackTunnel({
key: process.env.BROWSERSTACK_KEY,
hosts: [{
name: 'localhost',
port: port,
sslFlag: 0
}],
v: true
});
browserstack_tunnel.start(function(err) {
if (!err) gutil.log('BrowserStack tunnel started on', gutil.colors.green('http://localhost:' + port));
callback(err);
});
});
gulp.task('stop-browserstack-tunnel', function(callback) {
browserstack_tunnel.stop(callback);
});
gulp.task('run-node-test', function(callback) {
gulp
.src('./test/test.js', {read: false})
.pipe(mocha())
.on('end', callback)
.on('error', function() {});
});
gulp.task('run-browser-test', function(callback) {
gulp
.src('./test/browser-test.js', {read: false})
.pipe(mocha({timeout: 60000}))
.on('end', callback)
.on('error', function() {});
});
|
import * as ActionTypes from '../constants/ConnTypes';
const initialState = {
loading: false,
connected: false,
errorMessage: null,
};
export default function songs(state = initialState, action) {
switch (action.type) {
case ActionTypes.CONNECTING:
return {
loading: true,
connected: false,
errorMessage: null,
};
case ActionTypes.CONNECTED:
return {
loading: false,
connected: true,
errorMessage: null,
};
default:
return state;
}
}
|
var Barrayuda;
Barrayuda = (function() {
function Barrayuda() {}
Barrayuda.properties = function(options) {
var luckySide, luckyTop, luckyZ;
luckyTop = Math.floor(Math.random() * (400 - 0)) + 0;
luckySide = Math.floor(Math.random() * (options["size"] - 0)) + 0;
luckyZ = Math.floor(Math.random() * (5 - -5)) + -5;
return {
"overflow": "scroll",
"position": "absolute",
"width": options["size"] + "px",
"height": options["height"] + "px",
"max-width": "1000px",
"max-height": "800px",
"min-width": "200px",
"min-height": "400px",
"margin-top": "0px",
"margin-left": "0px",
"margin-right": "0px",
"margin-bottom": "0px",
"bottom": "0px",
"z-index": luckyZ,
"top": luckyTop + "px",
"left": luckySide + "px",
"right": luckySide + "px"
};
};
return Barrayuda;
})();
|
import { Geometry, Vector2 } from "../geometry";
import { Tool } from "./Tool";
import { generateActionId } from "../Actions";
import simplify from "simplify-js";
import { PenDrawing } from "../drawing_objects";
export class DrawTool extends Tool {
constructor(manager) {
super(manager);
this.pointBuffer = [];
this.drawingObject = null;
this.cursor = null;
}
eventNamespace() { return "Drawing"; }
minimumLineDistance() { return 0; }
saveAction() { }
isFog() { return false; }
createDrawingObject() { }
handleMouseMove(location) {
location = this.roundPoint(location);
this.pointBuffer.push(new Vector2(location));
this.drawingObject.setPoints(simplify(this.pointBuffer, 1, false));
}
ensureDrawingObject() {
if (this.drawingObject === null) {
this.drawingObject = this.createDrawingObject();
this.drawingObject.isFog = this.isFog();
if (this.isFog()) {
this.board.drawingLayer.addFogAction(this.drawingObject);
} else {
this.board.drawingLayer.addAction(this.drawingObject);
}
}
}
enable() {
var self = this;
this.board.event_manager.on('dragstart.' + this.eventNamespace(), function(mapEvt) {
self.ensureDrawingObject();
self.handleMouseMove(mapEvt.mapPoint);
});
this.board.event_manager.on('mousemove.' + this.eventNamespace(), function(mapEvt) {
self.cursor = mapEvt.mapPoint;
});
this.board.event_manager.on('drag.' + this.eventNamespace(), function(mapEvt) {
self.handleMouseMove(mapEvt.mapPoint);
});
this.board.event_manager.on('dragstop.' + this.eventNamespace(), function(mapEvt) {
self.saveAction();
self.pointBuffer = [];
self.removeDrawingObject();
});
}
disable() {
this.saveAction();
this.removeDrawingObject();
this.pointBuffer = [];
this.board.event_manager.off("." + this.eventNamespace());
}
removeDrawingObject() {
if (this.drawingObject) {
this.board.drawingLayer.removeAction(this.drawingObject.uid);
this.drawingObject = null;
}
}
}
export class Pen extends DrawTool {
constructor(board) {
super(board);
this.width = null;
this.color = null;
this.backgroundColor = null;
}
buildOptions() {
this.options.add(this.toolManager.sharedTool("drawingColor"));
this.options.add(this.toolManager.sharedTool("drawingWidth"));
}
optionsChanged() {
this.width = this.options.get("width").value;
this.color = this.options.get("color").value;
}
minimumLineDistance() { return this.width / 2; }
eventNamespace() { return "Pen"; }
createDrawingObject() {
return new PenDrawing(generateActionId(), this.board, this.pointBuffer, this.width, this.color, this.board.pcMode, this.board.getLevel().id);
}
draw() {
if (this.cursor) {
this.board.drawing.drawCircle(this.cursor[0], this.cursor[1], this.width / 2, 2, this.color, this.color)
}
}
saveAction() {
if (this.pointBuffer.length > 0) {
var action = {actionType: "penAction", version: 2, level: this.board.getLevel().id, isPcLayer: this.board.pcMode, color: this.color, width: this.width, points: simplify(this.pointBuffer, 1, true).map(p => [p.x, p.y]), uid: generateActionId()};
var undoAction = {actionType: "removeDrawingAction", actionId: action.uid, uid: generateActionId()};
this.board.addAction(action, undoAction, true);
}
}
}
export class Eraser extends DrawTool {
constructor(manager) {
super(manager);
this.width = null;
}
buildOptions() {
this.options.add({type: "size", name: "width", label: "Width", sizes: [20, 50, 75, 100, 150, 200], value: 75 });
}
optionsChanged() {
this.width = this.options.get("width").value;
}
minimumLineDistance() { return 0; }
eventNamespace() { return "Eraser"; }
createDrawingObject() {
return new PenDrawing(generateActionId(), this.board, this.pointBuffer, this.width, -1, this.board.pcMode, this.board.getLevel().id);
}
enable() {
super.enable();
this.setCursor('none');
var self = this;
this.board.event_manager.on('click.' + this.eventNamespace(), function(mapEvt) {
self.ensureDrawingObject();
self.handleMouseMove(mapEvt.mapPoint);
self.saveAction();
self.pointBuffer = [];
});
}
disable() {
super.disable();
this.clearCursor();
}
draw() {
var cursorColor = "#FFFFFF";
if (this.pointBuffer.length > 0) {
cursorColor = "#000000";
}
if (this.cursor) {
this.board.drawing.drawCircle(this.cursor[0], this.cursor[1], this.width / 2, 2, cursorColor);
this.board.drawing.drawCross(this.cursor[0], this.cursor[1], 5, 3, cursorColor);
}
}
saveAction() {
if (this.pointBuffer.length > 0) {
var action = {actionType: "eraseAction", version: 2, level: this.board.getLevel().id, isPcLayer: this.board.pcMode, width: this.width, points: simplify(this.pointBuffer, 1, true).map(p => [p.x, p.y]), uid: generateActionId()};
var undoAction = {actionType: "removeDrawingAction", actionId: action.uid, uid: generateActionId()};
this.board.addAction(action, undoAction, true);
}
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import ReduxToastr from 'react-redux-toastr';
import Header from './../header/header';
import Footer from './../../components/footer/footer.jsx';
const App = props => {
const { children } = props;
return (
<div className="App">
<Header />
<ReduxToastr
newestOnTop={false}
preventDuplicates
position="top-center"
transitionIn="fadeIn"
transitionOut="fadeOut"
/>
<div className="main">
{children}
</div>
<Footer />
</div>
);
};
App.propTypes = {
children: PropTypes.element.isRequired
};
export default App;
|
import { $isAsync, $async, $await, $iteratorSymbol } from '../generate/async.macro'
import { $ensureIterable } from './internal/$iterable'
import map from './map'
$async; function * $zipAll (...iterables) {
const iters = iterables.map(arg => $ensureIterable(arg)[$iteratorSymbol]())
const itersDone = iters.map(iter => ({ done: false, iter }))
try {
while (true) {
const results = map(iter => iter.next(), iters)
const syncResults = $isAsync ? $await(Promise.all(results)) : results
const zipped = new Array(iters.length)
let i = 0
let allDone = true
for (const { value, done } of syncResults) {
allDone = allDone && done
itersDone[i].done = done
zipped[i] = done ? undefined : value
i++
}
if (allDone) break
yield zipped
}
} finally {
for (const { iter, done } of itersDone) {
if (!done && typeof iter.return === 'function') $await(iter.return())
}
}
}
export default $zipAll
|
import assert from 'minimalistic-assert';
import { nameRegex } from './Primitive';
/**
* Constructs a new primitive from a serialized value.
*/
export default class Derivation {
/**
* @param {String} name - A title for the new type.
* @param {Primitive} primitive - Something to derive from.
* @param {Object} def - The derivation rule set.
*/
constructor(name, primitive, def) {
assert(nameRegex.test(name), `Invalid derivation name "${name}".`);
this.name = name;
this.subtype = primitive;
Object.defineProperty(this, '_definition', {
value: def,
});
}
/**
* Takes a derived type and turns it into a primitive.
* Ensure the type is a valid derivation before attempting dehyrdation.
* @throws {Error} - If the dehydrator returns an invalid value.
* @param {mixed} hydrated - Anything which makes it past the validator.
* @return {mixed} - Something belonging to the derived type.
*/
dehydrate(hydrated) {
const value = this._definition.dehydrate(hydrated);
assert(
this.subtype.isValid(value),
`Serializer for type "${this.name}" returned an invalid value.`
);
return value;
}
/**
* Takes a primitive value and turns it into the derived type.
* @param {mixed} dehydrated - Something of the derived type.
* @return {mixed} - The hydrated value.
*/
hydrate(dehydrated) {
return this._definition.hydrate(dehydrated);
}
/**
* Test whether the given value is a valid derivation instance.
* @param {mixed} value - Anything but undefined.
* @return {Boolean} - Whether the value is valid.
*/
isValid(value) {
return this._definition.isValid(value);
}
}
|
var bnf = {
// For type annotations
"type": [
["IDENTIFIER optTypeParamList", "$$ = new yy.TypeName($1, $2);"],
["FUNCTION ( optTypeFunctionArgList )", "$$ = new yy.TypeFunction($3);"],
["GENERIC", "$$ = new yy.Generic($1);"],
["[ type ]", "$$ = new yy.TypeArray($2);"],
["( typeList )", "$$ = new yy.TypeObject($2);"],
["{ optTypePairs }", "$$ = new yy.TypeObject($2);"]
],
"typeList": [
["type", "$$ = [$1];"],
["typeList , type", "$$ = $1; $1.push($3);"]
],
"optTypeParamList": [
["", "$$ = [];"],
["typeParamList", "$$ = $1;"]
],
"typeParamList": [
["IDENTIFIER", "$$ = [new yy.TypeName($1, [])];"],
["GENERIC", "$$ = [new yy.Generic($1, [])];"],
["( type )", "$$ = [$2];"],
["typeParamList IDENTIFIER", "$$ = $1; $1.push(new yy.TypeName($2, []));"],
["typeParamList GENERIC", "$$ = $1; $1.push(new yy.Generic($2, []));"],
["typeParamList ( type )", "$$ = $1; $1.push($3);"]
],
"optTypeFunctionArgList": [
["", "$$ = [];"],
["typeFunctionArgList", "$$ = $1;"]
],
"typeFunctionArgList": [
["type", "$$ = [$1];"],
["typeFunctionArgList , type", "$$ = $1; $1.push($3);"]
],
"optTypePairs": [
["", "$$ = {};"],
["keywordOrIdentifier : type", "$$ = {}; $$[$1] = $3;"],
["optTypePairs , keywordOrIdentifier : type", "$$ = $1; $1[$3] = $5;"]
],
"dataParamList": [
["IDENTIFIER", "$$ = [new yy.Arg($1)];"],
["dataParamList IDENTIFIER", "$$ = $1; $1.push(new yy.Arg($2));"]
],
"optDataParamList": [
["", "$$ = [];"],
["dataParamList", "$$ = $1;"]
],
"keywordOrIdentifier": [
["THEN", "$$ = $1;"],
["ELSE", "$$ = $1;"],
["DATA", "$$ = $1;"],
["TYPE", "$$ = $1;"],
["MATCH", "$$ = $1;"],
["CASE", "$$ = $1;"],
["DO", "$$ = $1;"],
["RETURN", "$$ = $1;"],
["WITH", "$$ = $1;"],
["WHERE", "$$ = $1;"],
["IDENTIFIER", "$$ = $1;"]
]
};
exports.bnf = bnf;
var grammar = {
"startSymbol": "typefile",
"bnf": {
"typefile": [
["EOF", "return {};"],
["body EOF", "return $1;"]
],
"body": [
["pair", "$$ = {types: {}, env: {}}; if($1.data) { $$.types[$1.name] = $1.params; } else { $$.env[$1.name] = $1.type; }"],
["body TERMINATOR pair", "$$ = $1; if($3.data) { $$.types[$3.name] = $3.params; } else { $$.env[$3.name] = $3.type; }"],
["body TERMINATOR", "$$ = $1;"]
],
"pair": [
["IDENTIFIER : type", "$$ = {name: $1, type: $3, data: false};"],
["TYPE IDENTIFIER optDataParamList", "$$ = {name: $2, params: $3, data: true};"]
],
"type": bnf.type,
"typeList": bnf.typeList,
"optTypeParamList": bnf.optTypeParamList,
"typeParamList": bnf.typeParamList,
"optTypeFunctionArgList": bnf.optTypeFunctionArgList,
"typeFunctionArgList": bnf.typeFunctionArgList,
"optTypePairs": bnf.optTypePairs,
"dataParamList": bnf.dataParamList,
"optDataParamList": bnf.optDataParamList,
"keywordOrIdentifier": bnf.keywordOrIdentifier
}
};
exports.grammar = grammar;
|
import React, { Component } from 'react'
import { Button } from 'stardust'
export default class ButtonFloatedExample extends Component {
render() {
return (
<div>
<Button className='right floated'>Right Floated</Button>
<Button className='left floated'>Left Floated</Button>
</div>
)
}
}
|
var Store = {
adp: [],
franchises: {},
players: {},
league: {}
};
module.exports = Store;
|
const csound = require('bindings')('csound-api.node');
const stringify = require('json-stable-stringify');
const Csound = csound.Create();
const ASTRoot = csound.ParseOrc(Csound, `
0dbfs = 1
giFunctionTableID ftgen 0, 0, 16384, 10, 1
instr A440
outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
endin
`);
// Convert the AST to an object that is not backed by a Csound structure.
const ASTObject = JSON.parse(JSON.stringify(ASTRoot));
csound.DeleteTree(Csound, ASTRoot);
csound.Destroy(Csound);
// The next property of an AST node seems to be for the second argument of an
// opcode, its next property for the third argument, and so on. Add nextNodes
// properties to AST objects to reflect this relationship.
function addNextNodesToASTObject(ASTObject) {
const ASTObjectsForDepths = [ASTObject];
function addNextNodes(ASTObject, depth) {
const depthPlus1 = depth + 1;
ASTObjectsForDepths[depthPlus1] = ASTObject;
if (ASTObject.left)
addNextNodes(ASTObject.left, depthPlus1);
if (ASTObject.right)
addNextNodes(ASTObject.right, depthPlus1);
if (ASTObject.next) {
const ASTObjectForDepth = ASTObjectsForDepths[depth];
if (ASTObjectForDepth.nextNodes)
ASTObjectForDepth.nextNodes.push(ASTObject.next);
else
ASTObjectForDepth.nextNodes = [ASTObject.next];
addNextNodes(ASTObject.next, depth);
}
}
addNextNodes(ASTObject, 0);
}
addNextNodesToASTObject(ASTObject);
// Log the AST as JSON.
console.log(stringify(ASTObject, {
cmp: (a, b) => {
// When converting AST objects to JSON, put the left, right, and nextNodes
// properties last.
function compareKeys(key1, key2) {
switch (key1) {
case 'left': if (key2 === 'right') return -1; /* falls through */
case 'right': if (key2 === 'nextNodes') return -1; /* falls through */
case 'nextNodes': return (key1 === key2) ? 0 : 1;
}
return null;
}
let result = compareKeys(a.key, b.key);
if (result !== null) return result;
result = compareKeys(b.key, a.key);
return (result !== null) ? -result : a.key.localeCompare(b.key);
},
replacer: (key, value) => (key === 'next') ? undefined : value,
space: ' '
}));
|
module.exports = [
{
startDate: '04-01-2021',
endDate: '31-01-2021',
totalCases: 215,
totalPoints: 13523,
availablePoints: 16191,
contractedHours: '290.3',
hoursReduction: '14.9',
cmsPoints: -99,
gsPoints: 0,
armsTotalCases: 0,
paromsPoints: 228,
sdrPoints: 0,
sdrConversionPoints: 0,
nominalTarget: 21651,
capacity: '83.5%',
cmsPercentage: '-0.6%',
gsPercentage: '0.0%',
regionName: 'Region 1',
lduName: 'PDU 1',
teamName: 'Team 1',
omName: 'N/A',
grade: 'N/A',
daysWithData: 20
},
{
startDate: '01-02-2021',
endDate: '28-02-2021',
totalCases: 195,
totalPoints: 13017,
availablePoints: 14322,
contractedHours: '258.5',
hoursReduction: '14.9',
cmsPoints: 29,
gsPoints: 0,
armsTotalCases: 1,
paromsPoints: 284,
sdrPoints: 0,
sdrConversionPoints: 0,
nominalTarget: 19782,
capacity: '90.9%',
cmsPercentage: '0.2%',
gsPercentage: '0.0%',
regionName: 'Region 1',
lduName: 'PDU 1',
teamName: 'Team 1',
omName: 'N/A',
grade: 'N/A',
daysWithData: 11
}
]
|
import React, { Component } from 'react/addons';
import DrawerTransitionGroupChild from './DrawerTransitionGroupChild';
const { TransitionGroup } = React.addons;
class DrawerTransitionGroup extends Component {
render() {
return <TransitionGroup {...this.props} childFactory={this.wrapChild} />;
}
wrapChild(child) {
return <DrawerTransitionGroupChild>{child}</DrawerTransitionGroupChild>;
}
}
export default DrawerTransitionGroup;
|
import React from 'react';
const Order = () => {
return (
<div className='method-order'>
<p className='method-order__description'>
Common convention for what the order should be for methods in ES6 React components.
</p>
<ol className='method-order__list'>
<li className='method-order__list-item'>
<code className='language-javascript'>static</code> declarations
</li>
<li className='method-order__list-item'>
<code className='language-javascript'>constructor</code>
</li>
<li className='method-order__list-item'>
Lifecycle methods
</li>
<li className='method-order__list-item'>
Your own functions and click handlers and/or event handlers
</li>
<li className='method-order__list-item'>
<code className='language-javascript'>render</code>
</li>
</ol>
<div className='order-example'>
<div className='order-example__label'></div>
<pre className='language-javascript'><code>{`\
export default class Component extends React.Component {
static displayName = ''
static propTypes = { ... }
constructor () { ... }
componentDidMount () { ... }
componentDidUpdate () { ... }
shouldComponentUpdate () { ... }
onClick () { ... }
onChange () { ... }
addLayer () { ... }
render () { ... }
}
`}
</code></pre>
</div>
</div>
);
};
export { Order as default };
|
/**
* Expose the getUserMedia function.
*/
module.exports = getUserMedia;
/**
* Dependencies.
*/
var
debug = require('debug')('iosrtc:getUserMedia'),
debugerror = require('debug')('iosrtc:ERROR:getUserMedia'),
exec = require('cordova/exec'),
MediaStream = require('./MediaStream'),
Errors = require('./Errors');
debugerror.log = console.warn.bind(console);
function isPositiveInteger(number) {
return typeof number === 'number' && number >= 0 && number % 1 === 0;
}
function isPositiveFloat(number) {
return typeof number === 'number' && number >= 0;
}
function getUserMedia(constraints) {
debug('[original constraints:%o]', constraints);
var
isPromise,
callback, errback,
audioRequested = false,
videoRequested = false,
newConstraints = {
audio: false,
video: false
};
if (typeof arguments[1] !== 'function') {
isPromise = true;
} else {
isPromise = false;
callback = arguments[1];
errback = arguments[2];
}
if (
typeof constraints !== 'object' ||
(!constraints.hasOwnProperty('audio') && !constraints.hasOwnProperty('video'))
) {
if (isPromise) {
return new Promise(function (resolve, reject) {
reject(new Errors.MediaStreamError('constraints must be an object with at least "audio" or "video" keys'));
});
} else {
if (typeof errback === 'function') {
errback(new Errors.MediaStreamError('constraints must be an object with at least "audio" or "video" keys'));
}
return;
}
}
if (constraints.audio) {
audioRequested = true;
newConstraints.audio = true;
}
if (constraints.video) {
videoRequested = true;
newConstraints.video = true;
}
// Example:
//
// getUserMedia({
// audio: true,
// video: {
// deviceId: 'qwer-asdf-zxcv',
// width: {
// min: 400,
// max: 600
// },
// frameRate: {
// min: 1.0,
// max: 60.0
// }
// }
// });
// Get video constraints
if (videoRequested) {
// Get requested video deviceId.
if (typeof constraints.video.deviceId === 'string') {
newConstraints.videoDeviceId = constraints.video.deviceId;
// Also check sourceId (mangled by adapter.js).
} else if (typeof constraints.video.sourceId === 'string') {
newConstraints.videoDeviceId = constraints.video.sourceId;
}
// Get requested min/max width.
if (typeof constraints.video.width === 'object') {
if (isPositiveInteger(constraints.video.width.min)) {
newConstraints.videoMinWidth = constraints.video.width.min;
}
if (isPositiveInteger(constraints.video.width.max)) {
newConstraints.videoMaxWidth = constraints.video.width.max;
}
}
// Get requested min/max height.
if (typeof constraints.video.height === 'object') {
if (isPositiveInteger(constraints.video.height.min)) {
newConstraints.videoMinHeight = constraints.video.height.min;
}
if (isPositiveInteger(constraints.video.height.max)) {
newConstraints.videoMaxHeight = constraints.video.height.max;
}
}
// Get requested min/max frame rate.
if (typeof constraints.video.frameRate === 'object') {
if (isPositiveFloat(constraints.video.frameRate.min)) {
newConstraints.videoMinFrameRate = constraints.video.frameRate.min;
}
if (isPositiveFloat(constraints.video.frameRate.max)) {
newConstraints.videoMaxFrameRate = constraints.video.frameRate.max;
}
} else if (isPositiveFloat(constraints.video.frameRate)) {
newConstraints.videoMinFrameRate = constraints.video.frameRate;
newConstraints.videoMaxFrameRate = constraints.video.frameRate;
}
}
debug('[computed constraints:%o]', newConstraints);
if (isPromise) {
return new Promise(function (resolve, reject) {
function onResultOK(data) {
debug('getUserMedia() | success');
var stream = MediaStream.create(data.stream);
resolve(stream);
// Emit "connected" on the stream.
stream.emitConnected();
}
function onResultError(error) {
debugerror('getUserMedia() | failure: %s', error);
reject(new Errors.MediaStreamError('getUserMedia() failed: ' + error));
}
exec(onResultOK, onResultError, 'iosrtcPlugin', 'getUserMedia', [newConstraints]);
});
}
function onResultOK(data) {
debug('getUserMedia() | success');
var stream = MediaStream.create(data.stream);
callback(stream);
// Emit "connected" on the stream.
stream.emitConnected();
}
function onResultError(error) {
debugerror('getUserMedia() | failure: %s', error);
if (typeof errback === 'function') {
errback(new Errors.MediaStreamError('getUserMedia() failed: ' + error));
}
}
exec(onResultOK, onResultError, 'iosrtcPlugin', 'getUserMedia', [newConstraints]);
}
|
// Generated by CoffeeScript 1.9.1
(function() {
var bcv_parser, bcv_passage, bcv_utils, root,
hasProp = {}.hasOwnProperty;
root = this;
bcv_parser = (function() {
bcv_parser.prototype.s = "";
bcv_parser.prototype.entities = [];
bcv_parser.prototype.passage = null;
bcv_parser.prototype.regexps = {};
bcv_parser.prototype.options = {
consecutive_combination_strategy: "combine",
osis_compaction_strategy: "b",
book_sequence_strategy: "ignore",
invalid_sequence_strategy: "ignore",
sequence_combination_strategy: "combine",
invalid_passage_strategy: "ignore",
non_latin_digits_strategy: "ignore",
passage_existence_strategy: "bcv",
zero_chapter_strategy: "error",
zero_verse_strategy: "error",
book_alone_strategy: "ignore",
book_range_strategy: "ignore",
captive_end_digits_strategy: "delete",
end_range_digits_strategy: "verse",
include_apocrypha: false,
ps151_strategy: "c",
versification_system: "default",
case_sensitive: "none"
};
function bcv_parser() {
var key, ref, val;
this.options = {};
ref = bcv_parser.prototype.options;
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
val = ref[key];
this.options[key] = val;
}
this.versification_system(this.options.versification_system);
}
bcv_parser.prototype.parse = function(s) {
var ref;
this.reset();
this.s = s;
s = this.replace_control_characters(s);
ref = this.match_books(s), s = ref[0], this.passage.books = ref[1];
this.entities = this.match_passages(s)[0];
return this;
};
bcv_parser.prototype.parse_with_context = function(s, context) {
var entities, ref, ref1, ref2;
this.reset();
ref = this.match_books(this.replace_control_characters(context)), context = ref[0], this.passage.books = ref[1];
ref1 = this.match_passages(context), entities = ref1[0], context = ref1[1];
this.reset();
this.s = s;
s = this.replace_control_characters(s);
ref2 = this.match_books(s), s = ref2[0], this.passage.books = ref2[1];
this.passage.books.push({
value: "",
parsed: [],
start_index: 0,
type: "context",
context: context
});
s = "\x1f" + (this.passage.books.length - 1) + "/9\x1f" + s;
this.entities = this.match_passages(s)[0];
return this;
};
bcv_parser.prototype.reset = function() {
this.s = "";
this.entities = [];
if (this.passage) {
this.passage.books = [];
return this.passage.indices = {};
} else {
this.passage = new bcv_passage;
this.passage.options = this.options;
return this.passage.translations = this.translations;
}
};
bcv_parser.prototype.set_options = function(options) {
var key, val;
for (key in options) {
if (!hasProp.call(options, key)) continue;
val = options[key];
if (key === "include_apocrypha" || key === "versification_system" || key === "case_sensitive") {
this[key](val);
} else {
this.options[key] = val;
}
}
return this;
};
bcv_parser.prototype.include_apocrypha = function(arg) {
var base, base1, ref, translation, verse_count;
if (!((arg != null) && (arg === true || arg === false))) {
return this;
}
this.options.include_apocrypha = arg;
this.regexps.books = this.regexps.get_books(arg, this.options.case_sensitive);
ref = this.translations;
for (translation in ref) {
if (!hasProp.call(ref, translation)) continue;
if (translation === "aliases" || translation === "alternates") {
continue;
}
if ((base = this.translations[translation]).chapters == null) {
base.chapters = {};
}
if ((base1 = this.translations[translation].chapters)["Ps"] == null) {
base1["Ps"] = bcv_utils.shallow_clone_array(this.translations["default"].chapters["Ps"]);
}
if (arg === true) {
if (this.translations[translation].chapters["Ps151"] != null) {
verse_count = this.translations[translation].chapters["Ps151"][0];
} else {
verse_count = this.translations["default"].chapters["Ps151"][0];
}
this.translations[translation].chapters["Ps"][150] = verse_count;
} else {
if (this.translations[translation].chapters["Ps"].length === 151) {
this.translations[translation].chapters["Ps"].pop();
}
}
}
return this;
};
bcv_parser.prototype.versification_system = function(system) {
var base, base1, base2, book, chapter_list, ref, ref1;
if (!((system != null) && (this.translations[system] != null))) {
return this;
}
if (this.translations.alternates["default"] != null) {
if (system === "default") {
if (this.translations.alternates["default"].order != null) {
this.translations["default"].order = bcv_utils.shallow_clone(this.translations.alternates["default"].order);
}
ref = this.translations.alternates["default"].chapters;
for (book in ref) {
if (!hasProp.call(ref, book)) continue;
chapter_list = ref[book];
this.translations["default"].chapters[book] = bcv_utils.shallow_clone_array(chapter_list);
}
} else {
this.versification_system("default");
}
}
if ((base = this.translations.alternates)["default"] == null) {
base["default"] = {
order: null,
chapters: {}
};
}
if (system !== "default" && (this.translations[system].order != null)) {
if ((base1 = this.translations.alternates["default"]).order == null) {
base1.order = bcv_utils.shallow_clone(this.translations["default"].order);
}
this.translations["default"].order = bcv_utils.shallow_clone(this.translations[system].order);
}
if (system !== "default" && (this.translations[system].chapters != null)) {
ref1 = this.translations[system].chapters;
for (book in ref1) {
if (!hasProp.call(ref1, book)) continue;
chapter_list = ref1[book];
if ((base2 = this.translations.alternates["default"].chapters)[book] == null) {
base2[book] = bcv_utils.shallow_clone_array(this.translations["default"].chapters[book]);
}
this.translations["default"].chapters[book] = bcv_utils.shallow_clone_array(chapter_list);
}
}
this.options.versification_system = system;
this.include_apocrypha(this.options.include_apocrypha);
return this;
};
bcv_parser.prototype.case_sensitive = function(arg) {
if (!((arg != null) && (arg === "none" || arg === "books"))) {
return this;
}
if (arg === this.options.case_sensitive) {
return this;
}
this.options.case_sensitive = arg;
this.regexps.books = this.regexps.get_books(this.options.include_apocrypha, arg);
return this;
};
bcv_parser.prototype.translation_info = function(new_translation) {
var book, chapter_list, id, old_translation, out, ref, ref1, ref2;
if (new_translation == null) {
new_translation = "default";
}
if ((new_translation != null) && (((ref = this.translations.aliases[new_translation]) != null ? ref.alias : void 0) != null)) {
new_translation = this.translations.aliases[new_translation].alias;
}
if (!((new_translation != null) && (this.translations[new_translation] != null))) {
new_translation = "default";
}
old_translation = this.options.versification_system;
if (new_translation !== old_translation) {
this.versification_system(new_translation);
}
out = {
order: bcv_utils.shallow_clone(this.translations["default"].order),
books: [],
chapters: {}
};
ref1 = this.translations["default"].chapters;
for (book in ref1) {
if (!hasProp.call(ref1, book)) continue;
chapter_list = ref1[book];
out.chapters[book] = bcv_utils.shallow_clone_array(chapter_list);
}
ref2 = out.order;
for (book in ref2) {
if (!hasProp.call(ref2, book)) continue;
id = ref2[book];
out.books[id - 1] = book;
}
if (new_translation !== old_translation) {
this.versification_system(old_translation);
}
return out;
};
bcv_parser.prototype.replace_control_characters = function(s) {
s = s.replace(this.regexps.control, " ");
if (this.options.non_latin_digits_strategy === "replace") {
s = s.replace(/[٠۰߀०০੦૦୦0౦೦൦๐໐༠၀႐០᠐᥆᧐᪀᪐᭐᮰᱀᱐꘠꣐꤀꧐꩐꯰0]/g, "0");
s = s.replace(/[١۱߁१১੧૧୧௧౧೧൧๑໑༡၁႑១᠑᥇᧑᪁᪑᭑᮱᱁᱑꘡꣑꤁꧑꩑꯱1]/g, "1");
s = s.replace(/[٢۲߂२২੨૨୨௨౨೨൨๒໒༢၂႒២᠒᥈᧒᪂᪒᭒᮲᱂᱒꘢꣒꤂꧒꩒꯲2]/g, "2");
s = s.replace(/[٣۳߃३৩੩૩୩௩౩೩൩๓໓༣၃႓៣᠓᥉᧓᪃᪓᭓᮳᱃᱓꘣꣓꤃꧓꩓꯳3]/g, "3");
s = s.replace(/[٤۴߄४৪੪૪୪௪౪೪൪๔໔༤၄႔៤᠔᥊᧔᪄᪔᭔᮴᱄᱔꘤꣔꤄꧔꩔꯴4]/g, "4");
s = s.replace(/[٥۵߅५৫੫૫୫௫౫೫൫๕໕༥၅႕៥᠕᥋᧕᪅᪕᭕᮵᱅᱕꘥꣕꤅꧕꩕꯵5]/g, "5");
s = s.replace(/[٦۶߆६৬੬૬୬௬౬೬൬๖໖༦၆႖៦᠖᥌᧖᪆᪖᭖᮶᱆᱖꘦꣖꤆꧖꩖꯶6]/g, "6");
s = s.replace(/[٧۷߇७৭੭૭୭௭౭೭൭๗໗༧၇႗៧᠗᥍᧗᪇᪗᭗᮷᱇᱗꘧꣗꤇꧗꩗꯷7]/g, "7");
s = s.replace(/[٨۸߈८৮੮૮୮௮౮೮൮๘໘༨၈႘៨᠘᥎᧘᪈᪘᭘᮸᱈᱘꘨꣘꤈꧘꩘꯸8]/g, "8");
s = s.replace(/[٩۹߉९৯੯૯୯௯౯೯൯๙໙༩၉႙៩᠙᥏᧙᪉᪙᭙᮹᱉᱙꘩꣙꤉꧙꩙꯹9]/g, "9");
}
return s;
};
bcv_parser.prototype.match_books = function(s) {
var book, books, has_replacement, k, len, ref;
books = [];
ref = this.regexps.books;
for (k = 0, len = ref.length; k < len; k++) {
book = ref[k];
has_replacement = false;
s = s.replace(book.regexp, function(full, prev, bk) {
var extra;
has_replacement = true;
books.push({
value: bk,
parsed: book.osis,
type: "book"
});
extra = book.extra != null ? "/" + book.extra : "";
return prev + "\x1f" + (books.length - 1) + extra + "\x1f";
});
if (has_replacement === true && /^[\s\x1f\d:.,;\-\u2013\u2014]+$/.test(s)) {
break;
}
}
s = s.replace(this.regexps.translations, function(match) {
books.push({
value: match,
parsed: match.toLowerCase(),
type: "translation"
});
return "\x1e" + (books.length - 1) + "\x1e";
});
return [s, this.get_book_indices(books, s)];
};
bcv_parser.prototype.get_book_indices = function(books, s) {
var add_index, match, re;
add_index = 0;
re = /([\x1f\x1e])(\d+)(?:\/\d+)?\1/g;
while (match = re.exec(s)) {
books[match[2]].start_index = match.index + add_index;
add_index += books[match[2]].value.length - match[0].length;
}
return books;
};
bcv_parser.prototype.match_passages = function(s) {
var accum, book_id, entities, full, match, next_char, original_part_length, part, passage, post_context, re, ref, regexp_index_adjust, start_index_adjust;
entities = [];
post_context = {};
while (match = this.regexps.escaped_passage.exec(s)) {
full = match[0], part = match[1], book_id = match[2];
original_part_length = part.length;
match.index += full.length - original_part_length;
if (/\s[2-9]\d\d\s*$|\s\d{4,}\s*$/.test(part)) {
re = /\s+\d+\s*$/;
part = part.replace(re, "");
}
if (!/[\d\x1f\x1e)]$/.test(part)) {
part = this.replace_match_end(part);
}
if (this.options.captive_end_digits_strategy === "delete") {
next_char = match.index + part.length;
if (s.length > next_char && /^\w/.test(s.substr(next_char, 1))) {
part = part.replace(/[\s*]+\d+$/, "");
}
part = part.replace(/(\x1e[)\]]?)[\s*]*\d+$/, "$1");
}
part = part.replace(/[A-Z]+/g, function(capitals) {
return capitals.toLowerCase();
});
start_index_adjust = part.substr(0, 1) === "\x1f" ? 0 : part.split("\x1f")[0].length;
passage = {
value: grammar.parse(part),
type: "base",
start_index: this.passage.books[book_id].start_index - start_index_adjust,
match: part
};
if (this.options.book_alone_strategy === "full" && this.options.book_range_strategy === "include" && passage.value[0].type === "b" && (passage.value.length === 1 || (passage.value.length > 1 && passage.value[1].type === "translation_sequence")) && start_index_adjust === 0 && (this.passage.books[book_id].parsed.length === 1 || (this.passage.books[book_id].parsed.length > 1 && this.passage.books[book_id].parsed[1].type === "translation")) && /^[234]/.test(this.passage.books[book_id].parsed[0])) {
this.create_book_range(s, passage, book_id);
}
ref = this.passage.handle_obj(passage), accum = ref[0], post_context = ref[1];
entities = entities.concat(accum);
regexp_index_adjust = this.adjust_regexp_end(accum, original_part_length, part.length);
if (regexp_index_adjust > 0) {
this.regexps.escaped_passage.lastIndex -= regexp_index_adjust;
}
}
return [entities, post_context];
};
bcv_parser.prototype.adjust_regexp_end = function(accum, old_length, new_length) {
var regexp_index_adjust;
regexp_index_adjust = 0;
if (accum.length > 0) {
regexp_index_adjust = old_length - accum[accum.length - 1].indices[1] - 1;
} else if (old_length !== new_length) {
regexp_index_adjust = old_length - new_length;
}
return regexp_index_adjust;
};
bcv_parser.prototype.replace_match_end = function(part) {
var match, remove;
remove = part.length;
while (match = this.regexps.match_end_split.exec(part)) {
remove = match.index + match[0].length;
}
if (remove < part.length) {
part = part.substr(0, remove);
}
return part;
};
bcv_parser.prototype.create_book_range = function(s, passage, book_id) {
var cases, i, k, limit, prev, range_regexp, ref;
cases = [bcv_parser.prototype.regexps.first, bcv_parser.prototype.regexps.second, bcv_parser.prototype.regexps.third];
limit = parseInt(this.passage.books[book_id].parsed[0].substr(0, 1), 10);
for (i = k = 1, ref = limit; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) {
range_regexp = i === limit - 1 ? bcv_parser.prototype.regexps.range_and : bcv_parser.prototype.regexps.range_only;
prev = s.match(RegExp("(?:^|\\W)(" + cases[i - 1] + "\\s*" + range_regexp + "\\s*)\\x1f" + book_id + "\\x1f", "i"));
if (prev != null) {
return this.add_book_range_object(passage, prev, i);
}
}
return false;
};
bcv_parser.prototype.add_book_range_object = function(passage, prev, start_book_number) {
var i, k, length, ref, ref1, results;
length = prev[1].length;
passage.value[0] = {
type: "b_range_pre",
value: [
{
type: "b_pre",
value: start_book_number.toString(),
indices: [prev.index, prev.index + length]
}, passage.value[0]
],
indices: [0, passage.value[0].indices[1] + length]
};
passage.value[0].value[1].indices[0] += length;
passage.value[0].value[1].indices[1] += length;
passage.start_index -= length;
passage.match = prev[1] + passage.match;
if (passage.value.length === 1) {
return;
}
results = [];
for (i = k = 1, ref = passage.value.length; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) {
if (passage.value[i].value == null) {
continue;
}
if (((ref1 = passage.value[i].value[0]) != null ? ref1.indices : void 0) != null) {
passage.value[i].value[0].indices[0] += length;
passage.value[i].value[0].indices[1] += length;
}
passage.value[i].indices[0] += length;
results.push(passage.value[i].indices[1] += length);
}
return results;
};
bcv_parser.prototype.osis = function() {
var k, len, osis, out, ref;
out = [];
ref = this.parsed_entities();
for (k = 0, len = ref.length; k < len; k++) {
osis = ref[k];
if (osis.osis.length > 0) {
out.push(osis.osis);
}
}
return out.join(",");
};
bcv_parser.prototype.osis_and_translations = function() {
var k, len, osis, out, ref;
out = [];
ref = this.parsed_entities();
for (k = 0, len = ref.length; k < len; k++) {
osis = ref[k];
if (osis.osis.length > 0) {
out.push([osis.osis, osis.translations.join(",")]);
}
}
return out;
};
bcv_parser.prototype.osis_and_indices = function() {
var k, len, osis, out, ref;
out = [];
ref = this.parsed_entities();
for (k = 0, len = ref.length; k < len; k++) {
osis = ref[k];
if (osis.osis.length > 0) {
out.push({
osis: osis.osis,
translations: osis.translations,
indices: osis.indices
});
}
}
return out;
};
bcv_parser.prototype.parsed_entities = function() {
var entity, entity_id, i, k, l, last_i, len, len1, length, m, n, osis, osises, out, passage, ref, ref1, ref2, ref3, strings, translation, translation_alias, translation_osis, translations;
out = [];
for (entity_id = k = 0, ref = this.entities.length; 0 <= ref ? k < ref : k > ref; entity_id = 0 <= ref ? ++k : --k) {
entity = this.entities[entity_id];
if (entity.type && entity.type === "translation_sequence" && out.length > 0 && entity_id === out[out.length - 1].entity_id + 1) {
out[out.length - 1].indices[1] = entity.absolute_indices[1];
}
if (entity.passages == null) {
continue;
}
if ((entity.type === "b" && this.options.book_alone_strategy === "ignore") || (entity.type === "b_range" && this.options.book_range_strategy === "ignore") || entity.type === "context") {
continue;
}
translations = [];
translation_alias = null;
if (entity.passages[0].translations != null) {
ref1 = entity.passages[0].translations;
for (l = 0, len = ref1.length; l < len; l++) {
translation = ref1[l];
translation_osis = ((ref2 = translation.osis) != null ? ref2.length : void 0) > 0 ? translation.osis : "";
if (translation_alias == null) {
translation_alias = translation.alias;
}
translations.push(translation_osis);
}
} else {
translations = [""];
translation_alias = "default";
}
osises = [];
length = entity.passages.length;
for (i = m = 0, ref3 = length; 0 <= ref3 ? m < ref3 : m > ref3; i = 0 <= ref3 ? ++m : --m) {
passage = entity.passages[i];
if (passage.type == null) {
passage.type = entity.type;
}
if (passage.valid.valid === false) {
if (this.options.invalid_sequence_strategy === "ignore" && entity.type === "sequence") {
this.snap_sequence("ignore", entity, osises, i, length);
}
if (this.options.invalid_passage_strategy === "ignore") {
continue;
}
}
if ((passage.type === "b" || passage.type === "b_range") && this.options.book_sequence_strategy === "ignore" && entity.type === "sequence") {
this.snap_sequence("book", entity, osises, i, length);
continue;
}
if ((passage.type === "b_range_start" || passage.type === "range_end_b") && this.options.book_range_strategy === "ignore") {
this.snap_range(entity, i);
}
if (passage.absolute_indices == null) {
passage.absolute_indices = entity.absolute_indices;
}
osises.push({
osis: passage.valid.valid ? this.to_osis(passage.start, passage.end, translation_alias) : "",
type: passage.type,
indices: passage.absolute_indices,
translations: translations,
start: passage.start,
end: passage.end,
enclosed_indices: passage.enclosed_absolute_indices,
entity_id: entity_id,
entities: [passage]
});
}
if (osises.length === 0) {
continue;
}
if (osises.length > 1 && this.options.consecutive_combination_strategy === "combine") {
osises = this.combine_consecutive_passages(osises, translation_alias);
}
if (this.options.sequence_combination_strategy === "separate") {
out = out.concat(osises);
} else {
strings = [];
last_i = osises.length - 1;
if ((osises[last_i].enclosed_indices != null) && osises[last_i].enclosed_indices[1] >= 0) {
entity.absolute_indices[1] = osises[last_i].enclosed_indices[1];
}
for (n = 0, len1 = osises.length; n < len1; n++) {
osis = osises[n];
if (osis.osis.length > 0) {
strings.push(osis.osis);
}
}
out.push({
osis: strings.join(","),
indices: entity.absolute_indices,
translations: translations,
entity_id: entity_id,
entities: osises
});
}
}
return out;
};
bcv_parser.prototype.to_osis = function(start, end, translation) {
var osis, out;
if ((end.c == null) && (end.v == null) && start.b === end.b && (start.c == null) && (start.v == null) && this.options.book_alone_strategy === "first_chapter") {
end.c = 1;
}
osis = {
start: "",
end: ""
};
if (start.c == null) {
start.c = 1;
}
if (start.v == null) {
start.v = 1;
}
if (end.c == null) {
if (this.options.passage_existence_strategy.indexOf("c") >= 0 || ((this.passage.translations[translation].chapters[end.b] != null) && this.passage.translations[translation].chapters[end.b].length === 1)) {
end.c = this.passage.translations[translation].chapters[end.b].length;
} else {
end.c = 999;
}
}
if (end.v == null) {
if ((this.passage.translations[translation].chapters[end.b][end.c - 1] != null) && this.options.passage_existence_strategy.indexOf("v") >= 0) {
end.v = this.passage.translations[translation].chapters[end.b][end.c - 1];
} else {
end.v = 999;
}
}
if (this.options.include_apocrypha && this.options.ps151_strategy === "b" && ((start.c === 151 && start.b === "Ps") || (end.c === 151 && end.b === "Ps"))) {
this.fix_ps151(start, end, translation);
}
if (this.options.osis_compaction_strategy === "b" && start.c === 1 && start.v === 1 && end.c === this.passage.translations[translation].chapters[end.b].length && end.v === this.passage.translations[translation].chapters[end.b][end.c - 1]) {
osis.start = start.b;
osis.end = end.b;
} else if (this.options.osis_compaction_strategy.length <= 2 && start.v === 1 && (end.v === 999 || end.v === this.passage.translations[translation].chapters[end.b][end.c - 1])) {
osis.start = start.b + "." + start.c.toString();
osis.end = end.b + "." + end.c.toString();
} else {
osis.start = start.b + "." + start.c.toString() + "." + start.v.toString();
osis.end = end.b + "." + end.c.toString() + "." + end.v.toString();
}
if (osis.start === osis.end) {
out = osis.start;
} else {
out = osis.start + "-" + osis.end;
}
if (start.extra != null) {
out = start.extra + "," + out;
}
if (end.extra != null) {
out += "," + end.extra;
}
return out;
};
bcv_parser.prototype.fix_ps151 = function(start, end, translation) {
var ref;
if (translation !== "default" && (((ref = this.translations[translation]) != null ? ref.chapters["Ps151"] : void 0) == null)) {
this.passage.promote_book_to_translation("Ps151", translation);
}
if (start.c === 151 && start.b === "Ps") {
if (end.c === 151 && end.b === "Ps") {
start.b = "Ps151";
start.c = 1;
end.b = "Ps151";
return end.c = 1;
} else {
start.extra = this.to_osis({
b: "Ps151",
c: 1,
v: start.v
}, {
b: "Ps151",
c: 1,
v: this.passage.translations[translation].chapters["Ps151"][0]
}, translation);
start.b = "Prov";
start.c = 1;
return start.v = 1;
}
} else {
end.extra = this.to_osis({
b: "Ps151",
c: 1,
v: 1
}, {
b: "Ps151",
c: 1,
v: end.v
}, translation);
end.c = 150;
return end.v = this.passage.translations[translation].chapters["Ps"][149];
}
};
bcv_parser.prototype.combine_consecutive_passages = function(osises, translation) {
var enclosed_sequence_start, has_enclosed, i, is_enclosed_last, k, last_i, osis, out, prev, prev_i, ref;
out = [];
prev = {};
last_i = osises.length - 1;
enclosed_sequence_start = -1;
has_enclosed = false;
for (i = k = 0, ref = last_i; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) {
osis = osises[i];
if (osis.osis.length > 0) {
prev_i = out.length - 1;
is_enclosed_last = false;
if (osis.enclosed_indices[0] !== enclosed_sequence_start) {
enclosed_sequence_start = osis.enclosed_indices[0];
}
if (enclosed_sequence_start >= 0 && (i === last_i || osises[i + 1].enclosed_indices[0] !== osis.enclosed_indices[0])) {
is_enclosed_last = true;
has_enclosed = true;
}
if (this.is_verse_consecutive(prev, osis.start, translation)) {
out[prev_i].end = osis.end;
out[prev_i].is_enclosed_last = is_enclosed_last;
out[prev_i].indices[1] = osis.indices[1];
out[prev_i].enclosed_indices[1] = osis.enclosed_indices[1];
out[prev_i].osis = this.to_osis(out[prev_i].start, osis.end, translation);
} else {
out.push(osis);
}
prev = {
b: osis.end.b,
c: osis.end.c,
v: osis.end.v
};
} else {
out.push(osis);
prev = {};
}
}
if (has_enclosed) {
this.snap_enclosed_indices(out);
}
return out;
};
bcv_parser.prototype.snap_enclosed_indices = function(osises) {
var k, len, osis;
for (k = 0, len = osises.length; k < len; k++) {
osis = osises[k];
if (osis.is_enclosed_last != null) {
if (osis.enclosed_indices[0] < 0 && osis.is_enclosed_last) {
osis.indices[1] = osis.enclosed_indices[1];
}
delete osis.is_enclosed_last;
}
}
return osises;
};
bcv_parser.prototype.is_verse_consecutive = function(prev, check, translation) {
var translation_order;
if (prev.b == null) {
return false;
}
translation_order = this.passage.translations[translation].order != null ? this.passage.translations[translation].order : this.passage.translations["default"].order;
if (prev.b === check.b) {
if (prev.c === check.c) {
if (prev.v === check.v - 1) {
return true;
}
} else if (check.v === 1 && prev.c === check.c - 1) {
if (prev.v === this.passage.translations[translation].chapters[prev.b][prev.c - 1]) {
return true;
}
}
} else if (check.c === 1 && check.v === 1 && translation_order[prev.b] === translation_order[check.b] - 1) {
if (prev.c === this.passage.translations[translation].chapters[prev.b].length && prev.v === this.passage.translations[translation].chapters[prev.b][prev.c - 1]) {
return true;
}
}
return false;
};
bcv_parser.prototype.snap_range = function(entity, passage_i) {
var entity_i, key, pluck, ref, source_entity, target_entity, temp, type;
if (entity.type === "b_range_start" || (entity.type === "sequence" && entity.passages[passage_i].type === "b_range_start")) {
entity_i = 1;
source_entity = "end";
type = "b_range_start";
} else {
entity_i = 0;
source_entity = "start";
type = "range_end_b";
}
target_entity = source_entity === "end" ? "start" : "end";
ref = entity.passages[passage_i][target_entity];
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
entity.passages[passage_i][target_entity][key] = entity.passages[passage_i][source_entity][key];
}
if (entity.type === "sequence") {
if (passage_i >= entity.value.length) {
passage_i = entity.value.length - 1;
}
pluck = this.passage.pluck(type, entity.value[passage_i]);
if (pluck != null) {
temp = this.snap_range(pluck, 0);
if (passage_i === 0) {
entity.absolute_indices[0] = temp.absolute_indices[0];
} else {
entity.absolute_indices[1] = temp.absolute_indices[1];
}
}
} else {
entity.original_type = entity.type;
entity.type = entity.value[entity_i].type;
entity.absolute_indices = [entity.value[entity_i].absolute_indices[0], entity.value[entity_i].absolute_indices[1]];
}
return entity;
};
bcv_parser.prototype.snap_sequence = function(type, entity, osises, i, length) {
var passage;
passage = entity.passages[i];
if (passage.absolute_indices[0] === entity.absolute_indices[0] && i < length - 1 && this.get_snap_sequence_i(entity.passages, i, length) !== i) {
entity.absolute_indices[0] = entity.passages[i + 1].absolute_indices[0];
this.remove_absolute_indices(entity.passages, i + 1);
} else if (passage.absolute_indices[1] === entity.absolute_indices[1] && i > 0) {
entity.absolute_indices[1] = osises.length > 0 ? osises[osises.length - 1].indices[1] : entity.passages[i - 1].absolute_indices[1];
} else if (type === "book" && i < length - 1 && !this.starts_with_book(entity.passages[i + 1])) {
entity.passages[i + 1].absolute_indices[0] = passage.absolute_indices[0];
}
return entity;
};
bcv_parser.prototype.get_snap_sequence_i = function(passages, i, length) {
var j, k, ref, ref1;
for (j = k = ref = i + 1, ref1 = length; ref <= ref1 ? k < ref1 : k > ref1; j = ref <= ref1 ? ++k : --k) {
if (this.starts_with_book(passages[j])) {
return j;
}
if (passages[j].valid.valid) {
return i;
}
}
return i;
};
bcv_parser.prototype.starts_with_book = function(passage) {
if (passage.type.substr(0, 1) === "b") {
return true;
}
if ((passage.type === "range" || passage.type === "ff") && passage.start.type.substr(0, 1) === "b") {
return true;
}
return false;
};
bcv_parser.prototype.remove_absolute_indices = function(passages, i) {
var end, k, len, passage, ref, ref1, start;
if (passages[i].enclosed_absolute_indices[0] < 0) {
return false;
}
ref = passages[i].enclosed_absolute_indices, start = ref[0], end = ref[1];
ref1 = passages.slice(i);
for (k = 0, len = ref1.length; k < len; k++) {
passage = ref1[k];
if (passage.enclosed_absolute_indices[0] === start && passage.enclosed_absolute_indices[1] === end) {
passage.enclosed_absolute_indices = [-1, -1];
} else {
break;
}
}
return true;
};
return bcv_parser;
})();
root.bcv_parser = bcv_parser;
bcv_passage = (function() {
function bcv_passage() {}
bcv_passage.prototype.books = [];
bcv_passage.prototype.indices = {};
bcv_passage.prototype.options = {};
bcv_passage.prototype.translations = {};
bcv_passage.prototype.handle_array = function(passages, accum, context) {
var k, len, passage, ref;
if (accum == null) {
accum = [];
}
if (context == null) {
context = {};
}
for (k = 0, len = passages.length; k < len; k++) {
passage = passages[k];
if (passage == null) {
continue;
}
if (passage.type === "stop") {
break;
}
ref = this.handle_obj(passage, accum, context), accum = ref[0], context = ref[1];
}
return [accum, context];
};
bcv_passage.prototype.handle_obj = function(passage, accum, context) {
if ((passage.type != null) && (this[passage.type] != null)) {
return this[passage.type](passage, accum, context);
} else {
return [accum, context];
}
};
bcv_passage.prototype.b = function(passage, accum, context) {
var alternates, b, k, len, obj, ref, valid;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
alternates = [];
ref = this.books[passage.value].parsed;
for (k = 0, len = ref.length; k < len; k++) {
b = ref[k];
valid = this.validate_ref(passage.start_context.translations, {
b: b
});
obj = {
start: {
b: b
},
end: {
b: b
},
valid: valid
};
if (passage.passages.length === 0 && valid.valid) {
passage.passages.push(obj);
} else {
alternates.push(obj);
}
}
if (passage.passages.length === 0) {
passage.passages.push(alternates.shift());
}
if (alternates.length > 0) {
passage.passages[0].alternates = alternates;
}
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
accum.push(passage);
context = {
b: passage.passages[0].start.b
};
if (passage.start_context.translations != null) {
context.translations = passage.start_context.translations;
}
return [accum, context];
};
bcv_passage.prototype.b_range = function(passage, accum, context) {
return this.range(passage, accum, context);
};
bcv_passage.prototype.b_range_pre = function(passage, accum, context) {
var alternates, book, end, ref, ref1, start_obj;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
alternates = [];
book = this.pluck("b", passage.value);
ref = this.b(book, [], context), (ref1 = ref[0], end = ref1[0]), context = ref[1];
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
start_obj = {
b: passage.value[0].value + end.passages[0].start.b.substr(1),
type: "b"
};
passage.passages = [
{
start: start_obj,
end: end.passages[0].end,
valid: end.passages[0].valid
}
];
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.b_range_start = function(passage, accum, context) {
return this.range(passage, accum, context);
};
bcv_passage.prototype.base = function(passage, accum, context) {
this.indices = this.calculate_indices(passage.match, passage.start_index);
return this.handle_array(passage.value, accum, context);
};
bcv_passage.prototype.bc = function(passage, accum, context) {
var alternates, b, c, context_key, k, len, obj, ref, ref1, valid;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
this.reset_context(context, ["b", "c", "v"]);
c = this.pluck("c", passage.value).value;
alternates = [];
ref = this.books[this.pluck("b", passage.value).value].parsed;
for (k = 0, len = ref.length; k < len; k++) {
b = ref[k];
context_key = "c";
valid = this.validate_ref(passage.start_context.translations, {
b: b,
c: c
});
obj = {
start: {
b: b
},
end: {
b: b
},
valid: valid
};
if (valid.messages.start_chapter_not_exist_in_single_chapter_book) {
obj.valid = this.validate_ref(passage.start_context.translations, {
b: b,
v: c
});
obj.valid.messages.start_chapter_not_exist_in_single_chapter_book = 1;
obj.start.c = 1;
obj.end.c = 1;
context_key = "v";
}
obj.start[context_key] = c;
ref1 = this.fix_start_zeroes(obj.valid, obj.start.c, obj.start.v), obj.start.c = ref1[0], obj.start.v = ref1[1];
if (obj.start.v == null) {
delete obj.start.v;
}
obj.end[context_key] = obj.start[context_key];
if (passage.passages.length === 0 && obj.valid.valid) {
passage.passages.push(obj);
} else {
alternates.push(obj);
}
}
if (passage.passages.length === 0) {
passage.passages.push(alternates.shift());
}
if (alternates.length > 0) {
passage.passages[0].alternates = alternates;
}
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
this.set_context_from_object(context, ["b", "c", "v"], passage.passages[0].start);
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.bc_title = function(passage, accum, context) {
var bc, i, k, ref, ref1, ref2, title;
passage.start_context = bcv_utils.shallow_clone(context);
ref = this.bc(this.pluck("bc", passage.value), [], context), (ref1 = ref[0], bc = ref1[0]), context = ref[1];
if (bc.passages[0].start.b.substr(0, 2) !== "Ps" && (bc.passages[0].alternates != null)) {
for (i = k = 0, ref2 = bc.passages[0].alternates.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
if (bc.passages[0].alternates[i].start.b.substr(0, 2) !== "Ps") {
continue;
}
bc.passages[0] = bc.passages[0].alternates[i];
break;
}
}
if (bc.passages[0].start.b.substr(0, 2) !== "Ps") {
accum.push(bc);
return [accum, context];
}
this.books[this.pluck("b", bc.value).value].parsed = ["Ps"];
title = this.pluck("title", passage.value);
if (title == null) {
title = this.pluck("v", passage.value);
}
passage.value[1] = {
type: "v",
value: [
{
type: "integer",
value: 1,
indices: title.indices
}
],
indices: title.indices
};
passage.type = "bcv";
return this.bcv(passage, accum, passage.start_context);
};
bcv_passage.prototype.bcv = function(passage, accum, context) {
var alternates, b, bc, c, k, len, obj, ref, ref1, v, valid;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
this.reset_context(context, ["b", "c", "v"]);
bc = this.pluck("bc", passage.value);
c = this.pluck("c", bc.value).value;
v = this.pluck("v", passage.value).value;
alternates = [];
ref = this.books[this.pluck("b", bc.value).value].parsed;
for (k = 0, len = ref.length; k < len; k++) {
b = ref[k];
valid = this.validate_ref(passage.start_context.translations, {
b: b,
c: c,
v: v
});
ref1 = this.fix_start_zeroes(valid, c, v), c = ref1[0], v = ref1[1];
obj = {
start: {
b: b,
c: c,
v: v
},
end: {
b: b,
c: c,
v: v
},
valid: valid
};
if (passage.passages.length === 0 && valid.valid) {
passage.passages.push(obj);
} else {
alternates.push(obj);
}
}
if (passage.passages.length === 0) {
passage.passages.push(alternates.shift());
}
if (alternates.length > 0) {
passage.passages[0].alternates = alternates;
}
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
this.set_context_from_object(context, ["b", "c", "v"], passage.passages[0].start);
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.bv = function(passage, accum, context) {
var b, bcv, ref, ref1, ref2, v;
passage.start_context = bcv_utils.shallow_clone(context);
ref = passage.value, b = ref[0], v = ref[1];
bcv = {
indices: passage.indices,
value: [
{
type: "bc",
value: [
b, {
type: "c",
value: [
{
type: "integer",
value: 1
}
]
}
]
}, v
]
};
ref1 = this.bcv(bcv, [], context), (ref2 = ref1[0], bcv = ref2[0]), context = ref1[1];
passage.passages = bcv.passages;
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.c = function(passage, accum, context) {
var c, valid;
passage.start_context = bcv_utils.shallow_clone(context);
c = passage.type === "integer" ? passage.value : this.pluck("integer", passage.value).value;
valid = this.validate_ref(passage.start_context.translations, {
b: context.b,
c: c
});
if (!valid.valid && valid.messages.start_chapter_not_exist_in_single_chapter_book) {
return this.v(passage, accum, context);
}
c = this.fix_start_zeroes(valid, c)[0];
passage.passages = [
{
start: {
b: context.b,
c: c
},
end: {
b: context.b,
c: c
},
valid: valid
}
];
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
accum.push(passage);
context.c = c;
this.reset_context(context, ["v"]);
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
return [accum, context];
};
bcv_passage.prototype.c_psalm = function(passage, accum, context) {
var c;
passage.type = "bc";
c = parseInt(this.books[passage.value].value.match(/^\d+/)[0], 10);
passage.value = [
{
type: "b",
value: passage.value,
indices: passage.indices
}, {
type: "c",
value: [
{
type: "integer",
value: c,
indices: passage.indices
}
],
indices: passage.indices
}
];
return this.bc(passage, accum, context);
};
bcv_passage.prototype.c_title = function(passage, accum, context) {
var title;
passage.start_context = bcv_utils.shallow_clone(context);
if (context.b !== "Ps") {
return this.c(passage.value[0], accum, context);
}
title = this.pluck("title", passage.value);
passage.value[1] = {
type: "v",
value: [
{
type: "integer",
value: 1,
indices: title.indices
}
],
indices: title.indices
};
passage.type = "cv";
return this.cv(passage, accum, passage.start_context);
};
bcv_passage.prototype.cv = function(passage, accum, context) {
var c, ref, v, valid;
passage.start_context = bcv_utils.shallow_clone(context);
c = this.pluck("c", passage.value).value;
v = this.pluck("v", passage.value).value;
valid = this.validate_ref(passage.start_context.translations, {
b: context.b,
c: c,
v: v
});
ref = this.fix_start_zeroes(valid, c, v), c = ref[0], v = ref[1];
passage.passages = [
{
start: {
b: context.b,
c: c,
v: v
},
end: {
b: context.b,
c: c,
v: v
},
valid: valid
}
];
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
accum.push(passage);
context.c = c;
context.v = v;
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
return [accum, context];
};
bcv_passage.prototype.cb_range = function(passage, accum, context) {
var b, end_c, ref, start_c;
passage.type = "range";
ref = passage.value, b = ref[0], start_c = ref[1], end_c = ref[2];
passage.value = [
{
type: "bc",
value: [b, start_c],
indices: passage.indices
}, end_c
];
end_c.indices[1] = passage.indices[1];
return this.range(passage, accum, context);
};
bcv_passage.prototype.context = function(passage, accum, context) {
var key, ref;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
ref = this.books[passage.value].context;
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
context[key] = this.books[passage.value].context[key];
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.cv_psalm = function(passage, accum, context) {
var bc, c_psalm, ref, v;
passage.start_context = bcv_utils.shallow_clone(context);
passage.type = "bcv";
ref = passage.value, c_psalm = ref[0], v = ref[1];
bc = this.c_psalm(c_psalm, [], passage.start_context)[0][0];
passage.value = [bc, v];
return this.bcv(passage, accum, context);
};
bcv_passage.prototype.ff = function(passage, accum, context) {
var ref, ref1;
passage.start_context = bcv_utils.shallow_clone(context);
passage.value.push({
type: "integer",
indices: passage.indices,
value: 999
});
ref = this.range(passage, [], passage.start_context), (ref1 = ref[0], passage = ref1[0]), context = ref[1];
passage.value[0].indices = passage.value[1].indices;
passage.value[0].absolute_indices = passage.value[1].absolute_indices;
passage.value.pop();
if (passage.passages[0].valid.messages.end_verse_not_exist != null) {
delete passage.passages[0].valid.messages.end_verse_not_exist;
}
if (passage.passages[0].valid.messages.end_chapter_not_exist != null) {
delete passage.passages[0].valid.messages.end_chapter_not_exist;
}
if (passage.passages[0].end.original_c != null) {
delete passage.passages[0].end.original_c;
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.integer_title = function(passage, accum, context) {
var v_indices;
passage.start_context = bcv_utils.shallow_clone(context);
if (context.b !== "Ps") {
return this.integer(passage.value[0], accum, context);
}
passage.value[0] = {
type: "c",
value: [passage.value[0]],
indices: [passage.value[0].indices[0], passage.value[0].indices[1]]
};
v_indices = [passage.indices[1] - 5, passage.indices[1]];
passage.value[1] = {
type: "v",
value: [
{
type: "integer",
value: 1,
indices: v_indices
}
],
indices: v_indices
};
passage.type = "cv";
return this.cv(passage, accum, passage.start_context);
};
bcv_passage.prototype.integer = function(passage, accum, context) {
if (context.v != null) {
return this.v(passage, accum, context);
}
return this.c(passage, accum, context);
};
bcv_passage.prototype.sequence = function(passage, accum, context) {
var k, l, len, len1, obj, psg, ref, ref1, ref2, ref3, sub_psg;
passage.start_context = bcv_utils.shallow_clone(context);
passage.passages = [];
ref = passage.value;
for (k = 0, len = ref.length; k < len; k++) {
obj = ref[k];
ref1 = this.handle_array(obj, [], context), (ref2 = ref1[0], psg = ref2[0]), context = ref1[1];
ref3 = psg.passages;
for (l = 0, len1 = ref3.length; l < len1; l++) {
sub_psg = ref3[l];
if (sub_psg.type == null) {
sub_psg.type = psg.type;
}
if (sub_psg.absolute_indices == null) {
sub_psg.absolute_indices = psg.absolute_indices;
}
if (psg.start_context.translations != null) {
sub_psg.translations = psg.start_context.translations;
}
sub_psg.enclosed_absolute_indices = psg.type === "sequence_post_enclosed" ? psg.absolute_indices : [-1, -1];
passage.passages.push(sub_psg);
}
}
if (passage.absolute_indices == null) {
if (passage.passages.length > 0 && passage.type === "sequence") {
passage.absolute_indices = [passage.passages[0].absolute_indices[0], passage.passages[passage.passages.length - 1].absolute_indices[1]];
} else {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.sequence_post_enclosed = function(passage, accum, context) {
return this.sequence(passage, accum, context);
};
bcv_passage.prototype.v = function(passage, accum, context) {
var c, no_c, ref, v, valid;
v = passage.type === "integer" ? passage.value : this.pluck("integer", passage.value).value;
passage.start_context = bcv_utils.shallow_clone(context);
c = context.c != null ? context.c : 1;
valid = this.validate_ref(passage.start_context.translations, {
b: context.b,
c: c,
v: v
});
ref = this.fix_start_zeroes(valid, 0, v), no_c = ref[0], v = ref[1];
passage.passages = [
{
start: {
b: context.b,
c: c,
v: v
},
end: {
b: context.b,
c: c,
v: v
},
valid: valid
}
];
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
accum.push(passage);
context.v = v;
return [accum, context];
};
bcv_passage.prototype.range = function(passage, accum, context) {
var end, end_obj, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, return_now, return_value, start, start_obj, valid;
passage.start_context = bcv_utils.shallow_clone(context);
ref = passage.value, start = ref[0], end = ref[1];
ref1 = this.handle_obj(start, [], context), (ref2 = ref1[0], start = ref2[0]), context = ref1[1];
if (end.type === "v" && ((start.type === "bc" && !((ref3 = start.passages) != null ? (ref4 = ref3[0]) != null ? (ref5 = ref4.valid) != null ? (ref6 = ref5.messages) != null ? ref6.start_chapter_not_exist_in_single_chapter_book : void 0 : void 0 : void 0 : void 0)) || start.type === "c") && this.options.end_range_digits_strategy === "verse") {
passage.value[0] = start;
return this.range_change_integer_end(passage, accum);
}
ref7 = this.handle_obj(end, [], context), (ref8 = ref7[0], end = ref8[0]), context = ref7[1];
passage.value = [start, end];
passage.indices = [start.indices[0], end.indices[1]];
delete passage.absolute_indices;
start_obj = {
b: start.passages[0].start.b,
c: start.passages[0].start.c,
v: start.passages[0].start.v,
type: start.type
};
end_obj = {
b: end.passages[0].end.b,
c: end.passages[0].end.c,
v: end.passages[0].end.v,
type: end.type
};
if (end.passages[0].valid.messages.start_chapter_is_zero) {
end_obj.c = 0;
}
if (end.passages[0].valid.messages.start_verse_is_zero) {
end_obj.v = 0;
}
valid = this.validate_ref(passage.start_context.translations, start_obj, end_obj);
if (valid.valid) {
ref9 = this.range_handle_valid(valid, passage, start, start_obj, end, end_obj, accum), return_now = ref9[0], return_value = ref9[1];
if (return_now) {
return return_value;
}
} else {
return this.range_handle_invalid(valid, passage, start, start_obj, end, end_obj, accum);
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
passage.passages = [
{
start: start_obj,
end: end_obj,
valid: valid
}
];
if (passage.start_context.translations != null) {
passage.passages[0].translations = passage.start_context.translations;
}
if (start_obj.type === "b") {
if (end_obj.type === "b") {
passage.type = "b_range";
} else {
passage.type = "b_range_start";
}
} else if (end_obj.type === "b") {
passage.type = "range_end_b";
}
accum.push(passage);
return [accum, context];
};
bcv_passage.prototype.range_change_end = function(passage, accum, new_end) {
var end, new_obj, ref, start;
ref = passage.value, start = ref[0], end = ref[1];
if (end.type === "integer") {
end.original_value = end.value;
end.value = new_end;
} else if (end.type === "v") {
new_obj = this.pluck("integer", end.value);
new_obj.original_value = new_obj.value;
new_obj.value = new_end;
} else if (end.type === "cv") {
new_obj = this.pluck("c", end.value);
new_obj.original_value = new_obj.value;
new_obj.value = new_end;
}
return this.handle_obj(passage, accum, passage.start_context);
};
bcv_passage.prototype.range_change_integer_end = function(passage, accum) {
var end, ref, start;
ref = passage.value, start = ref[0], end = ref[1];
if (passage.original_type == null) {
passage.original_type = passage.type;
}
if (passage.original_value == null) {
passage.original_value = [start, end];
}
passage.type = start.type === "integer" ? "cv" : start.type + "v";
if (start.type === "integer") {
passage.value[0] = {
type: "c",
value: [start],
indices: start.indices
};
}
if (end.type === "integer") {
passage.value[1] = {
type: "v",
value: [end],
indices: end.indices
};
}
return this.handle_obj(passage, accum, passage.start_context);
};
bcv_passage.prototype.range_check_new_end = function(translations, start_obj, end_obj, valid) {
var new_end, new_valid, obj_to_validate, type;
new_end = 0;
type = null;
if (valid.messages.end_chapter_before_start) {
type = "c";
} else if (valid.messages.end_verse_before_start) {
type = "v";
}
if (type != null) {
new_end = this.range_get_new_end_value(start_obj, end_obj, valid, type);
}
if (new_end > 0) {
obj_to_validate = {
b: end_obj.b,
c: end_obj.c,
v: end_obj.v
};
obj_to_validate[type] = new_end;
new_valid = this.validate_ref(translations, obj_to_validate);
if (!new_valid.valid) {
new_end = 0;
}
}
return new_end;
};
bcv_passage.prototype.range_end_b = function(passage, accum, context) {
return this.range(passage, accum, context);
};
bcv_passage.prototype.range_get_new_end_value = function(start_obj, end_obj, valid, key) {
var new_end;
new_end = 0;
if ((key === "c" && valid.messages.end_chapter_is_zero) || (key === "v" && valid.messages.end_verse_is_zero)) {
return new_end;
}
if (start_obj[key] >= 10 && end_obj[key] < 10 && start_obj[key] - 10 * Math.floor(start_obj[key] / 10) < end_obj[key]) {
new_end = end_obj[key] + 10 * Math.floor(start_obj[key] / 10);
} else if (start_obj[key] >= 100 && end_obj[key] < 100 && start_obj[key] - 100 < end_obj[key]) {
new_end = end_obj[key] + 100;
}
return new_end;
};
bcv_passage.prototype.range_handle_invalid = function(valid, passage, start, start_obj, end, end_obj, accum) {
var new_end, ref, temp_valid, temp_value;
if (valid.valid === false && (valid.messages.end_chapter_before_start || valid.messages.end_verse_before_start) && (end.type === "integer" || end.type === "v") || (valid.valid === false && valid.messages.end_chapter_before_start && end.type === "cv")) {
new_end = this.range_check_new_end(passage.start_context.translations, start_obj, end_obj, valid);
if (new_end > 0) {
return this.range_change_end(passage, accum, new_end);
}
}
if (this.options.end_range_digits_strategy === "verse" && (start_obj.v == null) && (end.type === "integer" || end.type === "v")) {
temp_value = end.type === "v" ? this.pluck("integer", end.value) : end.value;
temp_valid = this.validate_ref(passage.start_context.translations, {
b: start_obj.b,
c: start_obj.c,
v: temp_value
});
if (temp_valid.valid) {
return this.range_change_integer_end(passage, accum);
}
}
if (passage.original_type == null) {
passage.original_type = passage.type;
}
passage.type = "sequence";
ref = [[start, end], [[start], [end]]], passage.original_value = ref[0], passage.value = ref[1];
return this.sequence(passage, accum, passage.start_context);
};
bcv_passage.prototype.range_handle_valid = function(valid, passage, start, start_obj, end, end_obj, accum) {
var temp_valid, temp_value;
if (valid.messages.end_chapter_not_exist && this.options.end_range_digits_strategy === "verse" && (start_obj.v == null) && (end.type === "integer" || end.type === "v") && this.options.passage_existence_strategy.indexOf("v") >= 0) {
temp_value = end.type === "v" ? this.pluck("integer", end.value) : end.value;
temp_valid = this.validate_ref(passage.start_context.translations, {
b: start_obj.b,
c: start_obj.c,
v: temp_value
});
if (temp_valid.valid) {
return [true, this.range_change_integer_end(passage, accum)];
}
}
this.range_validate(valid, start_obj, end_obj, passage);
return [false, null];
};
bcv_passage.prototype.range_validate = function(valid, start_obj, end_obj, passage) {
var ref;
if (valid.messages.end_chapter_not_exist || valid.messages.end_chapter_not_exist_in_single_chapter_book) {
end_obj.original_c = end_obj.c;
end_obj.c = valid.messages.end_chapter_not_exist ? valid.messages.end_chapter_not_exist : valid.messages.end_chapter_not_exist_in_single_chapter_book;
if (end_obj.v != null) {
end_obj.v = this.validate_ref(passage.start_context.translations, {
b: end_obj.b,
c: end_obj.c,
v: 999
}).messages.end_verse_not_exist;
delete valid.messages.end_verse_is_zero;
}
} else if (valid.messages.end_verse_not_exist) {
end_obj.original_v = end_obj.v;
end_obj.v = valid.messages.end_verse_not_exist;
}
if (valid.messages.end_verse_is_zero && this.options.zero_verse_strategy !== "allow") {
end_obj.v = valid.messages.end_verse_is_zero;
}
if (valid.messages.end_chapter_is_zero) {
end_obj.c = valid.messages.end_chapter_is_zero;
}
ref = this.fix_start_zeroes(valid, start_obj.c, start_obj.v), start_obj.c = ref[0], start_obj.v = ref[1];
return true;
};
bcv_passage.prototype.translation_sequence = function(passage, accum, context) {
var k, l, len, len1, ref, translation, translations, val;
passage.start_context = bcv_utils.shallow_clone(context);
translations = [];
translations.push({
translation: this.books[passage.value[0].value].parsed
});
ref = passage.value[1];
for (k = 0, len = ref.length; k < len; k++) {
val = ref[k];
val = this.books[this.pluck("translation", val).value].parsed;
if (val != null) {
translations.push({
translation: val
});
}
}
for (l = 0, len1 = translations.length; l < len1; l++) {
translation = translations[l];
if (this.translations.aliases[translation.translation] != null) {
translation.alias = this.translations.aliases[translation.translation].alias;
translation.osis = this.translations.aliases[translation.translation].osis || "";
} else {
translation.alias = "default";
translation.osis = translation.translation.toUpperCase();
}
}
if (accum.length > 0) {
context = this.translation_sequence_apply(accum, translations);
}
if (passage.absolute_indices == null) {
passage.absolute_indices = this.get_absolute_indices(passage.indices);
}
accum.push(passage);
this.reset_context(context, ["translations"]);
return [accum, context];
};
bcv_passage.prototype.translation_sequence_apply = function(accum, translations) {
var context, i, k, new_accum, ref, ref1, use_i;
use_i = 0;
for (i = k = ref = accum.length - 1; ref <= 0 ? k <= 0 : k >= 0; i = ref <= 0 ? ++k : --k) {
if (accum[i].original_type != null) {
accum[i].type = accum[i].original_type;
}
if (accum[i].original_value != null) {
accum[i].value = accum[i].original_value;
}
if (accum[i].type !== "translation_sequence") {
continue;
}
use_i = i + 1;
break;
}
if (use_i < accum.length) {
accum[use_i].start_context.translations = translations;
ref1 = this.handle_array(accum.slice(use_i), [], accum[use_i].start_context), new_accum = ref1[0], context = ref1[1];
} else {
context = bcv_utils.shallow_clone(accum[accum.length - 1].start_context);
}
return context;
};
bcv_passage.prototype.pluck = function(type, passages) {
var k, len, passage;
for (k = 0, len = passages.length; k < len; k++) {
passage = passages[k];
if (!((passage != null) && (passage.type != null) && passage.type === type)) {
continue;
}
if (type === "c" || type === "v") {
return this.pluck("integer", passage.value);
}
return passage;
}
return null;
};
bcv_passage.prototype.set_context_from_object = function(context, keys, obj) {
var k, len, results, type;
results = [];
for (k = 0, len = keys.length; k < len; k++) {
type = keys[k];
if (obj[type] == null) {
continue;
}
results.push(context[type] = obj[type]);
}
return results;
};
bcv_passage.prototype.reset_context = function(context, keys) {
var k, len, results, type;
results = [];
for (k = 0, len = keys.length; k < len; k++) {
type = keys[k];
results.push(delete context[type]);
}
return results;
};
bcv_passage.prototype.fix_start_zeroes = function(valid, c, v) {
if (valid.messages.start_chapter_is_zero && this.options.zero_chapter_strategy === "upgrade") {
c = valid.messages.start_chapter_is_zero;
}
if (valid.messages.start_verse_is_zero && this.options.zero_verse_strategy === "upgrade") {
v = valid.messages.start_verse_is_zero;
}
return [c, v];
};
bcv_passage.prototype.calculate_indices = function(match, adjust) {
var character, end_index, indices, k, l, len, len1, len2, m, match_index, part, part_length, parts, ref, switch_type, temp;
switch_type = "book";
indices = [];
match_index = 0;
adjust = parseInt(adjust, 10);
parts = [match];
ref = ["\x1e", "\x1f"];
for (k = 0, len = ref.length; k < len; k++) {
character = ref[k];
temp = [];
for (l = 0, len1 = parts.length; l < len1; l++) {
part = parts[l];
temp = temp.concat(part.split(character));
}
parts = temp;
}
for (m = 0, len2 = parts.length; m < len2; m++) {
part = parts[m];
switch_type = switch_type === "book" ? "rest" : "book";
part_length = part.length;
if (part_length === 0) {
continue;
}
if (switch_type === "book") {
part = part.replace(/\/\d+$/, "");
end_index = match_index + part_length;
if (indices.length > 0 && indices[indices.length - 1].index === adjust) {
indices[indices.length - 1].end = end_index;
} else {
indices.push({
start: match_index,
end: end_index,
index: adjust
});
}
match_index += part_length + 2;
adjust = this.books[part].start_index + this.books[part].value.length - match_index;
indices.push({
start: end_index + 1,
end: end_index + 1,
index: adjust
});
} else {
end_index = match_index + part_length - 1;
if (indices.length > 0 && indices[indices.length - 1].index === adjust) {
indices[indices.length - 1].end = end_index;
} else {
indices.push({
start: match_index,
end: end_index,
index: adjust
});
}
match_index += part_length;
}
}
return indices;
};
bcv_passage.prototype.get_absolute_indices = function(arg1) {
var end, end_out, index, k, len, ref, start, start_out;
start = arg1[0], end = arg1[1];
start_out = null;
end_out = null;
ref = this.indices;
for (k = 0, len = ref.length; k < len; k++) {
index = ref[k];
if (start_out === null && (index.start <= start && start <= index.end)) {
start_out = start + index.index;
}
if ((index.start <= end && end <= index.end)) {
end_out = end + index.index + 1;
break;
}
}
return [start_out, end_out];
};
bcv_passage.prototype.validate_ref = function(translations, start, end) {
var k, len, messages, temp_valid, translation, valid;
if (!((translations != null) && translations.length > 0)) {
translations = [
{
translation: "default",
osis: "",
alias: "default"
}
];
}
valid = false;
messages = {};
for (k = 0, len = translations.length; k < len; k++) {
translation = translations[k];
if (translation.alias == null) {
translation.alias = "default";
}
if (translation.alias == null) {
if (messages.translation_invalid == null) {
messages.translation_invalid = [];
}
messages.translation_invalid.push(translation);
continue;
}
if (this.translations.aliases[translation.alias] == null) {
translation.alias = "default";
if (messages.translation_unknown == null) {
messages.translation_unknown = [];
}
messages.translation_unknown.push(translation);
}
temp_valid = this.validate_start_ref(translation.alias, start, messages)[0];
if (end) {
temp_valid = this.validate_end_ref(translation.alias, start, end, temp_valid, messages)[0];
}
if (temp_valid === true) {
valid = true;
}
}
return {
valid: valid,
messages: messages
};
};
bcv_passage.prototype.validate_start_ref = function(translation, start, messages) {
var ref, ref1, translation_order, valid;
valid = true;
if (translation !== "default" && (((ref = this.translations[translation]) != null ? ref.chapters[start.b] : void 0) == null)) {
this.promote_book_to_translation(start.b, translation);
}
translation_order = ((ref1 = this.translations[translation]) != null ? ref1.order : void 0) != null ? translation : "default";
if (start.v != null) {
start.v = parseInt(start.v, 10);
}
if (this.translations[translation_order].order[start.b] != null) {
if (start.c == null) {
start.c = 1;
}
start.c = parseInt(start.c, 10);
if (isNaN(start.c)) {
valid = false;
messages.start_chapter_not_numeric = true;
return [valid, messages];
}
if (start.c === 0) {
messages.start_chapter_is_zero = 1;
if (this.options.zero_chapter_strategy === "error") {
valid = false;
} else {
start.c = 1;
}
}
if ((start.v != null) && start.v === 0) {
messages.start_verse_is_zero = 1;
if (this.options.zero_verse_strategy === "error") {
valid = false;
} else if (this.options.zero_verse_strategy === "upgrade") {
start.v = 1;
}
}
if (start.c > 0 && (this.translations[translation].chapters[start.b][start.c - 1] != null)) {
if (start.v != null) {
if (isNaN(start.v)) {
valid = false;
messages.start_verse_not_numeric = true;
} else if (start.v > this.translations[translation].chapters[start.b][start.c - 1]) {
if (this.options.passage_existence_strategy.indexOf("v") >= 0) {
valid = false;
messages.start_verse_not_exist = this.translations[translation].chapters[start.b][start.c - 1];
}
}
}
} else {
if (start.c !== 1 && this.translations[translation].chapters[start.b].length === 1) {
valid = false;
messages.start_chapter_not_exist_in_single_chapter_book = 1;
} else if (start.c > 0 && this.options.passage_existence_strategy.indexOf("c") >= 0) {
valid = false;
messages.start_chapter_not_exist = this.translations[translation].chapters[start.b].length;
}
}
} else {
if (this.options.passage_existence_strategy.indexOf("b") >= 0) {
valid = false;
}
messages.start_book_not_exist = true;
}
return [valid, messages];
};
bcv_passage.prototype.validate_end_ref = function(translation, start, end, valid, messages) {
var ref, translation_order;
translation_order = ((ref = this.translations[translation]) != null ? ref.order : void 0) != null ? translation : "default";
if (end.c != null) {
end.c = parseInt(end.c, 10);
if (isNaN(end.c)) {
valid = false;
messages.end_chapter_not_numeric = true;
} else if (end.c === 0) {
messages.end_chapter_is_zero = 1;
if (this.options.zero_chapter_strategy === "error") {
valid = false;
} else {
end.c = 1;
}
}
}
if (end.v != null) {
end.v = parseInt(end.v, 10);
if (isNaN(end.v)) {
valid = false;
messages.end_verse_not_numeric = true;
} else if (end.v === 0) {
messages.end_verse_is_zero = 1;
if (this.options.zero_verse_strategy === "error") {
valid = false;
} else if (this.options.zero_verse_strategy === "upgrade") {
end.v = 1;
}
}
}
if (this.translations[translation_order].order[end.b] != null) {
if ((end.c == null) && this.translations[translation].chapters[end.b].length === 1) {
end.c = 1;
}
if ((this.translations[translation_order].order[start.b] != null) && this.translations[translation_order].order[start.b] > this.translations[translation_order].order[end.b]) {
if (this.options.passage_existence_strategy.indexOf("b") >= 0) {
valid = false;
}
messages.end_book_before_start = true;
}
if (start.b === end.b && (end.c != null) && !isNaN(end.c)) {
if (start.c == null) {
start.c = 1;
}
if (!isNaN(parseInt(start.c, 10)) && start.c > end.c) {
valid = false;
messages.end_chapter_before_start = true;
} else if (start.c === end.c && (end.v != null) && !isNaN(end.v)) {
if (start.v == null) {
start.v = 1;
}
if (!isNaN(parseInt(start.v, 10)) && start.v > end.v) {
valid = false;
messages.end_verse_before_start = true;
}
}
}
if ((end.c != null) && !isNaN(end.c)) {
if (this.translations[translation].chapters[end.b][end.c - 1] == null) {
if (this.translations[translation].chapters[end.b].length === 1) {
messages.end_chapter_not_exist_in_single_chapter_book = 1;
} else if (end.c > 0 && this.options.passage_existence_strategy.indexOf("c") >= 0) {
messages.end_chapter_not_exist = this.translations[translation].chapters[end.b].length;
}
}
}
if ((end.v != null) && !isNaN(end.v)) {
if (end.c == null) {
end.c = this.translations[translation].chapters[end.b].length;
}
if (end.v > this.translations[translation].chapters[end.b][end.c - 1] && this.options.passage_existence_strategy.indexOf("v") >= 0) {
messages.end_verse_not_exist = this.translations[translation].chapters[end.b][end.c - 1];
}
}
} else {
valid = false;
messages.end_book_not_exist = true;
}
return [valid, messages];
};
bcv_passage.prototype.promote_book_to_translation = function(book, translation) {
var base, base1;
if ((base = this.translations)[translation] == null) {
base[translation] = {};
}
if ((base1 = this.translations[translation]).chapters == null) {
base1.chapters = {};
}
if (this.translations[translation].chapters[book] == null) {
return this.translations[translation].chapters[book] = bcv_utils.shallow_clone_array(this.translations["default"].chapters[book]);
}
};
return bcv_passage;
})();
bcv_utils = {
shallow_clone: function(obj) {
var key, out, val;
if (obj == null) {
return obj;
}
out = {};
for (key in obj) {
if (!hasProp.call(obj, key)) continue;
val = obj[key];
out[key] = val;
}
return out;
},
shallow_clone_array: function(arr) {
var i, k, out, ref;
if (arr == null) {
return arr;
}
out = [];
for (i = k = 0, ref = arr.length; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) {
if (typeof arr[i] !== "undefined") {
out[i] = arr[i];
}
}
return out;
}
};
bcv_parser.prototype.regexps.translations = /(?:APSD)\b/gi;
bcv_parser.prototype.translations = {
aliases: {
"default": {
osis: "",
alias: "default"
}
},
alternates: {},
"default": {
order: {
"Gen": 1,
"Exod": 2,
"Lev": 3,
"Num": 4,
"Deut": 5,
"Josh": 6,
"Judg": 7,
"Ruth": 8,
"1Sam": 9,
"2Sam": 10,
"1Kgs": 11,
"2Kgs": 12,
"1Chr": 13,
"2Chr": 14,
"Ezra": 15,
"Neh": 16,
"Esth": 17,
"Job": 18,
"Ps": 19,
"Prov": 20,
"Eccl": 21,
"Song": 22,
"Isa": 23,
"Jer": 24,
"Lam": 25,
"Ezek": 26,
"Dan": 27,
"Hos": 28,
"Joel": 29,
"Amos": 30,
"Obad": 31,
"Jonah": 32,
"Mic": 33,
"Nah": 34,
"Hab": 35,
"Zeph": 36,
"Hag": 37,
"Zech": 38,
"Mal": 39,
"Matt": 40,
"Mark": 41,
"Luke": 42,
"John": 43,
"Acts": 44,
"Rom": 45,
"1Cor": 46,
"2Cor": 47,
"Gal": 48,
"Eph": 49,
"Phil": 50,
"Col": 51,
"1Thess": 52,
"2Thess": 53,
"1Tim": 54,
"2Tim": 55,
"Titus": 56,
"Phlm": 57,
"Heb": 58,
"Jas": 59,
"1Pet": 60,
"2Pet": 61,
"1John": 62,
"2John": 63,
"3John": 64,
"Jude": 65,
"Rev": 66,
"Tob": 67,
"Jdt": 68,
"GkEsth": 69,
"Wis": 70,
"Sir": 71,
"Bar": 72,
"PrAzar": 73,
"Sus": 74,
"Bel": 75,
"SgThree": 76,
"EpJer": 77,
"1Macc": 78,
"2Macc": 79,
"3Macc": 80,
"4Macc": 81,
"1Esd": 82,
"2Esd": 83,
"PrMan": 84
},
chapters: {
"Gen": [31, 25, 24, 26, 32, 22, 24, 22, 29, 32, 32, 20, 18, 24, 21, 16, 27, 33, 38, 18, 34, 24, 20, 67, 34, 35, 46, 22, 35, 43, 55, 32, 20, 31, 29, 43, 36, 30, 23, 23, 57, 38, 34, 34, 28, 34, 31, 22, 33, 26],
"Exod": [22, 25, 22, 31, 23, 30, 25, 32, 35, 29, 10, 51, 22, 31, 27, 36, 16, 27, 25, 26, 36, 31, 33, 18, 40, 37, 21, 43, 46, 38, 18, 35, 23, 35, 35, 38, 29, 31, 43, 38],
"Lev": [17, 16, 17, 35, 19, 30, 38, 36, 24, 20, 47, 8, 59, 57, 33, 34, 16, 30, 37, 27, 24, 33, 44, 23, 55, 46, 34],
"Num": [54, 34, 51, 49, 31, 27, 89, 26, 23, 36, 35, 16, 33, 45, 41, 50, 13, 32, 22, 29, 35, 41, 30, 25, 18, 65, 23, 31, 40, 16, 54, 42, 56, 29, 34, 13],
"Deut": [46, 37, 29, 49, 33, 25, 26, 20, 29, 22, 32, 32, 18, 29, 23, 22, 20, 22, 21, 20, 23, 30, 25, 22, 19, 19, 26, 68, 29, 20, 30, 52, 29, 12],
"Josh": [18, 24, 17, 24, 15, 27, 26, 35, 27, 43, 23, 24, 33, 15, 63, 10, 18, 28, 51, 9, 45, 34, 16, 33],
"Judg": [36, 23, 31, 24, 31, 40, 25, 35, 57, 18, 40, 15, 25, 20, 20, 31, 13, 31, 30, 48, 25],
"Ruth": [22, 23, 18, 22],
"1Sam": [28, 36, 21, 22, 12, 21, 17, 22, 27, 27, 15, 25, 23, 52, 35, 23, 58, 30, 24, 42, 15, 23, 29, 22, 44, 25, 12, 25, 11, 31, 13],
"2Sam": [27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 33, 43, 26, 22, 51, 39, 25],
"1Kgs": [53, 46, 28, 34, 18, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 53],
"2Kgs": [18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 21, 21, 25, 29, 38, 20, 41, 37, 37, 21, 26, 20, 37, 20, 30],
"1Chr": [54, 55, 24, 43, 26, 81, 40, 40, 44, 14, 47, 40, 14, 17, 29, 43, 27, 17, 19, 8, 30, 19, 32, 31, 31, 32, 34, 21, 30],
"2Chr": [17, 18, 17, 22, 14, 42, 22, 18, 31, 19, 23, 16, 22, 15, 19, 14, 19, 34, 11, 37, 20, 12, 21, 27, 28, 23, 9, 27, 36, 27, 21, 33, 25, 33, 27, 23],
"Ezra": [11, 70, 13, 24, 17, 22, 28, 36, 15, 44],
"Neh": [11, 20, 32, 23, 19, 19, 73, 18, 38, 39, 36, 47, 31],
"Esth": [22, 23, 15, 17, 14, 14, 10, 17, 32, 3],
"Job": [22, 13, 26, 21, 27, 30, 21, 22, 35, 22, 20, 25, 28, 22, 35, 22, 16, 21, 29, 29, 34, 30, 17, 25, 6, 14, 23, 28, 25, 31, 40, 22, 33, 37, 16, 33, 24, 41, 30, 24, 34, 17],
"Ps": [6, 12, 8, 8, 12, 10, 17, 9, 20, 18, 7, 8, 6, 7, 5, 11, 15, 50, 14, 9, 13, 31, 6, 10, 22, 12, 14, 9, 11, 12, 24, 11, 22, 22, 28, 12, 40, 22, 13, 17, 13, 11, 5, 26, 17, 11, 9, 14, 20, 23, 19, 9, 6, 7, 23, 13, 11, 11, 17, 12, 8, 12, 11, 10, 13, 20, 7, 35, 36, 5, 24, 20, 28, 23, 10, 12, 20, 72, 13, 19, 16, 8, 18, 12, 13, 17, 7, 18, 52, 17, 16, 15, 5, 23, 11, 13, 12, 9, 9, 5, 8, 28, 22, 35, 45, 48, 43, 13, 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 13, 10, 7, 12, 15, 21, 10, 20, 14, 9, 6],
"Prov": [33, 22, 35, 27, 23, 35, 27, 36, 18, 32, 31, 28, 25, 35, 33, 33, 28, 24, 29, 30, 31, 29, 35, 34, 28, 28, 27, 28, 27, 33, 31],
"Eccl": [18, 26, 22, 16, 20, 12, 29, 17, 18, 20, 10, 14],
"Song": [17, 17, 11, 16, 16, 13, 13, 14],
"Isa": [31, 22, 26, 6, 30, 13, 25, 22, 21, 34, 16, 6, 22, 32, 9, 14, 14, 7, 25, 6, 17, 25, 18, 23, 12, 21, 13, 29, 24, 33, 9, 20, 24, 17, 10, 22, 38, 22, 8, 31, 29, 25, 28, 28, 25, 13, 15, 22, 26, 11, 23, 15, 12, 17, 13, 12, 21, 14, 21, 22, 11, 12, 19, 12, 25, 24],
"Jer": [19, 37, 25, 31, 31, 30, 34, 22, 26, 25, 23, 17, 27, 22, 21, 21, 27, 23, 15, 18, 14, 30, 40, 10, 38, 24, 22, 17, 32, 24, 40, 44, 26, 22, 19, 32, 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34],
"Lam": [22, 22, 66, 22, 22],
"Ezek": [28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32, 14, 49, 32, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38, 28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35],
"Dan": [21, 49, 30, 37, 31, 28, 28, 27, 27, 21, 45, 13],
"Hos": [11, 23, 5, 19, 15, 11, 16, 14, 17, 15, 12, 14, 16, 9],
"Joel": [20, 32, 21],
"Amos": [15, 16, 15, 13, 27, 14, 17, 14, 15],
"Obad": [21],
"Jonah": [17, 10, 10, 11],
"Mic": [16, 13, 12, 13, 15, 16, 20],
"Nah": [15, 13, 19],
"Hab": [17, 20, 19],
"Zeph": [18, 15, 20],
"Hag": [15, 23],
"Zech": [21, 13, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21],
"Mal": [14, 17, 18, 6],
"Matt": [25, 23, 17, 25, 48, 34, 29, 34, 38, 42, 30, 50, 58, 36, 39, 28, 27, 35, 30, 34, 46, 46, 39, 51, 46, 75, 66, 20],
"Mark": [45, 28, 35, 41, 43, 56, 37, 38, 50, 52, 33, 44, 37, 72, 47, 20],
"Luke": [80, 52, 38, 44, 39, 49, 50, 56, 62, 42, 54, 59, 35, 35, 32, 31, 37, 43, 48, 47, 38, 71, 56, 53],
"John": [51, 25, 36, 54, 47, 71, 53, 59, 41, 42, 57, 50, 38, 31, 27, 33, 26, 40, 42, 31, 25],
"Acts": [26, 47, 26, 37, 42, 15, 60, 40, 43, 48, 30, 25, 52, 28, 41, 40, 34, 28, 41, 38, 40, 30, 35, 27, 27, 32, 44, 31],
"Rom": [32, 29, 31, 25, 21, 23, 25, 39, 33, 21, 36, 21, 14, 23, 33, 27],
"1Cor": [31, 16, 23, 21, 13, 20, 40, 13, 27, 33, 34, 31, 13, 40, 58, 24],
"2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 14],
"Gal": [24, 21, 29, 31, 26, 18],
"Eph": [23, 22, 21, 32, 33, 24],
"Phil": [30, 30, 21, 23],
"Col": [29, 23, 25, 18],
"1Thess": [10, 20, 13, 18, 28],
"2Thess": [12, 17, 18],
"1Tim": [20, 15, 16, 16, 25, 21],
"2Tim": [18, 26, 17, 22],
"Titus": [16, 15, 15],
"Phlm": [25],
"Heb": [14, 18, 19, 16, 14, 20, 28, 13, 28, 39, 40, 29, 25],
"Jas": [27, 26, 18, 17, 20],
"1Pet": [25, 25, 22, 19, 14],
"2Pet": [21, 22, 18],
"1John": [10, 29, 24, 21, 21],
"2John": [13],
"3John": [15],
"Jude": [25],
"Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 17, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21],
"Tob": [22, 14, 17, 21, 22, 18, 16, 21, 6, 13, 18, 22, 17, 15],
"Jdt": [16, 28, 10, 15, 24, 21, 32, 36, 14, 23, 23, 20, 20, 19, 14, 25],
"GkEsth": [22, 23, 15, 17, 14, 14, 10, 17, 32, 13, 12, 6, 18, 19, 16, 24],
"Wis": [16, 24, 19, 20, 23, 25, 30, 21, 18, 21, 26, 27, 19, 31, 19, 29, 21, 25, 22],
"Sir": [30, 18, 31, 31, 15, 37, 36, 19, 18, 31, 34, 18, 26, 27, 20, 30, 32, 33, 30, 31, 28, 27, 27, 34, 26, 29, 30, 26, 28, 25, 31, 24, 33, 31, 26, 31, 31, 34, 35, 30, 22, 25, 33, 23, 26, 20, 25, 25, 16, 29, 30],
"Bar": [22, 35, 37, 37, 9],
"PrAzar": [68],
"Sus": [64],
"Bel": [42],
"SgThree": [39],
"EpJer": [73],
"1Macc": [64, 70, 60, 61, 68, 63, 50, 32, 73, 89, 74, 53, 53, 49, 41, 24],
"2Macc": [36, 32, 40, 50, 27, 31, 42, 36, 29, 38, 38, 45, 26, 46, 39],
"3Macc": [29, 33, 30, 21, 51, 41, 23],
"4Macc": [35, 24, 21, 26, 38, 35, 23, 29, 32, 21, 27, 19, 27, 20, 32, 25, 24, 24],
"1Esd": [58, 30, 24, 63, 73, 34, 15, 96, 55],
"2Esd": [40, 48, 36, 52, 56, 59, 70, 63, 47, 59, 46, 51, 58, 48, 63, 78],
"PrMan": [15],
"Ps151": [7]
}
},
vulgate: {
chapters: {
"Ps": [6, 13, 9, 10, 13, 11, 18, 10, 39, 8, 9, 6, 7, 5, 10, 15, 51, 15, 10, 14, 32, 6, 10, 22, 12, 14, 9, 11, 13, 25, 11, 22, 23, 28, 13, 40, 23, 14, 18, 14, 12, 5, 26, 18, 12, 10, 15, 21, 23, 21, 11, 7, 9, 24, 13, 12, 12, 18, 14, 9, 13, 12, 11, 14, 20, 8, 36, 37, 6, 24, 20, 28, 23, 11, 13, 21, 72, 13, 20, 17, 8, 19, 13, 14, 17, 7, 19, 53, 17, 16, 16, 5, 23, 11, 13, 12, 9, 9, 5, 8, 29, 22, 35, 45, 48, 43, 14, 31, 7, 10, 10, 9, 26, 9, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 14, 10, 8, 12, 15, 21, 10, 11, 20, 14, 9, 7]
}
},
ceb: {
chapters: {
"2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13],
"Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21],
"Tob": [22, 14, 17, 21, 22, 18, 16, 21, 6, 13, 18, 22, 18, 15],
"PrAzar": [67],
"EpJer": [72],
"1Esd": [55, 26, 24, 63, 71, 33, 15, 92, 55]
}
},
kjv: {
chapters: {
"3John": [14]
}
},
nab: {
order: {
"Gen": 1,
"Exod": 2,
"Lev": 3,
"Num": 4,
"Deut": 5,
"Josh": 6,
"Judg": 7,
"Ruth": 8,
"1Sam": 9,
"2Sam": 10,
"1Kgs": 11,
"2Kgs": 12,
"1Chr": 13,
"2Chr": 14,
"PrMan": 15,
"Ezra": 16,
"Neh": 17,
"1Esd": 18,
"2Esd": 19,
"Tob": 20,
"Jdt": 21,
"Esth": 22,
"GkEsth": 23,
"1Macc": 24,
"2Macc": 25,
"3Macc": 26,
"4Macc": 27,
"Job": 28,
"Ps": 29,
"Prov": 30,
"Eccl": 31,
"Song": 32,
"Wis": 33,
"Sir": 34,
"Isa": 35,
"Jer": 36,
"Lam": 37,
"Bar": 38,
"EpJer": 39,
"Ezek": 40,
"Dan": 41,
"PrAzar": 42,
"Sus": 43,
"Bel": 44,
"SgThree": 45,
"Hos": 46,
"Joel": 47,
"Amos": 48,
"Obad": 49,
"Jonah": 50,
"Mic": 51,
"Nah": 52,
"Hab": 53,
"Zeph": 54,
"Hag": 55,
"Zech": 56,
"Mal": 57,
"Matt": 58,
"Mark": 59,
"Luke": 60,
"John": 61,
"Acts": 62,
"Rom": 63,
"1Cor": 64,
"2Cor": 65,
"Gal": 66,
"Eph": 67,
"Phil": 68,
"Col": 69,
"1Thess": 70,
"2Thess": 71,
"1Tim": 72,
"2Tim": 73,
"Titus": 74,
"Phlm": 75,
"Heb": 76,
"Jas": 77,
"1Pet": 78,
"2Pet": 79,
"1John": 80,
"2John": 81,
"3John": 82,
"Jude": 83,
"Rev": 84
},
chapters: {
"Gen": [31, 25, 24, 26, 32, 22, 24, 22, 29, 32, 32, 20, 18, 24, 21, 16, 27, 33, 38, 18, 34, 24, 20, 67, 34, 35, 46, 22, 35, 43, 54, 33, 20, 31, 29, 43, 36, 30, 23, 23, 57, 38, 34, 34, 28, 34, 31, 22, 33, 26],
"Exod": [22, 25, 22, 31, 23, 30, 29, 28, 35, 29, 10, 51, 22, 31, 27, 36, 16, 27, 25, 26, 37, 30, 33, 18, 40, 37, 21, 43, 46, 38, 18, 35, 23, 35, 35, 38, 29, 31, 43, 38],
"Lev": [17, 16, 17, 35, 26, 23, 38, 36, 24, 20, 47, 8, 59, 57, 33, 34, 16, 30, 37, 27, 24, 33, 44, 23, 55, 46, 34],
"Num": [54, 34, 51, 49, 31, 27, 89, 26, 23, 36, 35, 16, 33, 45, 41, 35, 28, 32, 22, 29, 35, 41, 30, 25, 19, 65, 23, 31, 39, 17, 54, 42, 56, 29, 34, 13],
"Deut": [46, 37, 29, 49, 33, 25, 26, 20, 29, 22, 32, 31, 19, 29, 23, 22, 20, 22, 21, 20, 23, 29, 26, 22, 19, 19, 26, 69, 28, 20, 30, 52, 29, 12],
"1Sam": [28, 36, 21, 22, 12, 21, 17, 22, 27, 27, 15, 25, 23, 52, 35, 23, 58, 30, 24, 42, 16, 23, 28, 23, 44, 25, 12, 25, 11, 31, 13],
"2Sam": [27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 32, 44, 26, 22, 51, 39, 25],
"1Kgs": [53, 46, 28, 20, 32, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46, 21, 43, 29, 54],
"2Kgs": [18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 20, 22, 25, 29, 38, 20, 41, 37, 37, 21, 26, 20, 37, 20, 30],
"1Chr": [54, 55, 24, 43, 41, 66, 40, 40, 44, 14, 47, 41, 14, 17, 29, 43, 27, 17, 19, 8, 30, 19, 32, 31, 31, 32, 34, 21, 30],
"2Chr": [18, 17, 17, 22, 14, 42, 22, 18, 31, 19, 23, 16, 23, 14, 19, 14, 19, 34, 11, 37, 20, 12, 21, 27, 28, 23, 9, 27, 36, 27, 21, 33, 25, 33, 27, 23],
"Neh": [11, 20, 38, 17, 19, 19, 72, 18, 37, 40, 36, 47, 31],
"Job": [22, 13, 26, 21, 27, 30, 21, 22, 35, 22, 20, 25, 28, 22, 35, 22, 16, 21, 29, 29, 34, 30, 17, 25, 6, 14, 23, 28, 25, 31, 40, 22, 33, 37, 16, 33, 24, 41, 30, 32, 26, 17],
"Ps": [6, 11, 9, 9, 13, 11, 18, 10, 21, 18, 7, 9, 6, 7, 5, 11, 15, 51, 15, 10, 14, 32, 6, 10, 22, 12, 14, 9, 11, 13, 25, 11, 22, 23, 28, 13, 40, 23, 14, 18, 14, 12, 5, 27, 18, 12, 10, 15, 21, 23, 21, 11, 7, 9, 24, 14, 12, 12, 18, 14, 9, 13, 12, 11, 14, 20, 8, 36, 37, 6, 24, 20, 28, 23, 11, 13, 21, 72, 13, 20, 17, 8, 19, 13, 14, 17, 7, 19, 53, 17, 16, 16, 5, 23, 11, 13, 12, 9, 9, 5, 8, 29, 22, 35, 45, 48, 43, 14, 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176, 7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 14, 10, 8, 12, 15, 21, 10, 20, 14, 9, 6],
"Eccl": [18, 26, 22, 17, 19, 12, 29, 17, 18, 20, 10, 14],
"Song": [17, 17, 11, 16, 16, 12, 14, 14],
"Isa": [31, 22, 26, 6, 30, 13, 25, 23, 20, 34, 16, 6, 22, 32, 9, 14, 14, 7, 25, 6, 17, 25, 18, 23, 12, 21, 13, 29, 24, 33, 9, 20, 24, 17, 10, 22, 38, 22, 8, 31, 29, 25, 28, 28, 25, 13, 15, 22, 26, 11, 23, 15, 12, 17, 13, 12, 21, 14, 21, 22, 11, 12, 19, 11, 25, 24],
"Jer": [19, 37, 25, 31, 31, 30, 34, 23, 25, 25, 23, 17, 27, 22, 21, 21, 27, 23, 15, 18, 14, 30, 40, 10, 38, 24, 22, 17, 32, 24, 40, 44, 26, 22, 19, 32, 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34],
"Ezek": [28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32, 14, 44, 37, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38, 28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35],
"Dan": [21, 49, 100, 34, 30, 29, 28, 27, 27, 21, 45, 13, 64, 42],
"Hos": [9, 25, 5, 19, 15, 11, 16, 14, 17, 15, 11, 15, 15, 10],
"Joel": [20, 27, 5, 21],
"Jonah": [16, 11, 10, 11],
"Mic": [16, 13, 12, 14, 14, 16, 20],
"Nah": [14, 14, 19],
"Zech": [17, 17, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21],
"Mal": [14, 17, 24],
"Acts": [26, 47, 26, 37, 42, 15, 60, 40, 43, 49, 30, 25, 52, 28, 41, 40, 34, 28, 40, 38, 40, 30, 35, 27, 27, 32, 44, 31],
"2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13],
"Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21],
"Tob": [22, 14, 17, 21, 22, 18, 17, 21, 6, 13, 18, 22, 18, 15],
"Sir": [30, 18, 31, 31, 15, 37, 36, 19, 18, 31, 34, 18, 26, 27, 20, 30, 32, 33, 30, 31, 28, 27, 27, 33, 26, 29, 30, 26, 28, 25, 31, 24, 33, 31, 26, 31, 31, 34, 35, 30, 22, 25, 33, 23, 26, 20, 25, 25, 16, 29, 30],
"Bar": [22, 35, 38, 37, 9, 72],
"2Macc": [36, 32, 40, 50, 27, 31, 42, 36, 29, 38, 38, 46, 26, 46, 39]
}
},
nlt: {
chapters: {
"Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21]
}
},
nrsv: {
chapters: {
"2Cor": [24, 17, 18, 18, 21, 18, 16, 24, 15, 18, 33, 21, 13],
"Rev": [20, 29, 22, 11, 14, 17, 17, 13, 21, 11, 19, 18, 18, 20, 8, 21, 18, 24, 21, 15, 27, 21]
}
}
};
bcv_parser.prototype.regexps.space = "[\\s\\xa0]";
bcv_parser.prototype.regexps.escaped_passage = /(?:^|[^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])((?:(?:ch(?:apters?|a?pts?\.?|a?p?s?\.?)?\s*\d+\s*(?:[\u2013\u2014\-]|through|thru|to)\s*\d+\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*)|(?:ch(?:apters?|a?pts?\.?|a?p?s?\.?)?\s*\d+\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*)|(?:\d+(?:th|nd|st)\s*ch(?:apter|a?pt\.?|a?p?\.?)?\s*(?:from|of|in)(?:\s+the\s+book\s+of)?\s*))?\x1f(\d+)(?:\/\d+)?\x1f(?:\/\d+\x1f|[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014]|title(?![a-z])|chapter|verse|ff|ug|og|-|[a-e](?!\w)|$)+)/gi;
bcv_parser.prototype.regexps.match_end_split = /\d\W*title|\d\W*ff(?:[\s\xa0*]*\.)?|\d[\s\xa0*]*[a-e](?!\w)|\x1e(?:[\s\xa0*]*[)\]\uff09])?|[\d\x1f]/gi;
bcv_parser.prototype.regexps.control = /[\x1e\x1f]/g;
bcv_parser.prototype.regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]";
bcv_parser.prototype.regexps.first = "1\\.?" + bcv_parser.prototype.regexps.space + "*";
bcv_parser.prototype.regexps.second = "2\\.?" + bcv_parser.prototype.regexps.space + "*";
bcv_parser.prototype.regexps.third = "3\\.?" + bcv_parser.prototype.regexps.space + "*";
bcv_parser.prototype.regexps.range_and = "(?:[&\u2013\u2014-]|(?:ug|og)|-)";
bcv_parser.prototype.regexps.range_only = "(?:[\u2013\u2014-]|-)";
bcv_parser.prototype.regexps.get_books = function(include_apocrypha, case_sensitive) {
var book, books, k, len, out;
books = [
{
osis: ["Ps"],
apocrypha: true,
extra: "2",
regexp: /(\b)(Ps151)(?=\.1)/g
}, {
osis: ["Gen"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Henesis|Gen(?:esis)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Exod"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(E(?:ksodo|xo(?:d(?:us)?)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Bel"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Bel)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Lev"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Le(?:bitiko|v(?:iticus)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Num"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Numeros?|Num(?:eros?)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Sir"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Sir)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Wis"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Wis)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Lam"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Pagbangotan|Pagbangotan|Lam))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["EpJer"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(EpJer)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Rev"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Gipadayag|Rev))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["PrMan"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(PrMan)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Deut"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(D(?:yuteronomyo|eu(?:t(?:eronomio)?)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Josh"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jos(?:u[eé]|h)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Judg"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:M(?:ga[\\s\\xa0]*Maghuhukom|aghuhukom)|Judg))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Ruth"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Ruth?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["1Esd"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1Esd)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["2Esd"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2Esd)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["Isa"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Isa(?:[ií]as)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["2Sam"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*Samuel|[\s\xa0]*Sam(?:uel)?|Sam))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Sam"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*Samuel|[\s\xa0]*Sam(?:uel)?|Sam))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["2Kgs"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Hari|Hari)|[\s\xa0]*(?:Mga[\s\xa0]*Hari|Hari)|Kgs))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Kgs"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Hari|Hari)|[\s\xa0]*(?:Mga[\s\xa0]*Hari|Hari)|Kgs))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["2Chr"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*[CK]roni(?:[ck]a)|[CK]roni(?:[ck]a))|[\s\xa0]*(?:Mga[\s\xa0]*[CK]roni(?:[ck]a)|Kroni[ck]a|Cro(?:n(?:i[ck]a)?)?)|Chr))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Chr"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*(?:Mga[\s\xa0]*[CK]roni(?:[ck]a)|[CK]roni(?:[ck]a))|[\s\xa0]*(?:Mga[\s\xa0]*[CK]roni(?:[ck]a)|Kroni[ck]a|Cro(?:n(?:i[ck]a)?)?)|Chr))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["Ezra"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(E(?:sdras|zra?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Neh"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Neh(?:em[ií]as)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["GkEsth"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(GkEsth)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Esth"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Est(?:er|h))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Job"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Job)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Ps"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Salmo|Sal(?:mo)?|Ps))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["PrAzar"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(PrAzar)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Prov"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Panultihon|P(?:anultihon|rov)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Eccl"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Magwawali|Kaalam|E(?:klesyastes|ccl)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["SgThree"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(SgThree)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Song"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Awit(?:[\\s\\xa0]*(?:sa[\\s\\xa0]*mga[\\s\\xa0]*Awit|ni[\\s\\xa0]*Solomon))?|Song))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Jer"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jer(?:em[ií]as)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Ezek"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Eze(?:quiel|k(?:iel)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Dan"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Dan(?:iel)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Hos"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Oseas|Hos(?:ea)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Joel"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Joel)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Amos"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Am(?:[oó]s))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Obad"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Abd[ií]as|Obad(?:ia)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Jonah"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jon(?:a[hs]|ás))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Mic"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Mi(?:queas|c|ka?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Nah"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Nah(?:um)?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Hab"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Hab(?:a(?:cuc|kuk))?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Zeph"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Sofon[ií]as|Ze(?:fania|ph)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Hag"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Ageo|Hag(?:eo)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Zech"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Z(?:acar[ií]as|ech))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Mal"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Mal(?:a(?:qu[ií]as|kias))?)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Matt"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Sulat[\\s\\xa0]*ni[\\s\\xa0]*San[\\s\\xa0]*Mateo|M(?:at(?:eo|t)|t)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Mark"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Sulat[\\s\\xa0]*ni[\\s\\xa0]*San[\\s\\xa0]*Marcos|M(?:ar(?:cos|k)|[ck])))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Luke"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Sulat[\\s\\xa0]*ni[\\s\\xa0]*San[\\s\\xa0]*Lucas|Lu(?:cas|ke)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["1John"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*Juan|John|[\s\xa0]*J(?:uan|n)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["2John"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*Juan|John|[\s\xa0]*J(?:uan|n)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["3John"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(3(?:\.[\s\xa0]*Juan|John|[\s\xa0]*J(?:uan|n)))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["John"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Sulat[\\s\\xa0]*ni[\\s\\xa0]*San[\\s\\xa0]*Juan|J(?:ohn|uan|n)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Acts"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:A(?:ng[\\s\\xa0]*Mga[\\s\\xa0]*Binuhatan|cts)|B(?:uhat[\\s\\xa0]*sa[\\s\\xa0]*mga[\\s\\xa0]*Apostoles|in(?:uhatan)?)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Rom"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Taga-?Roma|Roma?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["2Cor"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Corinto|Taga-?Corinto|Corinto)|[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Corinto|Taga-?Corinto|Co(?:r(?:into)?)?)|Cor))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Cor"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Corinto|Taga-?Corinto|Corinto)|[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Corinto|Taga-?Corinto|Co(?:r(?:into)?)?)|Cor))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["Gal"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Taga-?Galacia|Taga-?Galacia|Gal(?:acia)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Eph"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Taga-?[EÉ]feso|Taga-?[EÉ]feso|Éfeso|E(?:feso|ph)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Phil"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Taga-?Filipos|Taga-?Filipos|Filipos|Phil))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Col"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*Taga-?Colosas|Taga-?Colosas|Col(?:osas)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["2Thess"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Tesal[oó]ni(?:[ck]a)|T(?:aga-?Tesal[oó]ni(?:[ck]a)|esal[oó]ni(?:[ck]a)))|[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Tesal[oó]ni(?:[ck]a)|T(?:aga-?Tesal[oó]ni(?:[ck]a)|esal[oó]ni(?:[ck]a)))|Thess))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Thess"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Tesal[oó]ni(?:[ck]a)|T(?:aga-?Tesal[oó]ni(?:[ck]a)|esal[oó]ni(?:[ck]a)))|[\s\xa0]*(?:Mga[\s\xa0]*Taga-?Tesal[oó]ni(?:[ck]a)|T(?:aga-?Tesal[oó]ni(?:[ck]a)|esal[oó]ni(?:[ck]a)))|Thess))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["2Tim"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*(?:Kang[\s\xa0]*Timoteo|Timoteo)|[\s\xa0]*(?:Kang[\s\xa0]*Timoteo|Timoteo)|Tim))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Tim"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*(?:Kang[\s\xa0]*Timoteo|Timoteo)|[\s\xa0]*(?:Kang[\s\xa0]*Timoteo|Timoteo)|Tim))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["Titus"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Kang[\\s\\xa0]*Tito|Tit(?:us|o)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Phlm"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Kang[\\s\\xa0]*Filem[oó]n|Filem[oó]n|Phlm))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Heb"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Mga[\\s\\xa0]*(?:Hebrohanon|Ebreo)|Heb(?:reohanon)?))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Jas"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")((?:Santiago|Ja(?:cobo|s)))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["2Pet"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2(?:\.[\s\xa0]*Pedro|[\s\xa0]*Pedro|Pet))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Pet"],
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1(?:\.[\s\xa0]*Pedro|[\s\xa0]*Pedro|Pet))(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["Jude"],
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jud(?:as|e))(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Tob"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Tob)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Jdt"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Jdt)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Bar"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Bar)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["Sus"],
apocrypha: true,
regexp: RegExp("(^|" + bcv_parser.prototype.regexps.pre_book + ")(Sus)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)()\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)", "gi")
}, {
osis: ["2Macc"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(2Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["3Macc"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(3Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["4Macc"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(4Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}, {
osis: ["1Macc"],
apocrypha: true,
regexp: /(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(1Macc)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)()\[\]\/"'\*=~\-\u2013\u2014])|$)/gi
}
];
if (include_apocrypha === true && case_sensitive === "none") {
return books;
}
out = [];
for (k = 0, len = books.length; k < len; k++) {
book = books[k];
if (include_apocrypha === false && (book.apocrypha != null) && book.apocrypha === true) {
continue;
}
if (case_sensitive === "books") {
book.regexp = new RegExp(book.regexp.source, "g");
}
out.push(book);
}
return out;
};
bcv_parser.prototype.regexps.books = bcv_parser.prototype.regexps.get_books(false, "none");
var grammar = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = [],
peg$c1 = peg$FAILED,
peg$c2 = null,
peg$c3 = function(val_1, val_2) { val_2.unshift([val_1]); return {"type": "sequence", "value": val_2, "indices": [offset(), peg$currPos - 1]} },
peg$c4 = "(",
peg$c5 = { type: "literal", value: "(", description: "\"(\"" },
peg$c6 = ")",
peg$c7 = { type: "literal", value: ")", description: "\")\"" },
peg$c8 = function(val_1, val_2) { if (typeof(val_2) === "undefined") val_2 = []; val_2.unshift([val_1]); return {"type": "sequence_post_enclosed", "value": val_2, "indices": [offset(), peg$currPos - 1]} },
peg$c9 = void 0,
peg$c10 = function(val_1, val_2) { if (val_1.length && val_1.length === 2) val_1 = val_1[0]; // for `b`, which returns [object, undefined]
return {"type": "range", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c11 = "\x1F",
peg$c12 = { type: "literal", value: "\x1F", description: "\"\\x1F\"" },
peg$c13 = "/",
peg$c14 = { type: "literal", value: "/", description: "\"/\"" },
peg$c15 = /^[1-8]/,
peg$c16 = { type: "class", value: "[1-8]", description: "[1-8]" },
peg$c17 = function(val) { return {"type": "b", "value": val.value, "indices": [offset(), peg$currPos - 1]} },
peg$c18 = function(val_1, val_2) { return {"type": "bc", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c19 = ",",
peg$c20 = { type: "literal", value: ",", description: "\",\"" },
peg$c21 = function(val_1, val_2) { return {"type": "bc_title", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c22 = ".",
peg$c23 = { type: "literal", value: ".", description: "\".\"" },
peg$c24 = function(val_1, val_2) { return {"type": "bcv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c25 = "-",
peg$c26 = { type: "literal", value: "-", description: "\"-\"" },
peg$c27 = function(val_1, val_2, val_3, val_4) { return {"type": "range", "value": [{"type": "bcv", "value": [{"type": "bc", "value": [val_1, val_2], "indices": [val_1.indices[0], val_2.indices[1]]}, val_3], "indices": [val_1.indices[0], val_3.indices[1]]}, val_4], "indices": [offset(), peg$currPos - 1]} },
peg$c28 = function(val_1, val_2) { return {"type": "bv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c29 = function(val_1, val_2) { return {"type": "bc", "value": [val_2, val_1], "indices": [offset(), peg$currPos - 1]} },
peg$c30 = function(val_1, val_2, val_3) { return {"type": "cb_range", "value": [val_3, val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c31 = "th",
peg$c32 = { type: "literal", value: "th", description: "\"th\"" },
peg$c33 = "nd",
peg$c34 = { type: "literal", value: "nd", description: "\"nd\"" },
peg$c35 = "st",
peg$c36 = { type: "literal", value: "st", description: "\"st\"" },
peg$c37 = "/1\x1F",
peg$c38 = { type: "literal", value: "/1\x1F", description: "\"/1\\x1F\"" },
peg$c39 = function(val) { return {"type": "c_psalm", "value": val.value, "indices": [offset(), peg$currPos - 1]} },
peg$c40 = function(val_1, val_2) { return {"type": "cv_psalm", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c41 = function(val_1, val_2) { return {"type": "c_title", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c42 = function(val_1, val_2) { return {"type": "cv", "value": [val_1, val_2], "indices": [offset(), peg$currPos - 1]} },
peg$c43 = function(val) { return {"type": "c", "value": [val], "indices": [offset(), peg$currPos - 1]} },
peg$c44 = "ff",
peg$c45 = { type: "literal", value: "ff", description: "\"ff\"" },
peg$c46 = /^[a-z]/,
peg$c47 = { type: "class", value: "[a-z]", description: "[a-z]" },
peg$c48 = function(val_1) { return {"type": "ff", "value": [val_1], "indices": [offset(), peg$currPos - 1]} },
peg$c49 = "title",
peg$c50 = { type: "literal", value: "title", description: "\"title\"" },
peg$c51 = function(val_1) { return {"type": "integer_title", "value": [val_1], "indices": [offset(), peg$currPos - 1]} },
peg$c52 = "/9\x1F",
peg$c53 = { type: "literal", value: "/9\x1F", description: "\"/9\\x1F\"" },
peg$c54 = function(val) { return {"type": "context", "value": val.value, "indices": [offset(), peg$currPos - 1]} },
peg$c55 = "/2\x1F",
peg$c56 = { type: "literal", value: "/2\x1F", description: "\"/2\\x1F\"" },
peg$c57 = ".1",
peg$c58 = { type: "literal", value: ".1", description: "\".1\"" },
peg$c59 = /^[0-9]/,
peg$c60 = { type: "class", value: "[0-9]", description: "[0-9]" },
peg$c61 = function(val) { return {"type": "bc", "value": [val, {"type": "c", "value": [{"type": "integer", "value": 151, "indices": [peg$currPos - 2, peg$currPos - 1]}], "indices": [peg$currPos - 2, peg$currPos - 1]}], "indices": [offset(), peg$currPos - 1]} },
peg$c62 = function(val_1, val_2) { return {"type": "bcv", "value": [val_1, {"type": "v", "value": [val_2], "indices": [val_2.indices[0], val_2.indices[1]]}], "indices": [offset(), peg$currPos - 1]} },
peg$c63 = /^[a-e]/,
peg$c64 = { type: "class", value: "[a-e]", description: "[a-e]" },
peg$c65 = function(val) { return {"type": "v", "value": [val], "indices": [offset(), peg$currPos - 1]} },
peg$c66 = "chapter",
peg$c67 = { type: "literal", value: "chapter", description: "\"chapter\"" },
peg$c68 = function() { return {"type": "c_explicit"} },
peg$c69 = "verse",
peg$c70 = { type: "literal", value: "verse", description: "\"verse\"" },
peg$c71 = function() { return {"type": "v_explicit"} },
peg$c72 = /^["']/,
peg$c73 = { type: "class", value: "[\"']", description: "[\"']" },
peg$c74 = /^[;\/:&\-\u2013\u2014~]/,
peg$c75 = { type: "class", value: "[;\\/:&\\-\\u2013\\u2014~]", description: "[;\\/:&\\-\\u2013\\u2014~]" },
peg$c76 = "ug",
peg$c77 = { type: "literal", value: "ug", description: "\"ug\"" },
peg$c78 = "og",
peg$c79 = { type: "literal", value: "og", description: "\"og\"" },
peg$c80 = function() { return "" },
peg$c81 = /^[\-\u2013\u2014]/,
peg$c82 = { type: "class", value: "[\\-\\u2013\\u2014]", description: "[\\-\\u2013\\u2014]" },
peg$c83 = function(val) { return {type:"title", value: [val], "indices": [offset(), peg$currPos - 1]} },
peg$c84 = "from",
peg$c85 = { type: "literal", value: "from", description: "\"from\"" },
peg$c86 = "of",
peg$c87 = { type: "literal", value: "of", description: "\"of\"" },
peg$c88 = "in",
peg$c89 = { type: "literal", value: "in", description: "\"in\"" },
peg$c90 = "the",
peg$c91 = { type: "literal", value: "the", description: "\"the\"" },
peg$c92 = "book",
peg$c93 = { type: "literal", value: "book", description: "\"book\"" },
peg$c94 = /^[([]/,
peg$c95 = { type: "class", value: "[([]", description: "[([]" },
peg$c96 = /^[)\]]/,
peg$c97 = { type: "class", value: "[)\\]]", description: "[)\\]]" },
peg$c98 = function(val) { return {"type": "translation_sequence", "value": val, "indices": [offset(), peg$currPos - 1]} },
peg$c99 = "\x1E",
peg$c100 = { type: "literal", value: "\x1E", description: "\"\\x1E\"" },
peg$c101 = function(val) { return {"type": "translation", "value": val.value, "indices": [offset(), peg$currPos - 1]} },
peg$c102 = ",000",
peg$c103 = { type: "literal", value: ",000", description: "\",000\"" },
peg$c104 = function(val) { return {"type": "integer", "value": parseInt(val.join(""), 10), "indices": [offset(), peg$currPos - 1]} },
peg$c105 = /^[^\x1F\x1E([]/,
peg$c106 = { type: "class", value: "[^\\x1F\\x1E([]", description: "[^\\x1F\\x1E([]" },
peg$c107 = function(val) { return {"type": "word", "value": val.join(""), "indices": [offset(), peg$currPos - 1]} },
peg$c108 = function(val) { return {"type": "stop", "value": val, "indices": [offset(), peg$currPos - 1]} },
peg$c109 = /^[\s\xa0*]/,
peg$c110 = { type: "class", value: "[\\s\\xa0*]", description: "[\\s\\xa0*]" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0, s1;
s0 = [];
s1 = peg$parsebcv_hyphen_range();
if (s1 === peg$FAILED) {
s1 = peg$parsesequence();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_range();
if (s1 === peg$FAILED) {
s1 = peg$parserange();
if (s1 === peg$FAILED) {
s1 = peg$parseff();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_comma();
if (s1 === peg$FAILED) {
s1 = peg$parsebc_title();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parsebv();
if (s1 === peg$FAILED) {
s1 = peg$parsec_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parseb();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsecb();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsetranslation_sequence_enclosed();
if (s1 === peg$FAILED) {
s1 = peg$parsetranslation_sequence();
if (s1 === peg$FAILED) {
s1 = peg$parsesequence_sep();
if (s1 === peg$FAILED) {
s1 = peg$parsec_title();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger_title();
if (s1 === peg$FAILED) {
s1 = peg$parsecv();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parsev_letter();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger();
if (s1 === peg$FAILED) {
s1 = peg$parsec();
if (s1 === peg$FAILED) {
s1 = peg$parsev();
if (s1 === peg$FAILED) {
s1 = peg$parseword();
if (s1 === peg$FAILED) {
s1 = peg$parseword_parenthesis();
if (s1 === peg$FAILED) {
s1 = peg$parsecontext();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (s1 !== peg$FAILED) {
while (s1 !== peg$FAILED) {
s0.push(s1);
s1 = peg$parsebcv_hyphen_range();
if (s1 === peg$FAILED) {
s1 = peg$parsesequence();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_range();
if (s1 === peg$FAILED) {
s1 = peg$parserange();
if (s1 === peg$FAILED) {
s1 = peg$parseff();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_comma();
if (s1 === peg$FAILED) {
s1 = peg$parsebc_title();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parsebv();
if (s1 === peg$FAILED) {
s1 = peg$parsec_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parseb();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsecb();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsetranslation_sequence_enclosed();
if (s1 === peg$FAILED) {
s1 = peg$parsetranslation_sequence();
if (s1 === peg$FAILED) {
s1 = peg$parsesequence_sep();
if (s1 === peg$FAILED) {
s1 = peg$parsec_title();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger_title();
if (s1 === peg$FAILED) {
s1 = peg$parsecv();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parsev_letter();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger();
if (s1 === peg$FAILED) {
s1 = peg$parsec();
if (s1 === peg$FAILED) {
s1 = peg$parsev();
if (s1 === peg$FAILED) {
s1 = peg$parseword();
if (s1 === peg$FAILED) {
s1 = peg$parseword_parenthesis();
if (s1 === peg$FAILED) {
s1 = peg$parsecontext();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
s0 = peg$c1;
}
return s0;
}
function peg$parsesequence() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsecb_range();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_hyphen_range();
if (s1 === peg$FAILED) {
s1 = peg$parserange();
if (s1 === peg$FAILED) {
s1 = peg$parseff();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_comma();
if (s1 === peg$FAILED) {
s1 = peg$parsebc_title();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parsebv();
if (s1 === peg$FAILED) {
s1 = peg$parsec_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parseb();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsecb();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsecontext();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parsesequence_sep();
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence_post();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parsesequence_sep();
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesequence_post();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
}
} else {
s2 = peg$c1;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c3(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsesequence_post_enclosed() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 40) {
s1 = peg$c4;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c5); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parsesp();
if (s2 !== peg$FAILED) {
s3 = peg$parsesequence_sep();
if (s3 === peg$FAILED) {
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesequence_post();
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$currPos;
s7 = peg$parsesequence_sep();
if (s7 === peg$FAILED) {
s7 = peg$c2;
}
if (s7 !== peg$FAILED) {
s8 = peg$parsesequence_post();
if (s8 !== peg$FAILED) {
s7 = [s7, s8];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
} else {
peg$currPos = s6;
s6 = peg$c1;
}
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$currPos;
s7 = peg$parsesequence_sep();
if (s7 === peg$FAILED) {
s7 = peg$c2;
}
if (s7 !== peg$FAILED) {
s8 = peg$parsesequence_post();
if (s8 !== peg$FAILED) {
s7 = [s7, s8];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
} else {
peg$currPos = s6;
s6 = peg$c1;
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parsesp();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s7 = peg$c6;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c8(s4, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsesequence_post() {
var s0;
s0 = peg$parsesequence_post_enclosed();
if (s0 === peg$FAILED) {
s0 = peg$parsecb_range();
if (s0 === peg$FAILED) {
s0 = peg$parsebcv_hyphen_range();
if (s0 === peg$FAILED) {
s0 = peg$parserange();
if (s0 === peg$FAILED) {
s0 = peg$parseff();
if (s0 === peg$FAILED) {
s0 = peg$parsebcv_comma();
if (s0 === peg$FAILED) {
s0 = peg$parsebc_title();
if (s0 === peg$FAILED) {
s0 = peg$parseps151_bcv();
if (s0 === peg$FAILED) {
s0 = peg$parsebcv();
if (s0 === peg$FAILED) {
s0 = peg$parsebcv_weak();
if (s0 === peg$FAILED) {
s0 = peg$parseps151_bc();
if (s0 === peg$FAILED) {
s0 = peg$parsebc();
if (s0 === peg$FAILED) {
s0 = peg$parsecv_psalm();
if (s0 === peg$FAILED) {
s0 = peg$parsebv();
if (s0 === peg$FAILED) {
s0 = peg$parsec_psalm();
if (s0 === peg$FAILED) {
s0 = peg$parseb();
if (s0 === peg$FAILED) {
s0 = peg$parsecbv();
if (s0 === peg$FAILED) {
s0 = peg$parsecbv_ordinal();
if (s0 === peg$FAILED) {
s0 = peg$parsecb();
if (s0 === peg$FAILED) {
s0 = peg$parsecb_ordinal();
if (s0 === peg$FAILED) {
s0 = peg$parsec_title();
if (s0 === peg$FAILED) {
s0 = peg$parseinteger_title();
if (s0 === peg$FAILED) {
s0 = peg$parsecv();
if (s0 === peg$FAILED) {
s0 = peg$parsecv_weak();
if (s0 === peg$FAILED) {
s0 = peg$parsev_letter();
if (s0 === peg$FAILED) {
s0 = peg$parseinteger();
if (s0 === peg$FAILED) {
s0 = peg$parsec();
if (s0 === peg$FAILED) {
s0 = peg$parsev();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return s0;
}
function peg$parserange() {
var s0, s1, s2, s3, s4, s5, s6;
s0 = peg$currPos;
s1 = peg$parsebcv_comma();
if (s1 === peg$FAILED) {
s1 = peg$parsebc_title();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parsebv();
if (s1 === peg$FAILED) {
s1 = peg$currPos;
s2 = peg$parseb();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$currPos;
s5 = peg$parserange_sep();
if (s5 !== peg$FAILED) {
s6 = peg$parsebcv_comma();
if (s6 === peg$FAILED) {
s6 = peg$parsebc_title();
if (s6 === peg$FAILED) {
s6 = peg$parseps151_bcv();
if (s6 === peg$FAILED) {
s6 = peg$parsebcv();
if (s6 === peg$FAILED) {
s6 = peg$parsebcv_weak();
if (s6 === peg$FAILED) {
s6 = peg$parseps151_bc();
if (s6 === peg$FAILED) {
s6 = peg$parsebc();
if (s6 === peg$FAILED) {
s6 = peg$parsebv();
if (s6 === peg$FAILED) {
s6 = peg$parseb();
}
}
}
}
}
}
}
}
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
peg$silentFails--;
if (s4 !== peg$FAILED) {
peg$currPos = s3;
s3 = peg$c9;
} else {
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
s2 = [s2, s3];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c1;
}
} else {
peg$currPos = s1;
s1 = peg$c1;
}
if (s1 === peg$FAILED) {
s1 = peg$parsecbv();
if (s1 === peg$FAILED) {
s1 = peg$parsecbv_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsec_psalm();
if (s1 === peg$FAILED) {
s1 = peg$parsecb();
if (s1 === peg$FAILED) {
s1 = peg$parsecb_ordinal();
if (s1 === peg$FAILED) {
s1 = peg$parsec_title();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger_title();
if (s1 === peg$FAILED) {
s1 = peg$parsecv();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parsev_letter();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger();
if (s1 === peg$FAILED) {
s1 = peg$parsec();
if (s1 === peg$FAILED) {
s1 = peg$parsev();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parserange_sep();
if (s2 !== peg$FAILED) {
s3 = peg$parseff();
if (s3 === peg$FAILED) {
s3 = peg$parsebcv_comma();
if (s3 === peg$FAILED) {
s3 = peg$parsebc_title();
if (s3 === peg$FAILED) {
s3 = peg$parseps151_bcv();
if (s3 === peg$FAILED) {
s3 = peg$parsebcv();
if (s3 === peg$FAILED) {
s3 = peg$parsebcv_weak();
if (s3 === peg$FAILED) {
s3 = peg$parseps151_bc();
if (s3 === peg$FAILED) {
s3 = peg$parsebc();
if (s3 === peg$FAILED) {
s3 = peg$parsecv_psalm();
if (s3 === peg$FAILED) {
s3 = peg$parsebv();
if (s3 === peg$FAILED) {
s3 = peg$parseb();
if (s3 === peg$FAILED) {
s3 = peg$parsecbv();
if (s3 === peg$FAILED) {
s3 = peg$parsecbv_ordinal();
if (s3 === peg$FAILED) {
s3 = peg$parsec_psalm();
if (s3 === peg$FAILED) {
s3 = peg$parsecb();
if (s3 === peg$FAILED) {
s3 = peg$parsecb_ordinal();
if (s3 === peg$FAILED) {
s3 = peg$parsec_title();
if (s3 === peg$FAILED) {
s3 = peg$parseinteger_title();
if (s3 === peg$FAILED) {
s3 = peg$parsecv();
if (s3 === peg$FAILED) {
s3 = peg$parsev_letter();
if (s3 === peg$FAILED) {
s3 = peg$parseinteger();
if (s3 === peg$FAILED) {
s3 = peg$parsecv_weak();
if (s3 === peg$FAILED) {
s3 = peg$parsec();
if (s3 === peg$FAILED) {
s3 = peg$parsev();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c10(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseb() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 31) {
s1 = peg$c11;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseany_integer();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s4 = peg$c13;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c14); }
}
if (s4 !== peg$FAILED) {
if (peg$c15.test(input.charAt(peg$currPos))) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c16); }
}
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 === peg$FAILED) {
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 31) {
s4 = peg$c11;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c17(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebc() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8;
s0 = peg$currPos;
s1 = peg$parseb();
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parsev_explicit();
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$currPos;
s6 = peg$parsec();
if (s6 !== peg$FAILED) {
s7 = peg$parsecv_sep();
if (s7 !== peg$FAILED) {
s8 = peg$parsev();
if (s8 !== peg$FAILED) {
s6 = [s6, s7, s8];
s5 = s6;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
peg$silentFails--;
if (s5 !== peg$FAILED) {
peg$currPos = s4;
s4 = peg$c9;
} else {
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s3 = [s3, s4];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = [];
s3 = peg$parsecv_sep();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsecv_sep();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = [];
s3 = peg$parsecv_sep_weak();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsecv_sep_weak();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = [];
s3 = peg$parserange_sep();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parserange_sep();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = peg$parsesp();
}
}
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsec();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c18(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebc_comma() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseb();
if (s1 !== peg$FAILED) {
s2 = peg$parsesp();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s3 = peg$c19;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesp();
if (s4 !== peg$FAILED) {
s5 = peg$parsec();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c18(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebc_title() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsetitle();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c21(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebcv() {
var s0, s1, s2, s3, s4, s5, s6;
s0 = peg$currPos;
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c22;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsev_explicit();
if (s5 !== peg$FAILED) {
s6 = peg$parsev();
if (s6 !== peg$FAILED) {
s4 = [s4, s5, s6];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parsesequence_sep();
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsev_explicit();
if (s5 !== peg$FAILED) {
s6 = peg$parsecv();
if (s6 !== peg$FAILED) {
s4 = [s4, s5, s6];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c9;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parsecv_sep();
if (s4 === peg$FAILED) {
s4 = peg$parsesequence_sep();
}
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsev_explicit();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 === peg$FAILED) {
s3 = peg$parsecv_sep();
}
if (s3 !== peg$FAILED) {
s4 = peg$parsev_letter();
if (s4 === peg$FAILED) {
s4 = peg$parsev();
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebcv_weak() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseps151_bc();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsecv_sep_weak();
if (s2 !== peg$FAILED) {
s3 = peg$parsev_letter();
if (s3 === peg$FAILED) {
s3 = peg$parsev();
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$currPos;
s6 = peg$parsecv_sep();
if (s6 !== peg$FAILED) {
s7 = peg$parsev();
if (s7 !== peg$FAILED) {
s6 = [s6, s7];
s5 = s6;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c9;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebcv_comma() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = peg$parsebc_comma();
if (s1 !== peg$FAILED) {
s2 = peg$parsesp();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s3 = peg$c19;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesp();
if (s4 !== peg$FAILED) {
s5 = peg$parsev_letter();
if (s5 === peg$FAILED) {
s5 = peg$parsev();
}
if (s5 !== peg$FAILED) {
s6 = peg$currPos;
peg$silentFails++;
s7 = peg$currPos;
s8 = peg$parsecv_sep();
if (s8 !== peg$FAILED) {
s9 = peg$parsev();
if (s9 !== peg$FAILED) {
s8 = [s8, s9];
s7 = s8;
} else {
peg$currPos = s7;
s7 = peg$c1;
}
} else {
peg$currPos = s7;
s7 = peg$c1;
}
peg$silentFails--;
if (s7 === peg$FAILED) {
s6 = peg$c9;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebcv_hyphen_range() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseb();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s2 = peg$c25;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c26); }
}
if (s2 === peg$FAILED) {
s2 = peg$parsespace();
}
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsec();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s4 = peg$c25;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c26); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsev();
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s6 = peg$c25;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c26); }
}
if (s6 !== peg$FAILED) {
s7 = peg$parsev();
if (s7 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c27(s1, s3, s5, s7);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsebv() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseb();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsecv_sep();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsecv_sep();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = [];
s3 = peg$parsecv_sep_weak();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsecv_sep_weak();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = [];
s3 = peg$parserange_sep();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parserange_sep();
}
} else {
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = peg$currPos;
s3 = [];
s4 = peg$parsesequence_sep();
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsesequence_sep();
}
} else {
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parsev_explicit();
peg$silentFails--;
if (s5 !== peg$FAILED) {
peg$currPos = s4;
s4 = peg$c9;
} else {
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s3 = [s3, s4];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = peg$parsesp();
}
}
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsev_letter();
if (s3 === peg$FAILED) {
s3 = peg$parsev();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c28(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecb() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parsec_explicit();
if (s1 !== peg$FAILED) {
s2 = peg$parsec();
if (s2 !== peg$FAILED) {
s3 = peg$parsein_book_of();
if (s3 === peg$FAILED) {
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
s4 = peg$parseb();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c29(s2, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecb_range() {
var s0, s1, s2, s3, s4, s5, s6;
s0 = peg$currPos;
s1 = peg$parsec_explicit();
if (s1 !== peg$FAILED) {
s2 = peg$parsec();
if (s2 !== peg$FAILED) {
s3 = peg$parserange_sep();
if (s3 !== peg$FAILED) {
s4 = peg$parsec();
if (s4 !== peg$FAILED) {
s5 = peg$parsein_book_of();
if (s5 === peg$FAILED) {
s5 = peg$c2;
}
if (s5 !== peg$FAILED) {
s6 = peg$parseb();
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c30(s2, s4, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecbv() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parsecb();
if (s1 !== peg$FAILED) {
s2 = peg$parsesequence_sep();
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsev_explicit();
if (s3 !== peg$FAILED) {
s4 = peg$parsev();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecb_ordinal() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsec();
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c31) {
s2 = peg$c31;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c33) {
s2 = peg$c33;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c34); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c35) {
s2 = peg$c35;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsec_explicit();
if (s3 !== peg$FAILED) {
s4 = peg$parsein_book_of();
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseb();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c29(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecbv_ordinal() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parsecb_ordinal();
if (s1 !== peg$FAILED) {
s2 = peg$parsesequence_sep();
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsev_explicit();
if (s3 !== peg$FAILED) {
s4 = peg$parsev();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsec_psalm() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 31) {
s1 = peg$c11;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseany_integer();
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c37) {
s3 = peg$c37;
peg$currPos += 3;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c39(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecv_psalm() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parsec_psalm();
if (s1 !== peg$FAILED) {
s2 = peg$parsesequence_sep();
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsev_explicit();
if (s3 !== peg$FAILED) {
s4 = peg$parsev();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c40(s1, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsec_title() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsec_explicit();
if (s1 !== peg$FAILED) {
s2 = peg$parsec();
if (s2 !== peg$FAILED) {
s3 = peg$parsetitle();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c41(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecv() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parsev_explicit();
if (s1 === peg$FAILED) {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsec();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s5 = peg$c22;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parsev_explicit();
if (s6 !== peg$FAILED) {
s7 = peg$parsev();
if (s7 !== peg$FAILED) {
s5 = [s5, s6, s7];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c9;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
s5 = peg$parsecv_sep();
if (s5 === peg$FAILED) {
s5 = peg$c2;
}
if (s5 !== peg$FAILED) {
s6 = peg$parsev_explicit();
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 === peg$FAILED) {
s4 = peg$parsecv_sep();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsev_letter();
if (s5 === peg$FAILED) {
s5 = peg$parsev();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c42(s2, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecv_weak() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parsec();
if (s1 !== peg$FAILED) {
s2 = peg$parsecv_sep_weak();
if (s2 !== peg$FAILED) {
s3 = peg$parsev_letter();
if (s3 === peg$FAILED) {
s3 = peg$parsev();
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$currPos;
s6 = peg$parsecv_sep();
if (s6 !== peg$FAILED) {
s7 = peg$parsev();
if (s7 !== peg$FAILED) {
s6 = [s6, s7];
s5 = s6;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c9;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c42(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsec() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parsec_explicit();
if (s1 === peg$FAILED) {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseinteger();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c43(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseff() {
var s0, s1, s2, s3, s4, s5, s6;
s0 = peg$currPos;
s1 = peg$parsebcv();
if (s1 === peg$FAILED) {
s1 = peg$parsebcv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parsebc();
if (s1 === peg$FAILED) {
s1 = peg$parsebv();
if (s1 === peg$FAILED) {
s1 = peg$parsecv();
if (s1 === peg$FAILED) {
s1 = peg$parsecv_weak();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger();
if (s1 === peg$FAILED) {
s1 = peg$parsec();
if (s1 === peg$FAILED) {
s1 = peg$parsev();
}
}
}
}
}
}
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parsesp();
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c44) {
s3 = peg$c44;
peg$currPos += 2;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parseabbrev();
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s5 = peg$currPos;
peg$silentFails++;
if (peg$c46.test(input.charAt(peg$currPos))) {
s6 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c47); }
}
peg$silentFails--;
if (s6 === peg$FAILED) {
s5 = peg$c9;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c48(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseinteger_title() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseinteger();
if (s1 !== peg$FAILED) {
s2 = peg$parsecv_sep();
if (s2 === peg$FAILED) {
s2 = peg$parsesequence_sep();
}
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c49) {
s3 = peg$c49;
peg$currPos += 5;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c50); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c51(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecontext() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 31) {
s1 = peg$c11;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseany_integer();
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c52) {
s3 = peg$c52;
peg$currPos += 3;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c53); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c54(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseps151_b() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 31) {
s1 = peg$c11;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseany_integer();
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c55) {
s3 = peg$c55;
peg$currPos += 3;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c56); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c17(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseps151_bc() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parseps151_b();
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c57) {
s2 = peg$c57;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c58); }
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (peg$c59.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c60); }
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c9;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseps151_bcv() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseps151_bc();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s2 = peg$c22;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseinteger();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c62(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsev_letter() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parsev_explicit();
if (s1 === peg$FAILED) {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseinteger();
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c44) {
s5 = peg$c44;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c9;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
if (peg$c63.test(input.charAt(peg$currPos))) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c64); }
}
if (s5 !== peg$FAILED) {
s6 = peg$currPos;
peg$silentFails++;
if (peg$c46.test(input.charAt(peg$currPos))) {
s7 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c47); }
}
peg$silentFails--;
if (s7 === peg$FAILED) {
s6 = peg$c9;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c65(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsev() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parsev_explicit();
if (s1 === peg$FAILED) {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseinteger();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c65(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsec_explicit() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 7) === peg$c66) {
s2 = peg$c66;
peg$currPos += 7;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c67); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c68();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsev_explicit() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c69) {
s2 = peg$c69;
peg$currPos += 5;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c70); }
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (peg$c46.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c47); }
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c9;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesp();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c71();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecv_sep() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s2 = peg$c19;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecv_sep_weak() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (peg$c72.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
if (s0 === peg$FAILED) {
s0 = peg$parsespace();
}
return s0;
}
function peg$parsesequence_sep() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = [];
if (peg$c74.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s2 === peg$FAILED) {
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c22;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$currPos;
s6 = peg$parsesp();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s7 = peg$c22;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parsesp();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s9 = peg$c22;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s9 !== peg$FAILED) {
s6 = [s6, s7, s8, s9];
s5 = s6;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c9;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s3 = [s3, s4];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c76) {
s2 = peg$c76;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c77); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c78) {
s2 = peg$c78;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c79); }
}
if (s2 === peg$FAILED) {
s2 = peg$parsespace();
}
}
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c74.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s2 === peg$FAILED) {
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c22;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$currPos;
s6 = peg$parsesp();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s7 = peg$c22;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parsesp();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s9 = peg$c22;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s9 !== peg$FAILED) {
s6 = [s6, s7, s8, s9];
s5 = s6;
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
} else {
peg$currPos = s5;
s5 = peg$c1;
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c9;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s3 = [s3, s4];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c76) {
s2 = peg$c76;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c77); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c78) {
s2 = peg$c78;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c79); }
}
if (s2 === peg$FAILED) {
s2 = peg$parsespace();
}
}
}
}
}
} else {
s1 = peg$c1;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c80();
}
s0 = s1;
return s0;
}
function peg$parserange_sep() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
if (peg$c81.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s4 = peg$c25;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c26); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
if (peg$c81.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s4 = peg$c25;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c26); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
}
}
} else {
s2 = peg$c1;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsetitle() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parsecv_sep();
if (s1 === peg$FAILED) {
s1 = peg$parsesequence_sep();
}
if (s1 === peg$FAILED) {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c49) {
s2 = peg$c49;
peg$currPos += 5;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c50); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c83(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsein_book_of() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c84) {
s2 = peg$c84;
peg$currPos += 4;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c85); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c86) {
s2 = peg$c86;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c87); }
}
if (s2 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c88) {
s2 = peg$c88;
peg$currPos += 2;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c89); }
}
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c90) {
s5 = peg$c90;
peg$currPos += 3;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c91); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parsesp();
if (s6 !== peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c92) {
s7 = peg$c92;
peg$currPos += 4;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c93); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parsesp();
if (s8 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c86) {
s9 = peg$c86;
peg$currPos += 2;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c87); }
}
if (s9 !== peg$FAILED) {
s10 = peg$parsesp();
if (s10 !== peg$FAILED) {
s5 = [s5, s6, s7, s8, s9, s10];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 === peg$FAILED) {
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
s1 = [s1, s2, s3, s4];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseabbrev() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s2 = peg$c22;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$currPos;
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s6 = peg$c22;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s6 !== peg$FAILED) {
s7 = peg$parsesp();
if (s7 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s8 = peg$c22;
peg$currPos++;
} else {
s8 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s8 !== peg$FAILED) {
s5 = [s5, s6, s7, s8];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c9;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsetranslation_sequence_enclosed() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
if (peg$c94.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsesp();
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
s5 = peg$parsetranslation();
if (s5 !== peg$FAILED) {
s6 = [];
s7 = peg$currPos;
s8 = peg$parsesequence_sep();
if (s8 !== peg$FAILED) {
s9 = peg$parsetranslation();
if (s9 !== peg$FAILED) {
s8 = [s8, s9];
s7 = s8;
} else {
peg$currPos = s7;
s7 = peg$c1;
}
} else {
peg$currPos = s7;
s7 = peg$c1;
}
while (s7 !== peg$FAILED) {
s6.push(s7);
s7 = peg$currPos;
s8 = peg$parsesequence_sep();
if (s8 !== peg$FAILED) {
s9 = peg$parsetranslation();
if (s9 !== peg$FAILED) {
s8 = [s8, s9];
s7 = s8;
} else {
peg$currPos = s7;
s7 = peg$c1;
}
} else {
peg$currPos = s7;
s7 = peg$c1;
}
}
if (s6 !== peg$FAILED) {
s5 = [s5, s6];
s4 = s5;
} else {
peg$currPos = s4;
s4 = peg$c1;
}
} else {
peg$currPos = s4;
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsesp();
if (s5 !== peg$FAILED) {
if (peg$c96.test(input.charAt(peg$currPos))) {
s6 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c97); }
}
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c98(s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsetranslation_sequence() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8;
s0 = peg$currPos;
s1 = peg$parsesp();
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 44) {
s3 = peg$c19;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesp();
if (s4 !== peg$FAILED) {
s3 = [s3, s4];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c1;
}
} else {
peg$currPos = s2;
s2 = peg$c1;
}
if (s2 === peg$FAILED) {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parsetranslation();
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$currPos;
s7 = peg$parsesequence_sep();
if (s7 !== peg$FAILED) {
s8 = peg$parsetranslation();
if (s8 !== peg$FAILED) {
s7 = [s7, s8];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
} else {
peg$currPos = s6;
s6 = peg$c1;
}
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$currPos;
s7 = peg$parsesequence_sep();
if (s7 !== peg$FAILED) {
s8 = peg$parsetranslation();
if (s8 !== peg$FAILED) {
s7 = [s7, s8];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c1;
}
} else {
peg$currPos = s6;
s6 = peg$c1;
}
}
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c98(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsetranslation() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 30) {
s1 = peg$c99;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c100); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseany_integer();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 30) {
s3 = peg$c99;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c100); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c101(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parseinteger() {
var res;
if (res = /^[0-9]{1,3}(?!\d|,000)/.exec(input.substr(peg$currPos))) {
peg$reportedPos = peg$currPos;
peg$currPos += res[0].length;
return {"type": "integer", "value": parseInt(res[0], 10), "indices": [peg$reportedPos, peg$currPos - 1]}
} else {
return peg$c1;
}
}
function peg$parseany_integer() {
var res;
if (res = /^[0-9]+/.exec(input.substr(peg$currPos))) {
peg$reportedPos = peg$currPos;
peg$currPos += res[0].length;
return {"type": "integer", "value": parseInt(res[0], 10), "indices": [peg$reportedPos, peg$currPos - 1]}
} else {
return peg$c1;
}
}
function peg$parseword() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c105.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c106); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c105.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c106); }
}
}
} else {
s1 = peg$c1;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c107(s1);
}
s0 = s1;
return s0;
}
function peg$parseword_parenthesis() {
var s0, s1;
s0 = peg$currPos;
if (peg$c94.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c108(s1);
}
s0 = s1;
return s0;
}
function peg$parsesp() {
var s0;
s0 = peg$parsespace();
if (s0 === peg$FAILED) {
s0 = peg$c2;
}
return s0;
}
function peg$parsespace() {
var res;
if (res = /^[\s\xa0*]+/.exec(input.substr(peg$currPos))) {
peg$reportedPos = peg$currPos;
peg$currPos += res[0].length;
return [];
}
return peg$c1;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
}).call(this);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mobilePlaybackVolumeSelector = exports.playbackVolumeSelector = exports.canSkipSelector = exports.isCurrentDJSelector = exports.djSelector = exports.mediaProgressSelector = exports.timeRemainingSelector = exports.timeElapsedSelector = exports.endTimeSelector = exports.mediaDurationSelector = exports.startTimeSelector = exports.mediaSelector = exports.historyIDSelector = void 0;
var _reselect = require("reselect");
var _dialogSelectors = require("./dialogSelectors");
var _settingSelectors = require("./settingSelectors");
var _timeSelectors = require("./timeSelectors");
var _userSelectors = require("./userSelectors");
var baseSelector = function baseSelector(state) {
return state.booth;
};
var historyIDSelector = (0, _reselect.createSelector)(baseSelector, function (booth) {
return booth.historyID;
});
exports.historyIDSelector = historyIDSelector;
var mediaSelector = (0, _reselect.createSelector)(baseSelector, function (booth) {
return booth.media;
});
exports.mediaSelector = mediaSelector;
var startTimeSelector = (0, _reselect.createSelector)(baseSelector, function (booth) {
return booth.startTime || 0;
});
exports.startTimeSelector = startTimeSelector;
var mediaDurationSelector = (0, _reselect.createSelector)(mediaSelector, function (media) {
return media ? media.end - media.start : 0;
});
exports.mediaDurationSelector = mediaDurationSelector;
var endTimeSelector = (0, _reselect.createSelector)(startTimeSelector, mediaDurationSelector, function (startTime, duration) {
return startTime + duration * 1000 || 0;
});
exports.endTimeSelector = endTimeSelector;
var timeElapsedSelector = (0, _reselect.createSelector)(startTimeSelector, _timeSelectors.currentTimeSelector, // in seconds! because media duration is in seconds, too.
function (startTime, currentTime) {
return startTime ? Math.max((currentTime - startTime) / 1000, 0) : 0;
});
exports.timeElapsedSelector = timeElapsedSelector;
var timeRemainingSelector = (0, _reselect.createSelector)(mediaDurationSelector, timeElapsedSelector, function (duration, elapsed) {
return duration > 0 ? duration - elapsed : 0;
});
exports.timeRemainingSelector = timeRemainingSelector;
var mediaProgressSelector = (0, _reselect.createSelector)(mediaDurationSelector, timeElapsedSelector, function (duration, elapsed) {
return duration // Ensure that the result is between 0 and 1
// It can be outside this range if a network or server hiccup
// results in an advance event getting delayed.
? Math.max(0, Math.min(1, elapsed / duration)) : 0;
});
exports.mediaProgressSelector = mediaProgressSelector;
var djSelector = (0, _reselect.createSelector)(baseSelector, _userSelectors.usersSelector, function (booth, users) {
return users[booth.djID];
});
exports.djSelector = djSelector;
var isCurrentDJSelector = (0, _reselect.createSelector)(djSelector, _userSelectors.currentUserSelector, function (dj, me) {
return dj && me ? dj._id === me._id : false;
});
exports.isCurrentDJSelector = isCurrentDJSelector;
var canSkipSelector = (0, _reselect.createSelector)(historyIDSelector, isCurrentDJSelector, _userSelectors.currentUserHasRoleSelector, function (historyID, isCurrentDJ, hasRole) {
if (!historyID) {
return false;
}
return isCurrentDJ ? hasRole('booth.skip.self') : hasRole('booth.skip.other');
}); // Playback should be muted when the user requested it,
// and when a media preview dialog is open. (Otherwise their audio will interfere.)
exports.canSkipSelector = canSkipSelector;
var playbackMutedSelector = (0, _reselect.createSelector)(_settingSelectors.isMutedSelector, _dialogSelectors.isPreviewMediaDialogOpenSelector, function (isMuted, isPreviewMediaDialogOpen) {
return isMuted || isPreviewMediaDialogOpen;
});
var playbackVolumeSelector = (0, _reselect.createSelector)(_settingSelectors.volumeSelector, playbackMutedSelector, function (volume, isMuted) {
return isMuted ? 0 : volume;
});
exports.playbackVolumeSelector = playbackVolumeSelector;
var mobilePlaybackVolumeSelector = (0, _reselect.createSelector)(playbackMutedSelector, function (isMuted) {
return isMuted ? 0 : 100;
});
exports.mobilePlaybackVolumeSelector = mobilePlaybackVolumeSelector;
//# sourceMappingURL=boothSelectors.js.map
|
'use strict'
const path = require('path')
const { babel } = require('@rollup/plugin-babel')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const banner = require('./banner.js')
const BUNDLE = process.env.BUNDLE === 'true'
const ESM = process.env.ESM === 'true'
let fileDest = `bootstrap${ESM ? '.esm' : ''}`
const external = ['popper.js']
const plugins = [
babel({
// Only transpile our source code
exclude: 'node_modules/**',
// Include the helpers in the bundle, at most one copy of each
babelHelpers: 'bundled'
})
]
const globals = {
'popper.js': 'Popper'
}
if (BUNDLE) {
fileDest += '.bundle'
// Remove last entry in external array to bundle Popper
external.pop()
delete globals['popper.js']
plugins.push(nodeResolve())
}
const rollupConfig = {
input: path.resolve(__dirname, `../js/index.${ESM ? 'esm' : 'umd'}.js`),
output: {
banner,
file: path.resolve(__dirname, `../dist/js/${fileDest}.js`),
format: ESM ? 'esm' : 'umd',
globals
},
external,
plugins
}
if (!ESM) {
rollupConfig.output.name = 'bootstrap'
}
module.exports = rollupConfig
|
// allow content script access to user prefs for this extension
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.cmd == "get_prefs")
sendResponse({
hostlist: localStorage.hostlist || ''
});
else
sendResponse({}); // snub them.
});
|
var COMPLIANCE_APPLICANT = '__COMPLIANCE_APPLICANT__'
var applicant = require('__COMPLIANCE_APPLICANT__')
|
import React from 'react'
import TestRenderer from 'react-test-renderer'
import Image from './Logo.js'
const sizes = {
small: { width: 18, height: 18 },
medium: { width: 24, height: 24 },
large: { width: 36, height: 36 },
extralarge: { width: 48, height: 48 }
}
describe('Logo.svg generated styled component', () => {
let renderer
beforeEach(() => {
renderer = TestRenderer.create(<Image />)
})
it('sets the correct display name', () => {
expect(Image.displayName).toEqual('Logo')
})
it('renders a <svg> tag without crashing', () => {
expect(renderer.root.findAllByType('svg').length).toBe(1)
})
it('renders correctly according to snapshot', () => {
expect(renderer.toJSON()).toMatchSnapshot()
})
it('has dimensions greater than zero', () => {
const dimensions = Image.getDimensions()
expect(dimensions.width).not.toBe('0')
expect(parseInt(dimensions.width, 10)).toBeGreaterThan(0)
expect(dimensions.height).not.toBe('0')
expect(parseInt(dimensions.height, 10)).toBeGreaterThan(0)
})
it('works with dimension types of number', () => {
const size = sizes.medium
const dimensions = Image.getDimensions(size)
expect(dimensions).toEqual(size)
})
it('works with dimension types of string', () => {
const dimensions = Image.getDimensions('small', sizes)
expect(dimensions).toEqual(sizes.small)
})
it('returns an empty string if noStyles param is set', () => {
expect(Image.getCss(undefined, undefined, undefined, undefined, true)).toEqual('')
})
it('returns styles with getCss method', () => {
const fillColor = '#ff0000'
const fillRule = '&&& path, &&& use, &&& g'
expect(Image.getCss('medium', sizes, fillColor, fillRule)).toEqual(['\n width: ', String(sizes.medium.width), 'px;\n height: ', String(sizes.medium.height), 'px;\n ', `${fillRule}{ fill: ${fillColor}; }`, '\n '])
})
})
|
function resultState(state) {
return { state: state }
}
module.exports = resultState
|
import * as React from 'react';
import { expect } from 'chai';
import { act, createRenderer, fireEvent } from 'test/utils';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Dialog from '@mui/material/Dialog';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
describe('<Select> integration', () => {
const { clock, render } = createRenderer({ clock: 'fake' });
describe('with Dialog', () => {
function SelectAndDialog() {
const [value, setValue] = React.useState(10);
const handleChange = (event) => {
setValue(Number(event.target.value));
};
return (
<Dialog open>
<Select
MenuProps={{
transitionDuration: 0,
BackdropProps: { 'data-testid': 'select-backdrop' },
}}
value={value}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</Dialog>
);
}
it('should focus the selected item', () => {
const { getByTestId, getAllByRole, getByRole, queryByRole } = render(<SelectAndDialog />);
const trigger = getByRole('button');
// Let's open the select component
// in the browser user click also focuses
fireEvent.mouseDown(trigger);
const options = getAllByRole('option');
expect(options[1]).toHaveFocus();
// Now, let's close the select component
act(() => {
getByTestId('select-backdrop').click();
});
clock.tick(0);
expect(queryByRole('listbox')).to.equal(null);
expect(trigger).toHaveFocus();
});
it('should be able to change the selected item', () => {
const { getAllByRole, getByRole, queryByRole } = render(<SelectAndDialog />);
const trigger = getByRole('button');
expect(trigger).toHaveAccessibleName('Ten');
// Let's open the select component
// in the browser user click also focuses
fireEvent.mouseDown(trigger);
const options = getAllByRole('option');
expect(options[1]).toHaveFocus();
// Now, let's close the select component
act(() => {
options[2].click();
});
clock.tick(0);
expect(queryByRole('listbox')).to.equal(null);
expect(trigger).toHaveFocus();
expect(trigger).to.have.text('Twenty');
});
});
describe('with label', () => {
it('requires `id` and `labelId` for a proper accessible name', () => {
const { getByRole } = render(
<FormControl>
<InputLabel id="label">Age</InputLabel>
<Select id="input" labelId="label" value="10">
<MenuItem value="">none</MenuItem>
<MenuItem value="10">Ten</MenuItem>
</Select>
</FormControl>,
);
expect(getByRole('button')).toHaveAccessibleName('Age Ten');
});
// we're somewhat abusing "focus" here. What we're actually interested in is
// displaying it as "active". WAI-ARIA authoring practices do not consider the
// the trigger part of the widget while a native <select /> will outline the trigger
// as well
it('is displayed as focused while open', () => {
const { getByTestId, getByRole } = render(
<FormControl>
<InputLabel classes={{ focused: 'focused-label' }} data-testid="label">
Age
</InputLabel>
<Select
MenuProps={{
transitionDuration: 0,
}}
value=""
>
<MenuItem value="">none</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
</Select>
</FormControl>,
);
const trigger = getByRole('button');
act(() => {
trigger.focus();
});
fireEvent.keyDown(trigger, { key: 'Enter' });
clock.tick(0);
expect(getByTestId('label')).to.have.class('focused-label');
});
it('does not stays in an active state if an open action did not actually open', () => {
// test for https://github.com/mui/material-ui/issues/17294
// we used to set a flag to stop blur propagation when we wanted to open the
// select but never considered what happened if the select never opened
const { container, getByRole } = render(
<FormControl>
<InputLabel classes={{ focused: 'focused-label' }} htmlFor="age-simple">
Age
</InputLabel>
<Select inputProps={{ id: 'age' }} open={false} value="">
<MenuItem value="">none</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
</Select>
</FormControl>,
);
const trigger = getByRole('button');
act(() => {
trigger.focus();
});
expect(container.querySelector('[for="age-simple"]')).to.have.class('focused-label');
fireEvent.keyDown(trigger, { key: 'Enter' });
expect(container.querySelector('[for="age-simple"]')).to.have.class('focused-label');
act(() => {
trigger.blur();
});
expect(container.querySelector('[for="age-simple"]')).not.to.have.class('focused-label');
});
});
});
|
// helper method to load js files
// thanks to http://stackoverflow.com/questions/650377/javascript-rhino-use-library-or-include-other-scripts
var importLibrary = function(property) {
var jsFile = project.getProperty(property);
var fileReader = new java.io.FileReader(jsFile);
var fullRead = org.apache.tools.ant.util.FileUtils.readFully(fileReader);
return "" + new java.lang.String(fullRead);
}
// load the libraries
eval(importLibrary("main.library.resfile.js.general"));
var mapPom = function(pomfile, outfile, fallbackGroupId, fallbackArtifactId) {
var doc = createXmlDocument(pomfile);
if (doc == null) {
fail("The pom-file '" + pomfile + "' could not be read");
return null;
} else {
var rootNode = doc.getDocumentElement();
// get the direct depNode and iterate
var mainGroupIdNode = null;
var mainArtifactIdNode = null;
var mainNodes = rootNode.getChildNodes();
for (var i = 0; i < mainNodes.getLength(); i++) {
var mainNode = mainNodes.item(i);
var mainNodeName = mainNode.getNodeName();
// check the important values
if (PomStructure.groupIdNode.equals(mainNodeName)) {
mainGroupIdNode = mainNode;
} else if (PomStructure.artifactIdNode.equals(mainNodeName)) {
mainArtifactIdNode = mainNode;
} else if (PomStructure.parentNode.equalsIgnoreCase(mainNodeName)) {
mapDependency(mainNode);
} else if (PomStructure.dependencyMgmNode.equalsIgnoreCase(mainNodeName)) {
var depMgmNodes = mainNode.getChildNodes();
// find the dependencies node
var depsNodes = null;
for (var k = 0; k < depMgmNodes.getLength(); k++) {
if (PomStructure.dependenciesNode.equalsIgnoreCase(depMgmNodes.item(k).getNodeName())) {
depsNodes = depMgmNodes.item(k);
break;
}
}
if (depsNodes != null) {
for (var k = 0; k < depsNodes.getLength(); k++) {
var depsNode = depsNodes.item(k);
var depsNodeName = depsNode.getNodeName();
if (PomStructure.dependencyNode.equalsIgnoreCase(depsNodeName)) {
mapDependency(depsNode);
}
}
}
} else if (PomStructure.dependenciesNode.equalsIgnoreCase(mainNodeName)) {
// validate the attributes
var depsNodes = mainNode.getChildNodes();
for (var k = 0; k < depsNodes.getLength(); k++) {
var depsNode = depsNodes.item(k);
var depsNodeName = depsNode.getNodeName();
if (PomStructure.dependencyNode.equalsIgnoreCase(depsNodeName)) {
mapDependency(depsNode);
}
}
}
}
// make sure we have a group and artifact
var groupId = mainGroupIdNode == null ? fallbackGroupId : mainGroupIdNode.getTextContent().trim();
var artifactId = mainArtifactIdNode == null ? fallbackArtifactId : mainArtifactIdNode.getTextContent().trim();
// validate
if (checkEmpty(fallbackGroupId) != null && !fallbackGroupId.equals(groupId)) {
fail("The specified fallback groupId '" + fallbackGroupId + "' does not match the groupId determined '" + groupId + "'");
} else if (checkEmpty(fallbackArtifactId) != null && !fallbackArtifactId.equals(artifactId)) {
fail("The specified fallback artifactId '" + fallbackArtifactId + "' does not match the artifactId determined '" + artifactId + "'");
}
// do the main-replacements
var mapping = mapArtifact(groupId, artifactId);
if (mainGroupIdNode == null) {
mainGroupIdNode = doc.createElement(PomStructure.groupIdNode);
rootNode.appendChild(mainGroupIdNode);
}
mainGroupIdNode.setTextContent(mapping[0]);
if (mainGroupIdNode == null) {
mainArtifactIdNode = doc.createElement(PomStructure.artifactIdNode);
rootNode.appendChild(mainArtifactIdNode);
}
mainArtifactIdNode.setTextContent(mapping[1]);
// remove all the whitespaces to ensure nice indent
removeWhiteSpacesInXml(rootNode);
// write the new document
var transformer = javax.xml.transform.TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
var source = new javax.xml.transform.dom.DOMSource(doc);
// get the result
var result = new javax.xml.transform.stream.StreamResult(new java.io.FileOutputStream(outfile == null ? pomfile : outfile));
transformer.transform(source, result);
}
}
var mapDependency = function(node) {
var dependency = parseDependency(node);
var nodeName = node.getNodeName();
// get the mappings
var mapping = mapArtifact(dependency.groupId, dependency.artifactId);
// get the elements of the node
var depNodes = node.getChildNodes();
for (var h = 0; h < depNodes.getLength(); h++) {
var depNode = depNodes.item(h);
var depNodeName = depNode.getNodeName();
if (PomStructure.groupIdNode.equalsIgnoreCase(depNodeName)) {
depNode.setTextContent(mapping[0]);
} else if (PomStructure.artifactIdNode.equalsIgnoreCase(depNodeName)) {
depNode.setTextContent(mapping[1]);
}
}
}
var mapArtifact = function(group, artifact) {
var mapperGroup = "maven.mapped." + group;
var mapperArtifact = "maven.mapped." + group + "|" + artifact;
// get the mapper
var groupMapper = project.getProperty(mapperGroup);
var artifactMapper = project.getProperty(mapperArtifact);
// get the results
var mappedGroup = group;
var mappedArtifact = artifact;
if (artifactMapper != null) {
var splits = artifactMapper.split("\\|");
mappedGroup = splits[0];
mappedArtifact = splits.length > 1 ? splits[1] : artifact;
} else if (groupMapper != null) {
mappedGroup = groupMapper;
}
// return as array
var mapping = new Array();
mapping[0] = mappedGroup;
mapping[1] = mappedArtifact;
return mapping;
}
var loadPom = function(pomId, pomFile, settingsfile) {
var refIdPoms = "maven.mavenSetPom.mapOfPoms";
var refIdCache = "maven.mavenSetPom.mavenCache";
// get the map and create if not available
var poms = project.getReference(refIdPoms);
if (poms == null) {
poms = new java.util.HashMap();
project.addReference(refIdPoms, poms);
} else if (poms instanceof java.util.HashMap == false) {
fail("The collection of pom-projects could not be loaded, because it is of invalid type '" + poms.getClass().getName + "'");
}
// create the cache controller
var cache = project.getReference(refIdCache);
if (cache == null) {
cache = new MavenCaches();
project.addReference(refIdCache, cache);
}
// create the meta information of the new pomFile
newPomMeta = new PomMeta(pomId, pomFile, settingsFile);
// now let's check if we have this reference already and if we have to do something
var curPomMeta = poms.get(pomId);
var changes = newPomMeta.determineChange(curPomMeta);
if (changes < 0) {
fail("Invalid comparison of poms '" + curPomMeta + "' and '" + newPomMeta + "'");
} else if (changes > 0) {
// create the new pom
var pomTask = project.createTask("antlib:org.apache.maven.artifact.ant:pom");
pomTask.setId(pomId);
pomTask.setInheritAllProperties(false);
pomTask.setSettingsFile(newPomMeta.settingsFile);
pomTask.setFile(newPomMeta.pomFile);
pomTask.execute();
// keep the new one
poms.put(pomId, newPomMeta);
// make sure that this stupid fucked up cache is disabled
cache.disableCaching();
}
return project.getReference(pomId);
}
|
/**
* Section model events
*/
'use strict';
var EventEmitter = require('events').EventEmitter;
var Section = require('./section.model');
var SectionEvents = new EventEmitter();
// Set max event listeners (0 == unlimited)
SectionEvents.setMaxListeners(0);
// Model events
var events = {
'save': 'save',
'remove': 'remove'
};
// Register the event emitter to the model events
for (var e in events) {
var event = events[e];
Section.schema.post(e, emitEvent(event));
}
function emitEvent(event) {
return function(doc) {
SectionEvents.emit(event + ':' + doc._id, doc);
SectionEvents.emit(event, doc);
}
}
module.exports = SectionEvents;
|
/*
* Copyright (c) 2016-17 Francesco Marino
*
* @author Francesco Marino <francesco@360fun.net>
* @website www.360fun.net
*
* This is just a basic Class to start playing with the new Web Bluetooth API,
* specifications can change at any time so keep in mind that all of this is
* mostly experimental! ;)
*
* Check your browser and platform implementation status first
* https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/implementation-status.md
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function() {
'use strict';
// UTF-8
let encoder = new TextEncoder('utf-8');
let decoder = new TextDecoder('utf-8');
class WebBluetooth {
constructor() {
this.device = null;
this.server = null;
this._characteristics = new Map();
this._debug = false;
}
isConnected() {
return this.device && this.device.gatt.connected;
}
connect(options,services) {
return navigator.bluetooth.requestDevice(options)
.then(device => {
this.device = device;
this._log('Connected to device named "' + device.name + '" with ID "' + device.id + '"');
return device.gatt.connect();
})
.then(server => {
this.server = server;
return Promise.all(
Object.keys(services).map( serviceId => {
return server.getPrimaryService(serviceId).then(service => {
return Promise.all(
Object.keys(services[serviceId].characteristics).map( characteristicId => {
return this._cacheCharacteristic(service, characteristicId)
.then( () => {
this._log('Found characteristic "' + characteristicId + '"');
})
.catch( e => { this._error('Characteristic "' + characteristicId + '" NOT found') } );
})
);
})
.then( () => {
this._log('Found service "' + serviceId + '"');
})
.catch( e => { this._error('Service "' + serviceId + '"') } );
})
);
});
}
disconnect() {
return new Promise( (resolve, reject) => {
if( this.isConnected() ) {
resolve();
} else {
reject('Device not connected');
}
}
).then( ()=> {
this._log('Device disconnected')
return this.device.gatt.disconnect();
}).catch( e => { this._error(e) } );
}
readCharacteristicValue(characteristicUuid) {
return new Promise( (resolve, reject) => {
if( this.isConnected() ) {
resolve();
} else {
reject('Device not connected');
}
}
).then( ()=> {
let characteristic = this._characteristics.get(characteristicUuid);
return characteristic.readValue()
.then(value => {
// In Chrome 50+, a DataView is returned instead of an ArrayBuffer.
value = value.buffer ? value : new DataView(value);
this._log('READ', characteristic.uuid, value);
return value;
});
})
.catch( e => { this._error(e) } );
}
writeCharacteristicValue(characteristicUuid, value) {
return new Promise( (resolve, reject) => {
if( this.isConnected() ) {
resolve();
} else {
reject('Device not connected');
}
}
).then( ()=> {
let characteristic = this._characteristics.get(characteristicUuid);
this._log('WRITE', characteristic.uuid, value);
return characteristic.writeValue(value);
}).catch( e => { this._error(e) } );
}
_error(msg) {
if(this._debug) {
console.debug(msg);
} else {
throw msg;
}
}
_log(msg) {
if(this._debug) {
console.log(msg);
}
}
_cacheCharacteristic(service, characteristicUuid) {
return service.getCharacteristic(characteristicUuid)
.then(characteristic => {
this._characteristics.set(characteristicUuid, characteristic);
});
}
_decodeString(data) {
return decoder.decode(data);
}
_encodeString(data) {
return encoder.encode(data);
}
}
window.WebBluetooth = new WebBluetooth();
})();
|
import { UrlUtil } from './UrlUtil'
export class Effects {
constructor () {
this.bindHighlight()
}
// if a var highlight exists in the url it will be highlighted
bindHighlight () {
// get highlight from url
const highlightId = UrlUtil.getGetValue('highlight')
// id is set
if (highlightId !== '') {
// init selector of the element we want to highlight
let selector = '#' + highlightId
// item exists
if ($(selector).length > 0) {
// if its a table row we need to highlight all cells in that row
if ($(selector)[0].tagName.toLowerCase() === 'tr') {
selector += ' td'
}
// when we hover over the item we stop the effect, otherwise we will mess up background hover styles
$(selector).on('mouseover', () => {
$(selector).removeClass('highlighted')
})
// highlight!
$(selector).addClass('highlighted')
setTimeout(() => {
$(selector).removeClass('highlighted')
}, 5000)
}
}
}
}
|
//compute Async real
function heavyCompute(n){
var count = 0,
i, j;
for (i = n; i > 0; --i) {
for (j = n; j > 0; --j) {
count += 1;
}
}
}
var t =new Date();
setTimeout(function(){
console.log(new Date() -t);
} ,1000);
heavyCompute(50000);
|
8.0-alpha2:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha3:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha4:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha5:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha6:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha7:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha8:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha9:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha10:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha11:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
8.0-alpha12:2647350694960ffc321b0f2f1631f7a744f6dc7d85cb5512d8edb41f97afab78
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import Admin from '../../components/Admin/index.jsx';
// include actions as they are needed by each component
// they are called via dispatch()
const propTypes = {
dispatch: PropTypes.func,
content: PropTypes.object
};
// in here, we determine the props to be passed down to the specific component needed
class AdminContainer extends Component {
componentDidMount () {
const { dispatch, componentContent } = this.props;
}
render () {
return (
<Admin {...this.props} />
);
}
}
AdminContainer.propTypes = propTypes;
function mapStateToProps(state) {
const componentContent = state.content.project.components;
const projectName = state.content.projectName;
const loadedAdminComponents = state.admin.loadedAdminComponents;
const componentsLoaded = state.admin.componentsLoaded;
const activeComponentClass = state.admin.activeComponentClass;
const selectedComponent = state.admin.selectedComponent;
const loadedComponentContent = state.content.project.components;
return {
componentContent,
projectName,
selectedComponent,
loadedAdminComponents,
loadedComponentContent,
componentsLoaded,
activeComponentClass
};
}
function mapDispatchToProps (dispatch) {
return {
dispatchActivateComponent: (component) => {
dispatch(actions.activateComponent(component))
},
dispatchLoadAdminComponents: (components) => {
dispatch(actions.loadAdminComponents(components));
dispatch(actions.componentsLoadedAdmin(true));
},
dispatchSelectComponent: (component) => {
dispatch(actions.updateSelectedComponent(component))
},
dispatchEditContent: (name, value, selectedComponent) => {
dispatch(actions.editContent(name, value, selectedComponent))
},
dispatchLogout: () => {
dispatch(actions.logout())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AdminContainer);
|
import actionTypes from 'constants/action-types';
const initialState = {
collection: [],
loading: false,
error: {}
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case actionTypes.LANGUAGES_FETCH_REQUEST:
return {
...state,
loading: true
};
case actionTypes.LANGUAGES_FETCH_SUCCESS:
return {
...state,
loading: false,
collection: action.collection
};
case actionTypes.LANGUAGES_FETCH_ERROR:
return {
...state,
loading: false,
error: action.error
};
default:
return state;
}
}
|
require(
{
baseUrl: chrome.extension.getURL('/'),
paths: {
backbone: 'vendors/backbone.min',
underscore: 'vendors/lodash.custom.min',
jquery: 'vendors/jquery-2.1.4.min',
bluebird: 'vendors/bluebird.min',
moment: 'vendors/moment.min'
},
shim: {
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
}
}
},
['background/app'],
function (App) {
window.app = new App({});
window.app.run();
}
);
|
// ------------------------------------------------------------------------------------------- //
// ----------------------------------------- Schema ----------------------------------------- //
// ------------------------------------------------------------------------------------------- //
SimpleSchema.extendOptions({
editable: Match.Optional(Boolean) // editable: true means the field can be edited by the document's owner
});
postSchemaObject = {
_id: {
type: String,
optional: true,
autoform: {
omit: true
}
},
createdAt: {
type: Date,
optional: true,
autoform: {
omit: true
}
},
postedAt: {
type: Date,
optional: true,
autoform: {
group: 'admin',
type: "bootstrap-datetimepicker"
}
},
url: {
type: String,
label: "URL",
optional: true,
autoform: {
editable: true,
type: "bootstrap-url"
}
},
title: {
type: String,
optional: false,
label: "Title",
editable: true,
autoform: {
editable: true
}
},
body: {
type: String,
optional: true,
editable: true,
autoform: {
editable: true,
rows: 5
}
},
htmlBody: {
type: String,
optional: true,
autoform: {
omit: true
}
},
viewCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
commentCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
commenters: {
type: [String],
optional: true,
autoform: {
omit: true
}
},
lastCommentedAt: {
type: Date,
optional: true,
autoform: {
omit: true
}
},
clickCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
baseScore: {
type: Number,
decimal: true,
optional: true,
autoform: {
omit: true
}
},
upvotes: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
upvoters: {
type: [String], // XXX
optional: true,
autoform: {
omit: true
}
},
downvotes: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
downvoters: {
type: [String], // XXX
optional: true,
autoform: {
omit: true
}
},
score: {
type: Number,
decimal: true,
optional: true,
autoform: {
omit: true
}
},
status: {
type: Number,
optional: true,
autoValue: function () {
// only provide a default value
// 1) this is an insert operation
// 2) status field is not set in the document being inserted
if(this.isInsert && !this.isSet)
return getSetting('requirePostsApproval', false) ? STATUS_PENDING: STATUS_APPROVED
},
autoform: {
noselect: true,
options: postStatuses,
group: 'admin'
}
},
sticky: {
type: Boolean,
optional: true,
defaultValue: false,
autoform: {
group: 'admin',
leftLabel: "Sticky"
}
},
inactive: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
},
author: {
type: String,
optional: true,
autoform: {
omit: true
}
},
brand: {
type: String,
optional: true
},
userId: {
type: String, // XXX
optional: true,
autoform: {
group: 'admin',
options: function () {
return Meteor.users.find().map(function (user) {
return {
value: user._id,
label: getDisplayName(user)
}
});
}
}
}
};
// add any extra properties to postSchemaObject (provided by packages for example)
_.each(addToPostSchema, function(item){
postSchemaObject[item.propertyName] = item.propertySchema;
});
Posts = new Meteor.Collection("posts");
PostSchema = new SimpleSchema(postSchemaObject);
Posts.attachSchema(PostSchema);
// Posts.deny({
// update: function(userId, post, fieldNames) {
// if(isAdminById(userId))
// return false;
// // deny the update if it contains something other than the following fields
// return (_.without(fieldNames, 'title', 'url', 'body', 'shortUrl', 'shortTitle', 'categories').length > 0);
// }
// });
// Posts.allow({
// update: canEditById,
// remove: canEditById
// });
// ------------------------------------------------------------------------------------------- //
// ----------------------------------------- Helpers ----------------------------------------- //
// ------------------------------------------------------------------------------------------- //
getPostProperties = function (post) {
var postAuthor = Meteor.users.findOne(post.userId);
var p = {
postAuthorName : getDisplayName(postAuthor),
postTitle : cleanUp(post.title),
profileUrl: getProfileUrlBySlugOrId(post.userId),
postUrl: getPostPageUrl(post),
thumbnailUrl: post.thumbnailUrl,
linkUrl: !!post.url ? getOutgoingUrl(post.url) : getPostPageUrl(post._id)
};
if(post.url)
p.url = post.url;
if(post.htmlBody)
p.htmlBody = post.htmlBody;
return p;
};
getPostPageUrl = function(post){
return getSiteUrl()+'posts/'+post._id;
};
getPostEditUrl = function(id){
return getSiteUrl()+'posts/'+id+'/edit';
};
// for a given post, return its link if it has one, or else its post page URL
getPostLink = function (post) {
return !!post.url ? getOutgoingUrl(post.url) : getPostPageUrl(post);
};
checkForPostsWithSameUrl = function (url) {
// check that there are no previous posts with the same link in the past 6 months
var sixMonthsAgo = moment().subtract(6, 'months').toDate();
var postWithSameLink = Posts.findOne({url: url, postedAt: {$gte: sixMonthsAgo}});
if(typeof postWithSameLink !== 'undefined'){
Meteor.call('upvotePost', postWithSameLink);
// note: error.details returns undefined on the client, so add post ID to reason
throw new Meteor.Error('603', i18n.t('this_link_has_already_been_posted') + '|' + postWithSameLink._id, postWithSameLink._id);
}
}
// ------------------------------------------------------------------------------------------- //
// ------------------------------------------ Hooks ------------------------------------------ //
// ------------------------------------------------------------------------------------------- //
Posts.before.insert(function (userId, doc) {
if(Meteor.isServer && !!doc.body)
doc.htmlBody = sanitize(marked(doc.body));
});
Posts.before.update(function (userId, doc, fieldNames, modifier, options) {
// if body is being modified, update htmlBody too
if (Meteor.isServer && modifier.$set && modifier.$set.body) {
modifier.$set = modifier.$set || {};
modifier.$set.htmlBody = sanitize(marked(modifier.$set.body));
}
});
// ------------------------------------------------------------------------------------------- //
// ----------------------------------------- Methods ----------------------------------------- //
// ------------------------------------------------------------------------------------------- //
postClicks = [];
postViews = [];
Meteor.methods({
submitPost: function(post){
var title = cleanUp(post.title),
body = post.body,
userId = this.userId,
user = Meteor.users.findOne(userId),
timeSinceLastPost=timeSinceLast(user, Posts),
numberOfPostsInPast24Hours=numberOfItemsInPast24Hours(user, Posts),
postInterval = Math.abs(parseInt(getSetting('postInterval', 30))),
maxPostsPer24Hours = Math.abs(parseInt(getSetting('maxPostsPerDay', 30))),
postId = '';
// ------------------------------ Checks ------------------------------ //
// check that user can post
if (!user || !canPost(user))
throw new Meteor.Error(601, i18n.t('you_need_to_login_or_be_invited_to_post_new_stories'));
// check that user provided a title
if(!post.title)
throw new Meteor.Error(602, i18n.t('please_fill_in_a_title'));
// check that there are no posts with the same URL
if(!!post.url)
checkForPostsWithSameUrl(post.url);
// --------------------------- Rate Limiting -------------------------- //
if(!isAdmin(Meteor.user())){
// check that user waits more than X seconds between posts
if(!this.isSimulation && timeSinceLastPost < postInterval)
throw new Meteor.Error(604, i18n.t('please_wait')+(postInterval-timeSinceLastPost)+i18n.t('seconds_before_posting_again'));
// check that the user doesn't post more than Y posts per day
if(!this.isSimulation && numberOfPostsInPast24Hours > maxPostsPer24Hours)
throw new Meteor.Error(605, i18n.t('sorry_you_cannot_submit_more_than')+maxPostsPer24Hours+i18n.t('posts_per_day'));
}
// ------------------------------ Properties ------------------------------ //
// Basic Properties
properties = {
title: title,
body: body,
userId: userId,
author: getDisplayNameById(userId),
upvotes: 0,
downvotes: 0,
commentCount: 0,
clickCount: 0,
viewCount: 0,
baseScore: 0,
score: 0,
inactive: false
};
// UserId
if(isAdmin(Meteor.user()) && !!post.userId){ // only let admins post as other users
properties.userId = post.userId;
}
// Status
var defaultPostStatus = getSetting('requirePostsApproval') ? STATUS_PENDING : STATUS_APPROVED;
if(isAdmin(Meteor.user()) && !!post.status){ // if user is admin and a custom status has been set
properties.status = post.status;
}else{ // else use default status
properties.status = defaultPostStatus;
}
// CreatedAt
properties.createdAt = new Date();
// PostedAt
if(properties.status == 2){ // only set postedAt if post is approved
if(isAdmin(Meteor.user()) && !!post.postedAt){ // if user is admin and a custom postDate has been set
properties.postedAt = post.postedAt;
}else{ // else use current time
properties.postedAt = new Date();
}
}
post = _.extend(post, properties);
// ------------------------------ Callbacks ------------------------------ //
// run all post submit server callbacks on post object successively
post = postSubmitMethodCallbacks.reduce(function(result, currentFunction) {
return currentFunction(result);
}, post);
// ------------------------------ Insert ------------------------------ //
// console.log(post)
post._id = Posts.insert(post);
// ------------------------------ Callbacks ------------------------------ //
// run all post submit server callbacks on post object successively
post = postAfterSubmitMethodCallbacks.reduce(function(result, currentFunction) {
return currentFunction(result);
}, post);
// ------------------------------ After Insert ------------------------------ //
// increment posts count
Meteor.users.update({_id: userId}, {$inc: {postCount: 1}});
var postAuthor = Meteor.users.findOne(post.userId);
Meteor.call('upvotePost', post, postAuthor);
return post;
},
editPost: function (postId, updateObject) {
var user = Meteor.user();
// console.log(updateObject)
// ------------------------------ Checks ------------------------------ //
// check that user can edit
if (!user || !canEdit(user, Posts.findOne(postId)))
throw new Meteor.Error(601, i18n.t('sorry_you_cannot_edit_this_post'));
// ------------------------------ Callbacks ------------------------------ //
// run all post submit server callbacks on updateObject successively
updateObject = postEditMethodCallbacks.reduce(function(result, currentFunction) {
return currentFunction(result);
}, updateObject);
console.log(updateObject)
// ------------------------------ Update ------------------------------ //
Posts.update(postId, updateObject);
// ------------------------------ Callbacks ------------------------------ //
// run all post submit server callbacks on updateObject successively
updateObject = postAfterEditMethodCallbacks.reduce(function(result, currentFunction) {
return currentFunction(result);
}, updateObject);
// ------------------------------ After Update ------------------------------ //
return Posts.findOne(postId);
},
setPostedAt: function(post, customPostedAt){
var postedAt = new Date(); // default to current date and time
if(isAdmin(Meteor.user()) && typeof customPostedAt !== 'undefined') // if user is admin and a custom datetime has been set
postedAt = customPostedAt;
Posts.update(post._id, {$set: {postedAt: postedAt}});
},
approvePost: function(post){
if(isAdmin(Meteor.user())){
var set = {status: 2};
// unless post is already scheduled and has a postedAt date, set its postedAt date to now
if (!post.postedAt)
set.postedAt = new Date();
var result = Posts.update(post._id, {$set: set}, {validate: false});
}else{
flashMessage('You need to be an admin to do that.', "error");
}
},
unapprovePost: function(post){
if(isAdmin(Meteor.user())){
Posts.update(post._id, {$set: {status: 1}});
}else{
flashMessage('You need to be an admin to do that.', "error");
}
},
increasePostViews: function(postId, sessionId){
this.unblock();
// only let users increment a post's view counter once per session
var view = {_id: postId, userId: this.userId, sessionId: sessionId};
if(_.where(postViews, view).length == 0){
postViews.push(view);
Posts.update(postId, { $inc: { viewCount: 1 }});
}
},
increasePostClicks: function(postId, sessionId){
this.unblock();
// only let clients increment a post's click counter once per session
var click = {_id: postId, userId: this.userId, sessionId: sessionId};
if(_.where(postClicks, click).length == 0){
postClicks.push(click);
Posts.update(postId, { $inc: { clickCount: 1 }});
}
},
deletePostById: function(postId) {
// remove post comments
// if(!this.isSimulation) {
// Comments.remove({post: postId});
// }
// NOTE: actually, keep comments after all
var post = Posts.findOne({_id: postId});
if(!Meteor.userId() || !canEditById(Meteor.userId(), post)) throw new Meteor.Error(606, 'You need permission to edit or delete a post');
// decrement post count
Meteor.users.update({_id: post.userId}, {$inc: {postCount: -1}});
// delete post
Posts.remove(postId);
}
});
|
import React,{Component} from 'react'
import {HashRouter,Route,Switch} from 'react-router-dom'
import Root from './components/base/root'
export default () => {
return (
<HashRouter>
<div>
<Switch>
<Route path="/" component={Root}/>
</Switch>
</div>
</HashRouter>
)
}
|
Martin._version = '0.4.2';
|
#!/usr/bin/env node
'use strict'
const localWebServer = require('../')
const cliOptions = require('../lib/cli-options')
const commandLineArgs = require('command-line-args')
const ansi = require('ansi-escape-sequences')
const loadConfig = require('config-master')
const path = require('path')
const os = require('os')
const arrayify = require('array-back')
const t = require('typical')
const flatten = require('reduce-flatten')
const cli = commandLineArgs(cliOptions.definitions)
const usage = cli.getUsage(cliOptions.usageData)
const stored = loadConfig('local-web-server')
let options
let isHttps = false
try {
options = collectOptions()
} catch (err) {
stop([ `[red]{Error}: ${err.message}`, usage ], 1)
return
}
if (options.misc.help) {
stop(usage, 0)
} else if (options.misc.config) {
stop(JSON.stringify(options.server, null, ' '), 0)
} else {
const valid = validateOptions(options)
if (!valid) {
/* gracefully end the process */
return
}
const app = localWebServer({
static: {
root: options.server.directory,
options: {
hidden: true
}
},
serveIndex: {
path: options.server.directory,
options: {
icons: true,
hidden: true
}
},
log: {
format: options.server['log-format']
},
compress: options.server.compress,
mime: options.server.mime,
forbid: options.server.forbid,
spa: options.server.spa,
'no-cache': options.server['no-cache'],
rewrite: options.server.rewrite,
verbose: options.server.verbose,
mocks: options.server.mocks
})
app.on('error', err => {
if (options.server['log-format']) {
console.error(ansi.format(err.message, 'red'))
}
})
if (options.server.https) {
options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key')
options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt')
}
if (options.server.key && options.server.cert) {
const https = require('https')
const fs = require('fs')
isHttps = true
const serverOptions = {
key: fs.readFileSync(options.server.key),
cert: fs.readFileSync(options.server.cert)
}
const server = https.createServer(serverOptions, app.callback())
server.listen(options.server.port, onServerUp)
} else {
app.listen(options.server.port, onServerUp)
}
}
function stop (msgs, exitCode) {
arrayify(msgs).forEach(msg => console.error(ansi.format(msg)))
process.exitCode = exitCode
}
function onServerUp () {
let ipList = Object.keys(os.networkInterfaces())
.map(key => os.networkInterfaces()[key])
.reduce(flatten, [])
.filter(iface => iface.family === 'IPv4')
ipList.unshift({ address: os.hostname() })
ipList = ipList
.map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`)
.join(', ')
console.error(ansi.format(
path.resolve(options.server.directory) === process.cwd()
? `serving at ${ipList}`
: `serving [underline]{${options.server.directory}} at ${ipList}`
))
}
function collectOptions () {
let options = {}
/* parse command line args */
options = cli.parse()
const builtIn = {
port: 8000,
directory: process.cwd(),
forbid: [],
rewrite: []
}
if (options.server.rewrite) {
options.server.rewrite = parseRewriteRules(options.server.rewrite)
}
/* override built-in defaults with stored config and then command line args */
options.server = Object.assign(builtIn, stored, options.server)
return options
}
function parseRewriteRules (rules) {
return rules && rules.map(rule => {
const matches = rule.match(/(\S*)\s*->\s*(\S*)/)
return {
from: matches[1],
to: matches[2]
}
})
}
function validateOptions (options) {
let valid = true
function invalid (msg) {
return `[red underline]{Invalid:} [bold]{${msg}}`
}
if (!t.isNumber(options.server.port)) {
stop([ invalid(`--port must be numeric`), usage ], 1)
valid = false
}
return valid
}
|
map = null;
directionsDisplay = null;
directionsService = null;
pointsArr = new Array();
drawPath = function drawPath() {
if (pointsArr.length >= 2) {
var origen = pointsArr[0];
var destino = pointsArr[pointsArr.length - 1];
var waypointsArr = new Array();
//if (pointsArr.length > 2) {
// var i = 0;
pointsArr.forEach(function (item) {
//if (origen != item && destino != item) {
// waypointsArr.push({'location': item});
//}
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
'sandstone rock formation in the southern part of the '+
'Northern Territory, central Australia. It lies 335 km (208 mi) '+
'south west of the nearest large town, Alice Springs; 450 km '+
'(280 mi) by road. Kata Tjuta and Uluru are the two major '+
'features of the Uluru - Kata Tjuta National Park. Uluru is '+
'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
'Aboriginal people of the area. It has many springs, waterholes, '+
'rock caves and ancient paintings. Uluru is listed as a World '+
'Heritage Site.</p>'+
'<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
'https://en.wikipedia.org/w/index.php?title=Uluru</a> '+
'(last visited June 22, 2009).</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: item,
map: map,
title: 'Hello World!'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
//}
//
//var request = {
// origin: origen,
// waypoints: waypointsArr,
// destination: destino,
// travelMode: google.maps.TravelMode.WALKING
//};
//directionsService.route(request, function (response, status) {
// if (status == google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
// }
//});
directionsDisplay.setMap(map);
//directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
}
|
import BaseSerializer from './application';
export default BaseSerializer.extend({
});
|
/**
* @name SearchSource
*
* @description A promise-based stream of search results that can inherit from other search sources.
*
* Because filters/queries in Kibana have different levels of persistence and come from different
* places, it is important to keep track of where filters come from for when they are saved back to
* the savedObject store in the Kibana index. To do this, we create trees of searchSource objects
* that can have associated query parameters (index, query, filter, etc) which can also inherit from
* other searchSource objects.
*
* At query time, all of the searchSource objects that have subscribers are "flattened", at which
* point the query params from the searchSource are collected while traversing up the inheritance
* chain. At each link in the chain a decision about how to merge the query params is made until a
* single set of query parameters is created for each active searchSource (a searchSource with
* subscribers).
*
* That set of query parameters is then sent to elasticsearch. This is how the filter hierarchy
* works in Kibana.
*
* Visualize, starting from a new search:
*
* - the `savedVis.searchSource` is set as the `appSearchSource`.
* - The `savedVis.searchSource` would normally inherit from the `appSearchSource`, but now it is
* upgraded to inherit from the `rootSearchSource`.
* - Any interaction with the visualization will still apply filters to the `appSearchSource`, so
* they will be stored directly on the `savedVis.searchSource`.
* - Any interaction with the time filter will be written to the `rootSearchSource`, so those
* filters will not be saved by the `savedVis`.
* - When the `savedVis` is saved to elasticsearch, it takes with it all the filters that are
* defined on it directly, but none of the ones that it inherits from other places.
*
* Visualize, starting from an existing search:
*
* - The `savedVis` loads the `savedSearch` on which it is built.
* - The `savedVis.searchSource` is set to inherit from the `saveSearch.searchSource` and set as
* the `appSearchSource`.
* - The `savedSearch.searchSource`, is set to inherit from the `rootSearchSource`.
* - Then the `savedVis` is written to elasticsearch it will be flattened and only include the
* filters created in the visualize application and will reconnect the filters from the
* `savedSearch` at runtime to prevent losing the relationship
*
* Dashboard search sources:
*
* - Each panel in a dashboard has a search source.
* - The `savedDashboard` also has a searchsource, and it is set as the `appSearchSource`.
* - Each panel's search source inherits from the `appSearchSource`, meaning that they inherit from
* the dashboard search source.
* - When a filter is added to the search box, or via a visualization, it is written to the
* `appSearchSource`.
*/
import _ from 'lodash';
import NormalizeSortRequestProvider from './_normalize_sort_request';
import rootSearchSource from './_root_search_source';
import AbstractDataSourceProvider from './_abstract';
import SearchRequestProvider from '../fetch/request/search';
import SegmentedRequestProvider from '../fetch/request/segmented';
import SearchStrategyProvider from '../fetch/strategy/search';
export default function SearchSourceFactory(Promise, Private, config) {
const SourceAbstract = Private(AbstractDataSourceProvider);
const SearchRequest = Private(SearchRequestProvider);
const SegmentedRequest = Private(SegmentedRequestProvider);
const searchStrategy = Private(SearchStrategyProvider);
const normalizeSortRequest = Private(NormalizeSortRequestProvider);
const forIp = Symbol('for which index pattern?');
function isIndexPattern(val) {
return Boolean(val && typeof val.toIndexList === 'function');
}
_.class(SearchSource).inherits(SourceAbstract);
function SearchSource(initialState) {
SearchSource.Super.call(this, initialState, searchStrategy);
}
/*****
* PUBLIC API
*****/
/**
* List of the editable state properties that turn into a
* chainable API
*
* @type {Array}
*/
SearchSource.prototype._methods = [
'type',
'query',
'filter',
'sort',
'highlight',
'highlightAll',
'aggs',
'from',
'size',
'source'
];
SearchSource.prototype.index = function (indexPattern) {
const state = this._state;
const hasSource = state.source;
const sourceCameFromIp = hasSource && state.source.hasOwnProperty(forIp);
const sourceIsForOurIp = sourceCameFromIp && state.source[forIp] === state.index;
if (sourceIsForOurIp) {
delete state.source;
}
if (indexPattern === undefined) return state.index;
if (indexPattern === null) return delete state.index;
if (!isIndexPattern(indexPattern)) {
throw new TypeError('expected indexPattern to be an IndexPattern duck.');
}
state.index = indexPattern;
if (!state.source) {
// imply source filtering based on the index pattern, but allow overriding
// it by simply setting another value for "source". When index is changed
state.source = function () {
return indexPattern.getSourceFiltering();
};
state.source[forIp] = indexPattern;
}
return this;
};
SearchSource.prototype.extend = function () {
return (new SearchSource()).inherits(this);
};
/**
* Set a searchSource that this source should inherit from
* @param {SearchSource} searchSource - the parent searchSource
* @return {this} - chainable
*/
SearchSource.prototype.inherits = function (parent) {
this._parent = parent;
return this;
};
/**
* Get the parent of this SearchSource
* @return {undefined|searchSource}
*/
SearchSource.prototype.getParent = function (onlyHardLinked) {
const self = this;
if (self._parent === false) return;
if (self._parent) return self._parent;
return onlyHardLinked ? undefined : Private(rootSearchSource).get();
};
/**
* Temporarily prevent this Search from being fetched... not a fan but it's easy
*/
SearchSource.prototype.disable = function () {
this._fetchDisabled = true;
};
/**
* Reverse of SourceAbstract#disable(), only need to call this if source was previously disabled
*/
SearchSource.prototype.enable = function () {
this._fetchDisabled = false;
};
SearchSource.prototype.onBeginSegmentedFetch = function (initFunction) {
const self = this;
return Promise.try(function addRequest() {
const req = new SegmentedRequest(self, Promise.defer(), initFunction);
// return promises created by the completion handler so that
// errors will bubble properly
return req.getCompletePromise().then(addRequest);
});
};
/******
* PRIVATE APIS
******/
/**
* Gets the type of the DataSource
* @return {string}
*/
SearchSource.prototype._getType = function () {
return 'search';
};
/**
* Create a common search request object, which should
* be put into the pending request queye, for this search
* source
*
* @param {Deferred} defer - the deferred object that should be resolved
* when the request is complete
* @return {SearchRequest}
*/
SearchSource.prototype._createRequest = function (defer) {
return new SearchRequest(this, defer);
};
/**
* Used to merge properties into the state within ._flatten().
* The state is passed in and modified by the function
*
* @param {object} state - the current merged state
* @param {*} val - the value at `key`
* @param {*} key - The key of `val`
* @return {undefined}
*/
SearchSource.prototype._mergeProp = function (state, val, key) {
if (typeof val === 'function') {
const source = this;
return Promise.cast(val(this))
.then(function (newVal) {
return source._mergeProp(state, newVal, key);
});
}
if (val == null || !key || !_.isString(key)) return;
switch (key) {
case 'filter':
let verifiedFilters = val;
if (config.get('courier:ignoreFilterIfFieldNotInIndex')) {
if (!_.isArray(val)) val = [val];
verifiedFilters = val.filter(function (el) {
if ('meta' in el && 'index' in state) {
const field = state.index.fields.byName[el.meta.key];
if (!field) return false;
}
return true;
});
}
// user a shallow flatten to detect if val is an array, and pull the values out if it is
state.filters = _([ state.filters || [], verifiedFilters ])
.flatten()
// Yo Dawg! I heard you needed to filter out your filters
.reject(function (filter) {
return !filter || _.get(filter, 'meta.disabled');
})
.value();
return;
case 'index':
case 'type':
case 'id':
case 'highlightAll':
if (key && state[key] == null) {
state[key] = val;
}
return;
case 'source':
key = '_source';
addToBody();
break;
case 'sort':
val = normalizeSortRequest(val, this.get('index'));
addToBody();
break;
default:
addToBody();
}
/**
* Add the key and val to the body of the request
*/
function addToBody() {
state.body = state.body || {};
// ignore if we already have a value
if (state.body[key] == null) {
if (key === 'query' && _.isString(val)) {
val = { query_string: { query: val } };
}
state.body[key] = val;
}
}
};
return SearchSource;
}
|
'use strict';
const db = require('../config/connection');
function Product() {
this.list = function (query, res) {
let count = 0;
let where = '';
if (query.search) {
where = " where name like '%" + query.search + "%'";
}
db.one('select count(*) from product' + where)
.then(function (data) {
count = data.count;
db.any('select id, name, cost, category, status from product' +
where + ' order by ' + query.sort + ' ' + query.sortType + ' limit ' + query.limit + ' offset ' +
(query.page - 1) * query.limit)
.then(function (data) {
res.status(200)
.json({
count: count,
data: data,
message: 'Retrieved ALL'
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
};
this.get = function (id, res) {
db.one('select id, name, category, description, cost, status, file_grp as "fileGrp" from product where id = $1', id)
.then(function (data) {
res.status(200)
.json({
data: data,
message: 'Retrieved One'
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
};
this.create = function (product, res) {
if (!product.category) product.category = 0;
if (!product.cost) product.cost = null;
if (!product.status) product.status = 0;
if (!product.file_grp) product.file_grp = null;
db.one('insert into product (name, category, description, cost, status, file_grp)' +
' values (${name}, ${category}, ${description}, ${cost}, ${status}, ${fileGrp}) RETURNING id', product)
.then(function (data) {
res.status(201)
.json({
data: data,
message: 'Inserted one'
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
};
this.update = function (product, res) {
if (!product.category) product.category = 0;
if (!product.cost) product.cost = null;
if (!product.status) product.status = 0;
if (!product.file_grp) product.file_grp = null;
db.none('update product set name = ${name}, description = ${description}, category = ${category}, ' +
'cost = ${cost}, status = ${status}, file_grp = ${fileGrp} where id = ${id}', product)
.then(function () {
res.status(204)
.json({
message: 'Updated one'
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
};
this.delete = function (id, res) {
db.none('delete from product where id = $1', [id])
.then(function () {
res.status(204)
.json({
message: 'Deleted one'
});
})
.catch(function (err) {
console.log(err);
res.status(500).send(err);
});
};
}
module.exports = new Product();
|
import r from 'restructure';
export default new r.Pointer(
r.uint32le,
new r.String(null, 'utf8'),
{
type: 'global',
relativeTo: 'parent.stringBlockOffset'
}
);
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.employee',
'myApp.employeesList',
'myApp.assetsList',
'myApp.createChecklist',
'myApp.editChecklist',
'myApp.version',
'myApp.login',
'myApp.services',
'myApp.directives',
'myApp.todo'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.otherwise({redirectTo: '/showChecklist'});
$routeProvider.when('/createChecklist', {
templateUrl: 'modules/createChecklist/createChecklist.html',
controller: 'createChecklistCtrl'
});
$routeProvider.when('/editChecklist', {
templateUrl: 'modules/editChecklist/editChecklist.html',
controller: 'editChecklistCtrl'
});
$routeProvider.when('/assetsList', {
templateUrl: 'modules/assetsList/assetsList.html',
controller: 'assetsListCtrl'
});
$routeProvider.when('/employeesList', {
templateUrl: 'modules/employeesList/employeesList.html',
controller: 'employeesListCtrl'
});
$routeProvider.when('/employee', {
templateUrl: 'modules/employee/employee.html',
controller: 'employeeCtrl'
});
$routeProvider.when('/asset', {
templateUrl: 'modules/asset/asset.html',
controller: 'assetCtrl'
});
$routeProvider.when('/login', {
templateUrl: 'modules/login/login.html',
controller: 'LoginCtrl'
});
$routeProvider.when('/todo', {
templateUrl: 'modules/todo/todo.html',
controller: 'todoCtrl'
});
}]);
|
export {GeneTransformer} from './data/geneTransformer';
export * from './renderer';
|
var fs = require('fs'),
path = require('path'),
request = require('request');
var filePath = path.join(__dirname, 'start.html'),
previousOutput = 0;
try {
// input/output with respect to the lua script.
var output = parseInt(fs.readFileSync('output.txt'), 10);
} catch (err) {
console.error(err);
}
setInterval(function() {
if(output > previousOutput) {
request.get('http://bearcatfacts.info', function(err, res, body) {
if(err) { console.log(err); return; }
console.log(body);
fs.writeFileSync('input.txt', body);
});
}
}, 1000);
|
(function() {
loadOptions();
buttonHandler();
})();
function buttonHandler() {
var $submitButton = $('#submitButton');
$submitButton.on('click', function() {
console.log('Submit');
var return_to = getQueryParam('return_to', 'pebblejs://close#');
document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData()));
});
var $cancelButton = $('#cancelButton');
$cancelButton.on('click', function() {
console.log('Cancel');
var return_to = getQueryParam('return_to', 'pebblejs://close#');
document.location = return_to;
});
}
// Radio control for inverting colors
var $dateValue;
$("input[name=datemode]").change(function () {
$datemodeValue = parseInt(this.value);
});
function loadOptions() {
if (localStorage.datemode) {
$datemodeValue = localStorage.datemode;
console.log('localStorage.digital: ' + $digitalValue);
// setting radio' value
} else {
$datemodeValue = 0;
console.log('localStorage.datemode was undefined, now set to: ' + $datemodeValue);
}
$("input[name=datemode][value='" + $datemodeValue + "']").attr('checked', 'checked');
}
function getAndStoreConfigData() {
console.log('datemode value: ' + $datemodeValue);
var options = {
datemode: $datemodeValue
};
localStorage.datemode = options.datemode;
console.log('Got options: ' + JSON.stringify(options));
return options;
}
function getQueryParam(variable, defaultValue) {
var query = location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] === variable) {
return decodeURIComponent(pair[1]);
}
}
return defaultValue || false;
}
|
/*jshint loopfunc: true */
var debug = require('debug')('l2cap-ble');
var events = require('events');
var spawn = require('child_process').spawn;
var util = require('util');
var ATT_OP_ERROR = 0x01;
var ATT_OP_MTU_REQ = 0x02;
var ATT_OP_MTU_RESP = 0x03;
var ATT_OP_FIND_INFO_REQ = 0x04;
var ATT_OP_FIND_INFO_RESP = 0x05;
var ATT_OP_READ_BY_TYPE_REQ = 0x08;
var ATT_OP_READ_BY_TYPE_RESP = 0x09;
var ATT_OP_READ_REQ = 0x0a;
var ATT_OP_READ_RESP = 0x0b;
var ATT_OP_READ_BLOB_REQ = 0x0c;
var ATT_OP_READ_BLOB_RESP = 0x0d;
var ATT_OP_READ_BY_GROUP_REQ = 0x10;
var ATT_OP_READ_BY_GROUP_RESP = 0x11;
var ATT_OP_WRITE_REQ = 0x12;
var ATT_OP_WRITE_RESP = 0x13;
var ATT_OP_HANDLE_NOTIFY = 0x1b;
var ATT_OP_HANDLE_IND = 0x1d;
var ATT_OP_WRITE_CMD = 0x52;
var ATT_ECODE_SUCCESS = 0x00;
var ATT_ECODE_INVALID_HANDLE = 0x01;
var ATT_ECODE_READ_NOT_PERM = 0x02;
var ATT_ECODE_WRITE_NOT_PERM = 0x03;
var ATT_ECODE_INVALID_PDU = 0x04;
var ATT_ECODE_AUTHENTICATION = 0x05;
var ATT_ECODE_REQ_NOT_SUPP = 0x06;
var ATT_ECODE_INVALID_OFFSET = 0x07;
var ATT_ECODE_AUTHORIZATION = 0x08;
var ATT_ECODE_PREP_QUEUE_FULL = 0x09;
var ATT_ECODE_ATTR_NOT_FOUND = 0x0a;
var ATT_ECODE_ATTR_NOT_LONG = 0x0b;
var ATT_ECODE_INSUFF_ENCR_KEY_SIZE = 0x0c;
var ATT_ECODE_INVAL_ATTR_VALUE_LEN = 0x0d;
var ATT_ECODE_UNLIKELY = 0x0e;
var ATT_ECODE_INSUFF_ENC = 0x0f;
var ATT_ECODE_UNSUPP_GRP_TYPE = 0x10;
var ATT_ECODE_INSUFF_RESOURCES = 0x11;
var GATT_PRIM_SVC_UUID = 0x2800;
var GATT_INCLUDE_UUID = 0x2802;
var GATT_CHARAC_UUID = 0x2803;
var GATT_CLIENT_CHARAC_CFG_UUID = 0x2902;
var GATT_SERVER_CHARAC_CFG_UUID = 0x2903;
//Connect parameter given to l2cap child process
var L2capConnectType = Object.freeze({CONNECT : 1, RECONNECT : 2});
var L2capBle = function(address, addressType) {
this._address = address;
this._addressType = addressType;
this._security = 'low';
this._services = {};
this._characteristics = {};
this._descriptors = {};
this._currentCommand = null;
this._commandQueue = [];
this._mtu = 23;
};
util.inherits(L2capBle, events.EventEmitter);
L2capBle.prototype.kill = function() {
this._l2capBle.kill();
};
L2capBle.prototype.onClose = function(code) {
debug(this._address + ': close = ' + code);
};
L2capBle.prototype.onStdoutData = function(data) {
this._buffer += data.toString();
debug(this._address + ': buffer = ' + JSON.stringify(this._buffer));
var newLineIndex;
while ((newLineIndex = this._buffer.indexOf('\n')) !== -1) {
var line = this._buffer.substring(0, newLineIndex);
var found;
this._buffer = this._buffer.substring(newLineIndex + 1);
debug(this._address + ': line = ' + line);
if ((found = line.match(/^connect (.*)$/))) {
var status = found[1];
var error = ('success' === status) ? null : new Error(status);
this.emit('connect', this._address, error);
} else if ((found = line.match(/^disconnect$/))) {
this.emit('disconnect', this._address);
}else if ((found = line.match(/^connectionDrop = (.*)$/))) {
debug(this._address + ': connection drop, error = ' + line.split(' = ')[1]);
this.emit('connectionDrop', this._address);
return;
}else if ((found = line.match(/^reconnect (.*)$/))) {
debug(this._address + ': reconnect');
this.emit('reconnect', this._address);
}else if ((found = line.match(/^rssi = (.*)$/))) {
var rssi = parseInt(found[1], 10);
this.emit('rssi', this._address, rssi);
} else if ((found = line.match(/^security = (.*)$/))) {
this._security = found[1];
if (this._security === 'medium') {
// re-issue the current command
debug(this._address + ': write: ' + this._currentCommand.buffer.toString('hex'));
this._l2capBle.stdin.write(this._currentCommand.buffer.toString('hex') + '\n');
} else {
this.upgradeSecurity();
}
} else if ((found = line.match(/^data (.*)$/))) {
var lineData = new Buffer(found[1], 'hex');
if (this._currentCommand && lineData.toString('hex') === this._currentCommand.buffer.toString('hex')) {
debug(this._address + ': echo ... echo ... echo ...');
} else if (lineData[0] % 2 === 0) {
debug(this._address + ': ignoring request/command ...');
} else if (lineData[0] === ATT_OP_HANDLE_NOTIFY || lineData[0] === ATT_OP_HANDLE_IND) {
var valueHandle = lineData.readUInt16LE(1);
var valueData = lineData.slice(3);
this.emit('handleNotify', this._address, valueHandle, valueData);
for (var serviceUuid in this._services) {
for (var characteristicUuid in this._characteristics[serviceUuid]) {
if (this._characteristics[serviceUuid][characteristicUuid].valueHandle === valueHandle) {
this.emit('notification', this._address, serviceUuid, characteristicUuid, valueData);
}
}
}
} else if (!this._currentCommand) {
debug(this._address + ': uh oh, no current command');
} else {
if (lineData[0] === ATT_OP_ERROR &&
(lineData[4] === ATT_ECODE_AUTHENTICATION || lineData[4] === ATT_ECODE_AUTHORIZATION || lineData[4] === ATT_ECODE_INSUFF_ENC) &&
this._security !== 'medium') {
this.upgradeSecurity();
return;
}
this._currentCommand.callback(lineData);
this._currentCommand = null;
while(this._commandQueue.length) {
this._currentCommand = this._commandQueue.pop();
debug(this._address + ': write: ' + this._currentCommand.buffer.toString('hex'));
this._l2capBle.stdin.write(this._currentCommand.buffer.toString('hex') + '\n');
if (this._currentCommand.callback) {
break;
} else if (this._currentCommand.writeCallback) {
this._currentCommand.writeCallback();
this._currentCommand = null;
}
}
}
}
}
};
L2capBle.prototype.onStdinError = function(error) {
};
L2capBle.prototype.onStderrData = function(data) {
console.error(this._address + ': stderr: ' + data);
};
L2capBle.prototype.connect = function(connectType) {
if(typeof(connectType) === 'undefined') connectType = L2capConnectType.CONNECT;
var l2capBle = __dirname + '/../../build/Release/l2cap-ble';
debug(this._address + ': l2capBle = ' + l2capBle);
this._l2capBle = spawn(l2capBle, [this._address, this._addressType, connectType]);
this._l2capBle.on('close', this.onClose.bind(this));
this._l2capBle.stdout.on('data', this.onStdoutData.bind(this));
this._l2capBle.stdin.on('error', this.onStdinError.bind(this));
this._l2capBle.stderr.on('data', this.onStderrData.bind(this));
this._buffer = "";
this._currentCommand = null;
this._commandQueue = [];
};
L2capBle.prototype.reconnect = function() {
//Be sure l2cap disconnected
this.disconnect();
this.connect(L2capConnectType.RECONNECT);
};
L2capBle.prototype.disconnect = function() {
this._l2capBle.kill('SIGHUP');
};
L2capBle.prototype.updateRssi = function() {
this._l2capBle.kill('SIGUSR1');
};
L2capBle.prototype.upgradeSecurity = function() {
this._l2capBle.kill('SIGUSR2');
};
L2capBle.prototype._queueCommand = function(buffer, callback, writeCallback) {
this._commandQueue.push({
buffer: buffer,
callback: callback,
writeCallback: writeCallback
});
if (this._currentCommand === null) {
while (this._commandQueue.length) {
this._currentCommand = this._commandQueue.shift();
debug(this._address + ': write: ' + this._currentCommand.buffer.toString('hex'));
this._l2capBle.stdin.write(this._currentCommand.buffer.toString('hex') + '\n');
if (this._currentCommand.callback) {
break;
} else if (this._currentCommand.writeCallback) {
this._currentCommand.writeCallback();
this._currentCommand = null;
}
}
}
};
L2capBle.prototype.mtuRequest = function(mtu) {
var buf = new Buffer(3);
buf.writeUInt8(ATT_OP_MTU_REQ, 0);
buf.writeUInt16LE(mtu, 1);
return buf;
};
L2capBle.prototype.readByGroupRequest = function(startHandle, endHandle, groupUuid) {
var buf = new Buffer(7);
buf.writeUInt8(ATT_OP_READ_BY_GROUP_REQ, 0);
buf.writeUInt16LE(startHandle, 1);
buf.writeUInt16LE(endHandle, 3);
buf.writeUInt16LE(groupUuid, 5);
return buf;
};
L2capBle.prototype.readByTypeRequest = function(startHandle, endHandle, groupUuid) {
var buf = new Buffer(7);
buf.writeUInt8(ATT_OP_READ_BY_TYPE_REQ, 0);
buf.writeUInt16LE(startHandle, 1);
buf.writeUInt16LE(endHandle, 3);
buf.writeUInt16LE(groupUuid, 5);
return buf;
};
L2capBle.prototype.readRequest = function(handle) {
var buf = new Buffer(3);
buf.writeUInt8(ATT_OP_READ_REQ, 0);
buf.writeUInt16LE(handle, 1);
return buf;
};
L2capBle.prototype.readBlobRequest = function(handle, offset) {
var buf = new Buffer(5);
buf.writeUInt8(ATT_OP_READ_BLOB_REQ, 0);
buf.writeUInt16LE(handle, 1);
buf.writeUInt16LE(offset, 3);
return buf;
};
L2capBle.prototype.findInfoRequest = function(startHandle, endHandle) {
var buf = new Buffer(5);
buf.writeUInt8(ATT_OP_FIND_INFO_REQ, 0);
buf.writeUInt16LE(startHandle, 1);
buf.writeUInt16LE(endHandle, 3);
return buf;
};
L2capBle.prototype.writeRequest = function(handle, data, withoutResponse) {
var buf = new Buffer(3 + data.length);
buf.writeUInt8(withoutResponse ? ATT_OP_WRITE_CMD : ATT_OP_WRITE_REQ , 0);
buf.writeUInt16LE(handle, 1);
for (var i = 0; i < data.length; i++) {
buf.writeUInt8(data.readUInt8(i), i + 3);
}
return buf;
};
L2capBle.prototype.exchangeMtu = function(mtu) {
this._queueCommand(this.mtuRequest(mtu), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_MTU_RESP) {
var newMtu = data.readUInt16LE(1);
debug(this._address + ': new MTU is ' + newMtu);
this._mtu = newMtu;
this.emit('mtu', this._address, mtu);
} else {
this.emit('mtu', this._address, 23);
}
}.bind(this));
};
L2capBle.prototype.discoverServices = function(uuids) {
var services = [];
var callback = function(data) {
var opcode = data[0];
var i = 0;
if (opcode === ATT_OP_READ_BY_GROUP_RESP) {
var type = data[1];
var num = (data.length - 2) / type;
for (i = 0; i < num; i++) {
services.push({
startHandle: data.readUInt16LE(2 + i * type + 0),
endHandle: data.readUInt16LE(2 + i * type + 2),
uuid: (type == 6) ? data.readUInt16LE(2 + i * type + 4).toString(16) : data.slice(2 + i * type + 4).slice(0, 16).toString('hex').match(/.{1,2}/g).reverse().join('')
});
}
}
if (opcode !== ATT_OP_READ_BY_GROUP_RESP || services[services.length - 1].endHandle === 0xffff) {
var serviceUuids = [];
for (i = 0; i < services.length; i++) {
if (uuids.length === 0 || uuids.indexOf(services[i].uuid) !== -1) {
serviceUuids.push(services[i].uuid);
}
this._services[services[i].uuid] = services[i];
}
this.emit('servicesDiscover', this._address, serviceUuids);
} else {
this._queueCommand(this.readByGroupRequest(services[services.length - 1].endHandle + 1, 0xffff, GATT_PRIM_SVC_UUID), callback);
}
}.bind(this);
this._queueCommand(this.readByGroupRequest(0x0001, 0xffff, GATT_PRIM_SVC_UUID), callback);
};
L2capBle.prototype.discoverIncludedServices = function(serviceUuid, uuids) {
var service = this._services[serviceUuid];
var includedServices = [];
var callback = function(data) {
var opcode = data[0];
var i = 0;
if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
var type = data[1];
var num = (data.length - 2) / type;
for (i = 0; i < num; i++) {
includedServices.push({
endHandle: data.readUInt16LE(2 + i * type + 0),
startHandle: data.readUInt16LE(2 + i * type + 2),
uuid: (type == 8) ? data.readUInt16LE(2 + i * type + 6).toString(16) : data.slice(2 + i * type + 6).slice(0, 16).toString('hex').match(/.{1,2}/g).reverse().join('')
});
}
}
if (opcode !== ATT_OP_READ_BY_TYPE_RESP || includedServices[includedServices.length - 1].endHandle === service.endHandle) {
var includedServiceUuids = [];
for (i = 0; i < includedServices.length; i++) {
if (uuids.length === 0 || uuids.indexOf(includedServices[i].uuid) !== -1) {
includedServiceUuids.push(includedServices[i].uuid);
}
}
this.emit('includedServicesDiscover', this._address, service.uuid, includedServiceUuids);
} else {
this._queueCommand(this.readByTypeRequest(includedServices[includedServices.length - 1].endHandle + 1, service.endHandle, GATT_INCLUDE_UUID), callback);
}
}.bind(this);
this._queueCommand(this.readByTypeRequest(service.startHandle, service.endHandle, GATT_INCLUDE_UUID), callback);
};
L2capBle.prototype.discoverCharacteristics = function(serviceUuid, characteristicUuids) {
var service = this._services[serviceUuid];
var characteristics = [];
this._characteristics[serviceUuid] = {};
this._descriptors[serviceUuid] = {};
var callback = function(data) {
var opcode = data[0];
var i = 0;
if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
var type = data[1];
var num = (data.length - 2) / type;
for (i = 0; i < num; i++) {
characteristics.push({
startHandle: data.readUInt16LE(2 + i * type + 0),
properties: data.readUInt8(2 + i * type + 2),
valueHandle: data.readUInt16LE(2 + i * type + 3),
uuid: (type == 7) ? data.readUInt16LE(2 + i * type + 5).toString(16) : data.slice(2 + i * type + 5).slice(0, 16).toString('hex').match(/.{1,2}/g).reverse().join('')
});
}
}
if (opcode !== ATT_OP_READ_BY_TYPE_RESP || characteristics[characteristics.length - 1].valueHandle === service.endHandle) {
var characteristicsDiscovered = [];
for (i = 0; i < characteristics.length; i++) {
var properties = characteristics[i].properties;
var characteristic = {
properties: [],
uuid: characteristics[i].uuid
};
if (i !== 0) {
characteristics[i - 1].endHandle = characteristics[i].startHandle - 1;
}
if (i === (characteristics.length - 1)) {
characteristics[i].endHandle = service.endHandle;
}
this._characteristics[serviceUuid][characteristics[i].uuid] = characteristics[i];
if (properties & 0x01) {
characteristic.properties.push('broadcast');
}
if (properties & 0x02) {
characteristic.properties.push('read');
}
if (properties & 0x04) {
characteristic.properties.push('writeWithoutResponse');
}
if (properties & 0x08) {
characteristic.properties.push('write');
}
if (properties & 0x10) {
characteristic.properties.push('notify');
}
if (properties & 0x20) {
characteristic.properties.push('indicate');
}
if (properties & 0x40) {
characteristic.properties.push('authenticatedSignedWrites');
}
if (properties & 0x80) {
characteristic.properties.push('extendedProperties');
}
if (characteristicUuids.length === 0 || characteristicUuids.indexOf(characteristic.uuid) !== -1) {
characteristicsDiscovered.push(characteristic);
}
}
this.emit('characteristicsDiscover', this._address, serviceUuid, characteristicsDiscovered);
} else {
this._queueCommand(this.readByTypeRequest(characteristics[characteristics.length - 1].valueHandle + 1, service.endHandle, GATT_CHARAC_UUID), callback);
}
}.bind(this);
this._queueCommand(this.readByTypeRequest(service.startHandle, service.endHandle, GATT_CHARAC_UUID), callback);
};
L2capBle.prototype.read = function(serviceUuid, characteristicUuid) {
var characteristic = this._characteristics[serviceUuid][characteristicUuid];
var readData = new Buffer(0);
var callback = function(data) {
var opcode = data[0];
if (opcode === ATT_OP_READ_RESP || opcode === ATT_OP_READ_BLOB_RESP) {
readData = new Buffer(readData.toString('hex') + data.slice(1).toString('hex'), 'hex');
if (data.length === this._mtu) {
this._queueCommand(this.readBlobRequest(characteristic.valueHandle, readData.length), callback);
} else {
this.emit('read', this._address, serviceUuid, characteristicUuid, readData);
}
} else {
this.emit('read', this._address, serviceUuid, characteristicUuid, readData);
}
}.bind(this);
this._queueCommand(this.readRequest(characteristic.valueHandle), callback);
};
L2capBle.prototype.write = function(serviceUuid, characteristicUuid, data, withoutResponse) {
var characteristic = this._characteristics[serviceUuid][characteristicUuid];
if (withoutResponse) {
this._queueCommand(this.writeRequest(characteristic.valueHandle, data, true), null, function() {
this.emit('write', this._address, serviceUuid, characteristicUuid);
}.bind(this));
} else {
this._queueCommand(this.writeRequest(characteristic.valueHandle, data, false), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_WRITE_RESP) {
this.emit('write', this._address, serviceUuid, characteristicUuid);
}
}.bind(this));
}
};
L2capBle.prototype.broadcast = function(serviceUuid, characteristicUuid, broadcast) {
var characteristic = this._characteristics[serviceUuid][characteristicUuid];
this._queueCommand(this.readByTypeRequest(characteristic.startHandle, characteristic.endHandle, GATT_SERVER_CHARAC_CFG_UUID), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
var type = data[1];
var handle = data.readUInt16LE(2);
var value = data.readUInt16LE(4);
if (notify) {
value |= 0x0001;
} else {
value &= 0xfffe;
}
var valueBuffer = new Buffer(2);
valueBuffer.writeUInt16LE(value, 0);
this._queueCommand(this.writeRequest(handle, valueBuffer, false), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_WRITE_RESP) {
this.emit('broadcast', this._address, serviceUuid, characteristicUuid, broadcast);
}
}.bind(this));
}
}.bind(this));
};
L2capBle.prototype.notify = function(serviceUuid, characteristicUuid, notify) {
var characteristic = this._characteristics[serviceUuid][characteristicUuid];
this._queueCommand(this.readByTypeRequest(characteristic.startHandle, characteristic.endHandle, GATT_CLIENT_CHARAC_CFG_UUID), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_READ_BY_TYPE_RESP) {
var type = data[1];
var handle = data.readUInt16LE(2);
var value = data.readUInt16LE(4);
var useNotify = characteristic.properties & 0x10;
var useIndicate = characteristic.properties & 0x20;
if (notify) {
if (useNotify) {
value |= 0x0001;
} else if (useIndicate) {
value |= 0x0002;
}
} else {
if (useNotify) {
value &= 0xfffe;
} else if (useIndicate) {
value &= 0xfffd;
}
}
var valueBuffer = new Buffer(2);
valueBuffer.writeUInt16LE(value, 0);
this._queueCommand(this.writeRequest(handle, valueBuffer, false), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_WRITE_RESP) {
this.emit('notify', this._address, serviceUuid, characteristicUuid, notify);
}
}.bind(this));
}
}.bind(this));
};
L2capBle.prototype.discoverDescriptors = function(serviceUuid, characteristicUuid) {
var characteristic = this._characteristics[serviceUuid][characteristicUuid];
var descriptors = [];
this._descriptors[serviceUuid][characteristicUuid] = {};
var callback = function(data) {
var opcode = data[0];
var i = 0;
if (opcode === ATT_OP_FIND_INFO_RESP) {
var num = data[1];
for (i = 0; i < num; i++) {
descriptors.push({
handle: data.readUInt16LE(2 + i * 4 + 0),
uuid: data.readUInt16LE(2 + i * 4 + 2).toString(16)
});
}
}
if (opcode !== ATT_OP_FIND_INFO_RESP || descriptors[descriptors.length - 1].handle === characteristic.endHandle) {
var descriptorUuids = [];
for (i = 0; i < descriptors.length; i++) {
descriptorUuids.push(descriptors[i].uuid);
this._descriptors[serviceUuid][characteristicUuid][descriptors[i].uuid] = descriptors[i];
}
this.emit('descriptorsDiscover', this._address, serviceUuid, characteristicUuid, descriptorUuids);
} else {
this._queueCommand(this.findInfoRequest(descriptors[descriptors.length - 1].handle + 1, characteristic.endHandle), callback);
}
}.bind(this);
this._queueCommand(this.findInfoRequest(characteristic.valueHandle + 1, characteristic.endHandle), callback);
};
L2capBle.prototype.readValue = function(serviceUuid, characteristicUuid, descriptorUuid) {
var descriptor = this._descriptors[serviceUuid][characteristicUuid][descriptorUuid];
this._queueCommand(this.readRequest(descriptor.handle), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_READ_RESP) {
this.emit('valueRead', this._address, serviceUuid, characteristicUuid, descriptorUuid, data.slice(1));
}
}.bind(this));
};
L2capBle.prototype.writeValue = function(serviceUuid, characteristicUuid, descriptorUuid, data) {
var descriptor = this._descriptors[serviceUuid][characteristicUuid][descriptorUuid];
this._queueCommand(this.writeRequest(descriptor.handle, data, false), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_WRITE_RESP) {
this.emit('valueWrite', this._address, serviceUuid, characteristicUuid, descriptorUuid);
}
}.bind(this));
};
L2capBle.prototype.readHandle = function(handle) {
this._queueCommand(this.readRequest(handle), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_READ_RESP) {
this.emit('handleRead', this._address, handle, data.slice(1));
}
}.bind(this));
};
L2capBle.prototype.writeHandle = function(handle, data, withoutResponse) {
if (withoutResponse) {
this._queueCommand(this.writeRequest(handle, data, true), null, function() {
this.emit('handleWrite', this._address, handle);
}.bind(this));
} else {
this._queueCommand(this.writeRequest(handle, data, false), function(data) {
var opcode = data[0];
if (opcode === ATT_OP_WRITE_RESP) {
this.emit('handleWrite', this._address, handle);
}
}.bind(this));
}
};
module.exports = L2capBle;
|
app.factory("GetDataService", ['$http',
function ($http) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http.defaults.transformRequest = function(data) {
return data != undefined ? $.param(data) : null;
}
var obj = {};
obj.get = function (q) {
return $http.get(q).then(function (results) {
return results;
});
};
obj.post = function (q, object) {
return $http.post(q, object).then(function (results) {
return results;
});
};
obj.put = function (q, object) {
return $http.put(q, object).then(function (results) {
return results;
});
};
obj.delete = function (q) {
return $http.delete(q).then(function (results) {
return results;
});
};
return obj;
}]);
app.factory("getIndexForStatus",
function() {
var obj = {};
obj.getIndex = function(status) {
}
return obj;
});
app.factory("converDate",
function() {
var obj = {};
obj.convert = function(date) {
var arr_string = date.split('-');
}
return obj;
});
app.factory("updateURL", ['$location',
function ($location) {
var obj = {};
obj.update = function(data, url) {
for (var i in data) {
$location.path(url).search(i, data[i]);
};
}
return obj;
}]);
app.factory("parseGetParams", ['$location',
function ($location) {
var obj1 = {};
obj1.parse = function() {
var a = /\+/g;
var r = /([^&=]+)=?([^&]*)/g;
var d = function(s) {
return decodeURIComponent(s.replace(a, ''));
};
var q = $location.url().split('?')[1];
var obj = {};
if(q) {
while (e = r.exec(q)) {
obj[d(e[1])] = d(e[2]);
}
}
return obj;
}
return obj1;
}])
app.factory("parseGetPage", ['$location',
function ($location) {
var obj1 = {};
obj1.parse = function() {
var q = $location.path().split('/')[1];
var obj = 0;
switch(q) {
case 'dashboard':
obj = 1;
break;
case 'settings':
obj = 2;
break;
case 'statistics':
obj = 3;
break;
}
return obj;
}
return obj1;
}])
app.factory("getIndexForStatus",
function() {
var obj = {};
obj.getIndex = function(status) {
var index = 0;
switch (status) {
case 'Neobdelano':
index = 1;
break;
case 'Klicano':
index = 2;
break;
case 'Rezervirano':
index = 3;
break;
case 'Realizirano':
index = 4;
break;
case 'Račun':
index = 5;
break;
case 'Plačano':
index = 6;
break;
case 'Arhiv':
index = 7;
break;
case 'Izbrisano':
index = 8;
break;
default:
index = 9;
}
return index;
}
return obj;
});
app.filter('range', function(){
return function(n) {
var res = [];
for (var i = 0; i < n; i++) {
res.push(i);
}
return res;
};
});
app.factory("notification", [
function() {
var alerts = [
{ id: 'badRequest', msg: 'Napaka, prosimo poskusite kasneje.', type: 'danger' },
{ id: 'wrongParameters', msg: 'Napačni parametri, prosimo poskusite spet.', type: 'danger' },
{ id: 'statusSuccess', msg: 'Uspešno ste spremenili status.', type: 'success' },
{ id: 'userEditSuccess', msg: 'Uspešno ste posodobili uporadabnika.', type: 'success' },
{ id: 'userCreateSuccess', msg: 'Uspešno ste dodali uporadabnika.', type: 'success' },
{ id: 'colorChangeSuccess', msg: 'Uspešno ste spremenili barvo.', type: 'success' },
{ id: 'smsEditSuccess', msg: 'Uspešno ste posodobili SMS.', type: 'success' },
{ id: 'smsCreateSuccess', msg: 'Uspešno ste dodali SMS.', type: 'success' },
{ id: 'offerSuccess', msg: 'Uspešno ste shranili ponudbo.', type: 'success' },
{ id: 'expensesAddSuccess', msg: 'Uspešno ste dodali mesečne stroške.', type: 'success' },
{ id: 'badUserPass', msg: 'Napačno uporabniško ime ali geslo, poskusite še enkrat', type: 'danger' },
{ id: 'success_mail', msg: 'Uspešno ste poslali mail', type: 'success' },
{ id: 'exportSuccess', msg: 'Uspešno ste izvozili narocila', type: 'success' },
{ id: 'sendSMSSuccess', msg: 'Uspešno ste poslali SMS.', type: 'success' },
{ id: 'orderSuccess', msg: 'Uspešno ste posodobili naročilo.', type: 'success' }
];
var obj = {};
obj.get = function(id) {
var alert = {};
angular.forEach(alerts, function(element, index) {
if (element.id == id) {
alert = element;
}
});
return alert;
}
return obj;
}]);
|
'use strict';
const ui = new WebUIWindow('chat', 'package://chat/ui/index.html', new Vector2(Math.round(jcmp.viewportSize.x * 0.3), 320));
ui.autoResize = true;
// Gets overridden by the server anyway
let MAX_MESSAGE_LENGTH = 1024;
jcmp.events.AddRemoteCallable('chat_message', (msg, r, g, b) => {
jcmp.ui.CallEvent('chat_message', msg, r, g, b);
});
jcmp.events.AddRemoteCallable('chat_settings', maxLength => {
MAX_MESSAGE_LENGTH = maxLength;
jcmp.ui.CallEvent('chat_settings', MAX_MESSAGE_LENGTH);
});
jcmp.ui.AddEvent('chat_ready', () => {
jcmp.events.CallRemote('chat_ready');
});
jcmp.ui.AddEvent('chat_input_state', s => {
// Ask the main menu to stop opening. It will still open at the second time (in a short period), though
jcmp.ui.CallEvent('mainui_prevent_open_menu', s);
if (s) {
jcmp.localPlayer.controlsEnabled = true;
jcmp.localPlayer.controlsEnabled = false;
} else {
jcmp.localPlayer.controlsEnabled = true;
}
});
jcmp.events.AddRemoteCallable('chat_set_custom_css', css => {
jcmp.ui.CallEvent('chat_set_custom_css', css);
});
jcmp.ui.AddEvent('chat_submit_message', msg => {
if (msg.length > MAX_MESSAGE_LENGTH) {
return;
}
jcmp.events.CallRemote('chat_submit_message', msg);
});
|
/* eslint-disable */
/* global MessageBus, bootbox */
import Repo from "manager-client/models/repo";
import Controller from "@ember/controller";
import { equal } from "@ember/object/computed";
import { computed } from "@ember/object";
export default Controller.extend({
output: null,
init() {
this._super();
this.reset();
},
complete: equal("status", "complete"),
failed: equal("status", "failed"),
multiUpgrade: computed("model.length", function () {
return this.get("model.length") !== 1;
}),
title: computed("model.@each.name", function () {
return this.get("multiUpgrade") ? "All" : this.get("model")[0].get("name");
}),
isUpToDate: computed("model.@each.upToDate", function () {
return this.get("model").every((repo) => repo.get("upToDate"));
}),
upgrading: computed("model.@each.upgrading", function () {
return this.get("model").some((repo) => repo.get("upgrading"));
}),
repos() {
const model = this.get("model");
return this.get("isMultiple") ? model : [model];
},
updateAttribute(key, value, valueIsKey = false) {
this.get("model").forEach((repo) => {
value = valueIsKey ? repo.get(value) : value;
repo.set(key, value);
});
},
messageReceived(msg) {
switch (msg.type) {
case "log":
this.set("output", this.get("output") + msg.value + "\n");
break;
case "percent":
this.set("percent", msg.value);
break;
case "status":
this.set("status", msg.value);
if (msg.value === "complete") {
this.get("model")
.filter((repo) => repo.get("upgrading"))
.forEach((repo) => {
repo.set("version", repo.get("latest.version"));
});
}
if (msg.value === "complete" || msg.value === "failed") {
this.updateAttribute("upgrading", false);
}
break;
}
},
upgradeButtonText: computed("upgrading", function () {
if (this.get("upgrading")) {
return "Upgrading...";
} else {
return "Start Upgrading";
}
}),
startBus() {
MessageBus.subscribe("/docker/upgrade", (msg) => {
this.messageReceived(msg);
});
},
stopBus() {
MessageBus.unsubscribe("/docker/upgrade");
},
reset() {
this.setProperties({ output: "", status: null, percent: 0 });
},
actions: {
start() {
this.reset();
if (this.get("multiUpgrade")) {
this.get("model")
.filter((repo) => !repo.get("upToDate"))
.forEach((repo) => repo.set("upgrading", true));
return Repo.upgradeAll();
}
const repo = this.get("model")[0];
if (repo.get("upgrading")) {
return;
}
repo.startUpgrade();
},
resetUpgrade() {
bootbox.confirm(
"WARNING: You should only reset upgrades that have failed and are not running.\n\n" +
"This will NOT cancel currently running builds and should only be used as a last resort.",
(result) => {
if (result) {
if (this.get("multiUpgrade")) {
return Repo.resetAll(
this.get("model").filter((repo) => !repo.get("upToDate"))
).finally(() => {
this.reset();
this.updateAttribute("upgrading", false);
});
}
const repo = this.get("model")[0];
repo.resetUpgrade().then(() => {
this.reset();
});
}
}
);
},
},
});
/* eslint-enable */
|
Kojak.Config = {
// enums / constants
CURRENT_VERSION: 1,
AUTO_START_NONE: 'none',
AUTO_START_IMMEDIATE: 'immediate',
AUTO_ON_JQUERY_LOAD: 'on_jquery_load',
AUTO_START_DELAYED: 'delayed',
_LOCAL_STORAGE_KEY: 'kojak',
_LOCAL_STORAGE_BACKUP_KEY: 'kojak_backup',
load: function () {
if (localStorage.getItem('kojak')) {
this._configValues = this._loadLocalStorage();
}
else {
this._configValues = this._createDefaults();
this._save();
}
},
saveBackup: function(){
Kojak.Core.assert(localStorage.getItem(Kojak.Config._LOCAL_STORAGE_KEY), 'kojak not defined yet in local storage');
localStorage.setItem('kojak_backup', localStorage.getItem(Kojak.Config._LOCAL_STORAGE_KEY));
},
restoreBackup: function(){
Kojak.Core.assert(localStorage.getItem(Kojak.Config._LOCAL_STORAGE_BACKUP_KEY), 'no backup existed in local storage');
localStorage.setItem(Kojak.Config._LOCAL_STORAGE_KEY, localStorage.getItem(Kojak.Config._LOCAL_STORAGE_BACKUP_KEY));
this._configValues = this._loadLocalStorage();
},
getAutoStartInstrumentation: function(){
return this._configValues.autoStartInstrumentation;
},
setAutoStartInstrumentation: function (val) {
Kojak.Core.assert( [Kojak.Config.AUTO_START_NONE, Kojak.Config.AUTO_START_IMMEDIATE, Kojak.Config.AUTO_ON_JQUERY_LOAD, Kojak.Config.AUTO_START_DELAYED].indexOf(val) !== -1,
'Invalid auto start option \'' + val + '\'.');
this._configValues.autoStartInstrumentation = val;
this._save();
console.log('autoStartInstrumentation updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
if(val === Kojak.Config.AUTO_START_DELAYED && !this._isAutoStartDelayValid(this.getAutoStartDelay())){
console.log('setting a default auto start delay');
this.setAutoStartDelay(4000);
}
},
getEnableNetWatcher: function(){
return this._configValues.enableNetWatcher;
},
setEnableNetWatcher: function (val) {
Kojak.Core.assert(Kojak.Core.isBoolean(val), 'Invalid enableNetWatcher option \'' + val + '\'.');
this._configValues.enableNetWatcher = val;
this._save();
console.log('enableNetWatcher updated');
console.log('reload your browser to notice the change.');
},
// *****************************************************************************************************************
// Included pakages
addIncludedPakage: function (pkg) {
Kojak.Core.assert(this._configValues.includedPakages.indexOf(pkg) === -1, 'Pakage is already included');
this._configValues.includedPakages.push(pkg);
this._save();
console.log('includedPakages updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change');
}
},
setIncludedPakages: function (pks) {
Kojak.Core.assert(Kojak.Core.isArray(pks), 'Only pass an array of strings for the included pakage names');
this._configValues.includedPakages = pks;
this._save();
console.log('includedPakages updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
removeIncludedPakage: function (pkg) {
var pathIndex = this._configValues.includedPakages.indexOf(pkg);
Kojak.Core.assert(pathIndex !== -1, 'Pakage is not currently included.');
this._configValues.includedPakages.splice(pathIndex, 1);
this._save();
console.log('included path removed');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
getIncludedPakages: function(){
return this._configValues.includedPakages;
},
// Included pakages
// *****************************************************************************************************************
// *****************************************************************************************************************
// Excluded paths
arePathsExcluded: function(){
var args = Array.prototype.slice.call(arguments), i, path;
for(i = 0; i < args.length; i++){
path = args[i];
if(this.isPathExcluded(path)){
return true;
}
}
return false;
},
isPathExcluded: function(path){
var i, excludePaths = this._configValues.excludedPaths, isExcluded = false;
for(i = 0; i < excludePaths.length; i++){
if(path.contains(excludePaths[i])){
isExcluded = true;
break;
}
}
return isExcluded;
},
getExcludedPaths: function(){
return this._configValues.excludedPaths;
},
addExcludedPath: function (path) {
Kojak.Core.assert(this._configValues.excludedPaths.indexOf(path) === -1, 'Path is already excluded');
this._configValues.excludedPaths.push(path);
this._save();
console.log('excluded paths updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
removeExcludedPath: function (path) {
var pathIndex = this._configValues.excludedPaths.indexOf(path);
Kojak.Core.assert(pathIndex !== -1, 'Path is not currently excluded.');
this._configValues.excludedPaths.splice(pathIndex, 1);
this._save();
console.log('excluded paths updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
setExcludedPaths: function (paths) {
Kojak.Core.assert(Kojak.Core.isArray(paths), 'Only pass an array of strings for the excluded paths');
this._configValues.excludedPaths = paths;
this._save();
console.log('excludePaths updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
// Excluded paths
// *****************************************************************************************************************
getAutoStartDelay: function(){
return this._configValues.autoStartDelay;
},
_isAutoStartDelayValid: function(delay){
return delay > 0 && delay < 100000;
},
setAutoStartDelay: function (delay) {
Kojak.Core.assert(this._isAutoStartDelayValid(delay), 'The autoStartDelay option should be a valid number in milliseconds');
this._configValues.autoStartDelay = delay;
this._save();
console.log('set autoStartDelay to ' + delay + ' milliseconds');
if(this.getAutoStartInstrumentation() !== Kojak.Config.AUTO_START_DELAYED){
console.log('warning, the auto start is not current auto delayed.');
}
console.log('autoStartDelay updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('reload your browser to notice the change.');
}
},
getRealTimeFunctionLogging: function(){
return this._configValues.realTimeFunctionLogging;
},
setRealTimeFunctionLogging: function(val){
Kojak.Core.assert(val === true || val === false, 'The realTimeFunctionLogging option should be true or false');
this._configValues.realTimeFunctionLogging = val;
this._save();
console.log('realTimeFunctionLogging updated');
if(Kojak.instrumentor.hasInstrumented()){
console.log('changes should be reflected immediately');
}
},
_save: function () {
localStorage.setItem(Kojak.Config._LOCAL_STORAGE_KEY, JSON.stringify(this._configValues));
},
_loadLocalStorage: function () {
var storageString = localStorage.getItem(Kojak.Config._LOCAL_STORAGE_KEY);
var configValues = JSON.parse(storageString);
// a simple check to see if the storage item resembles a kojak config item
Kojak.Core.assert(configValues.version, 'There is no version in the item \'' + Kojak.Config._LOCAL_STORAGE_KEY + '\' in localStorage. It looks wrong.');
this._upgradeConfig(configValues);
return configValues;
},
_upgradeConfig: function (configValues) {
while (configValues.version !== Kojak.Config.CURRENT_VERSION) {
switch (configValues.version) {
case 1:
// Example
// console.log('upgrading Kojak config from v1 to v2');
// add config values or modify existing ones
// configValues.version = 2;
break;
case 2:
// upgrade from v2 to v3
break;
default:
throw 'Unknown version found in your configuration ' + config.version;
}
}
},
_createDefaults: function () {
return {
version: Kojak.Config.CURRENT_VERSION,
realTimeFunctionLogging: false,
includedPakages: [],
excludedPaths: [],
autoStartInstrumentation: Kojak.Config.AUTO_START_NONE,
enableNetWatcher: false
};
}
};
|
import messageTypes from 'ringcentral-integration/enums/messageTypes';
export default {
title: "消息",
search: "搜索...",
composeText: "编辑短信",
noMessages: "无消息",
noSearchResults: "未找到匹配记录",
[messageTypes.all]: "全部",
[messageTypes.voiceMail]: "语音",
[messageTypes.text]: "短信",
[messageTypes.fax]: "传真"
};
// @key: @#@"title"@#@ @source: @#@"Messages"@#@
// @key: @#@"search"@#@ @source: @#@"Search..."@#@
// @key: @#@"composeText"@#@ @source: @#@"Compose Text"@#@
// @key: @#@"noMessages"@#@ @source: @#@"No Messages"@#@
// @key: @#@"noSearchResults"@#@ @source: @#@"No matching records found"@#@
// @key: @#@"[messageTypes.all]"@#@ @source: @#@"All"@#@
// @key: @#@"[messageTypes.voiceMail]"@#@ @source: @#@"Voice"@#@
// @key: @#@"[messageTypes.text]"@#@ @source: @#@"Text"@#@
// @key: @#@"[messageTypes.fax]"@#@ @source: @#@"Fax"@#@
|
Template.musicstandmenu.helpers({
setsSelector: {
collection: sets,
displayTemplate: 'musicstandSetDisplay',
fields: [{field: 'title', type: String}],
sort: [['title', 'asc']],
addbutton: false
}
});
|
import { getLocaleInfo } from './info';
export default function numberSymbols(locale) {
var info = getLocaleInfo(locale);
return info.numbers.symbols;
}
//# sourceMappingURL=number-symbols.js.map
|
'use strict';
angular.module('CST.version.interpolate-filter', [])
.filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
};
}]);
|
BASE.require([
], function () {
BASE.namespace("app.properties");
app.properties.TouchInput = function () {
this["@class"] = "app.properties.TouchInput";
this.type = "touch-input";
this.x = 0;
this.y= 0;
this.isTouching = false;
};
});
|
/* eslint-env jest */
import {
createEntitiesSelectors,
} from './selectors';
const constant = x => () => x;
describe('Test selectors - legacy api', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.selectors = createEntitiesSelectors('collection');
testContext.state1 = {
ddp: {
entities: {
collection: {
1: { _id: '1', flag: false },
2: { _id: '2', flag: true },
},
},
},
};
testContext.state2 = {
ddp: {
entities: {
collection: {
...testContext.state1.ddp.entities.collection,
3: { _id: '3', flag: false },
},
},
},
};
testContext.state3 = {
ddp: {
entities: {
collection: {
...testContext.state2.ddp.entities.collection,
3: { _id: '3', flag: true },
},
},
},
};
testContext.state4 = {
ddp: {
entities: {
collection: {
...testContext.state3.ddp.entities.collection,
2: {
...testContext.state3.ddp.entities.collection[2],
letter: 'x',
},
},
},
},
};
});
beforeEach(() => {
//---------------------------------------------------------
const find = testContext.selectors.find(doc => !!doc.flag);
//---------------------------------------------------------
testContext.result1 = find(testContext.state1);
testContext.result2 = find(testContext.state2);
testContext.result3 = find(testContext.state3);
testContext.result4 = find(testContext.state4);
});
describe('createEntitiesSelectors.find()', () => {
test('should find one flagged document', () => {
expect(testContext.result1).toEqual(expect.arrayContaining([
testContext.state1.ddp.entities.collection[2],
]));
});
test('should return the same value on second try', () => {
expect(testContext.result1).toBe(testContext.result2);
});
test('should update result when new element is added', () => {
expect(testContext.result3).toEqual(expect.arrayContaining([
testContext.state3.ddp.entities.collection[2],
testContext.state3.ddp.entities.collection[3],
]));
});
test('should update result when an element is changed', () => {
expect(testContext.result4).toEqual(expect.arrayContaining([
testContext.state4.ddp.entities.collection[2],
testContext.state4.ddp.entities.collection[3],
]));
});
});
});
describe('Test selectors - "where" api', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.selectors = {
col1: createEntitiesSelectors('col1'),
col2: createEntitiesSelectors('col2'),
};
testContext.entities1 = {
col1: {
1: {
_id: '1',
a: 1,
b: 2,
c: 3,
d: 4,
},
},
col2: {
1: {
_id: '1',
a: 9,
b: 2,
},
},
};
testContext.entities2 = {
...testContext.entities1,
col1: {
...testContext.entities1.col1,
2: {
_id: '2',
a: 1,
b: 2,
},
},
};
testContext.state1 = { ddp: { entities: testContext.entities1 } };
testContext.state2 = { ddp: { entities: testContext.entities2 } };
});
it('should select a document by id', () => {
const selector = testContext.selectors.col1.one.whereIdEquals('1');
const expected = {
_id: '1',
a: 1,
b: 2,
c: 3,
d: 4,
};
const doc1 = selector(testContext.state1);
const doc2 = selector(testContext.state2);
expect(doc1).toEqual(expected);
expect(doc2).toBe(doc1);
});
it('should find all documents', () => {
const predicate = constant(true);
const selector = testContext.selectors.col1.all.satisfying(predicate);
const doc1 = {
_id: '1',
a: 1,
b: 2,
c: 3,
d: 4,
};
const doc2 = {
_id: '2',
a: 1,
b: 2,
};
const results1 = selector(testContext.state1);
const results2 = selector(testContext.state2);
expect(results1).toEqual([
doc1,
]);
expect(results2).toEqual([
doc1,
doc2,
]);
});
it('should find all matching documents', () => {
const predicate = x => x.c === 3;
const selector = testContext.selectors.col1.where(() => predicate);
const doc1 = {
_id: '1',
a: 1,
b: 2,
c: 3,
d: 4,
};
const results1 = selector(testContext.state1);
const results2 = selector(testContext.state2);
expect(results1).toEqual([
doc1,
]);
expect(results2).toEqual([
doc1,
]);
});
it('should find one matching document', () => {
const predicate = x => x.c === 3;
const selector = testContext.selectors.col1.one.where(() => predicate);
const doc1 = {
_id: '1',
a: 1,
b: 2,
c: 3,
d: 4,
};
const results1 = selector(testContext.state1);
const results2 = selector(testContext.state2);
expect(results1).toEqual(doc1);
expect(results2).toEqual(doc1);
});
});
|
var five = require('johnny-five');
var plane = require('./plane');
var config = require('../config');
var state = 'waiting';
var board, paintMotor;
module.exports = {
init: function() {
if (config.arduino) {
board = new five.Board();
board.on('ready', this.onBoardReady);
}
},
onBoardReady: function() {
console.log('OK')
plane.init();
paintMotor = new five.Servo({
pin: 9,
range: [80,170]
});
this.repl.inject({
paint: paintMotor
});
state = 'ready';
},
applyRotation: function(gamma, beta) {
if (state === 'ready') {
plane.applyRotation(gamma, beta)
}
},
paintStart: function() {
if (state === 'ready') {
paintMotor.min(750);
}
},
paintStop: function() {
if (state === 'ready') {
paintMotor.max(500);
}
}
}
|
/* eslint-env jest */
const childProcess = require('child-process-promise')
exports.realCli = function (args, env) {
return childProcess.spawn('node', ['bin/scriptfodder-publish.js', ...args], {
capture: [ 'stdout', 'stderr' ],
env
})
}
class ProcessExitError {
constructor (code) {
this.code = code
}
}
exports.ProcessExitError = ProcessExitError
exports.requireCli = function (args, env = {}) {
const argv = ['node', 'script.js', ...args]
const process = {
exit: code => { throw new ProcessExitError(code) },
env
}
return require.requireActual('../../src/index')(argv, process)
}
|
export default function (app) {
return {
configure: function (router) {
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title: 'Express'});
});
return router;
}
};
};
|
function authenticating(options) {
return requesting({
method: 'POST',
path: '/auth/authenticate/' + options.user,
versionRange: '0.1.0',
body: JSON.stringify({
pass: options.pass
})
})
.then(function (result) {
return {
token: result.token
};
});
}
function greeting(options) {
return requesting({
method: 'GET',
path: '/hello/' + options.name,
versionRange: '0.1.0'
})
.then(function (result) {
return {
message: result
};
});
}
function gettingLatestEntries() {
return requesting({
method: 'GET',
path: '/entry/latest'
})
.then(function (result) {
return {
entries: result.entry
};
});
}
function patchingEntry(options) {
return requesting({
method: 'PATCH',
path: '/entry/' + options.id,
version: options.version,
body: JSON.stringify(options.patch)
});
}
function requesting(options) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(options.method, 'https://' + window.app.apiServer + options.path, true);
if(options.versionRange) {
xhr.setRequestHeader('Accept-Version', options.versionRange);
}
if(window.app.token) {
xhr.setRequestHeader('Authorization', getAuthorizationHeader());
}
if(options.method === 'PATCH' || options.method === 'POST') {
xhr.setRequestHeader('Content-type', 'application/json');
}
if(options.version) {
xhr.setRequestHeader('If-Match', options.version);
}
xhr.onload = function () {
var response;
try {
response = JSON.parse(this.responseText);
}
catch(ex) {
// Note: ignore
}
// ToDo: read ETag response header
// console.dir(response);
if(this.status === 200) {
resolve(response);
} else {
reject(new Error(response ? response.message : this.statusText));
}
};
xhr.onerror = function () {
// console.dir(this);
reject('failed');
};
xhr.send(options.body);
});
}
function getAuthorizationHeader() {
return 'Bearer ' + window.app.token;
}
|
import {types as tt} from "./tokentype"
import {Parser} from "./state"
import {lineBreak, skipWhiteSpace} from "./whitespace"
import {isIdentifierStart, isIdentifierChar} from "./identifier"
import {has} from "./util"
import {DestructuringErrors} from "./parseutil"
const pp = Parser.prototype
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp.parseTopLevel = function(node) {
let exports = {}
if (!node.body) node.body = []
while (this.type !== tt.eof) {
let stmt = this.parseStatement(true, true, exports)
node.body.push(stmt)
}
this.next()
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType
}
return this.finishNode(node, "Program")
}
const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}
pp.isLet = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false
skipWhiteSpace.lastIndex = this.pos
let skip = skipWhiteSpace.exec(this.input)
let next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
if (nextCh === 91 || nextCh == 123) return true // '{' and '['
if (isIdentifierStart(nextCh, true)) {
let pos = next + 1
while (isIdentifierChar(this.input.charCodeAt(pos), true)) ++pos
let ident = this.input.slice(next, pos)
if (!this.isKeyword(ident)) return true
}
return false
}
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp.isAsyncFunction = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async")
return false
skipWhiteSpace.lastIndex = this.pos
let skip = skipWhiteSpace.exec(this.input)
let next = this.pos + skip[0].length
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp.parseStatement = function(declaration, topLevel, exports) {
let starttype = this.type, node = this.startNode(), kind
if (this.isLet()) {
starttype = tt._var
kind = "let"
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case tt._debugger: return this.parseDebuggerStatement(node)
case tt._do: return this.parseDoStatement(node)
case tt._for: return this.parseForStatement(node)
case tt._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
return this.parseFunctionStatement(node, false)
case tt._class:
if (!declaration) this.unexpected()
return this.parseClass(node, true)
case tt._if: return this.parseIfStatement(node)
case tt._return: return this.parseReturnStatement(node)
case tt._switch: return this.parseSwitchStatement(node)
case tt._throw: return this.parseThrowStatement(node)
case tt._try: return this.parseTryStatement(node)
case tt._const: case tt._var:
kind = kind || this.value
if (!declaration && kind != "var") this.unexpected()
return this.parseVarStatement(node, kind)
case tt._while: return this.parseWhileStatement(node)
case tt._with: return this.parseWithStatement(node)
case tt.braceL: return this.parseBlock()
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
if (!this.inModule)
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction() && declaration) {
this.next()
return this.parseFunctionStatement(node, true)
}
let maybeName = this.value, expr = this.parseExpression()
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
return this.parseLabeledStatement(node, maybeName, expr)
else return this.parseExpressionStatement(node, expr)
}
}
pp.parseBreakContinueStatement = function(node, keyword) {
let isBreak = keyword == "break"
this.next()
if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
else if (this.type !== tt.name) this.unexpected()
else {
node.label = this.parseIdent()
this.semicolon()
}
// Verify that there is an actual destination to break or
// continue to.
let i = 0
for (; i < this.labels.length; ++i) {
let lab = this.labels[i]
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break
if (node.label && isBreak) break
}
}
if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}
pp.parseDebuggerStatement = function(node) {
this.next()
this.semicolon()
return this.finishNode(node, "DebuggerStatement")
}
pp.parseDoStatement = function(node) {
this.next()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
this.eat(tt.semi)
else
this.semicolon()
return this.finishNode(node, "DoWhileStatement")
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp.parseForStatement = function(node) {
this.next()
this.labels.push(loopLabel)
this.enterLexicalScope()
this.expect(tt.parenL)
if (this.type === tt.semi) return this.parseFor(node, null)
let isLet = this.isLet()
if (this.type === tt._var || this.type === tt._const || isLet) {
let init = this.startNode(), kind = isLet ? "let" : this.value
this.next()
this.parseVar(init, true, kind)
this.finishNode(init, "VariableDeclaration")
if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1 &&
!(kind !== "var" && init.declarations[0].init))
return this.parseForIn(node, init)
return this.parseFor(node, init)
}
let refDestructuringErrors = new DestructuringErrors
let init = this.parseExpression(true, refDestructuringErrors)
if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.toAssignable(init)
this.checkLVal(init)
this.checkPatternErrors(refDestructuringErrors, true)
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true)
}
return this.parseFor(node, init)
}
pp.parseFunctionStatement = function(node, isAsync) {
this.next()
return this.parseFunction(node, true, false, isAsync)
}
pp.isFunction = function() {
return this.type === tt._function || this.isAsyncFunction()
}
pp.parseIfStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement(!this.strict && this.isFunction())
node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null
return this.finishNode(node, "IfStatement")
}
pp.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
this.raise(this.start, "'return' outside of function")
this.next()
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
else { node.argument = this.parseExpression(); this.semicolon() }
return this.finishNode(node, "ReturnStatement")
}
pp.parseSwitchStatement = function(node) {
this.next()
node.discriminant = this.parseParenExpression()
node.cases = []
this.expect(tt.braceL)
this.labels.push(switchLabel)
this.enterLexicalScope()
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
let cur
for (let sawDefault = false; this.type != tt.braceR;) {
if (this.type === tt._case || this.type === tt._default) {
let isCase = this.type === tt._case
if (cur) this.finishNode(cur, "SwitchCase")
node.cases.push(cur = this.startNode())
cur.consequent = []
this.next()
if (isCase) {
cur.test = this.parseExpression()
} else {
if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses")
sawDefault = true
cur.test = null
}
this.expect(tt.colon)
} else {
if (!cur) this.unexpected()
cur.consequent.push(this.parseStatement(true))
}
}
this.exitLexicalScope()
if (cur) this.finishNode(cur, "SwitchCase")
this.next() // Closing brace
this.labels.pop()
return this.finishNode(node, "SwitchStatement")
}
pp.parseThrowStatement = function(node) {
this.next()
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
this.raise(this.lastTokEnd, "Illegal newline after throw")
node.argument = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ThrowStatement")
}
// Reused empty array added for node fields that are always empty.
const empty = []
pp.parseTryStatement = function(node) {
this.next()
node.block = this.parseBlock()
node.handler = null
if (this.type === tt._catch) {
let clause = this.startNode()
this.next()
this.expect(tt.parenL)
clause.param = this.parseBindingAtom()
this.enterLexicalScope()
this.checkLVal(clause.param, "let")
this.expect(tt.parenR)
clause.body = this.parseBlock(false)
this.exitLexicalScope()
node.handler = this.finishNode(clause, "CatchClause")
}
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
if (!node.handler && !node.finalizer)
this.raise(node.start, "Missing catch or finally clause")
return this.finishNode(node, "TryStatement")
}
pp.parseVarStatement = function(node, kind) {
this.next()
this.parseVar(node, false, kind)
this.semicolon()
return this.finishNode(node, "VariableDeclaration")
}
pp.parseWhileStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "WhileStatement")
}
pp.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode")
this.next()
node.object = this.parseParenExpression()
node.body = this.parseStatement(false)
return this.finishNode(node, "WithStatement")
}
pp.parseEmptyStatement = function(node) {
this.next()
return this.finishNode(node, "EmptyStatement")
}
pp.parseLabeledStatement = function(node, maybeName, expr) {
for (let label of this.labels)
if (label.name === maybeName)
this.raise(expr.start, "Label '" + maybeName + "' is already declared")
let kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
for (let i = this.labels.length - 1; i >= 0; i--) {
let label = this.labels[i]
if (label.statementStart == node.start) {
label.statementStart = this.start
label.kind = kind
} else break
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
node.body = this.parseStatement(true)
if (node.body.type == "ClassDeclaration" ||
node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
this.raiseRecoverable(node.body.start, "Invalid labeled declaration")
this.labels.pop()
node.label = expr
return this.finishNode(node, "LabeledStatement")
}
pp.parseExpressionStatement = function(node, expr) {
node.expression = expr
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp.parseBlock = function(createNewLexicalScope = true) {
let node = this.startNode()
node.body = []
this.expect(tt.braceL)
if (createNewLexicalScope) {
this.enterLexicalScope()
}
while (!this.eat(tt.braceR)) {
let stmt = this.parseStatement(true)
node.body.push(stmt)
}
if (createNewLexicalScope) {
this.exitLexicalScope()
}
return this.finishNode(node, "BlockStatement")
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp.parseFor = function(node, init) {
node.init = init
this.expect(tt.semi)
node.test = this.type === tt.semi ? null : this.parseExpression()
this.expect(tt.semi)
node.update = this.type === tt.parenR ? null : this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "ForStatement")
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp.parseForIn = function(node, init) {
let type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
this.next()
node.left = init
node.right = this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, type)
}
// Parse a list of variable declarations.
pp.parseVar = function(node, isFor, kind) {
node.declarations = []
node.kind = kind
for (;;) {
let decl = this.startNode()
this.parseVarId(decl, kind)
if (this.eat(tt.eq)) {
decl.init = this.parseMaybeAssign(isFor)
} else if (kind === "const" && !(this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected()
} else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value")
} else {
decl.init = null
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"))
if (!this.eat(tt.comma)) break
}
return node
}
pp.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom(kind)
this.checkLVal(decl.id, kind, false)
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node)
if (this.options.ecmaVersion >= 6 && !isAsync)
node.generator = this.eat(tt.star)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
if (isStatement) {
node.id = isStatement === "nullableID" && this.type != tt.name ? null : this.parseIdent()
if (node.id) {
this.checkLVal(node.id, "var")
}
}
let oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
if (!isStatement)
node.id = this.type == tt.name ? this.parseIdent() : null
this.parseFunctionParams(node)
this.parseFunctionBody(node, allowExpressionBody)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
}
pp.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
this.checkYieldAwaitInDefaultParams()
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp.parseClass = function(node, isStatement) {
this.next()
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
let classBody = this.startNode()
let hadConstructor = false
classBody.body = []
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) continue
let method = this.startNode()
let isGenerator = this.eat(tt.star)
let isAsync = false
let isMaybeStatic = this.type === tt.name && this.value === "static"
this.parsePropertyName(method)
method.static = isMaybeStatic && this.type !== tt.parenL
if (method.static) {
if (isGenerator) this.unexpected()
isGenerator = this.eat(tt.star)
this.parsePropertyName(method)
}
if (this.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
method.key.type === "Identifier" && method.key.name === "async" && this.type !== tt.parenL &&
!this.canInsertSemicolon()) {
isAsync = true
this.parsePropertyName(method)
}
method.kind = "method"
let isGetSet = false
if (!method.computed) {
let {key} = method
if (!isGenerator && !isAsync && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true
method.kind = key.name
key = this.parsePropertyName(method)
}
if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class")
if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier")
if (isGenerator) this.raise(key.start, "Constructor can't be a generator")
if (isAsync) this.raise(key.start, "Constructor can't be an async method")
method.kind = "constructor"
hadConstructor = true
}
}
this.parseClassMethod(classBody, method, isGenerator, isAsync)
if (isGetSet) {
let paramCount = method.kind === "get" ? 0 : 1
if (method.value.params.length !== paramCount) {
let start = method.value.start
if (method.kind === "get")
this.raiseRecoverable(start, "getter should have no params")
else
this.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (method.kind === "set" && method.value.params[0].type === "RestElement")
this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params")
}
}
}
node.body = this.finishNode(classBody, "ClassBody")
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}
pp.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync)
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
pp.parseClassId = function(node, isStatement) {
node.id = this.type === tt.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null
}
pp.parseClassSuper = function(node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
}
// Parses module export declaration.
pp.parseExport = function(node, exports) {
this.next()
// export * from '...'
if (this.eat(tt.star)) {
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.semicolon()
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(tt._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart)
let isAsync
if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
let fNode = this.startNode()
this.next()
if (isAsync) this.next()
node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync)
} else if (this.type === tt._class) {
let cNode = this.startNode()
node.declaration = this.parseClass(cNode, "nullableID")
} else {
node.declaration = this.parseMaybeAssign()
this.semicolon()
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(true)
if (node.declaration.type === "VariableDeclaration")
this.checkVariableExport(exports, node.declaration.declarations)
else
this.checkExport(exports, node.declaration.id.name, node.declaration.id.start)
node.specifiers = []
node.source = null
} else { // export { x, y as z } [from '...']
node.declaration = null
node.specifiers = this.parseExportSpecifiers(exports)
if (this.eatContextual("from")) {
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
} else {
// check for keywords used as local names
for (let spec of node.specifiers) {
this.checkUnreserved(spec.local)
}
node.source = null
}
this.semicolon()
}
return this.finishNode(node, "ExportNamedDeclaration")
}
pp.checkExport = function(exports, name, pos) {
if (!exports) return
if (has(exports, name))
this.raiseRecoverable(pos, "Duplicate export '" + name + "'")
exports[name] = true
}
pp.checkPatternExport = function(exports, pat) {
let type = pat.type
if (type == "Identifier")
this.checkExport(exports, pat.name, pat.start)
else if (type == "ObjectPattern")
for (let prop of pat.properties)
this.checkPatternExport(exports, prop.value)
else if (type == "ArrayPattern")
for (let elt of pat.elements) {
if (elt) this.checkPatternExport(exports, elt)
}
else if (type == "AssignmentPattern")
this.checkPatternExport(exports, pat.left)
else if (type == "ParenthesizedExpression")
this.checkPatternExport(exports, pat.expression)
}
pp.checkVariableExport = function(exports, decls) {
if (!exports) return
for (let decl of decls)
this.checkPatternExport(exports, decl.id)
}
pp.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
}
// Parses a comma-separated list of module exports.
pp.parseExportSpecifiers = function(exports) {
let nodes = [], first = true
// export { x, y as z } [from '...']
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
let node = this.startNode()
node.local = this.parseIdent(true)
node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local
this.checkExport(exports, node.exported.name, node.exported.start)
nodes.push(this.finishNode(node, "ExportSpecifier"))
}
return nodes
}
// Parses import declaration.
pp.parseImport = function(node) {
this.next()
// import '...'
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
} else {
node.specifiers = this.parseImportSpecifiers()
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
}
this.semicolon()
return this.finishNode(node, "ImportDeclaration")
}
// Parses a comma-separated list of module imports.
pp.parseImportSpecifiers = function() {
let nodes = [], first = true
if (this.type === tt.name) {
// import defaultObj, { x, y as z } from '...'
let node = this.startNode()
node.local = this.parseIdent()
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
if (!this.eat(tt.comma)) return nodes
}
if (this.type === tt.star) {
let node = this.startNode()
this.next()
this.expectContextual("as")
node.local = this.parseIdent()
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"))
return nodes
}
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.afterTrailingComma(tt.braceR)) break
} else first = false
let node = this.startNode()
node.imported = this.parseIdent(true)
if (this.eatContextual("as")) {
node.local = this.parseIdent()
} else {
this.checkUnreserved(node.imported)
node.local = node.imported
}
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportSpecifier"))
}
return nodes
}
|
Lexicon.add('dregus/alchemist/TrainAlchemy1', {
layout: 'event',
gained: [
{ skill:'alchemy' },
],
lost: [
{ currency:true, count:100 },
],
links: [
{ name:'Complete', action:'event:complete' },
],
body:[
{ tag:"p", text:"Proctor motions for you to follow him upstairs into the tower, and after a lengthy climb you "+
"reach a small but well stocked laboratory. There you and the alchemist pour over eldritch texts, "+
"speaking the unutterable, concocting the abominable, and learning that which should have been left "+
"unknown." },
{ tag:"p", _:[
"After what feels like days of study you come down from the tower, out into the ",
{ tag:"span", requirements:['Game:IsNight'], text:"cold desert night." },
{ tag:"span", requirements:['Game:IsDay'], text:"desert sunlight." },
"You're not sure how long it's been. Maybe days, perhaps only just hours. You feel changed, more ",
"knowledgeable certainly, but with the comprehension that there's far more that you don't understand ",
"then you do. It's unsettling, but exhilarating too.",
]},
],
});
|
import test from 'ava';
import request from 'supertest';
import { checkArrayLength, checkFail, checkSuccess } from './helpers/general';
const PORT = process.env.PORT || 3500;
const api = request(`http://0.0.0.0:${PORT}`);
test('testing for failure on invalid height', async t => {
const res = await api
.get('/noise/2/fail')
.send();
checkFail(t, res, 400);
});
test('testing for failure on invalid width', async t => {
const res = await api
.get('/noise/fail/656')
.send();
checkFail(t, res, 400);
});
test('testing for failure 404', async t => {
const res = await api
.get('/missing')
.send();
checkFail(t, res, 404);
});
test('2x2', async t => {
const res = await api
.get('/noise/2/2')
.send();
checkSuccess(t, res);
checkArrayLength(t, res, 4);
});
test('20x20', async t => {
const res = await api
.get('/noise/20/20')
.send();
checkSuccess(t, res);
checkArrayLength(t, res, 400);
});
test('testing options', async t => {
const res = await api
.get('/noise/2/2?octaveCount=5&litude=0.5&persistence=0.75')
.send();
checkSuccess(t, res);
checkArrayLength(t, res, 4);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.