code stringlengths 2 1.05M |
|---|
import _ from 'lodash';
import setup from "../../../setup";
import {SELECT_COURT_CASE} from "../../../../src/client/store/actions/CourtCaseActions";
import reducer, {initialState} from "../../../../src/client/store/reducers/selectedCaseReducer";
describe("selectedCaseReducer", () => {
const {expect, chance} = setup();
it("default / unknown state", () => {
const state = reducer(undefined, {type: chance.word()});
expect(state).to.eql(initialState);
});
it("select case", () => {
const action = {
type: SELECT_COURT_CASE,
payload: {
courtCase: chance.courtCase(),
pastEvents: chance.n(chance.event, 3),
futureEvents: chance.n(chance.event, 3),
stakeholders: chance.n(chance.stakeholder, 3)
}
};
const state = reducer(undefined, action);
expect(state).to.eql({
...action.payload,
events: _.union(action.payload.futureEvents, action.payload.pastEvents)
});
});
});
|
import smallText from './smallText';
export default {...smallText, marginLeft: '0.8em'};
|
/**
* Linked List Cycle
*
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
const hasCycle = head => {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
};
export { hasCycle };
|
/**
* Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED.
*/
if (typeof define !== 'function') { var define = require('amdefine')(module) }
define([
'./collection'],
function (Collection) {
var domains = function (api) {
this.api = api;
this.collection = 'domains';
};
domains.prototype = Object.create(new Collection());
return domains;
}
);
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc4-master-3e15998
*/
goog.provide('ng.material.components.datepicker');
goog.require('ng.material.components.icon');
goog.require('ng.material.components.virtualRepeat');
goog.require('ng.material.core');
(function() {
'use strict';
/**
* @ngdoc module
* @name material.components.datepicker
* @description Datepicker
*/
angular.module('material.components.datepicker', [
'material.core',
'material.components.icon',
'material.components.virtualRepeat'
]).directive('mdCalendar', calendarDirective);
// POST RELEASE
// TODO(jelbourn): Mac Cmd + left / right == Home / End
// TODO(jelbourn): Clicking on the month label opens the month-picker.
// TODO(jelbourn): Minimum and maximum date
// TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
// TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
// TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
// TODO(jelbourn): Scroll snapping (virtual repeat)
// TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
// TODO(jelbourn): Month headers stick to top when scrolling.
// TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
// TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
// announcement and key handling).
// Read-only calendar (not just date-picker).
/**
* Height of one calendar month tbody. This must be made known to the virtual-repeat and is
* subsequently used for scrolling to specific months.
*/
var TBODY_HEIGHT = 265;
/**
* Height of a calendar month with a single row. This is needed to calculate the offset for
* rendering an extra month in virtual-repeat that only contains one row.
*/
var TBODY_SINGLE_ROW_HEIGHT = 45;
function calendarDirective() {
return {
template:
'<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
'<div class="md-calendar-scroll-mask">' +
'<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
'<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
'<tbody role="rowgroup" md-virtual-repeat="i in ctrl.items" md-calendar-month ' +
'md-month-offset="$index" class="md-calendar-month" ' +
'md-start-index="ctrl.getSelectedMonthIndex()" ' +
'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
'</table>' +
'</md-virtual-repeat-container>' +
'</div>',
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
dateFilter: '=mdDateFilter',
},
require: ['ngModel', 'mdCalendar'],
controller: CalendarCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var ngModelCtrl = controllers[0];
var mdCalendarCtrl = controllers[1];
mdCalendarCtrl.configureNgModel(ngModelCtrl);
}
};
}
/** Class applied to the selected date cell/. */
var SELECTED_DATE_CLASS = 'md-calendar-selected-date';
/** Class applied to the focused date cell/. */
var FOCUSED_DATE_CLASS = 'md-focus';
/** Next identifier for calendar instance. */
var nextUniqueId = 0;
/** The first renderable date in the virtual-scrolling calendar (for all instances). */
var firstRenderableDate = null;
/**
* Controller for the mdCalendar component.
* ngInject @constructor
*/
function CalendarCtrl($element, $attrs, $scope, $animate, $q, $mdConstant,
$mdTheming, $$mdDateUtil, $mdDateLocale, $mdInkRipple, $mdUtil) {
$mdTheming($element);
/**
* Dummy array-like object for virtual-repeat to iterate over. The length is the total
* number of months that can be viewed. This is shorter than ideal because of (potential)
* Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
*/
this.items = {length: 2000};
if (this.maxDate && this.minDate) {
// Limit the number of months if min and max dates are set.
var numMonths = $$mdDateUtil.getMonthDistance(this.minDate, this.maxDate) + 1;
numMonths = Math.max(numMonths, 1);
// Add an additional month as the final dummy month for rendering purposes.
numMonths += 1;
this.items.length = numMonths;
}
/** @final {!angular.$animate} */
this.$animate = $animate;
/** @final {!angular.$q} */
this.$q = $q;
/** @final */
this.$mdInkRipple = $mdInkRipple;
/** @final */
this.$mdUtil = $mdUtil;
/** @final */
this.keyCode = $mdConstant.KEY_CODE;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @final {HTMLElement} */
this.calendarElement = $element[0].querySelector('.md-calendar');
/** @final {HTMLElement} */
this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
/** @final {Date} */
this.today = this.dateUtil.createDateAtMidnight();
/** @type {Date} */
this.firstRenderableDate = this.dateUtil.incrementMonths(this.today, -this.items.length / 2);
if (this.minDate && this.minDate > this.firstRenderableDate) {
this.firstRenderableDate = this.minDate;
} else if (this.maxDate) {
// Calculate the difference between the start date and max date.
// Subtract 1 because it's an inclusive difference and 1 for the final dummy month.
//
var monthDifference = this.items.length - 2;
this.firstRenderableDate = this.dateUtil.incrementMonths(this.maxDate, -(this.items.length - 2));
}
/** @final {number} Unique ID for this calendar instance. */
this.id = nextUniqueId++;
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/**
* The selected date. Keep track of this separately from the ng-model value so that we
* can know, when the ng-model value changes, what the previous value was before it's updated
* in the component's UI.
*
* @type {Date}
*/
this.selectedDate = null;
/**
* The date that is currently focused or showing in the calendar. This will initially be set
* to the ng-model value if set, otherwise to today. It will be updated as the user navigates
* to other months. The cell corresponding to the displayDate does not necesarily always have
* focus in the document (such as for cases when the user is scrolling the calendar).
* @type {Date}
*/
this.displayDate = null;
/**
* The date that has or should have focus.
* @type {Date}
*/
this.focusDate = null;
/** @type {boolean} */
this.isInitialized = false;
/** @type {boolean} */
this.isMonthTransitionInProgress = false;
// Unless the user specifies so, the calendar should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs['tabindex']) {
$element.attr('tabindex', '-1');
}
var self = this;
/**
* Handles a click event on a date cell.
* Created here so that every cell can use the same function instance.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.cellClickHandler = function() {
var cellElement = this;
if (this.hasAttribute('data-timestamp')) {
$scope.$apply(function() {
var timestamp = Number(cellElement.getAttribute('data-timestamp'));
self.setNgModelValue(self.dateUtil.createDateAtMidnight(timestamp));
});
}
};
this.attachCalendarEventListeners();
}
CalendarCtrl.$inject = ["$element", "$attrs", "$scope", "$animate", "$q", "$mdConstant", "$mdTheming", "$$mdDateUtil", "$mdDateLocale", "$mdInkRipple", "$mdUtil"];
/*** Initialization ***/
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
self.changeSelectedDate(self.ngModelCtrl.$viewValue);
};
};
/**
* Initialize the calendar by building the months that are initially visible.
* Initialization should occur after the ngModel value is known.
*/
CalendarCtrl.prototype.buildInitialCalendarDisplay = function() {
this.buildWeekHeader();
this.hideVerticalScrollbar();
this.displayDate = this.selectedDate || this.today;
this.isInitialized = true;
};
/**
* Hides the vertical scrollbar on the calendar scroller by setting the width on the
* calendar scroller and the `overflow: hidden` wrapper around the scroller, and then setting
* a padding-right on the scroller equal to the width of the browser's scrollbar.
*
* This will cause a reflow.
*/
CalendarCtrl.prototype.hideVerticalScrollbar = function() {
var element = this.$element[0];
var scrollMask = element.querySelector('.md-calendar-scroll-mask');
var scroller = this.calendarScroller;
var headerWidth = element.querySelector('.md-calendar-day-header').clientWidth;
var scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
scrollMask.style.width = headerWidth + 'px';
scroller.style.width = (headerWidth + scrollbarWidth) + 'px';
scroller.style.paddingRight = scrollbarWidth + 'px';
};
/** Attach event listeners for the calendar. */
CalendarCtrl.prototype.attachCalendarEventListeners = function() {
// Keyboard interaction.
this.$element.on('keydown', angular.bind(this, this.handleKeyEvent));
};
/*** User input handling ***/
/**
* Handles a key event in the calendar with the appropriate action. The action will either
* be to select the focused date or to navigate to focus a new date.
* @param {KeyboardEvent} event
*/
CalendarCtrl.prototype.handleKeyEvent = function(event) {
var self = this;
this.$scope.$apply(function() {
// Capture escape and emit back up so that a wrapping component
// (such as a date-picker) can decide to close.
if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
self.$scope.$emit('md-calendar-close');
if (event.which == self.keyCode.TAB) {
event.preventDefault();
}
return;
}
// Remaining key events fall into two categories: selection and navigation.
// Start by checking if this is a selection event.
if (event.which === self.keyCode.ENTER) {
self.setNgModelValue(self.displayDate);
event.preventDefault();
return;
}
// Selection isn't occuring, so the key event is either navigation or nothing.
var date = self.getFocusDateFromKeyEvent(event);
if (date) {
date = self.boundDateByMinAndMax(date);
event.preventDefault();
event.stopPropagation();
// Since this is a keyboard interaction, actually give the newly focused date keyboard
// focus after the been brought into view.
self.changeDisplayDate(date).then(function () {
self.focus(date);
});
}
});
};
/**
* Gets the date to focus as the result of a key event.
* @param {KeyboardEvent} event
* @returns {Date} Date to navigate to, or null if the key does not match a calendar shortcut.
*/
CalendarCtrl.prototype.getFocusDateFromKeyEvent = function(event) {
var dateUtil = this.dateUtil;
var keyCode = this.keyCode;
switch (event.which) {
case keyCode.RIGHT_ARROW: return dateUtil.incrementDays(this.displayDate, 1);
case keyCode.LEFT_ARROW: return dateUtil.incrementDays(this.displayDate, -1);
case keyCode.DOWN_ARROW:
return event.metaKey ?
dateUtil.incrementMonths(this.displayDate, 1) :
dateUtil.incrementDays(this.displayDate, 7);
case keyCode.UP_ARROW:
return event.metaKey ?
dateUtil.incrementMonths(this.displayDate, -1) :
dateUtil.incrementDays(this.displayDate, -7);
case keyCode.PAGE_DOWN: return dateUtil.incrementMonths(this.displayDate, 1);
case keyCode.PAGE_UP: return dateUtil.incrementMonths(this.displayDate, -1);
case keyCode.HOME: return dateUtil.getFirstDateOfMonth(this.displayDate);
case keyCode.END: return dateUtil.getLastDateOfMonth(this.displayDate);
default: return null;
}
};
/**
* Gets the "index" of the currently selected date as it would be in the virtual-repeat.
* @returns {number}
*/
CalendarCtrl.prototype.getSelectedMonthIndex = function() {
return this.dateUtil.getMonthDistance(this.firstRenderableDate,
this.selectedDate || this.today);
};
/**
* Scrolls to the month of the given date.
* @param {Date} date
*/
CalendarCtrl.prototype.scrollToMonth = function(date) {
if (!this.dateUtil.isValidDate(date)) {
return;
}
var monthDistance = this.dateUtil.getMonthDistance(this.firstRenderableDate, date);
this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
};
/**
* Sets the ng-model value for the calendar and emits a change event.
* @param {Date} date
*/
CalendarCtrl.prototype.setNgModelValue = function(date) {
this.$scope.$emit('md-calendar-change', date);
this.ngModelCtrl.$setViewValue(date);
this.ngModelCtrl.$render();
};
/**
* Focus the cell corresponding to the given date.
* @param {Date=} opt_date
*/
CalendarCtrl.prototype.focus = function(opt_date) {
var date = opt_date || this.selectedDate || this.today;
var previousFocus = this.calendarElement.querySelector('.md-focus');
if (previousFocus) {
previousFocus.classList.remove(FOCUSED_DATE_CLASS);
}
var cellId = this.getDateId(date);
var cell = document.getElementById(cellId);
if (cell) {
cell.classList.add(FOCUSED_DATE_CLASS);
cell.focus();
} else {
this.focusDate = date;
}
};
/**
* If a date exceeds minDate or maxDate, returns date matching minDate or maxDate, respectively.
* Otherwise, returns the date.
* @param {Date} date
* @return {Date}
*/
CalendarCtrl.prototype.boundDateByMinAndMax = function(date) {
var boundDate = date;
if (this.minDate && date < this.minDate) {
boundDate = new Date(this.minDate.getTime());
}
if (this.maxDate && date > this.maxDate) {
boundDate = new Date(this.maxDate.getTime());
}
return boundDate;
};
/*** Updating the displayed / selected date ***/
/**
* Change the selected date in the calendar (ngModel value has already been changed).
* @param {Date} date
*/
CalendarCtrl.prototype.changeSelectedDate = function(date) {
var self = this;
var previousSelectedDate = this.selectedDate;
this.selectedDate = date;
this.changeDisplayDate(date).then(function() {
// Remove the selected class from the previously selected date, if any.
if (previousSelectedDate) {
var prevDateCell =
document.getElementById(self.getDateId(previousSelectedDate));
if (prevDateCell) {
prevDateCell.classList.remove(SELECTED_DATE_CLASS);
prevDateCell.setAttribute('aria-selected', 'false');
}
}
// Apply the select class to the new selected date if it is set.
if (date) {
var dateCell = document.getElementById(self.getDateId(date));
if (dateCell) {
dateCell.classList.add(SELECTED_DATE_CLASS);
dateCell.setAttribute('aria-selected', 'true');
}
}
});
};
/**
* Change the date that is being shown in the calendar. If the given date is in a different
* month, the displayed month will be transitioned.
* @param {Date} date
*/
CalendarCtrl.prototype.changeDisplayDate = function(date) {
// Initialization is deferred until this function is called because we want to reflect
// the starting value of ngModel.
if (!this.isInitialized) {
this.buildInitialCalendarDisplay();
return this.$q.when();
}
// If trying to show an invalid date or a transition is in progress, do nothing.
if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
return this.$q.when();
}
this.isMonthTransitionInProgress = true;
var animationPromise = this.animateDateChange(date);
this.displayDate = date;
var self = this;
animationPromise.then(function() {
self.isMonthTransitionInProgress = false;
});
return animationPromise;
};
/**
* Animates the transition from the calendar's current month to the given month.
* @param {Date} date
* @returns {angular.$q.Promise} The animation promise.
*/
CalendarCtrl.prototype.animateDateChange = function(date) {
this.scrollToMonth(date);
return this.$q.when();
};
/*** Constructing the calendar table ***/
/**
* Builds and appends a day-of-the-week header to the calendar.
* This should only need to be called once during initialization.
*/
CalendarCtrl.prototype.buildWeekHeader = function() {
var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
var shortDays = this.dateLocale.shortDays;
var row = document.createElement('tr');
for (var i = 0; i < 7; i++) {
var th = document.createElement('th');
th.textContent = shortDays[(i + firstDayOfWeek) % 7];
row.appendChild(th);
}
this.$element.find('thead').append(row);
};
/**
* Gets an identifier for a date unique to the calendar instance for internal
* purposes. Not to be displayed.
* @param {Date} date
* @returns {string}
*/
CalendarCtrl.prototype.getDateId = function(date) {
return [
'md',
this.id,
date.getFullYear(),
date.getMonth(),
date.getDate()
].join('-');
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarMonth', mdCalendarMonthDirective);
/**
* Private directive consumed by md-calendar. Having this directive lets the calender use
* md-virtual-repeat and also cleanly separates the month DOM construction functions from
* the rest of the calendar controller logic.
*/
function mdCalendarMonthDirective() {
return {
require: ['^^mdCalendar', 'mdCalendarMonth'],
scope: {offset: '=mdMonthOffset'},
controller: CalendarMonthCtrl,
controllerAs: 'mdMonthCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var monthCtrl = controllers[1];
monthCtrl.calendarCtrl = calendarCtrl;
monthCtrl.generateContent();
// The virtual-repeat re-uses the same DOM elements, so there are only a limited number
// of repeated items that are linked, and then those elements have their bindings updataed.
// Since the months are not generated by bindings, we simply regenerate the entire thing
// when the binding (offset) changes.
scope.$watch(function() { return monthCtrl.offset; }, function(offset, oldOffset) {
if (offset != oldOffset) {
monthCtrl.generateContent();
}
});
}
};
}
/** Class applied to the cell for today. */
var TODAY_CLASS = 'md-calendar-date-today';
/** Class applied to the selected date cell/. */
var SELECTED_DATE_CLASS = 'md-calendar-selected-date';
/** Class applied to the focused date cell/. */
var FOCUSED_DATE_CLASS = 'md-focus';
/**
* Controller for a single calendar month.
* ngInject @constructor
*/
function CalendarMonthCtrl($element, $$mdDateUtil, $mdDateLocale) {
this.dateUtil = $$mdDateUtil;
this.dateLocale = $mdDateLocale;
this.$element = $element;
this.calendarCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
CalendarMonthCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
/** Generate and append the content for this month to the directive element. */
CalendarMonthCtrl.prototype.generateContent = function() {
var calendarCtrl = this.calendarCtrl;
var date = this.dateUtil.incrementMonths(calendarCtrl.firstRenderableDate, this.offset);
this.$element.empty();
this.$element.append(this.buildCalendarForMonth(date));
if (this.focusAfterAppend) {
this.focusAfterAppend.classList.add(FOCUSED_DATE_CLASS);
this.focusAfterAppend.focus();
this.focusAfterAppend = null;
}
};
/**
* Creates a single cell to contain a date in the calendar with all appropriate
* attributes and classes added. If a date is given, the cell content will be set
* based on the date.
* @param {Date=} opt_date
* @returns {HTMLElement}
*/
CalendarMonthCtrl.prototype.buildDateCell = function(opt_date) {
var calendarCtrl = this.calendarCtrl;
// TODO(jelbourn): cloneNode is likely a faster way of doing this.
var cell = document.createElement('td');
cell.tabIndex = -1;
cell.classList.add('md-calendar-date');
cell.setAttribute('role', 'gridcell');
if (opt_date) {
cell.setAttribute('tabindex', '-1');
cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
cell.id = calendarCtrl.getDateId(opt_date);
// Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
cell.setAttribute('data-timestamp', opt_date.getTime());
// TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
// It may be better to finish the construction and then query the node and add the class.
if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
cell.classList.add(TODAY_CLASS);
}
if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
cell.classList.add(SELECTED_DATE_CLASS);
cell.setAttribute('aria-selected', 'true');
}
var cellText = this.dateLocale.dates[opt_date.getDate()];
if (this.isDateEnabled(opt_date)) {
// Add a indicator for select, hover, and focus states.
var selectionIndicator = document.createElement('span');
cell.appendChild(selectionIndicator);
selectionIndicator.classList.add('md-calendar-date-selection-indicator');
selectionIndicator.textContent = cellText;
cell.addEventListener('click', calendarCtrl.cellClickHandler);
if (calendarCtrl.focusDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.focusDate)) {
this.focusAfterAppend = cell;
}
} else {
cell.classList.add('md-calendar-date-disabled');
cell.textContent = cellText;
}
}
return cell;
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
CalendarMonthCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date,
this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
(!angular.isFunction(this.calendarCtrl.dateFilter)
|| this.calendarCtrl.dateFilter(opt_date));
}
/**
* Builds a `tr` element for the calendar grid.
* @param rowNumber The week number within the month.
* @returns {HTMLElement}
*/
CalendarMonthCtrl.prototype.buildDateRow = function(rowNumber) {
var row = document.createElement('tr');
row.setAttribute('role', 'row');
// Because of an NVDA bug (with Firefox), the row needs an aria-label in order
// to prevent the entire row being read aloud when the user moves between rows.
// See http://community.nvda-project.org/ticket/4643.
row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
return row;
};
/**
* Builds the <tbody> content for the given date's month.
* @param {Date=} opt_dateInMonth
* @returns {DocumentFragment} A document fragment containing the <tr> elements.
*/
CalendarMonthCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
// Store rows for the month in a document fragment so that we can append them all at once.
var monthBody = document.createDocumentFragment();
var rowNumber = 1;
var row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
// If this is the final month in the list of items, only the first week should render,
// so we should return immediately after the first row is complete and has been
// attached to the body.
var isFinalMonth = this.offset === this.calendarCtrl.items.length - 1;
// Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
// goes on a row above the first of the month. Otherwise, the month label takes up the first
// two cells of the first row.
var blankCellOffset = 0;
var monthLabelCell = document.createElement('td');
monthLabelCell.classList.add('md-calendar-month-label');
// If the entire month is after the max date, render the label as a disabled state.
if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
monthLabelCell.classList.add('md-calendar-month-label-disabled');
}
monthLabelCell.textContent = this.dateLocale.monthHeaderFormatter(date);
if (firstDayOfTheWeek <= 2) {
monthLabelCell.setAttribute('colspan', '7');
var monthLabelRow = this.buildDateRow();
monthLabelRow.appendChild(monthLabelCell);
monthBody.insertBefore(monthLabelRow, row);
if (isFinalMonth) {
return monthBody;
}
} else {
blankCellOffset = 2;
monthLabelCell.setAttribute('colspan', '2');
row.appendChild(monthLabelCell);
}
// Add a blank cell for each day of the week that occurs before the first of the month.
// For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
// The blankCellOffset is needed in cases where the first N cells are used by the month label.
for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
row.appendChild(this.buildDateCell());
}
// Add a cell for each day of the month, keeping track of the day of the week so that
// we know when to start a new row.
var dayOfWeek = firstDayOfTheWeek;
var iterationDate = firstDayOfMonth;
for (var d = 1; d <= numberOfDaysInMonth; d++) {
// If we've reached the end of the week, start a new row.
if (dayOfWeek === 7) {
// We've finished the first row, so we're done if this is the final month.
if (isFinalMonth) {
return monthBody;
}
dayOfWeek = 0;
rowNumber++;
row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
}
iterationDate.setDate(d);
var cell = this.buildDateCell(iterationDate);
row.appendChild(cell);
dayOfWeek++;
}
// Ensure that the last row of the month has 7 cells.
while (row.childNodes.length < 7) {
row.appendChild(this.buildDateCell());
}
// Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
// requires that all items have exactly the same height.
while (monthBody.childNodes.length < 6) {
var whitespaceRow = this.buildDateRow();
for (var i = 0; i < 7; i++) {
whitespaceRow.appendChild(this.buildDateCell());
}
monthBody.appendChild(whitespaceRow);
}
return monthBody;
};
/**
* Gets the day-of-the-week index for a date for the current locale.
* @private
* @param {Date} date
* @returns {number} The column index of the date in the calendar.
*/
CalendarMonthCtrl.prototype.getLocaleDay_ = function(date) {
return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7
};
})();
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdDateLocaleProvider
* @module material.components.datepicker
*
* @description
* The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
* This provider that allows the user to specify messages, formatters, and parsers for date
* internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
* components that deal with dates.
*
* @property {(Array<string>)=} months Array of month names (in order).
* @property {(Array<string>)=} shortMonths Array of abbreviated month names.
* @property {(Array<string>)=} days Array of the days of the week (in order).
* @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
* @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
* using a numeral system other than [1, 2, 3...].
* @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
* etc.
* @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
* @property {(function(Date): string)=} formatDate Function to format a date object to a string.
* @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
* a month given a date.
* @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
* a week given the week number.
* @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
* @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
* current locale.
*
* @usage
* <hljs lang="js">
* myAppModule.config(function($mdDateLocaleProvider) {
*
* // Example of a French localization.
* $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
* $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
* $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
* $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
*
* // Can change week display to start on Monday.
* $mdDateLocaleProvider.firstDayOfWeek = 1;
*
* // Optional.
* $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
*
* // Example uses moment.js to parse and format dates.
* $mdDateLocaleProvider.parseDate = function(dateString) {
* var m = moment(dateString, 'L', true);
* return m.isValid() ? m.toDate() : new Date(NaN);
* };
*
* $mdDateLocaleProvider.formatDate = function(date) {
* var m = moment(date);
* return m.isValid() ? m.format('L') : '';
* };
*
* $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
* return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
* };
*
* // In addition to date display, date components also need localized messages
* // for aria-labels for screen-reader users.
*
* $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
* return 'Semaine ' + weekNumber;
* };
*
* $mdDateLocaleProvider.msgCalendar = 'Calendrier';
* $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
*
* });
* </hljs>
*
*/
angular.module('material.components.datepicker').config(["$provide", function($provide) {
// TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
/** @constructor */
function DateLocaleProvider() {
/** Array of full month names. E.g., ['January', 'Febuary', ...] */
this.months = null;
/** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
this.shortMonths = null;
/** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
this.days = null;
/** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
this.shortDays = null;
/** Array of dates of a month (1 - 31). Characters might be different in some locales. */
this.dates = null;
/** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
this.firstDayOfWeek = 0;
/**
* Function that converts the date portion of a Date to a string.
* @type {(function(Date): string)}
*/
this.formatDate = null;
/**
* Function that converts a date string to a Date object (the date portion)
* @type {function(string): Date}
*/
this.parseDate = null;
/**
* Function that formats a Date into a month header string.
* @type {function(Date): string}
*/
this.monthHeaderFormatter = null;
/**
* Function that formats a week number into a label for the week.
* @type {function(number): string}
*/
this.weekNumberFormatter = null;
/**
* Function that formats a date into a long aria-label that is read
* when the focused date changes.
* @type {function(Date): string}
*/
this.longDateFormatter = null;
/**
* ARIA label for the calendar "dialog" used in the datepicker.
* @type {string}
*/
this.msgCalendar = '';
/**
* ARIA label for the datepicker's "Open calendar" buttons.
* @type {string}
*/
this.msgOpenCalendar = '';
}
/**
* Factory function that returns an instance of the dateLocale service.
* ngInject
* @param $locale
* @returns {DateLocale}
*/
DateLocaleProvider.prototype.$get = function($locale) {
/**
* Default date-to-string formatting function.
* @param {!Date} date
* @returns {string}
*/
function defaultFormatDate(date) {
if (!date) {
return '';
}
// All of the dates created through ng-material *should* be set to midnight.
// If we encounter a date where the localeTime shows at 11pm instead of midnight,
// we have run into an issue with DST where we need to increment the hour by one:
// var d = new Date(1992, 9, 8, 0, 0, 0);
// d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
var localeTime = date.toLocaleTimeString();
var formatDate = date;
if (date.getHours() == 0 &&
(localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
}
return formatDate.toLocaleDateString();
}
/**
* Default string-to-date parsing function.
* @param {string} dateString
* @returns {!Date}
*/
function defaultParseDate(dateString) {
return new Date(dateString);
}
/**
* Default function to determine whether a string makes sense to be
* parsed to a Date object.
*
* This is very permissive and is just a basic sanity check to ensure that
* things like single integers aren't able to be parsed into dates.
* @param {string} dateString
* @returns {boolean}
*/
function defaultIsDateComplete(dateString) {
dateString = dateString.trim();
// Looks for three chunks of content (either numbers or text) separated
// by delimiters.
var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
return re.test(dateString);
}
/**
* Default date-to-string formatter to get a month header.
* @param {!Date} date
* @returns {string}
*/
function defaultMonthHeaderFormatter(date) {
return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
}
/**
* Default week number formatter.
* @param number
* @returns {string}
*/
function defaultWeekNumberFormatter(number) {
return 'Week ' + number;
}
/**
* Default formatter for date cell aria-labels.
* @param {!Date} date
* @returns {string}
*/
function defaultLongDateFormatter(date) {
// Example: 'Thursday June 18 2015'
return [
service.days[date.getDay()],
service.months[date.getMonth()],
service.dates[date.getDate()],
date.getFullYear()
].join(' ');
}
// The default "short" day strings are the first character of each day,
// e.g., "Monday" => "M".
var defaultShortDays = $locale.DATETIME_FORMATS.DAY.map(function(day) {
return day[0];
});
// The default dates are simply the numbers 1 through 31.
var defaultDates = Array(32);
for (var i = 1; i <= 31; i++) {
defaultDates[i] = i;
}
// Default ARIA messages are in English (US).
var defaultMsgCalendar = 'Calendar';
var defaultMsgOpenCalendar = 'Open calendar';
var service = {
months: this.months || $locale.DATETIME_FORMATS.MONTH,
shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
days: this.days || $locale.DATETIME_FORMATS.DAY,
shortDays: this.shortDays || defaultShortDays,
dates: this.dates || defaultDates,
firstDayOfWeek: this.firstDayOfWeek || 0,
formatDate: this.formatDate || defaultFormatDate,
parseDate: this.parseDate || defaultParseDate,
isDateComplete: this.isDateComplete || defaultIsDateComplete,
monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
msgCalendar: this.msgCalendar || defaultMsgCalendar,
msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar
};
return service;
};
DateLocaleProvider.prototype.$get.$inject = ["$locale"];
$provide.provider('$mdDateLocale', new DateLocaleProvider());
}]);
})();
(function() {
'use strict';
// POST RELEASE
// TODO(jelbourn): Demo that uses moment.js
// TODO(jelbourn): make sure this plays well with validation and ngMessages.
// TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
// TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
// TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
// TODO(jelbourn): input behavior (masking? auto-complete?)
// TODO(jelbourn): UTC mode
// TODO(jelbourn): RTL
angular.module('material.components.datepicker')
.directive('mdDatepicker', datePickerDirective);
/**
* @ngdoc directive
* @name mdDatepicker
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Expects a JavaScript Date object.
* @param {expression=} ng-change Expression evaluated when the model value changes.
* @param {Date=} md-min-date Expression representing a min date (inclusive).
* @param {Date=} md-max-date Expression representing a max date (inclusive).
* @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
* @param {String=} md-placeholder The date input placeholder value.
* @param {boolean=} ng-disabled Whether the datepicker is disabled.
* @param {boolean=} ng-required Whether a value is required for the datepicker.
*
* @description
* `<md-datepicker>` is a component used to select a single date.
* For information on how to configure internationalization for the date picker,
* see `$mdDateLocaleProvider`.
*
* This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
* Supported attributes are:
* * `required`: whether a required date is not set.
* * `mindate`: whether the selected date is before the minimum allowed date.
* * `maxdate`: whether the selected date is after the maximum allowed date.
*
* @usage
* <hljs lang="html">
* <md-datepicker ng-model="birthday"></md-datepicker>
* </hljs>
*
*/
function datePickerDirective() {
return {
template:
// Buttons are not in the tab order because users can open the calendar via keyboard
// interaction on the text input, and multiple tab stops for one component (picker)
// may be confusing.
'<md-button class="md-datepicker-button md-icon-button" type="button" ' +
'tabindex="-1" aria-hidden="true" ' +
'ng-click="ctrl.openCalendarPane($event)">' +
'<md-icon class="md-datepicker-calendar-icon" md-svg-icon="md-calendar"></md-icon>' +
'</md-button>' +
'<div class="md-datepicker-input-container" ' +
'ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
'<input class="md-datepicker-input" aria-haspopup="true" ' +
'ng-focus="ctrl.setFocused(true)" ng-blur="ctrl.setFocused(false)">' +
'<md-button type="button" md-no-ink ' +
'class="md-datepicker-triangle-button md-icon-button" ' +
'ng-click="ctrl.openCalendarPane($event)" ' +
'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
'<div class="md-datepicker-expand-triangle"></div>' +
'</md-button>' +
'</div>' +
// This pane will be detached from here and re-attached to the document body.
'<div class="md-datepicker-calendar-pane md-whiteframe-z1">' +
'<div class="md-datepicker-input-mask">' +
'<div class="md-datepicker-input-mask-opaque"></div>' +
'</div>' +
'<div class="md-datepicker-calendar">' +
'<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
'md-min-date="ctrl.minDate" md-max-date="ctrl.maxDate"' +
'md-date-filter="ctrl.dateFilter"' +
'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
'</md-calendar>' +
'</div>' +
'</div>',
require: ['ngModel', 'mdDatepicker', '?^mdInputContainer'],
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
placeholder: '@mdPlaceholder',
dateFilter: '=mdDateFilter'
},
controller: DatePickerCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attr, controllers) {
var ngModelCtrl = controllers[0];
var mdDatePickerCtrl = controllers[1];
var mdInputContainer = controllers[2];
if (mdInputContainer) {
throw Error('md-datepicker should not be placed inside md-input-container.');
}
mdDatePickerCtrl.configureNgModel(ngModelCtrl);
}
};
}
/** Additional offset for the input's `size` attribute, which is updated based on its content. */
var EXTRA_INPUT_SIZE = 3;
/** Class applied to the container if the date is invalid. */
var INVALID_CLASS = 'md-datepicker-invalid';
/** Default time in ms to debounce input event by. */
var DEFAULT_DEBOUNCE_INTERVAL = 500;
/**
* Height of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_HEIGHT = 368;
/**
* Width of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_WIDTH = 360;
/**
* Controller for md-datepicker.
*
* ngInject @constructor
*/
function DatePickerCtrl($scope, $element, $attrs, $compile, $timeout, $window,
$mdConstant, $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF) {
/** @final */
this.$compile = $compile;
/** @final */
this.$timeout = $timeout;
/** @final */
this.$window = $window;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdConstant = $mdConstant;
/* @final */
this.$mdUtil = $mdUtil;
/** @final */
this.$$rAF = $$rAF;
/**
* The root document element. This is used for attaching a top-level click handler to
* close the calendar panel when a click outside said panel occurs. We use `documentElement`
* instead of body because, when scrolling is disabled, some browsers consider the body element
* to be completely off the screen and propagate events directly to the html element.
* @type {!angular.JQLite}
*/
this.documentElement = angular.element(document.documentElement);
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {HTMLInputElement} */
this.inputElement = $element[0].querySelector('input');
/** @final {!angular.JQLite} */
this.ngInputElement = angular.element(this.inputElement);
/** @type {HTMLElement} */
this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
/** @type {HTMLElement} Floating calendar pane. */
this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
/** @type {HTMLElement} Calendar icon button. */
this.calendarButton = $element[0].querySelector('.md-datepicker-button');
/**
* Element covering everything but the input in the top of the floating calendar pane.
* @type {HTMLElement}
*/
this.inputMask = $element[0].querySelector('.md-datepicker-input-mask-opaque');
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Attributes} */
this.$attrs = $attrs;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @type {Date} */
this.date = null;
/** @type {boolean} */
this.isFocused = false;
/** @type {boolean} */
this.isDisabled;
this.setDisabled($element[0].disabled || angular.isString($attrs['disabled']));
/** @type {boolean} Whether the date-picker's calendar pane is open. */
this.isCalendarOpen = false;
/**
* Element from which the calendar pane was opened. Keep track of this so that we can return
* focus to it when the pane is closed.
* @type {HTMLElement}
*/
this.calendarPaneOpenedFrom = null;
this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();
$mdTheming($element);
/** Pre-bound click handler is saved so that the event listener can be removed. */
this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
/** Pre-bound resize handler so that the event listener can be removed. */
this.windowResizeHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
// Unless the user specifies so, the datepicker should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs['tabindex']) {
$element.attr('tabindex', '-1');
}
this.installPropertyInterceptors();
this.attachChangeListeners();
this.attachInteractionListeners();
var self = this;
$scope.$on('$destroy', function() {
self.detachCalendarPane();
});
}
DatePickerCtrl.$inject = ["$scope", "$element", "$attrs", "$compile", "$timeout", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF"];
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
var value = self.ngModelCtrl.$viewValue;
if (value && !(value instanceof Date)) {
throw Error('The ng-model for md-datepicker must be a Date instance. ' +
'Currently the model is a: ' + (typeof value));
}
self.date = value;
self.inputElement.value = self.dateLocale.formatDate(value);
self.resizeInputElement();
self.updateErrorState();
};
};
/**
* Attach event listeners for both the text input and the md-calendar.
* Events are used instead of ng-model so that updates don't infinitely update the other
* on a change. This should also be more performant than using a $watch.
*/
DatePickerCtrl.prototype.attachChangeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-change', function(event, date) {
self.ngModelCtrl.$setViewValue(date);
self.date = date;
self.inputElement.value = self.dateLocale.formatDate(date);
self.closeCalendarPane();
self.resizeInputElement();
self.updateErrorState();
});
self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
// TODO(chenmike): Add ability for users to specify this interval.
self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
DEFAULT_DEBOUNCE_INTERVAL, self));
};
/** Attach event listeners for user interaction. */
DatePickerCtrl.prototype.attachInteractionListeners = function() {
var self = this;
var $scope = this.$scope;
var keyCodes = this.$mdConstant.KEY_CODE;
// Add event listener through angular so that we can triggerHandler in unit tests.
self.ngInputElement.on('keydown', function(event) {
if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
self.openCalendarPane(event);
$scope.$digest();
}
});
$scope.$on('md-calendar-close', function() {
self.closeCalendarPane();
});
};
/**
* Capture properties set to the date-picker and imperitively handle internal changes.
* This is done to avoid setting up additional $watches.
*/
DatePickerCtrl.prototype.installPropertyInterceptors = function() {
var self = this;
if (this.$attrs['ngDisabled']) {
// The expression is to be evaluated against the directive element's scope and not
// the directive's isolate scope.
var scope = this.$scope.$parent;
if (scope) {
scope.$watch(this.$attrs['ngDisabled'], function(isDisabled) {
self.setDisabled(isDisabled);
});
}
}
Object.defineProperty(this, 'placeholder', {
get: function() { return self.inputElement.placeholder; },
set: function(value) { self.inputElement.placeholder = value || ''; }
});
};
/**
* Sets whether the date-picker is disabled.
* @param {boolean} isDisabled
*/
DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
this.isDisabled = isDisabled;
this.inputElement.disabled = isDisabled;
this.calendarButton.disabled = isDisabled;
};
/**
* Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
* - mindate: whether the selected date is before the minimum date.
* - maxdate: whether the selected flag is after the maximum date.
* - filtered: whether the selected date is allowed by the custom filtering function.
* - valid: whether the entered text input is a valid date
*
* The 'required' flag is handled automatically by ngModel.
*
* @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
*/
DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
var date = opt_date || this.date;
// Clear any existing errors to get rid of anything that's no longer relevant.
this.clearErrorState();
if (this.dateUtil.isValidDate(date)) {
// Force all dates to midnight in order to ignore the time portion.
date = this.dateUtil.createDateAtMidnight(date);
if (this.dateUtil.isValidDate(this.minDate)) {
var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
this.ngModelCtrl.$setValidity('mindate', date >= minDate);
}
if (this.dateUtil.isValidDate(this.maxDate)) {
var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
}
if (angular.isFunction(this.dateFilter)) {
this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
}
} else {
// The date is seen as "not a valid date" if there is *something* set
// (i.e.., not null or undefined), but that something isn't a valid date.
this.ngModelCtrl.$setValidity('valid', date == null);
}
// TODO(jelbourn): Change this to classList.toggle when we stop using PhantomJS in unit tests
// because it doesn't conform to the DOMTokenList spec.
// See https://github.com/ariya/phantomjs/issues/12782.
if (!this.ngModelCtrl.$valid) {
this.inputContainer.classList.add(INVALID_CLASS);
}
};
/** Clears any error flags set by `updateErrorState`. */
DatePickerCtrl.prototype.clearErrorState = function() {
this.inputContainer.classList.remove(INVALID_CLASS);
['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
this.ngModelCtrl.$setValidity(field, true);
}, this);
};
/** Resizes the input element based on the size of its content. */
DatePickerCtrl.prototype.resizeInputElement = function() {
this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
};
/**
* Sets the model value if the user input is a valid date.
* Adds an invalid class to the input element if not.
*/
DatePickerCtrl.prototype.handleInputEvent = function() {
var inputString = this.inputElement.value;
var parsedDate = inputString ? this.dateLocale.parseDate(inputString) : null;
this.dateUtil.setDateTimeToMidnight(parsedDate);
// An input string is valid if it is either empty (representing no date)
// or if it parses to a valid date that the user is allowed to select.
var isValidInput = inputString == '' || (
this.dateUtil.isValidDate(parsedDate) &&
this.dateLocale.isDateComplete(inputString) &&
this.isDateEnabled(parsedDate)
);
// The datepicker's model is only updated when there is a valid input.
if (isValidInput) {
this.ngModelCtrl.$setViewValue(parsedDate);
this.date = parsedDate;
}
this.updateErrorState(parsedDate);
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
(!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
};
/** Position and attach the floating calendar to the document. */
DatePickerCtrl.prototype.attachCalendarPane = function() {
var calendarPane = this.calendarPane;
calendarPane.style.transform = '';
this.$element.addClass('md-datepicker-open');
var elementRect = this.inputContainer.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
// Check to see if the calendar pane would go off the screen. If so, adjust position
// accordingly to keep it within the viewport.
var paneTop = elementRect.top - bodyRect.top;
var paneLeft = elementRect.left - bodyRect.left;
// If ng-material has disabled body scrolling (for example, if a dialog is open),
// then it's possible that the already-scrolled body has a negative top/left. In this case,
// we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
// though, the top of the viewport should just be the body's scroll position.
var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
-bodyRect.top :
document.body.scrollTop;
var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
-bodyRect.left :
document.body.scrollLeft;
var viewportBottom = viewportTop + this.$window.innerHeight;
var viewportRight = viewportLeft + this.$window.innerWidth;
// If the right edge of the pane would be off the screen and shifting it left by the
// difference would not go past the left edge of the screen. If the calendar pane is too
// big to fit on the screen at all, move it to the left of the screen and scale the entire
// element down to fit.
if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
} else {
paneLeft = viewportLeft;
var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
calendarPane.style.transform = 'scale(' + scale + ')';
}
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
// If the bottom edge of the pane would be off the screen and shifting it up by the
// difference would not go past the top edge of the screen.
if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
calendarPane.style.left = paneLeft + 'px';
calendarPane.style.top = paneTop + 'px';
document.body.appendChild(calendarPane);
// The top of the calendar pane is a transparent box that shows the text input underneath.
// Since the pane is floating, though, the page underneath the pane *adjacent* to the input is
// also shown unless we cover it up. The inputMask does this by filling up the remaining space
// based on the width of the input.
this.inputMask.style.left = elementRect.width + 'px';
// Add CSS class after one frame to trigger open animation.
this.$$rAF(function() {
calendarPane.classList.add('md-pane-open');
});
};
/** Detach the floating calendar pane from the document. */
DatePickerCtrl.prototype.detachCalendarPane = function() {
this.$element.removeClass('md-datepicker-open');
this.calendarPane.classList.remove('md-pane-open');
this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
if (this.isCalendarOpen) {
this.$mdUtil.enableScrolling();
}
if (this.calendarPane.parentNode) {
// Use native DOM removal because we do not want any of the angular state of this element
// to be disposed.
this.calendarPane.parentNode.removeChild(this.calendarPane);
}
};
/**
* Open the floating calendar pane.
* @param {Event} event
*/
DatePickerCtrl.prototype.openCalendarPane = function(event) {
if (!this.isCalendarOpen && !this.isDisabled) {
this.isCalendarOpen = true;
this.calendarPaneOpenedFrom = event.target;
// Because the calendar pane is attached directly to the body, it is possible that the
// rest of the component (input, etc) is in a different scrolling container, such as
// an md-content. This means that, if the container is scrolled, the pane would remain
// stationary. To remedy this, we disable scrolling while the calendar pane is open, which
// also matches the native behavior for things like `<select>` on Mac and Windows.
this.$mdUtil.disableScrollAround(this.calendarPane);
this.attachCalendarPane();
this.focusCalendar();
// Attach click listener inside of a timeout because, if this open call was triggered by a
// click, we don't want it to be immediately propogated up to the body and handled.
var self = this;
this.$mdUtil.nextTick(function() {
// Use 'touchstart` in addition to click in order to work on iOS Safari, where click
// events aren't propogated under most circumstances.
// See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
self.documentElement.on('click touchstart', self.bodyClickHandler);
}, false);
window.addEventListener('resize', this.windowResizeHandler);
}
};
/** Close the floating calendar pane. */
DatePickerCtrl.prototype.closeCalendarPane = function() {
if (this.isCalendarOpen) {
this.detachCalendarPane();
this.isCalendarOpen = false;
this.calendarPaneOpenedFrom.focus();
this.calendarPaneOpenedFrom = null;
this.ngModelCtrl.$setTouched();
this.documentElement.off('click touchstart', this.bodyClickHandler);
window.removeEventListener('resize', this.windowResizeHandler);
}
};
/** Gets the controller instance for the calendar in the floating pane. */
DatePickerCtrl.prototype.getCalendarCtrl = function() {
return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
};
/** Focus the calendar in the floating pane. */
DatePickerCtrl.prototype.focusCalendar = function() {
// Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
var self = this;
this.$mdUtil.nextTick(function() {
self.getCalendarCtrl().focus();
}, false);
};
/**
* Sets whether the input is currently focused.
* @param {boolean} isFocused
*/
DatePickerCtrl.prototype.setFocused = function(isFocused) {
if (!isFocused) {
this.ngModelCtrl.$setTouched();
}
this.isFocused = isFocused;
};
/**
* Handles a click on the document body when the floating calendar pane is open.
* Closes the floating calendar pane if the click is not inside of it.
* @param {MouseEvent} event
*/
DatePickerCtrl.prototype.handleBodyClick = function(event) {
if (this.isCalendarOpen) {
// TODO(jelbourn): way want to also include the md-datepicker itself in this check.
var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
if (!isInCalendar) {
this.closeCalendarPane();
}
this.$scope.$digest();
}
};
})();
(function() {
'use strict';
/**
* Utility for performing date calculations to facilitate operation of the calendar and
* datepicker.
*/
angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
return {
getFirstDateOfMonth: getFirstDateOfMonth,
getNumberOfDaysInMonth: getNumberOfDaysInMonth,
getDateInNextMonth: getDateInNextMonth,
getDateInPreviousMonth: getDateInPreviousMonth,
isInNextMonth: isInNextMonth,
isInPreviousMonth: isInPreviousMonth,
getDateMidpoint: getDateMidpoint,
isSameMonthAndYear: isSameMonthAndYear,
getWeekOfMonth: getWeekOfMonth,
incrementDays: incrementDays,
incrementMonths: incrementMonths,
getLastDateOfMonth: getLastDateOfMonth,
isSameDay: isSameDay,
getMonthDistance: getMonthDistance,
isValidDate: isValidDate,
setDateTimeToMidnight: setDateTimeToMidnight,
createDateAtMidnight: createDateAtMidnight,
isDateWithinRange: isDateWithinRange
};
/**
* Gets the first day of the month for the given date's month.
* @param {Date} date
* @returns {Date}
*/
function getFirstDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
/**
* Gets the number of days in the month for the given date's month.
* @param date
* @returns {number}
*/
function getNumberOfDaysInMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}
/**
* Get an arbitrary date in the month after the given date's month.
* @param date
* @returns {Date}
*/
function getDateInNextMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 1);
}
/**
* Get an arbitrary date in the month before the given date's month.
* @param date
* @returns {Date}
*/
function getDateInPreviousMonth(date) {
return new Date(date.getFullYear(), date.getMonth() - 1, 1);
}
/**
* Gets whether two dates have the same month and year.
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameMonthAndYear(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
}
/**
* Gets whether two dates are the same day (not not necesarily the same time).
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameDay(d1, d2) {
return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
}
/**
* Gets whether a date is in the month immediately after some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInNextMonth(startDate, endDate) {
var nextMonth = getDateInNextMonth(startDate);
return isSameMonthAndYear(nextMonth, endDate);
}
/**
* Gets whether a date is in the month immediately before some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInPreviousMonth(startDate, endDate) {
var previousMonth = getDateInPreviousMonth(startDate);
return isSameMonthAndYear(endDate, previousMonth);
}
/**
* Gets the midpoint between two dates.
* @param {Date} d1
* @param {Date} d2
* @returns {Date}
*/
function getDateMidpoint(d1, d2) {
return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
}
/**
* Gets the week of the month that a given date occurs in.
* @param {Date} date
* @returns {number} Index of the week of the month (zero-based).
*/
function getWeekOfMonth(date) {
var firstDayOfMonth = getFirstDateOfMonth(date);
return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
}
/**
* Gets a new date incremented by the given number of days. Number of days can be negative.
* @param {Date} date
* @param {number} numberOfDays
* @returns {Date}
*/
function incrementDays(date, numberOfDays) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
}
/**
* Gets a new date incremented by the given number of months. Number of months can be negative.
* If the date of the given month does not match the target month, the date will be set to the
* last day of the month.
* @param {Date} date
* @param {number} numberOfMonths
* @returns {Date}
*/
function incrementMonths(date, numberOfMonths) {
// If the same date in the target month does not actually exist, the Date object will
// automatically advance *another* month by the number of missing days.
// For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
// So, we check if the month overflowed and go to the last day of the target month instead.
var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
if (numberOfDaysInMonth < date.getDate()) {
dateInTargetMonth.setDate(numberOfDaysInMonth);
} else {
dateInTargetMonth.setDate(date.getDate());
}
return dateInTargetMonth;
}
/**
* Get the integer distance between two months. This *only* considers the month and year
* portion of the Date instances.
*
* @param {Date} start
* @param {Date} end
* @returns {number} Number of months between `start` and `end`. If `end` is before `start`
* chronologically, this number will be negative.
*/
function getMonthDistance(start, end) {
return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
}
/**
* Gets the last day of the month for the given date.
* @param {Date} date
* @returns {Date}
*/
function getLastDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
}
/**
* Checks whether a date is valid.
* @param {Date} date
* @return {boolean} Whether the date is a valid Date.
*/
function isValidDate(date) {
return date != null && date.getTime && !isNaN(date.getTime());
}
/**
* Sets a date's time to midnight.
* @param {Date} date
*/
function setDateTimeToMidnight(date) {
if (isValidDate(date)) {
date.setHours(0, 0, 0, 0);
}
}
/**
* Creates a date with the time set to midnight.
* Drop-in replacement for two forms of the Date constructor:
* 1. No argument for Date representing now.
* 2. Single-argument value representing number of seconds since Unix Epoch
* or a Date object.
* @param {number|Date=} opt_value
* @return {Date} New date with time set to midnight.
*/
function createDateAtMidnight(opt_value) {
var date;
if (angular.isUndefined(opt_value)) {
date = new Date();
} else {
date = new Date(opt_value);
}
setDateTimeToMidnight(date);
return date;
}
/**
* Checks if a date is within a min and max range, ignoring the time component.
* If minDate or maxDate are not dates, they are ignored.
* @param {Date} date
* @param {Date} minDate
* @param {Date} maxDate
*/
function isDateWithinRange(date, minDate, maxDate) {
var dateAtMidnight = createDateAtMidnight(date);
var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
(!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
}
});
})();
ng.material.components.datepicker = angular.module("material.components.datepicker"); |
'use strict'
const qiniu = require('qiniu');
qiniu.conf.ACCESS_KEY = APP.qiniu.ACCESS_KEY
qiniu.conf.SECRET_KEY = APP.qiniu.SECRET_KEY
exports.uploadFileToken = async (ctx, next) => {
let putPolicy = new qiniu.rs.PutPolicy(APP.qiniu.bucket)
putPolicy.expires = APP.qiniu.signedUrlExpires
let token = putPolicy.token()
ctx.body = {
url: 'http://up.qiniu.com/',
token: token
}
return next()
}
|
import jasmineEnzyme from 'jasmine-enzyme';
import { shallow } from 'enzyme';
import React from 'react';
import AddEditExerciseForm from '../AddEditExerciseForm';
describe('<AddEditExerciseForm />', () => {
beforeEach(() => {
jasmineEnzyme();
});
it('should exist', () => {
const wrapper = shallow(<AddEditExerciseForm />);
expect(wrapper.find('div')).toBePresent();
});
});
|
/*!
* NETEYE Activity Indicator jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
/**
* Plugin that renders a customisable activity indicator (spinner) using SVG or VML.
*/
(function($) {
$.fn.activity = function(opts) {
this.each(function() {
var $this = $(this);
var el = $this.data('activity');
if (el) {
clearInterval(el.data('interval'));
el.remove();
$this.removeData('activity');
}
if (opts !== false) {
opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts);
el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this);
var h = $this.outerHeight() - el.height();
var w = $this.outerWidth() - el.width();
var margin = {
top: opts.valign == 'top' ? opts.padding : opts.valign == 'bottom' ? h - opts.padding : Math.floor(h / 2),
left: opts.align == 'left' ? opts.padding : opts.align == 'right' ? w - opts.padding : Math.floor(w / 2)
};
var offset = $this.offset();
if (opts.outside) {
el.css({top: offset.top + 'px', left: offset.left + 'px'});
}
else {
margin.top -= el.offset().top - offset.top;
margin.left -= el.offset().left - offset.left;
}
el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'});
animate(el, opts.segments, Math.round(10 / opts.speed) / 10);
$this.data('activity', el);
}
});
return this;
};
$.fn.activity.defaults = {
segments: 12,
space: 3,
length: 7,
width: 4,
speed: 1.2,
align: 'center',
valign: 'center',
padding: 4
};
$.fn.activity.getOpacity = function(opts, i) {
var steps = opts.steps || opts.segments-1;
var end = opts.opacity !== undefined ? opts.opacity : 1/steps;
return 1 - Math.min(i, steps) * (1 - end) / steps;
};
/**
* Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy'
* is inserted, that can be styled with CSS to display an animated gif as fallback.
*/
var render = function() {
return $('<div>').addClass('busy');
};
/**
* The default animation strategy does nothing as we expect an animated gif as fallback.
*/
var animate = function() {
};
/**
* Utility function to create elements in the SVG namespace.
*/
function svg(tag, attr) {
var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
if (attr) {
$.each(attr, function(k, v) {
el.setAttributeNS(null, k, v);
});
}
return $(el);
}
if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) {
// =======================================================================================
// SVG Rendering
// =======================================================================================
/**
* Rendering strategy that creates a SVG tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var el = svg().width(r*2).height(r*2);
var g = svg('g', {
'stroke-width': d.width,
'stroke-linecap': 'round',
stroke: d.color
}).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el));
for (var i = 0; i < d.segments; i++) {
g.append(svg('line', {
x1: 0,
y1: innerRadius,
x2: 0,
y2: innerRadius + d.length,
transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)',
opacity: $.fn.activity.getOpacity(d, i)
}));
}
return $('<div>').append(el).width(2*r).height(2*r);
};
// Check if Webkit CSS animations are available, as they work much better on the iPad
// than setTimeout() based animations.
if (document.createElement('div').style.WebkitAnimationName !== undefined) {
var animations = {};
/**
* Animation strategy that uses dynamically created CSS animation rules.
*/
animate = function(el, steps, duration) {
if (!animations[steps]) {
var name = 'spin' + steps;
var rule = '@-webkit-keyframes '+ name +' {';
for (var i=0; i < steps; i++) {
var p1 = Math.round(100000 / steps * i) / 1000;
var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000;
var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n';
rule += p1 + value + p2 + value;
}
rule += '100% { -webkit-transform:rotate(100deg); }\n}';
document.styleSheets[0].insertRule(rule);
animations[steps] = name;
}
el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite');
};
}
else {
/**
* Animation strategy that transforms a SVG element using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.find('g g').get(0);
el.data('interval', setInterval(function() {
g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')');
}, duration * 1000 / steps));
};
}
}
else {
// =======================================================================================
// VML Rendering
// =======================================================================================
var s = $('<shape>').css('behavior', 'url(#default#VML)').appendTo('body');
if (s.get(0).adj) {
// VML support detected. Insert CSS rules for group, shape and stroke.
var sheet = document.createStyleSheet();
$.each(['group', 'shape', 'stroke'], function() {
sheet.addRule(this, "behavior:url(#default#VML);");
});
/**
* Rendering strategy that creates a VML tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var s = r*2;
var o = -Math.ceil(s/2);
var el = $('<group>', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s});
for (var i = 0; i < d.segments; i++) {
el.append($('<shape>', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({
width: s,
height: s,
rotation: (360 / d.segments * i) + 'deg'
}).append($('<stroke>', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)})));
}
return $('<group>', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el);
};
/**
* Animation strategy that modifies the VML rotation property using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.get(0);
el.data('interval', setInterval(function() {
g.style.rotation = ++rotation % steps * (360 / steps);
}, duration * 1000 / steps));
};
}
$(s).remove();
}
})(jQuery);
/*!
* NETEYE Activity Indicator jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
/**
* Plugin that renders a customisable activity indicator (spinner) using SVG or VML.
*/
(function($) {
$.fn.activity = function(opts) {
this.each(function() {
var $this = $(this);
var el = $this.data('activity');
if (el) {
clearInterval(el.data('interval'));
el.remove();
$this.removeData('activity');
}
if (opts !== false) {
opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts);
el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this);
var margin = {
top: Math.floor(($this.outerHeight() - el.height()) / 2),
left: Math.floor(($this.outerWidth() - el.width()) / 2)
};
var offset = $this.offset();
if (opts.outside) {
el.css({top: offset.top + 'px', left: offset.left + 'px'});
}
else {
margin.top -= el.offset().top - offset.top;
margin.left -= el.offset().left - offset.left;
}
el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'});
animate(el, opts.segments, Math.round(10 / opts.speed) / 10);
$this.data('activity', el);
}
});
return this;
};
$.fn.activity.defaults = {
segments: 12,
space: 3,
length: 7,
width: 4,
speed: 1.2
};
$.fn.activity.getOpacity = function(opts, i) {
var steps = opts.steps || opts.segments-1;
var end = opts.opacity !== undefined ? opts.opacity : 1/steps;
return 1 - Math.min(i, steps) * (1 - end) / steps;
};
/**
* Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy'
* is inserted, that can be styled with CSS to display an animated gif as fallback.
*/
var render = function() {
return $('<div>').addClass('busy');
};
/**
* The default animation strategy does nothing as we expect an animated gif as fallback.
*/
var animate = function() {
};
/**
* Utility function to create elements in the SVG namespace.
*/
function svg(tag, attr) {
var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
if (attr) {
$.each(attr, function(k, v) {
el.setAttributeNS(null, k, v);
});
}
return $(el);
}
if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) {
// =======================================================================================
// SVG Rendering
// =======================================================================================
/**
* Rendering strategy that creates a SVG tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var el = svg().width(r*2).height(r*2);
var g = svg('g', {
'stroke-width': d.width,
'stroke-linecap': 'round',
stroke: d.color
}).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el));
for (var i = 0; i < d.segments; i++) {
g.append(svg('line', {
x1: 0,
y1: innerRadius,
x2: 0,
y2: innerRadius + d.length,
transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)',
opacity: $.fn.activity.getOpacity(d, i)
}));
}
return $('<div>').append(el).width(2*r).height(2*r);
};
// Check if Webkit CSS animations are available, as they work much better on the iPad
// than setTimeout() based animations.
if (document.createElement('div').style.WebkitAnimationName !== undefined) {
var animations = {};
/**
* Animation strategy that uses dynamically created CSS animation rules.
*/
animate = function(el, steps, duration) {
if (!animations[steps]) {
var name = 'spin' + steps;
var rule = '@-webkit-keyframes '+ name +' {';
for (var i=0; i < steps; i++) {
var p1 = Math.round(100000 / steps * i) / 1000;
var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000;
var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n';
rule += p1 + value + p2 + value;
}
rule += '100% { -webkit-transform:rotate(100deg); }\n}';
document.styleSheets[0].insertRule(rule);
animations[steps] = name;
}
el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite');
};
}
else {
/**
* Animation strategy that transforms a SVG element using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.find('g g').get(0);
el.data('interval', setInterval(function() {
g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')');
}, duration * 1000 / steps));
};
}
}
else {
// =======================================================================================
// VML Rendering
// =======================================================================================
var s = $('<shape>').css('behavior', 'url(#default#VML)').appendTo('body');
if (s.get(0).adj) {
// VML support detected. Insert CSS rules for group, shape and stroke.
var sheet = document.createStyleSheet();
$.each(['group', 'shape', 'stroke'], function() {
sheet.addRule(this, "behavior:url(#default#VML);");
});
/**
* Rendering strategy that creates a VML tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var s = r*2;
var o = -Math.ceil(s/2);
var el = $('<group>', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s});
for (var i = 0; i < d.segments; i++) {
el.append($('<shape>', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({
width: s,
height: s,
rotation: (360 / d.segments * i) + 'deg'
}).append($('<stroke>', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)})));
}
return $('<group>', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el);
};
/**
* Animation strategy that modifies the VML rotation property using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.get(0);
el.data('interval', setInterval(function() {
g.style.rotation = ++rotation % steps * (360 / steps);
}, duration * 1000 / steps));
};
}
$(s).remove();
}
})(jQuery);
/*!
* NETEYE Transform & Transition Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
(function($) {
// ==========================================================================================
// Private functions
// ==========================================================================================
var props = (function() {
var prefixes = ['Webkit', 'Moz', 'O'];
var style = document.createElement('div').style;
function findProp(name) {
var result = '';
if (style[name] !== undefined) {
return name;
}
$.each(prefixes, function() {
var p = this + name.charAt(0).toUpperCase() + name.substring(1);
if (style[p] !== undefined) {
result = p;
return false;
}
});
return result;
}
var result = {};
$.each(['transitionDuration', 'transitionProperty', 'transform', 'transformOrigin'], function() {
result[this] = findProp(this);
});
return result;
})();
var supports3d = (function() {
var s = document.createElement('div').style;
try {
s[props.transform] = 'translate3d(0,0,0)';
return s[props.transform].length > 0;
}
catch (ex) {
return false;
}
})();
function transform(el, commands) {
var t = el.data('transform');
if (!t) {
t = new Transformation();
el.data('transform', t);
}
if (commands !== undefined) {
if (commands === false || commands.reset) {
t.reset();
}
else {
t.exec(commands);
}
}
return t;
}
/**
* Class that keeps track of numeric values and converts them into a string representation
* that can be used as value for the -webkit-transform property. TransformFunctions are used
* internally by the Transformation class.
*
* // Example:
*
* var t = new TransformFunction('translate3d({x}px,{y}px,{z}px)', {x:0, y:0, z:0});
* t.x = 23;
* console.assert(t.format() == 'translate3d(23px,0px,0px)')
*/
function TransformFunction(pattern, defaults) {
function fillIn(pattern, data) {
return pattern.replace(/\{(\w+)\}/g, function(s, p1) { return data[p1]; });
}
this.reset = function() {
$.extend(this, defaults);
};
this.format = function() {
return fillIn(pattern, this);
};
this.reset();
}
/**
* Class that encapsulates the state of multiple TransformFunctions. The state can be modified
* using commands and converted into a string representation that can be used as CSS value.
* The class is used internally by the transform plugin.
*/
function Transformation() {
var fn = {
translate: new TransformFunction('translate({x}px,{y}px)', {x:0, y:0}),
scale: new TransformFunction('scale({x},{y})', {x:1, y:1}),
rotate: new TransformFunction('rotate({deg}deg)', {deg:0})
};
if (supports3d) {
// Use 3D transforms for better performance
fn.translate = new TransformFunction('translate3d({x}px,{y}px,0px)', {x:0, y:0});
fn.scale = new TransformFunction('scale3d({x},{y},1)', {x:1, y:1});
}
var commands = {
rotate: function(deg) {
fn.rotate.deg = deg;
},
rotateBy: function(deg) {
fn.rotate.deg += deg;
},
scale: function(s) {
if (typeof s == 'number') {
s = {x: s, y: s};
}
fn.scale.x = s.x;
fn.scale.y = s.y;
},
scaleBy: function(s) {
if (typeof s == 'number') {
s = {x: s, y: s};
}
fn.scale.x *= s.x;
fn.scale.y *= s.y;
},
translate: function(s) {
var t = fn.translate;
if (!s) {
s = {x: 0, y: 0};
}
t.x = (s.x !== undefined) ? parseInt(s.x, 10) : t.x;
t.y = (s.y !== undefined) ? parseInt(s.y, 10) : t.y;
},
translateBy: function(s) {
var t = fn.translate;
t.x += parseInt(s.x, 10) || 0;
t.y += parseInt(s.y, 10) || 0;
}
};
this.fn = fn;
this.exec = function(cmd) {
for (var n in cmd) {
if (commands[n]) {
commands[n](cmd[n]);
}
}
};
this.reset = function() {
$.each(fn, function() {
this.reset();
});
};
this.format = function() {
var s = '';
$.each(fn, function(k, v) {
s += v.format() + ' ';
});
return s;
};
}
// ==========================================================================================
// Public API
// ==========================================================================================
$.fn.transform = function(opts) {
var result = this;
if ($.fn.transform.supported) {
this.each(function() {
var $this = $(this);
var t = transform($this, opts);
if (opts === undefined) {
result = t.fn;
return false;
}
var origin = opts && opts.origin ? opts.origin : '0 0';
$this.css(props.transitionDuration, '0s')
.css(props.transformOrigin, origin)
.css(props.transform, t.format());
});
}
return result;
};
$.fn.transform.supported = !!props.transform;
$.fn.transition = function(css, opts) {
opts = $.extend({
delay: 0,
duration: 0.4
}, opts);
var property = '';
$.each(css, function(k, v) {
property += k + ',';
});
this.each(function() {
var $this = $(this);
if (!$.fn.transition.supported) {
$this.css(css);
if (opts.onFinish) {
$.proxy(opts.onFinish, $this)();
}
return;
}
var _duration = $this.css(props.transitionDuration);
function apply() {
$this.css(props.transitionProperty, property).css(props.transitionDuration, opts.duration + 's');
$this.css(css);
if (opts.duration > 0) {
$this.one('webkitTransitionEnd oTransitionEnd transitionend', afterCompletion);
}
else {
setTimeout(afterCompletion, 1);
}
}
function afterCompletion() {
$this.css(props.transitionDuration, _duration);
if (opts.onFinish) {
$.proxy(opts.onFinish, $this)();
}
}
if (opts.delay > 0) {
setTimeout(apply, opts.delay);
}
else {
apply();
}
});
return this;
};
$.fn.transition.supported = !!props.transitionProperty;
$.fn.transformTransition = function(opts) {
opts = $.extend({
origin: '0 0',
css: {}
}, opts);
var css = opts.css;
if ($.fn.transform.supported) {
css[props.transform] = transform(this, opts).format();
this.css(props.transformOrigin, opts.origin);
}
return this.transition(css, opts);
};
})(jQuery);
/*!
* NETEYE Touch-Gallery jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
(function($) {
var mobileSafari = /Mobile.*Safari/.test(navigator.userAgent);
$.fn.touchGallery = function(opts) {
opts = $.extend({}, $.fn.touchGallery.defaults, opts);
var thumbs = this;
this.live('click', function(ev) {
ev.preventDefault();
var clickedThumb = $(this);
if (!clickedThumb.is('.open')) {
thumbs.addClass('open');
openGallery(thumbs, clickedThumb, opts);
}
});
return this;
};
/**
* Default options.
*/
$.fn.touchGallery.defaults = {
getSource: function() {
return this.href;
}
};
// ==========================================================================================
// Private functions
// ==========================================================================================
/**
* Opens the gallery. A spining activity indicator is displayed until the clicked image has
* been loaded. When ready, showGallery() is called.
*/
function openGallery(thumbs, clickedThumb, opts) {
clickedThumb.activity();
var img = new Image();
img.onload = function() {
clickedThumb.activity(false);
showGallery(thumbs, thumbs.index(clickedThumb), this, opts.getSource);
};
img.src = $.proxy(opts.getSource, clickedThumb.get(0))();
}
/**
* Creates DOM elements to actually show the gallery.
*/
function showGallery(thumbs, index, clickedImage, getSrcCallback) {
var viewport = fitToView(preventTouch($('<div id="galleryViewport">').css({
position: 'fixed',
top: 0,
left: 0,
overflow: 'hidden'
}).transform(false).appendTo('body')));
var stripe = $('<div id="galleryStripe">').css({
position: 'absolute',
height: '100%',
top: 0,
left: (-index * getInnerWidth()) + 'px'
}).width(thumbs.length * getInnerWidth()).transform(false).appendTo(viewport);
setupEventListeners(stripe, getInnerWidth(), index, thumbs.length-1);
$(window).bind('orientationchange.gallery', function() {
fitToView(viewport);
stripe.find('img').each(centerImage);
});
thumbs.each(function(i) {
var page = $('<div>').addClass('galleryPage').css({
display: 'block',
position: 'absolute',
left: i * getInnerWidth() + 'px',
overflow: 'hidden',
height: '100%'
}).width(getInnerWidth()).data('thumbs', thumbs).data('thumb', $(this)).transform(false).appendTo(stripe);
if (i == index) {
var $img = $(clickedImage).css({position: 'absolute', display: 'block'}).transform(false);
makeInvisible(centerImage(index, clickedImage, $img)).appendTo(page);
zoomIn($(this), $img, function() {
stripe.addClass('ready');
loadSurroundingImages(index);
});
insertShade(viewport);
}
else {
page.activity({color: '#fff'});
var img = new Image();
var src = $.proxy(getSrcCallback, this)();
page.one('loadImage', function() {
img.src = src;
});
img.onload = function() {
var $this = $(this).css({position: 'absolute', display: 'block'}).transform(false);
centerImage(i, this, $this).appendTo(page.activity(false));
page.trigger('loaded');
};
}
});
}
function hideGallery(stripe) {
if (stripe.is('.ready') && !stripe.is('.panning')) {
$('#galleryShade').remove();
var page = stripe.find('.galleryPage').eq(stripe.data('galleryIndex'));
page.data('thumbs').removeClass('open');
var thumb = page.data('thumb');
stripe.add(window).add(document).unbind('.gallery');
zoomOut(page.find('img'), thumb, function() {
makeVisible(thumb).transform(false);
$('#galleryViewport').remove();
});
}
}
/**
* Inserts a black DIV before the given target element and performs an opacity
* transition form 0 to 1.
*/
function insertShade(target, onFinish) {
var el = $('<div id="galleryShade">').css({
top: 0, left: 0, background: '#000', opacity: 0
});
if (mobileSafari) {
// Make the shade bigger so that it shadows the surface upon rotation
var l = Math.max(screen.width, screen.height) * (window.devicePixelRatio || 1) + Math.max(getScrollLeft(), getScrollTop()) + 100;
el.css({position: 'absolute'}).width(l).height(l);
}
else {
el.css({position: 'fixed', width: '100%', height: '100%'});
}
el.insertBefore(target)
.transform(false)
.transition({opacity: 1}, {delay: 200, duration: 0.8, onFinish: onFinish});
}
/**
* Scales and centers an element according to the dimensions of the given image.
* The first argument is ignored, it's just there so that the function can be used with .each()
*/
function centerImage(i, img, el) {
el = el || $(img);
if (!img.naturalWidth) {
//Work-around for Opera which doesn't support naturalWidth/Height. This works because
//the function is invoked once for each image before it is scaled.
img.naturalWidth = img.width;
img.naturalHeight = img.height;
}
var s = Math.min(getViewportScale(), Math.min(getInnerHeight()/img.naturalHeight, getInnerWidth()/img.naturalWidth));
el.css({
top: Math.round((getInnerHeight() - img.naturalHeight * s) / 2) + 'px',
left: Math.round((getInnerWidth() - img.naturalWidth * s) / 2) + 'px'
}).width(Math.round(img.naturalWidth * s));
return el;
}
/**
* Performs a zoom animation from the small to the large element. The large element is scaled
* down and centered over the small element. Then a transition is performed that
* resets the transformation.
*/
function zoomIn(small, large, onFinish) {
var b = bounds(large);
var t = bounds(small);
var s = Math.max(t.width / large.width(), t.height / large.height());
var ox = mobileSafari ? 0 : getScrollLeft();
var oy = mobileSafari ? 0 : getScrollTop();
large.transform({
translate: {
x: t.left - b.left - ox - Math.round((b.width * s - t.width) / 2),
y: t.top - b.top - oy - Math.round((b.height * s - t.height) / 2)
},
scale: s
});
setTimeout(function() {
makeVisible(large);
makeInvisible(small);
large.transformTransition({reset: true, onFinish: onFinish});
}, 1);
}
/**
* Performs a zoom animation from the large to the small element. Since the small version
* may have a different aspect ratio, the large element is wrapped inside a div and clipped
* to match the aspect of the small version. The wrapper div is appended to the body, as
* leaving it in place causes strange z-index/flickering issues.
*/
function zoomOut(large, small, onFinish) {
if (large.length === 0 || !$.fn.transition.supported) {
if (onFinish) {
onFinish();
}
return;
}
var b = bounds(large);
var t = bounds(small);
var w = Math.min(b.height * t.width / t.height, b.width);
var h = Math.min(b.width * t.height / t.width, b.height);
var s = Math.max(t.width / w, t.height / h);
var div = $('<div>').css({
overflow: 'hidden',
position: 'absolute',
width: w + 'px',
height: h + 'px',
top: getScrollTop() + Math.round((getInnerHeight()-h) / 2) + 'px',
left: getScrollLeft() + Math.round((getInnerWidth()-w) / 2) + 'px'
})
.appendTo('body').append(large.css({
top: 1-Math.floor((b.height-h) / 2) + 'px', // -1px offset to match Flickr's square crops
left: -Math.floor((b.width-w) / 2) + 'px'
}))
.transform(false);
b = bounds(div);
div.transformTransition({
translate: {
x: t.left - b.left - Math.round((w * s - t.width) / 2),
y: t.top - b.top - Math.round((h * s - t.height) / 2)
},
scale: s,
onFinish: function() {
onFinish();
div.remove();
}
});
}
function getPage(i) {
return $('#galleryStripe .galleryPage').eq(i);
}
function getThumb(i) {
return getPage(i).data('thumb');
}
function loadSurroundingImages(i) {
var page = getPage(i);
function triggerLoad() {
getPage(i-1).add(getPage(i+1)).trigger('loadImage');
}
if (page.find('img').length > 0) {
triggerLoad();
}
else {
page.one('loaded', triggerLoad);
}
}
/**
* Registers event listeners to enable flicking through the images.
*/
function setupEventListeners(el, pageWidth, currentIndex, max) {
var scale = getViewportScale();
var xOffset = parseInt(el.css('left'), 10);
el.data('galleryIndex', currentIndex);
function flick(dir) {
var i = el.data('galleryIndex');
makeVisible(getThumb(i));
i = Math.max(0, Math.min(i + dir, max));
el.data('galleryIndex', i);
makeInvisible(getThumb(i));
loadSurroundingImages(i);
if ($.fn.transform.supported) {
var x = -i * pageWidth - xOffset;
if (x != el.transform().translate.x) {
el.addClass('panning').transformTransition({translate: {x: x}, onFinish: function() { this.removeClass('panning'); }});
}
}
else {
el.css('left', -i * pageWidth + 'px');
}
}
$(document).bind('keydown.gallery', function(event) {
if (event.keyCode == 37) {
el.trigger('prev');
}
else if (event.keyCode == 39) {
el.trigger('next');
}
if (event.keyCode == 27 || event.keyCode == 32) {
el.trigger('close');
}
return false;
});
el.bind('touchstart', function() {
$(this).data('pan', {
startX: event.targetTouches[0].screenX,
lastX:event.targetTouches[0].screenX,
startTime: new Date().getTime(),
startOffset: $(this).transform().translate.x,
distance: function() {
return Math.round(scale * (this.startX - this.lastX));
},
delta: function() {
var x = event.targetTouches[0].screenX;
this.dir = this.lastX > x ? 1 : -1;
var delta = Math.round(scale * (this.lastX - x));
this.lastX = x;
return delta;
},
duration: function() {
return new Date().getTime() - this.startTime;
}
});
return false;
})
.bind('touchmove', function() {
var pan = $(this).data('pan');
$(this).transform({translateBy: {x: -pan.delta()}});
return false;
})
.bind('touchend', function() {
var pan = $(this).data('pan');
if (pan.distance() === 0 && pan.duration() < 500) {
$(event.target).trigger('click');
}
else {
flick(pan.dir);
}
return false;
})
.bind('prev', function() {
flick(-1);
})
.bind('next', function() {
flick(1);
})
.bind('click close', function() {
hideGallery(el);
});
}
/**
* Sets position and size of the given jQuery object to match the current viewport dimensions.
*/
function fitToView(el) {
if (mobileSafari) {
el.css({top: getScrollTop() + 'px', left: getScrollLeft() + 'px'});
}
return el.width(getInnerWidth()).height(getInnerHeight());
}
/**
* Returns the reciprocal of the current zoom-factor.
* @REVISIT Use screen.width / screen.availWidth instead?
*/
function getViewportScale() {
return getInnerWidth() / document.documentElement.clientWidth;
}
/**
* Returns a window property with fallback to a property on the
* documentElement in Internet Explorer.
*/
function getWindowProp(name, ie) {
if (window[name] !== undefined) {
return window[name];
}
var d = document.documentElement;
if (d && d[ie]) {
return d[ie];
}
return document.body[ie];
}
function getScrollTop() {
return getWindowProp('pageYOffset', 'scrollTop');
}
function getScrollLeft() {
return getWindowProp('pageXOffset', 'scrollLeft');
}
function getInnerWidth() {
return getWindowProp('innerWidth', 'clientWidth');
}
function getInnerHeight() {
return getWindowProp('innerHeight', 'clientHeight');
}
function makeVisible(el) {
return el.css('visibility', 'visible');
}
function makeInvisible(el) {
return el.css('visibility', 'hidden');
}
function bounds(el) {
var e = el.get(0);
if (e && e.getBoundingClientRect) {
return e.getBoundingClientRect();
}
return $.extend({width: el.width(), height: el.height()}, el.offset());
}
function preventTouch(el) {
return el.bind('touchstart', function() { return false; });
}
})(jQuery);
|
import * as Parser from './parser'
export function encode(object = {}) {
return {
siteId: object.siteId,
songId: object.songId
}
}
export function decode(object = {}) {
return {
id: `${object.siteId}.${object.songId}`,
siteId: object.siteId,
songId: object.songId,
title: object.title,
album: object.album,
artist: object.artist,
artwork: Parser.file(object.artwork),
length: object.length,
bitrate: object.bitrate,
link: object.webUrl,
mvLink: object.mvWebUrl,
files: Parser.file(object.musics, true),
mvFile: Parser.file(object.mv),
lyrics: Parser.lyrics(object.lyrics)
}
}
|
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var google = require("googleapis");
var routes = require("./routes/index");
var users = require("./routes/users");
// ----------
// var site = require("./routes/site");
// var api = require("./routes/api");
// var register = require("./routes/register");
// var gapi = require("./routes/gapi");
var about = require("./routes/about");
var event = require("./routes/addEvent");
var contact = require("./routes/contact");
var oa2back = require("./routes/oauth2callback");
var rdftest = require("./routes/rdftest");
var eventadder = require("./routes/eventadder");
// ----------
var app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + "/public/favicon.ico"));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(require("stylus").middleware(path.join(__dirname, "public")));
app.use("/", routes);
app.use("/users", users);
app.use("/oauth2callback", oa2back);
app.use("/rdftest", rdftest);
app.use("/about", about);
app.use("/addEvent", event);
app.use("/contact", contact);
app.use("/eventadder", eventadder);
// app.use("/site/register", register);
// ---------------------------------------
// app.get("/", function(req, res, next) {
// res.render("index", {
// title: "Express",
// url: gapi.url
// });
// });
// ---------------------------------------
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {}
});
});
module.exports = app;
// node .\bin\www
|
import FactoryGuy from 'ember-data-factory-guy';
FactoryGuy.define('employee', {
default: {
name: FactoryGuy.belongsTo('name'),
titles: ['Mr.', 'Dr.'],
gender: 'Male',
birthDate: new Date('2016-05-01')
},
traits: {
default_name_setup: {
name: {}
},
jon: {
name: {
firstName: 'Jon',
lastName: 'Snow'
}
},
geoffrey: {
name: FactoryGuy.belongsTo('employee_geoffrey')
},
with_department_employments: {
departmentEmployments: FactoryGuy.hasMany('department-employment', 2),
}
}
});
|
import * as actions from 'redux/actions'
import _ from 'lodash'
import * as utils from 'utils'
export default async (
dispatch,
institutionRegistration,
onOpenSnackbar
) => {
let body = _.cloneDeep(institutionRegistration)
body.status = utils.constants.status.accepted
body.updatedAt = Date.now()
const result = await dispatch(actions.asians.registrationInstitutions.update(institutionRegistration._tournament, institutionRegistration._id, body))
if (result) {
onOpenSnackbar('Registration accepted')
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:273d6a60c54c3c08f32beeb6b7c5632dd438726c7ea7f24ae1c60fa098184175
size 6460
|
'use strict';
const chai = require('chai'),
expect = chai.expect,
Support = require(__dirname + '/../../support'),
dialect = Support.getTestDialect(),
_ = require('lodash'),
QueryGenerator = require('../../../../lib/dialects/mysql/query-generator');
if (dialect === 'mysql') {
describe('[MYSQL Specific] QueryGenerator', () => {
const suites = {
arithmeticQuery: [
{
title:'Should use the plus operator',
arguments: ['+', 'myTable', { foo: 'bar' }, {}, {}],
expectation: 'UPDATE `myTable` SET `foo`=`foo`+\'bar\' '
},
{
title:'Should use the plus operator with where clause',
arguments: ['+', 'myTable', { foo: 'bar' }, { bar: 'biz'}, {}],
expectation: 'UPDATE `myTable` SET `foo`=`foo`+\'bar\' WHERE `bar` = \'biz\''
},
{
title:'Should use the minus operator',
arguments: ['-', 'myTable', { foo: 'bar' }, {}, {}],
expectation: 'UPDATE `myTable` SET `foo`=`foo`-\'bar\' '
},
{
title:'Should use the minus operator with where clause',
arguments: ['-', 'myTable', { foo: 'bar' }, { bar: 'biz'}, {}],
expectation: 'UPDATE `myTable` SET `foo`=`foo`-\'bar\' WHERE `bar` = \'biz\''
}
],
attributesToSQL: [
{
arguments: [{id: 'INTEGER'}],
expectation: {id: 'INTEGER'}
},
{
arguments: [{id: 'INTEGER', foo: 'VARCHAR(255)'}],
expectation: {id: 'INTEGER', foo: 'VARCHAR(255)'}
},
{
arguments: [{id: {type: 'INTEGER'}}],
expectation: {id: 'INTEGER'}
},
{
arguments: [{id: {type: 'INTEGER', allowNull: false}}],
expectation: {id: 'INTEGER NOT NULL'}
},
{
arguments: [{id: {type: 'INTEGER', allowNull: true}}],
expectation: {id: 'INTEGER'}
},
{
arguments: [{id: {type: 'INTEGER', primaryKey: true, autoIncrement: true}}],
expectation: {id: 'INTEGER auto_increment PRIMARY KEY'}
},
{
arguments: [{id: {type: 'INTEGER', defaultValue: 0}}],
expectation: {id: 'INTEGER DEFAULT 0'}
},
{
arguments: [{id: {type: 'INTEGER', unique: true}}],
expectation: {id: 'INTEGER UNIQUE'}
},
{
arguments: [{id: {type: 'INTEGER', after: 'Bar'}}],
expectation: {id: 'INTEGER AFTER `Bar`'}
},
// New references style
{
arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }}}],
expectation: {id: 'INTEGER REFERENCES `Bar` (`id`)'}
},
{
arguments: [{id: {type: 'INTEGER', references: { model: 'Bar', key: 'pk' }}}],
expectation: {id: 'INTEGER REFERENCES `Bar` (`pk`)'}
},
{
arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onDelete: 'CASCADE'}}],
expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON DELETE CASCADE'}
},
{
arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onUpdate: 'RESTRICT'}}],
expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON UPDATE RESTRICT'}
},
{
arguments: [{id: {type: 'INTEGER', allowNull: false, autoIncrement: true, defaultValue: 1, references: { model: 'Bar' }, onDelete: 'CASCADE', onUpdate: 'RESTRICT'}}],
expectation: {id: 'INTEGER NOT NULL auto_increment DEFAULT 1 REFERENCES `Bar` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT'}
}
],
createTableQuery: [
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255)) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {data: 'BLOB'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` BLOB) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {data: 'LONGBLOB'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` LONGBLOB) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}, {engine: 'MyISAM'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255)) ENGINE=MyISAM;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}, {charset: 'utf8', collate: 'utf8_unicode_ci'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}, {charset: 'latin1'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'
},
{
arguments: ['myTable', {title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)'}, {charset: 'latin1'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}, { rowFormat: 'default' }],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255)) ENGINE=InnoDB ROW_FORMAT=default;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `id` INTEGER , PRIMARY KEY (`id`)) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', otherId: 'INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION'}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `otherId` INTEGER, FOREIGN KEY (`otherId`) REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}, {uniqueKeys: [{fields: ['title', 'name']}]}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), UNIQUE `uniq_myTable_title_name` (`title`, `name`)) ENGINE=InnoDB;'
},
{
arguments: ['myTable', {id: 'INTEGER auto_increment PRIMARY KEY'}, {initialAutoIncrement: 1000001}],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER auto_increment , PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1000001;'
}
],
dropTableQuery: [
{
arguments: ['myTable'],
expectation: 'DROP TABLE IF EXISTS `myTable`;'
}
],
selectQuery: [
{
arguments: ['myTable'],
expectation: 'SELECT * FROM `myTable`;',
context: QueryGenerator
}, {
arguments: ['myTable', {attributes: ['id', 'name']}],
expectation: 'SELECT `id`, `name` FROM `myTable`;',
context: QueryGenerator
}, {
arguments: ['myTable', {where: {id: 2}}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;',
context: QueryGenerator
}, {
arguments: ['myTable', {where: {name: 'foo'}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo';",
context: QueryGenerator
}, {
arguments: ['myTable', {where: {name: "foo';DROP TABLE myTable;"}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo\\';DROP TABLE myTable;';",
context: QueryGenerator
}, {
arguments: ['myTable', {where: 2}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;',
context: QueryGenerator
}, {
arguments: ['foo', { attributes: [['count(*)', 'count']] }],
expectation: 'SELECT count(*) AS `count` FROM `foo`;',
context: QueryGenerator
}, {
arguments: ['myTable', {order: ['id']}],
expectation: 'SELECT * FROM `myTable` ORDER BY `id`;',
context: QueryGenerator
}, {
arguments: ['myTable', {order: ['id', 'DESC']}],
expectation: 'SELECT * FROM `myTable` ORDER BY `id`, `DESC`;',
context: QueryGenerator
}, {
arguments: ['myTable', {order: ['myTable.id']}],
expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id`;',
context: QueryGenerator
}, {
arguments: ['myTable', {order: [['myTable.id', 'DESC']]}],
expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id` DESC;',
context: QueryGenerator
}, {
arguments: ['myTable', {order: [['id', 'DESC']]}, function(sequelize) {return sequelize.define('myTable', {});}],
expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC;',
context: QueryGenerator,
needsSequelize: true
}, {
arguments: ['myTable', {order: [['id', 'DESC'], ['name']]}, function(sequelize) {return sequelize.define('myTable', {});}],
expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC, `myTable`.`name`;',
context: QueryGenerator,
needsSequelize: true
}, {
title: 'functions can take functions as arguments',
arguments: ['myTable', function(sequelize) {
return {
order: [[sequelize.fn('f1', sequelize.fn('f2', sequelize.col('id'))), 'DESC']]
};
}],
expectation: 'SELECT * FROM `myTable` ORDER BY f1(f2(`id`)) DESC;',
context: QueryGenerator,
needsSequelize: true
}, {
title: 'functions can take all types as arguments',
arguments: ['myTable', function(sequelize) {
return {
order: [
[sequelize.fn('f1', sequelize.col('myTable.id')), 'DESC'],
[sequelize.fn('f2', 12, 'lalala', new Date(Date.UTC(2011, 2, 27, 10, 1, 55))), 'ASC']
]
};
}],
expectation: "SELECT * FROM `myTable` ORDER BY f1(`myTable`.`id`) DESC, f2(12, 'lalala', '2011-03-27 10:01:55') ASC;",
context: QueryGenerator,
needsSequelize: true
}, {
title: 'sequelize.where with .fn as attribute and default comparator',
arguments: ['myTable', function(sequelize) {
return {
where: sequelize.and(
sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'jan'),
{ type: 1 }
)
};
}],
expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) = 'jan' AND `myTable`.`type` = 1);",
context: QueryGenerator,
needsSequelize: true
}, {
title: 'sequelize.where with .fn as attribute and LIKE comparator',
arguments: ['myTable', function(sequelize) {
return {
where: sequelize.and(
sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'LIKE', '%t%'),
{ type: 1 }
)
};
}],
expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) LIKE '%t%' AND `myTable`.`type` = 1);",
context: QueryGenerator,
needsSequelize: true
}, {
title: 'single string argument is not quoted',
arguments: ['myTable', {group: 'name'}],
expectation: 'SELECT * FROM `myTable` GROUP BY name;',
context: QueryGenerator
}, {
arguments: ['myTable', { group: ['name'] }],
expectation: 'SELECT * FROM `myTable` GROUP BY `name`;',
context: QueryGenerator
}, {
title: 'functions work for group by',
arguments: ['myTable', function(sequelize) {
return {
group: [sequelize.fn('YEAR', sequelize.col('createdAt'))]
};
}],
expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`);',
context: QueryGenerator,
needsSequelize: true
}, {
title: 'It is possible to mix sequelize.fn and string arguments to group by',
arguments: ['myTable', function(sequelize) {
return {
group: [sequelize.fn('YEAR', sequelize.col('createdAt')), 'title']
};
}],
expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`), `title`;',
context: QueryGenerator,
needsSequelize: true
}, {
arguments: ['myTable', {group: 'name', order: [['id', 'DESC']]}],
expectation: 'SELECT * FROM `myTable` GROUP BY name ORDER BY `id` DESC;',
context: QueryGenerator
}, {
title: 'HAVING clause works with where-like hash',
arguments: ['myTable', function(sequelize) {
return {
attributes: ['*', [sequelize.fn('YEAR', sequelize.col('createdAt')), 'creationYear']],
group: ['creationYear', 'title'],
having: { creationYear: { gt: 2002 } }
};
}],
expectation: 'SELECT *, YEAR(`createdAt`) AS `creationYear` FROM `myTable` GROUP BY `creationYear`, `title` HAVING `creationYear` > 2002;',
context: QueryGenerator,
needsSequelize: true
}, {
title: 'Combination of sequelize.fn, sequelize.col and { in: ... }',
arguments: ['myTable', function(sequelize) {
return {
where: sequelize.and(
{ archived: null},
sequelize.where(sequelize.fn('COALESCE', sequelize.col('place_type_codename'), sequelize.col('announcement_type_codename')), { in : ['Lost', 'Found'] })
)
};
}],
expectation: "SELECT * FROM `myTable` WHERE (`myTable`.`archived` IS NULL AND COALESCE(`place_type_codename`, `announcement_type_codename`) IN ('Lost', 'Found'));",
context: QueryGenerator,
needsSequelize: true
}, {
arguments: ['myTable', {limit: 10}],
expectation: 'SELECT * FROM `myTable` LIMIT 10;',
context: QueryGenerator
}, {
arguments: ['myTable', {limit: 10, offset: 2}],
expectation: 'SELECT * FROM `myTable` LIMIT 2, 10;',
context: QueryGenerator
}, {
title: 'uses default limit if only offset is specified',
arguments: ['myTable', {offset: 2}],
expectation: 'SELECT * FROM `myTable` LIMIT 2, 10000000000000;',
context: QueryGenerator
}, {
title: 'uses limit 0',
arguments: ['myTable', {limit: 0}],
expectation: 'SELECT * FROM `myTable` LIMIT 0;',
context: QueryGenerator
}, {
title: 'uses offset 0',
arguments: ['myTable', {offset: 0}],
expectation: 'SELECT * FROM `myTable` LIMIT 0, 10000000000000;',
context: QueryGenerator
}, {
title: 'multiple where arguments',
arguments: ['myTable', {where: {boat: 'canoe', weather: 'cold'}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`boat` = 'canoe' AND `myTable`.`weather` = 'cold';",
context: QueryGenerator
}, {
title: 'no where arguments (object)',
arguments: ['myTable', {where: {}}],
expectation: 'SELECT * FROM `myTable`;',
context: QueryGenerator
}, {
title: 'no where arguments (string)',
arguments: ['myTable', {where: ['']}],
expectation: 'SELECT * FROM `myTable` WHERE 1=1;',
context: QueryGenerator
}, {
title: 'no where arguments (null)',
arguments: ['myTable', {where: null}],
expectation: 'SELECT * FROM `myTable`;',
context: QueryGenerator
}, {
title: 'buffer as where argument',
arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';",
context: QueryGenerator
}, {
title: 'use != if ne !== null',
arguments: ['myTable', {where: {field: {ne: 0}}}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 0;',
context: QueryGenerator
}, {
title: 'use IS NOT if ne === null',
arguments: ['myTable', {where: {field: {ne: null}}}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT NULL;',
context: QueryGenerator
}, {
title: 'use IS NOT if not === BOOLEAN',
arguments: ['myTable', {where: {field: {not: true}}}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT true;',
context: QueryGenerator
}, {
title: 'use != if not !== BOOLEAN',
arguments: ['myTable', {where: {field: {not: 3}}}],
expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 3;',
context: QueryGenerator
}
],
insertQuery: [
{
arguments: ['myTable', {name: 'foo'}],
expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo');"
}, {
arguments: ['myTable', {name: "foo';DROP TABLE myTable;"}],
expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo\\';DROP TABLE myTable;');"
}, {
arguments: ['myTable', {name: 'foo', birthday: new Date(Date.UTC(2011, 2, 27, 10, 1, 55))}],
expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55');"
}, {
arguments: ['myTable', {name: 'foo', foo: 1}],
expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);"
}, {
arguments: ['myTable', {data: new Buffer('Sequelize') }],
expectation: "INSERT INTO `myTable` (`data`) VALUES (X'53657175656c697a65');"
}, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);"
}, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);",
context: {options: {omitNull: false}}
}, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}],
expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);",
context: {options: {omitNull: true}}
}, {
arguments: ['myTable', {name: 'foo', foo: 1, nullValue: undefined}],
expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);",
context: {options: {omitNull: true}}
}, {
arguments: ['myTable', {foo: false}],
expectation: 'INSERT INTO `myTable` (`foo`) VALUES (false);'
}, {
arguments: ['myTable', {foo: true}],
expectation: 'INSERT INTO `myTable` (`foo`) VALUES (true);'
}, {
arguments: ['myTable', function(sequelize) {
return {
foo: sequelize.fn('NOW')
};
}],
expectation: 'INSERT INTO `myTable` (`foo`) VALUES (NOW());',
needsSequelize: true
}
],
bulkInsertQuery: [
{
arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}]],
expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo'),('bar');"
}, {
arguments: ['myTable', [{name: "foo';DROP TABLE myTable;"}, {name: 'bar'}]],
expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo\\';DROP TABLE myTable;'),('bar');"
}, {
arguments: ['myTable', [{name: 'foo', birthday: new Date(Date.UTC(2011, 2, 27, 10, 1, 55))}, {name: 'bar', birthday: new Date(Date.UTC(2012, 2, 27, 10, 1, 55))}]],
expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55'),('bar','2012-03-27 10:01:55');"
}, {
arguments: ['myTable', [{name: 'foo', foo: 1}, {name: 'bar', foo: 2}]],
expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1),('bar',2);"
}, {
arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', nullValue: null}]],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',NULL,NULL);"
}, {
arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);",
context: {options: {omitNull: false}}
}, {
arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);",
context: {options: {omitNull: true}} // Note: We don't honour this because it makes little sense when some rows may have nulls and others not
}, {
arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: undefined}, {name: 'bar', foo: 2, undefinedValue: undefined}]],
expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`,`undefinedValue`) VALUES ('foo',1,NULL,NULL),('bar',2,NULL,NULL);",
context: {options: {omitNull: true}} // Note: As above
}, {
arguments: ['myTable', [{name: 'foo', value: true}, {name: 'bar', value: false}]],
expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',true),('bar',false);"
}, {
arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}], {ignoreDuplicates: true}],
expectation: "INSERT IGNORE INTO `myTable` (`name`) VALUES ('foo'),('bar');"
}, {
arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}], {updateOnDuplicate: ['name']}],
expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo'),('bar') ON DUPLICATE KEY UPDATE `name`=VALUES(`name`);"
}
],
updateQuery: [
{
arguments: ['myTable', {name: 'foo', birthday: new Date(Date.UTC(2011, 2, 27, 10, 1, 55))}, {id: 2}],
expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55' WHERE `id` = 2"
}, {
arguments: ['myTable', {name: 'foo', birthday: new Date(Date.UTC(2011, 2, 27, 10, 1, 55))}, {id: 2}],
expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55' WHERE `id` = 2"
}, {
arguments: ['myTable', {bar: 2}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=2 WHERE `name` = 'foo'"
}, {
arguments: ['myTable', {name: "foo';DROP TABLE myTable;"}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `name`='foo\\';DROP TABLE myTable;' WHERE `name` = 'foo'"
}, {
arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'"
}, {
arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'",
context: {options: {omitNull: false}}
}, {
arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=2 WHERE `name` = 'foo'",
context: {options: {omitNull: true}}
}, {
arguments: ['myTable', {bar: false}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=false WHERE `name` = 'foo'"
}, {
arguments: ['myTable', {bar: true}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=true WHERE `name` = 'foo'"
}, {
arguments: ['myTable', function(sequelize) {
return {
bar: sequelize.fn('NOW')
};
}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=NOW() WHERE `name` = 'foo'",
needsSequelize: true
}, {
arguments: ['myTable', function(sequelize) {
return {
bar: sequelize.col('foo')
};
}, {name: 'foo'}],
expectation: "UPDATE `myTable` SET `bar`=`foo` WHERE `name` = 'foo'",
needsSequelize: true
}
],
showIndexesQuery: [
{
arguments: ['User'],
expectation: 'SHOW INDEX FROM `User`'
}, {
arguments: ['User', { database: 'sequelize' }],
expectation: 'SHOW INDEX FROM `User` FROM `sequelize`'
}
],
removeIndexQuery: [
{
arguments: ['User', 'user_foo_bar'],
expectation: 'DROP INDEX `user_foo_bar` ON `User`'
}, {
arguments: ['User', ['foo', 'bar']],
expectation: 'DROP INDEX `user_foo_bar` ON `User`'
}
]
};
_.each(suites, (tests, suiteTitle) => {
describe(suiteTitle, () => {
tests.forEach(test => {
const title = test.title || 'MySQL correctly returns ' + test.expectation + ' for ' + JSON.stringify(test.arguments);
it(title, function() {
// Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly
const context = test.context || {options: {}};
if (test.needsSequelize) {
if (_.isFunction(test.arguments[1])) test.arguments[1] = test.arguments[1](this.sequelize);
if (_.isFunction(test.arguments[2])) test.arguments[2] = test.arguments[2](this.sequelize);
}
QueryGenerator.options = _.assign(context.options, { timezone: '+00:00' });
QueryGenerator._dialect = this.sequelize.dialect;
QueryGenerator.sequelize = this.sequelize;
const conditions = QueryGenerator[suiteTitle].apply(QueryGenerator, test.arguments);
expect(conditions).to.deep.equal(test.expectation);
});
});
});
});
});
}
|
var path = require('path');
module.exports = {
context: path.resolve('src/'),
entry: ['./index'],
output: {
path: path.resolve('dist/'),
publicPath: '/public/assets/',
filename: 'proxify.js',
library: 'proxify'
},
devServer: {
contentBase: 'public',
host: 'localhost',
port: 8080
},
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}
],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
extensions: ['', '.js']
}
};
|
/* ===========================================================
* bootstrap-modal.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.init(element, options);
};
Modal.prototype = {
constructor: Modal,
init: function (element, options) {
var that = this;
this.options = options;
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));
this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
var e = $.Event('loaded');
that.$element.trigger(e);
});
var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;
manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');
manager.appendModal(this);
},
toggle: function () {
return this[!this.isShown ? 'show' : 'hide']();
},
show: function () {
var e = $.Event('show');
if (this.isShown) return;
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.escape();
this.tab();
this.options.loading && this.loading();
},
hide: function (e) {
e && e.preventDefault();
e = $.Event('hide');
this.$element.trigger(e);
if (!this.isShown || e.isDefaultPrevented()) return;
this.isShown = false;
this.escape();
this.tab();
this.isLoading && this.loading();
$(document).off('focusin.modal');
this.$element
.removeClass('in')
.removeClass('animated')
.removeClass(this.options.attentionAnimation)
.removeClass('modal-overflow')
.attr('aria-hidden', true);
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal();
},
layout: function () {
var prop = this.options.height ? 'height' : 'max-height',
value = this.options.height || this.options.maxHeight;
if (this.options.width) {
this.$element.css('width', this.options.width);
var that = this;
this.$element.css('margin-left', function () {
if (/%/ig.test(that.options.width)) {
return -(parseInt(that.options.width) / 2) + '%';
} else {
return -($(this).width() / 2) + 'px';
}
});
} else {
this.$element.css('width', '');
this.$element.css('margin-left', '');
}
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
if (value) {
this.$element.find('.modal-body')
.css('overflow', 'auto')
.css(prop, value);
}
var modalOverflow = $(window).height() - 10 < this.$element.height();
if (modalOverflow || this.options.modalOverflow) {
this.$element
.css('margin-top', 0)
.addClass('modal-overflow');
} else {
this.$element
.css('margin-top', 0 - this.$element.height() / 2)
.removeClass('modal-overflow');
}
},
tab: function () {
var that = this;
if (this.isShown && this.options.consumeTab) {
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
if (e.keyCode && e.keyCode == 9) {
var elements = [],
tabindex = Number($(this).data('tabindex'));
that.$element.find('[data-tabindex]:enabled:visible:not([readonly])').each(function (ev) {
elements.push(Number($(this).data('tabindex')));
});
elements.sort(function (a, b) {
return a - b
});
var arrayPos = $.inArray(tabindex, elements);
if (!e.shiftKey) {
arrayPos < elements.length - 1 ?
that.$element.find('[data-tabindex=' + elements[arrayPos + 1] + ']').focus() :
that.$element.find('[data-tabindex=' + elements[0] + ']').focus();
} else {
arrayPos == 0 ?
that.$element.find('[data-tabindex=' + elements[elements.length - 1] + ']').focus() :
that.$element.find('[data-tabindex=' + elements[arrayPos - 1] + ']').focus();
}
e.preventDefault();
}
});
} else if (!this.isShown) {
this.$element.off('keydown.tabindex.modal');
}
},
escape: function () {
var that = this;
if (this.isShown && this.options.keyboard) {
if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);
this.$element.on('keyup.dismiss.modal', function (e) {
e.which == 27 && that.hide();
});
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},
hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end);
that.hideModal();
}, 500);
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout);
that.hideModal();
});
},
hideModal: function () {
var prop = this.options.height ? 'height' : 'max-height';
var value = this.options.height || this.options.maxHeight;
if (value) {
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
}
this.$element
.hide()
.trigger('hidden');
},
removeLoading: function () {
this.$loading.remove();
this.$loading = null;
this.isLoading = false;
},
loading: function (callback) {
callback = callback || function () {
};
var animate = this.$element.hasClass('fade') ? 'fade' : '';
if (!this.isLoading) {
var doAnimate = $.support.transition && animate;
this.$loading = $('<div class="loading-mask ' + animate + '">')
.append(this.options.spinner)
.appendTo(this.$element);
if (doAnimate) this.$loading[0].offsetWidth; // force reflow
this.$loading.addClass('in');
this.isLoading = true;
doAnimate ?
this.$loading.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$loading) {
this.$loading.removeClass('in');
var that = this;
$.support.transition && this.$element.hasClass('fade') ?
this.$loading.one($.support.transition.end, function () {
that.removeLoading()
}) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
},
focus: function () {
var $focusElem = this.$element.find(this.options.focusOn);
$focusElem = $focusElem.length ? $focusElem : this.$element;
$focusElem.focus();
},
attention: function () {
// NOTE: transitionEnd with keyframes causes odd behaviour
if (this.options.attentionAnimation) {
this.$element
.removeClass('animated')
.removeClass(this.options.attentionAnimation);
var that = this;
setTimeout(function () {
that.$element
.addClass('animated')
.addClass(that.options.attentionAnimation);
}, 0);
}
this.focus();
},
destroy: function () {
var e = $.Event('destroy');
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.$element
.off('.modal')
.removeData('modal')
.removeClass('in')
.attr('aria-hidden', true);
if (this.$parent !== this.$element.parent()) {
this.$element.appendTo(this.$parent);
} else if (!this.$parent.length) {
// modal is not part of the DOM so remove it.
this.$element.remove();
this.$element = null;
}
this.$element.trigger('destroyed');
}
};
/* MODAL PLUGIN DEFINITION
* ======================= */
$.fn.modal = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('modal', (data = new Modal(this, options)));
if (typeof option == 'string') data[option].apply(data, [].concat(args));
else if (options.show) data.show()
})
};
$.fn.modal.defaults = {
keyboard: true,
backdrop: true,
loading: false,
show: true,
width: null,
height: null,
maxHeight: null,
modalOverflow: false,
consumeTab: true,
focusOn: null,
replace: false,
resize: false,
attentionAnimation: 'shake',
manager: 'body',
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
$.fn.modal.Constructor = Modal;
/* MODAL DATA-API
* ============== */
$(function () {
$(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
option = $target.data('modal') ? 'toggle' : $.extend({remote: !/#/.test(href) && href}, $target.data(), $this.data());
e.preventDefault();
$target
.modal(option)
.one('hide', function () {
$this.focus();
})
});
});
}(window.jQuery);
|
/* ========================================================================
* App.base64 v1.0
* base64转换插件
* ========================================================================
* Copyright 2016-2026 WangXin nvlbs,Inc.
*
* ======================================================================== */
(function (app) {
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
var base64encode = function (str) {
var out, i, len;
var c1, c2, c3;
len = str.length;
i = 0;
out = "";
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}
var base64decode = function (str) {
var c1, c2, c3, c4;
var i, len, out;
len = str.length;
i = 0;
out = "";
while (i < len) {
/* c1 */
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
if (c1 == -1)
break;
/* c2 */
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c2 == -1);
if (c2 == -1)
break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61)
return out;
c3 = base64DecodeChars[c3];
} while (i < len && c3 == -1);
if (c3 == -1)
break;
out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
/* c4 */
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61)
return out;
c4 = base64DecodeChars[c4];
} while (i < len && c4 == -1);
if (c4 == -1)
break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
}
var utf16to8 = function (str) {
var out, c;
out = "";
for (let i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
var utf8to16 = function (str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while (i < len) {
c = str.charCodeAt(i++);
switch (c >> 4) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += str.charAt(i - 1);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
var CharToHex = function (str) {
var out, i, len, c, h;
out = "";
len = str.length;
i = 0;
while (i < len) {
c = str.charCodeAt(i++);
h = c.toString(16);
if (h.length < 2)
h = "0" + h;
out += "\\x" + h + " ";
if (i > 0 && i % 8 == 0)
out += "\r\n";
}
return out;
}
var doEncode = function (src) {
return base64encode(utf16to8(src));
}
var doDecode = function (src, opt) {
if (opt) {
return CharToHex(base64decode(src));
}
else {
return utf8to16(base64decode(src));
}
}
app.base64 = {
encode: function (str) {
if (str) {
try {
return doEncode(str);
} catch (ex) {
console.log("[ERROR]App.base64.encode:" + ex.message);
return "";
}
} else {
return "";
}
}
, decode: function (str) {
if (str) {
try {
return doDecode(str, false);
} catch (ex) {
console.log("[ERROR]App.base64.decode:" + ex.message);
return "";
}
} else {
return "";
}
}
};
})(App); |
var
chai = require('chai'),
expect = chai.expect,
should = chai.should(),
Circle = require('./../../../../../lib/ci/environments/circle').Circle
describe('Circle', function() {
describe('in', function() {
it('should return true if relevant env variables are set', function() {
if(!process.env.CIRCLE_BUILD_URL) {
process.env.CIRCLE_BUILD_URL = 1
expect(Circle.in).to.be.true
delete process.env.CIRCLE_BUILD_URL
}
else {
expect(Circle.in).to.be.true
}
})
})
describe('project', function() {
it('should return a string in expected format "{username}/{repo}" if relevant env variables are set', function() {
if(!process.env.CIRCLE_PROJECT_USERNAME && !process.env.CIRCLE_PROJECT_REPONAME) {
process.env.CIRCLE_PROJECT_USERNAME = 'a'
process.env.CIRCLE_PROJECT_REPONAME = 'b'
expect(Circle.project).to.equal('a/b')
delete process.env.CIRCLE_PROJECT_USERNAME
delete process.env.CIRCLE_PROJECT_REPONAME
}
else {
expect(Circle.project).to.not.be.empty
}
})
})
describe('session', function() {
it('should return a string in expected format "CIRCLE-{build_no}.{node_index}-{uuid}" if relevant env variables are set', function() {
if(!process.env.CIRCLE_BUILD_NUM) {
process.env.CIRCLE_BUILD_NUM = 4
process.env.CIRCLE_NODE_INDEX = 1
expect(Circle.session).to.match(/CIRCLE\-4\.1\-/)
delete process.env.CIRCLE_BUILD_NUM
delete process.env.CIRCLE_NODE_INDEX
}
else {
expect(Circle.session).to.not.be.empty
}
})
})
describe('commit', function() {
it('should return a commit sha1 string if relevant env variables are set', function() {
if(!process.env.CIRCLE_SHA1) {
process.env.CIRCLE_SHA1 = 'hex'
expect(Circle.commit).to.equal('hex')
delete process.env.CIRCLE_SHA1
}
else {
expect(Circle.commit).to.not.be.empty
}
})
})
})
|
var a = {
b: {
}
};
a.b.c = require('./bar');
exports.bar = a.b.c; |
Reveal.addEventListener('ready', function () {
QUnit.module('Markdown');
test('Options are set', function () {
strictEqual(marked.defaults.smartypants, true);
});
test('Smart quotes are activated', function () {
var text = document.querySelector('.reveal .slides>section>p').textContent;
strictEqual(/['"]/.test(text), false);
strictEqual(/[“”‘’]/.test(text), true);
});
});
Reveal.initialize({
dependencies: [
{src: '../plugin/markdown/marked.js'},
{src: '../plugin/markdown/markdown.js'},
],
markdown: {
smartypants: true
}
});
|
angular
.module('arb.controllers', [
'ui.router',
'arb.controllers.AppCtrl',
'arb.controllers.LoginCtrl',
'arb.controllers.NavbarCtrl'
]);
|
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const fs = require('fs');
const path = require('path');
if (module.parent) {
module.exports = testDependencies;
} else {
// Called directly
const topLevelPackagePath = path.join(__dirname, '../');
const packagesRoot = path.join(topLevelPackagePath, 'packages');
const packagePaths = fs
.readdirSync(packagesRoot)
.map(filepath => path.join(packagesRoot, filepath))
.filter(filepath => fs.statSync(filepath).isDirectory());
// Temporary edge case, graphql-compiler is an internal dependency.
packagePaths.push(path.join(packagesRoot, 'relay-compiler/graphql-compiler'));
const errors = testDependencies(topLevelPackagePath, packagePaths);
if (errors.length !== 0) {
errors.forEach(error => console.error(error));
process.exit(1);
}
}
function testDependencies(topLevelPackagePath, packagePaths) {
return packagePaths.reduce(
(errors, packagePath) =>
errors.concat(testPackageDependencies(topLevelPackagePath, packagePath)),
[],
);
}
function testPackageDependencies(topLevelPackagePath, packagePath) {
const errors = [];
const topLevelPackageJson = require(path.join(
topLevelPackagePath,
'package.json',
));
const packageJson = require(path.join(packagePath, 'package.json'));
const packageName = path.basename(packagePath);
expectEqual(
errors,
packageJson.name,
packageName,
`${packageName} should have a matching package name.`,
);
expectEqual(
errors,
packageJson.optionalDependencies,
undefined,
`${packageName} should have no optional dependencies.`,
);
expectEqual(
errors,
packageJson.bundledDependencies,
undefined,
`${packageName} should have no bundled dependencies.`,
);
expectEqual(
errors,
packageJson.devDependencies,
undefined,
`${packageName} should have no dev dependencies.`,
);
for (const dependencyName in packageJson.dependencies) {
// relay-runtime is one of the packages in this repo, it won't be in the
// top level package.json.
if (dependencyName === 'relay-runtime') {
continue;
}
expectEqual(
errors,
getDependency(topLevelPackageJson, dependencyName),
getDependency(packageJson, dependencyName),
`${packageName} should have same ${dependencyName} version ` +
'as the top level package.json.',
);
}
return errors;
}
function expectEqual(errors, expected, actual, message) {
if (expected !== actual) {
errors.push(`Expected ${actual} to equal ${expected}. ${message}`);
}
}
function getDependency(packageJson, name) {
const version = packageJson.dependencies[name];
return version ? `${name}@${version}` : `(missing ${name})`;
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:471f706893f6071559795a23dfcac236c3e4fae66c4c5e24c4e81d4c04a854ef
size 3826
|
function changeTxt(txt) {
document.getElementById("md2html").innerHTML = txt;
}
function saveButton() {
var editor = ace.edit("editor-div");
editor.getSession().setMode("ace/mode/markdown");
editor.setTheme("ace/theme/twilight");
saveText(editor.getValue());
}
function changeHtml() {
var editor = ace.edit("editor-div");
contents = editor.getValue();
$.post('road_md2html',
{
'contents': contents
},
function (data) {
changeTxt(data);
}
);
}
window.onload = function () {
var editor = ace.edit("editor-div");
editor.getSession().setMode("ace/mode/markdown");
editor.setTheme("ace/theme/twilight");
editor.getSession().on('change', function () {
changeHtml();
});
editor.commands.addCommand({
name: 'save',
bindKey: {
win: 'Ctrl-S',
mac: 'Command-S'
},
exec: function (editor) {
saveText(editor.getValue());
},
readOnly: true
});
};
setTimeout("changeHtml()", 10); |
'use strict';
describe('ProAct.BufferedStream', function () {
describe('#delay', function () {
it ('fires all the buffered events', function () {
var stream = new ProAct.Stream().delay(100), res = [];
stream.on(function (el) {
res.push(el);
});
stream.trigger('a');
stream.trigger('b');
stream.trigger('c');
stream.trigger('d');
expect(res).toEqual([]);
waits(110);
runs(function () {
expect(res).toEqual(['a', 'b', 'c', 'd']);
});
});
});
describe('#throttle', function () {
it ('can trigger the same event in a given time tunnel only once', function () {
var stream = new ProAct.Stream().throttle(100), res = [];
stream.on(function (el) {
res.push(el);
});
stream.trigger('a');
stream.trigger('b');
stream.trigger('c');
stream.trigger('a');
stream.trigger('f');
expect(res).toEqual([]);
waits(110);
runs(function () {
expect(res).toEqual(['f']);
stream.trigger('m');
stream.trigger('a');
});
waits(100);
runs(function () {
expect(res).toEqual(['f', 'a']);
});
});
});
describe('#debounce', function () {
it ('an event should be triggered only onle in the passed time period, or the period will grow', function () {
var stream = new ProAct.Stream().debounce(50), res = [];
stream.on(function (el) {
res.push(el);
});
waits(15);
runs(function () {
stream.trigger('a');
stream.trigger('b');
});
waits(25);
runs(function () {
stream.trigger('c');
stream.trigger('a');
});
waits(45);
runs(function () {
stream.trigger('g');
});
waits(45);
runs(function () {
stream.trigger('f');
});
expect(res).toEqual([]);
waits(55);
runs(function () {
expect(res).toEqual(['f']);
stream.trigger('m');
stream.trigger('a');
});
waits(45);
runs(function () {
stream.trigger('p');
});
waits(50);
runs(function () {
expect(res).toEqual(['f', 'p']);
});
});
});
describe('#buffer', function () {
it ('fires all the buffered events', function () {
var stream = new ProAct.Stream().bufferit(5), res = [];
stream.on(function (el) {
res.push(el);
});
stream.trigger('a');
stream.trigger('b');
stream.trigger('c');
stream.trigger('d');
expect(res).toEqual([]);
stream.trigger('e');
expect(res).toEqual(['a', 'b', 'c', 'd', 'e']);
});
});
});
|
watchn.watch('coffee', [libs, tests], function(options) {
watchn.execute('make coffee', options, 'coffee', false, true)
})
|
import { BodyComponent, suffixCssClasses } from 'mjml-core'
import { flow, identity, join, filter } from 'lodash/fp'
const makeBackgroundString = flow(filter(identity), join(' '))
export default class MjSection extends BodyComponent {
static componentName = 'mj-section'
static allowedAttributes = {
'background-color': 'color',
'background-url': 'string',
'background-repeat': 'enum(repeat,no-repeat)',
'background-size': 'string',
'background-position': 'string',
'background-position-x': 'string',
'background-position-y': 'string',
border: 'string',
'border-bottom': 'string',
'border-left': 'string',
'border-radius': 'string',
'border-right': 'string',
'border-top': 'string',
direction: 'enum(ltr,rtl)',
'full-width': 'enum(full-width,false,)',
padding: 'unit(px,%){1,4}',
'padding-top': 'unit(px,%)',
'padding-bottom': 'unit(px,%)',
'padding-left': 'unit(px,%)',
'padding-right': 'unit(px,%)',
'text-align': 'enum(left,center,right)',
'text-padding': 'unit(px,%){1,4}',
}
static defaultAttributes = {
'background-repeat': 'repeat',
'background-size': 'auto',
'background-position': 'top center',
direction: 'ltr',
padding: '20px 0',
'text-align': 'center',
'text-padding': '4px 4px 4px 0',
}
getChildContext() {
const { box } = this.getBoxWidths()
return {
...this.context,
containerWidth: `${box}px`,
}
}
getStyles() {
const { containerWidth } = this.context
const fullWidth = this.isFullWidth()
const background = this.getAttribute('background-url')
? {
background: this.getBackground(),
// background size, repeat and position has to be seperate since yahoo does not support shorthand background css property
'background-position': this.getBackgroundString(),
'background-repeat': this.getAttribute('background-repeat'),
'background-size': this.getAttribute('background-size'),
}
: {
background: this.getAttribute('background-color'),
'background-color': this.getAttribute('background-color'),
}
return {
tableFullwidth: {
...(fullWidth ? background : {}),
width: '100%',
'border-radius': this.getAttribute('border-radius'),
},
table: {
...(fullWidth ? {} : background),
width: '100%',
'border-radius': this.getAttribute('border-radius'),
},
td: {
border: this.getAttribute('border'),
'border-bottom': this.getAttribute('border-bottom'),
'border-left': this.getAttribute('border-left'),
'border-right': this.getAttribute('border-right'),
'border-top': this.getAttribute('border-top'),
direction: this.getAttribute('direction'),
'font-size': '0px',
padding: this.getAttribute('padding'),
'padding-bottom': this.getAttribute('padding-bottom'),
'padding-left': this.getAttribute('padding-left'),
'padding-right': this.getAttribute('padding-right'),
'padding-top': this.getAttribute('padding-top'),
'text-align': this.getAttribute('text-align'),
},
div: {
...(fullWidth ? {} : background),
margin: '0px auto',
'border-radius': this.getAttribute('border-radius'),
'max-width': containerWidth,
},
innerDiv: {
'line-height': '0',
'font-size': '0',
},
}
}
getBackground() {
return makeBackgroundString([
this.getAttribute('background-color'),
...(this.hasBackground()
? [
`url('${this.getAttribute('background-url')}')`,
this.getBackgroundString(),
`/ ${this.getAttribute('background-size')}`,
this.getAttribute('background-repeat'),
]
: []),
])
}
getBackgroundString() {
const { posX, posY } = this.getBackgroundPosition()
return `${posX} ${posY}`
}
getBackgroundPosition() {
const { x, y } = this.parseBackgroundPosition()
return {
posX: this.getAttribute('background-position-x') || x,
posY: this.getAttribute('background-position-y') || y,
}
}
parseBackgroundPosition() {
const posSplit = this.getAttribute('background-position').split(' ')
if (posSplit.length === 1) {
const val = posSplit[0]
// here we must determine if x or y was provided ; other will be center
if (['top', 'bottom'].includes(val)) {
return {
x: 'center',
y: val,
}
}
return {
x: val,
y: 'center',
}
}
if (posSplit.length === 2) {
// x and y can be put in any order in background-position so we need to determine that based on values
const val1 = posSplit[0]
const val2 = posSplit[1]
if (
['top', 'bottom'].includes(val1) ||
(val1 === 'center' && ['left', 'right'].includes(val2))
) {
return {
x: val2,
y: val1,
}
}
return {
x: val1,
y: val2,
}
}
// more than 2 values is not supported, let's treat as default value
return { x: 'center', y: 'top' }
}
hasBackground() {
return this.getAttribute('background-url') != null
}
isFullWidth() {
return this.getAttribute('full-width') === 'full-width'
}
renderBefore() {
const { containerWidth } = this.context
const bgcolorAttr = this.getAttribute('background-color')
? { bgcolor: this.getAttribute('background-color') }
: {}
return `
<!--[if mso | IE]>
<table
${this.htmlAttributes({
align: 'center',
border: '0',
cellpadding: '0',
cellspacing: '0',
class: suffixCssClasses(this.getAttribute('css-class'), 'outlook'),
role: 'presentation',
style: { width: `${containerWidth}` },
width: parseInt(containerWidth, 10),
...bgcolorAttr,
})}
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
`
}
// eslint-disable-next-line class-methods-use-this
renderAfter() {
return `
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
`
}
renderWrappedChildren() {
const { children } = this.props
return `
<!--[if mso | IE]>
<tr>
<![endif]-->
${this.renderChildren(children, {
renderer: (component) =>
component.constructor.isRawElement()
? component.render()
: `
<!--[if mso | IE]>
<td
${component.htmlAttributes({
align: component.getAttribute('align'),
class: suffixCssClasses(
component.getAttribute('css-class'),
'outlook',
),
style: 'tdOutlook',
})}
>
<![endif]-->
${component.render()}
<!--[if mso | IE]>
</td>
<![endif]-->
`,
})}
<!--[if mso | IE]>
</tr>
<![endif]-->
`
}
renderWithBackground(content) {
const fullWidth = this.isFullWidth()
const { containerWidth } = this.context
const isPercentage = (str) => /^\d+(\.\d+)?%$/.test(str)
let vSizeAttributes = {}
let { posX: bgPosX, posY: bgPosY } = this.getBackgroundPosition()
switch (bgPosX) {
case 'left':
bgPosX = '0%'
break
case 'center':
bgPosX = '50%'
break
case 'right':
bgPosX = '100%'
break
default:
if (!isPercentage(bgPosX)) {
bgPosX = '50%'
}
break
}
switch (bgPosY) {
case 'top':
bgPosY = '0%'
break
case 'center':
bgPosY = '50%'
break
case 'bottom':
bgPosY = '100%'
break
default:
if (!isPercentage(bgPosY)) {
bgPosY = '0%'
}
break
}
// this logic is different when using repeat or no-repeat
let [[vOriginX, vPosX], [vOriginY, vPosY]] = ['x', 'y'].map(
(coordinate) => {
const isX = coordinate === 'x'
const bgRepeat = this.getAttribute('background-repeat') === 'repeat'
let pos = isX ? bgPosX : bgPosY
let origin = isX ? bgPosX : bgPosY
if (isPercentage(pos)) {
// Should be percentage at this point
const percentageValue = pos.match(/^(\d+(\.\d+)?)%$/)[1]
const decimal = parseInt(percentageValue, 10) / 100
if (bgRepeat) {
pos = decimal
origin = decimal
} else {
pos = (-50 + decimal * 100) / 100
origin = (-50 + decimal * 100) / 100
}
} else if (bgRepeat) {
// top (y) or center (x)
origin = isX ? '0.5' : '0'
pos = isX ? '0.5' : '0'
} else {
origin = isX ? '0' : '-0.5'
pos = isX ? '0' : '-0.5'
}
return [origin, pos]
},
this,
)
// If background size is either cover or contain, we tell VML to keep the aspect
// and fill the entire element.
if (
this.getAttribute('background-size') === 'cover' ||
this.getAttribute('background-size') === 'contain'
) {
vSizeAttributes = {
size: '1,1',
aspect:
this.getAttribute('background-size') === 'cover'
? 'atleast'
: 'atmost',
}
} else if (this.getAttribute('background-size') !== 'auto') {
const bgSplit = this.getAttribute('background-size').split(' ')
if (bgSplit.length === 1) {
vSizeAttributes = {
size: this.getAttribute('background-size'),
aspect: 'atmost', // reproduces height auto
}
} else {
vSizeAttributes = {
size: bgSplit.join(','),
}
}
}
let vmlType =
this.getAttribute('background-repeat') === 'no-repeat' ? 'frame' : 'tile'
if (this.getAttribute('background-size') === 'auto') {
vmlType = 'tile' // if no size provided, keep old behavior because outlook can't use original image size with "frame"
;[[vOriginX, vPosX], [vOriginY, vPosY]] = [
[0.5, 0.5],
[0, 0],
] // also ensure that images are still cropped the same way
}
return `
<!--[if mso | IE]>
<v:rect ${this.htmlAttributes({
style: fullWidth
? { 'mso-width-percent': '1000' }
: { width: containerWidth },
'xmlns:v': 'urn:schemas-microsoft-com:vml',
fill: 'true',
stroke: 'false',
})}>
<v:fill ${this.htmlAttributes({
origin: `${vOriginX}, ${vOriginY}`,
position: `${vPosX}, ${vPosY}`,
src: this.getAttribute('background-url'),
color: this.getAttribute('background-color'),
type: vmlType,
...vSizeAttributes,
})} />
<v:textbox style="mso-fit-shape-to-text:true" inset="0,0,0,0">
<![endif]-->
${content}
<!--[if mso | IE]>
</v:textbox>
</v:rect>
<![endif]-->
`
}
renderSection() {
const hasBackground = this.hasBackground()
return `
<div ${this.htmlAttributes({
class: this.isFullWidth() ? null : this.getAttribute('css-class'),
style: 'div',
})}>
${
hasBackground
? `<div ${this.htmlAttributes({ style: 'innerDiv' })}>`
: ''
}
<table
${this.htmlAttributes({
align: 'center',
background: this.isFullWidth()
? null
: this.getAttribute('background-url'),
border: '0',
cellpadding: '0',
cellspacing: '0',
role: 'presentation',
style: 'table',
})}
>
<tbody>
<tr>
<td
${this.htmlAttributes({
style: 'td',
})}
>
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<![endif]-->
${this.renderWrappedChildren()}
<!--[if mso | IE]>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
${hasBackground ? '</div>' : ''}
</div>
`
}
renderFullWidth() {
const content = this.hasBackground()
? this.renderWithBackground(`
${this.renderBefore()}
${this.renderSection()}
${this.renderAfter()}
`)
: `
${this.renderBefore()}
${this.renderSection()}
${this.renderAfter()}
`
return `
<table
${this.htmlAttributes({
align: 'center',
class: this.getAttribute('css-class'),
background: this.getAttribute('background-url'),
border: '0',
cellpadding: '0',
cellspacing: '0',
role: 'presentation',
style: 'tableFullwidth',
})}
>
<tbody>
<tr>
<td>
${content}
</td>
</tr>
</tbody>
</table>
`
}
renderSimple() {
const section = this.renderSection()
return `
${this.renderBefore()}
${this.hasBackground() ? this.renderWithBackground(section) : section}
${this.renderAfter()}
`
}
render() {
return this.isFullWidth() ? this.renderFullWidth() : this.renderSimple()
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var rss = exports.rss = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M2.4,2.4v2.367c7.086,0,12.83,5.746,12.83,12.832h2.369C17.599,9.205,10.794,2.4,2.4,2.4z M2.4,7.137v2.369\r\n\tc4.469,0,8.093,3.623,8.093,8.094h2.368C12.861,11.822,8.177,7.137,2.4,7.137z M4.669,13.059c-1.254,0-2.27,1.018-2.27,2.271\r\n\ts1.016,2.27,2.27,2.27s2.269-1.016,2.269-2.27S5.923,13.059,4.669,13.059z" } }] }; |
(function() {
tinymce.PluginManager.add('image_full_plugin', function( editor, url ) {
editor.addButton('image_full_plugin', {
text: 'Изображение во всю ширину',
icon: 'image',
onclick: function() {
var image = '';
editor.windowManager.open( {
title: 'Вставить изображение во всю ширину',
body: [
{
type: 'button',
name: 'image_button',
label: 'Изображение',
library: { type: 'image' },
text: 'Выбрать изображение',
onclick: function(){
var frame = wp.media({
title: 'Выберите изображение',
button: {
text: 'Выбрать'
},
multiple: false
})
.on('select',function(){
var attachment = frame.state().get('selection').first().toJSON();
//document.getElementById('mceu_67').val(attachment.url);
image = attachment.url;
})
.open();
}
},
{
type: 'textbox',
name: 'caption',
label: 'Подпись к фотографии'
}
],
onsubmit: function( e ) {
var cap = '';
if(e.data.caption!=''){
cap = '<figcaption>'+e.data.caption+'</figcaption>';
}
editor.insertContent('<figure class="image image--full"><div class="image__wrap"><img src="'+image+'" alt=""></div>'+cap+'</figure><br>');
}
});
}
});
});
})(); |
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'VBB Map' });
}; |
import diacritics from 'diacritics';
export async function getTrendsAsync() {
let response = await fetch("https://tonicdev.io/ccheever/57c7f03b8d4e5c1600153b68/branches/master");
try {
let trends = await response.json();
return trends;
} catch (e) {
throw new Error("Could not get trends from API. " + e);
}
}
function randomChoice(arr) {
return arr[Math.floor(arr.length * Math.random())];
}
export async function randomWordAsync() {
// console.log("randomWordAsync called");
let trends = await getTrendsAsync();
let word = randomChoice(trends);
word = diacritics.remove(word);
word = word.toUpperCase();
return word;
}
export function wordForDisplay(word, guessedLetterSet) {
if (!word) {
return word;
}
let dw = '' ;
for (let i = 0; i < word.length; i++) {
let c = word.substr(i, 1).toUpperCase();
if (c.match(/\s/)) {
dw += ' ';
} else if (guessedLetterSet[c]) {
dw += c;
} else {
dw += '_';
}
}
return dw;
}
|
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mounted } from '../setupTests';
import Timer from '../Timer';
beforeEach(() => jest.useFakeTimers());
test('timer', () => {
let [component] = mounted(<Timer />);
let timer = component.children();
expect(component.children().name()).toEqual('div');
let now = new Date().getTime();
component.message({ cmd: 'timer', start: now, duration: 10000 });
expect(clearInterval).toHaveBeenCalledTimes(1);
expect(setInterval).toHaveBeenCalledTimes(1);
// component.update();
timer = component.children();
expect(timer.name()).toEqual('Meter');
let values = timer.prop('values')[0];
expect(values.value).toBeCloseTo(0, 0);
expect(values.color).toBe('white');
now = new Date().getTime() - 6100;
component.message({ cmd: 'timer', start: now, duration: 9000 });
expect(clearInterval).toHaveBeenCalledTimes(2);
expect(setInterval).toHaveBeenCalledTimes(2);
act(() => jest.runOnlyPendingTimers());
component.update();
timer = component.children();
expect(timer.name()).toEqual('Meter');
values = timer.prop('values')[0];
expect(values.value).toBeCloseTo(68, 0);
expect(values.color).toBe('orange');
now = new Date().getTime() - 7600;
component.message({ cmd: 'timer', start: now, duration: 9000 });
expect(clearInterval).toHaveBeenCalledTimes(3);
expect(setInterval).toHaveBeenCalledTimes(3);
act(() => jest.runOnlyPendingTimers());
component.update();
timer = component.children();
expect(timer.name()).toEqual('Meter');
values = timer.prop('values')[0];
expect(values.value).toBeCloseTo(84.5, 0);
expect(values.color).toBe('red');
component.unmount();
expect(clearInterval).toHaveBeenCalledTimes(4);
});
test('existing timer', () => {
let [component] = mounted(<Timer />, {
public: {
timer: {
start: new Date().getTime() - 5000,
duration: 10000,
}
}
});
let timer = component.children();
expect(clearInterval).toHaveBeenCalledTimes(0);
expect(setInterval).toHaveBeenCalledTimes(1);
expect(timer.name()).toEqual('Meter');
let values = timer.prop('values')[0];
expect(values.value).toBeCloseTo(50, 0);
expect(values.color).toBe('white');
component.unmount();
expect(clearInterval).toHaveBeenCalledTimes(1);
});
test('cancel timer on state change', () => {
let [component] = mounted(<Timer />, {
public: {
timer: {
start: new Date().getTime() - 5000,
duration: 10000,
}
}
});
let timer = component.children();
expect(setInterval).toHaveBeenCalledTimes(1);
expect(timer.name()).toEqual('Meter');
component.message({ cmd: 'state', state: 'next' });
timer = component.children();
expect(clearInterval).toHaveBeenCalledTimes(1);
expect(setInterval).toHaveBeenCalledTimes(1);
expect(timer.name()).toEqual('div');
component.unmount();
expect(clearInterval).toHaveBeenCalledTimes(2);
});
|
#!/usr/bin/env node
var amqp = require('amqplib/callback_api');
var args = process.argv.slice(2);
if (args.length == 0) {
console.log("Korzystanie: bezposredni-subskrybent-logow.js [info] [warning] [error]");
process.exit(1);
}
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var ex = 'direct_logs';
ch.assertExchange(ex, 'direct', {durable: false});
ch.assertQueue('', {exclusive: true}, function(err, q) {
console.log(" [*] Oczekiwanie na wiadomości w %s.", q.queue);
console.log(" Naciśnij CTRL+C aby zakończyć.");
args.forEach(function(severity) {
ch.bindQueue(q.queue, ex, severity);
});
ch.consume(q.queue, function(msg) {
console.log(" [x] %s: '%s'", msg.fields.routingKey, msg.content.toString());
}, {noAck: true});
});
});
});
|
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Dataset",
"Easing",
"Yamori"
],
"modules": [
"Yamori"
],
"allModules": [
{
"displayName": "Yamori",
"name": "Yamori",
"description": "yamori.js"
}
]
} };
}); |
function KeyControls () {
console.log('Key Controls');
}
KeyControls.prototype.constructor = KeyControls;
export default KeyControls;
|
import * as mixins from "~utils/mixins";
import * as styles from "gatsby-theme-docz/src/components/Header/styles";
import { lighten } from "@theme-ui/color";
export const wrapper = styles.wrapper;
export const innerContainer = styles.innerContainer;
export const menuIcon = styles.menuIcon;
export const menuButton = styles.menuButton;
export const editButton = styles.editButton;
export const headerButton = {
...mixins.centerAlign,
outline: "none",
p: "12px",
border: "none",
borderRadius: 9999,
fontSize: 0,
fontWeight: 600,
cursor: "pointer",
color: "white",
bg: lighten("primary", 0.05),
":hover": {
bg: "primary",
},
};
|
import request from 'superagent';
import Promise from 'promise';
import {
GIPHY_SEARCH_API_KEY,
GIPHY_UPLOAD_API_KEY
} from '../config';
export const isGiphyUrl = (url) => {
return url.search('giphy.com') !== -1;
};
export const getStillFromUrl = (url) => {
let a = url.split('.');
a.splice(a.length - 2, 1, a[a.length - 2] + '_s');
return a.join('.');
};
export const get = (id) => {
NProgress.start();
return new Promise((resolve, reject) => {
request
.get('http://api.giphy.com/v1/gifs/' + id)
.query({
api_key: GIPHY_SEARCH_API_KEY
})
.end((err, res) => {
NProgress.done();
if (err) {
reject(err);
} else if (res.body.meta && res.body.meta.status !== 200) {
reject(res.body.meta);
} else {
resolve(res.body);
}
});
});
};
export const search = (req) => {
NProgress.start();
return new Promise((resolve, reject) => {
request
.get('http://api.giphy.com/v1/gifs/search')
.query({
api_key: GIPHY_SEARCH_API_KEY,
q: req.query,
limit: req.limit || 10,
offset: req.offset || 0
})
.end((err, res) => {
NProgress.done();
if (err) {
reject(err);
} else if (res.body.meta && res.body.meta.status !== 200) {
reject(res.body.meta);
} else {
resolve(res.body);
}
});
});
};
export const upload = (name, url) => {
NProgress.start();
return new Promise((resolve, reject) => {
request
.post('http://upload.giphy.com/v1/gifs')
.query({
api_key: GIPHY_UPLOAD_API_KEY,
source_image_url: encodeURI(url),
tags: name.split(' ').join(',')
})
.end((err, res) => {
NProgress.done();
if (err) {
reject(err);
} else if (res.body.meta && res.body.meta.status !== 200) {
reject(res.body.meta);
} else {
resolve(res.body);
}
});
});
};
export const uploadGet = (name, url) => {
return new Promise((resolve, reject) => {
upload(name, url)
.then((body) => {
var id = body.data.id;
get(id)
.then((body) => {
let data = body.data;
resolve({
url: data.images.downsized.url,
still_url: data.images.downsized_still.url
});
})
.catch((error) => {
reject({
name: 'Giphy',
status: error.status,
msg: error.msg
});
});
})
.catch((error) => {
reject({
name: 'Giphy',
status: error.status,
msg: error.msg
});
});
});
}; |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Octicon from 'react-octicon';
import Clipboard from 'react-clipboard.js';
export const CopyUrl = props =>
((props.constraint || {}).semver || (props.version || {}).semver) && (
<section className={`row ${props.className || ''}`}>
<div className="col">
<h6>COPY THE URL TO THIS CHECK</h6>
<div className="input-group">
<input className="form-control" type="text" value={document.location.href} readOnly />
<div className="input-group-append">
<Clipboard data-clipboard-text={document.location.href} className="btn btn-secondary">
<Octicon name="clippy" />
</Clipboard>
</div>
</div>
</div>
</section>
);
CopyUrl.propTypes = {
className: PropTypes.string,
constraint: PropTypes.object,
version: PropTypes.object,
};
export default connect(state => state)(CopyUrl);
|
'use strict'
let _
module.exports = class CSVConfig {
constructor (config = {}) {
this.config = config
}
get (path, config) {
return config
? this.config[path] && this.config[path][config]
: this.config[path]
}
set (path, config, value) {
if (this.config[path] == null) { this.config[path] = {} }
this.config[path][config] = value
}
move (oldPath, newPath) {
this.config[newPath] = this.config[oldPath]
delete this.config[oldPath]
}
clear () { this.config = {} }
clearOption (option) {
for (let path in this.config) {
let config = this.config[path]
delete config[option]
}
}
serialize () {
return {deserializer : CSVConfig, data: this.config}
}
}
|
const iconv = require('iconv-lite');
const XMLDeclBeginnings = [
{
encoding: 'utf8', // This is common for more encodings, all of them can be used to read the declaration
buffer: Buffer.from([0x3C, 0x3F, 0x78, 0x6D])
},
{
encoding: 'utf16le',
buffer: Buffer.from([0x3C, 0x00, 0x3F, 0x00])
},
{
encoding: 'utf16be',
buffer: Buffer.from([0x00, 0x3C, 0x00, 0x3F])
}
];
const BOMs = [
{
encoding: 'utf8',
buffer: Buffer.from([0xEF, 0xBB, 0xBF])
},
{
encoding: 'utf16le',
buffer: Buffer.from([0xFF, 0xFE])
},
{
encoding: 'utf16be',
buffer: Buffer.from([0xFE, 0xFF])
}
];
// XML => nodejs
const ENCODING_MAP = {
'UTF-8': 'utf8',
'UTF-16': ['utf16le','utf16be']
};
function normalizeEncoding(xmlEncoding, detectedEncoding) {
const encoding = ENCODING_MAP[xmlEncoding];
if (!encoding) { return xmlEncoding; }
if (Array.isArray(encoding)) {
return encoding.find(e => e === detectedEncoding);
} else {
return encoding;
}
}
function bufferStartsWith(buffer, beginning) {
return buffer.slice(0, beginning.length).equals(beginning);
}
function getXMLDeclTagEncoding(xmlBuffer) {
const found = XMLDeclBeginnings.find(beginning => bufferStartsWith(xmlBuffer, beginning.buffer));
return found ? found.encoding : null;
}
function getXMLDeclaration(xmlBuffer, encoding) {
const closeTag = iconv.encode('?>', encoding);
const xmlDeclEnd = xmlBuffer.indexOf(closeTag);
if (xmlDeclEnd === -1) { return null; } // no ?> found
return iconv.decode(xmlBuffer.slice(0, xmlDeclEnd), encoding); // End index not included
}
function getEncodingAttr(xmlDecl) {
const result = /encoding=['"]([A-Za-z]([A-Za-z0-9._]|-)*)['"]/.exec(xmlDecl);
return result ? result[1] : null;
}
function getBOM(textBuffer) {
return BOMs.find(bom => bufferStartsWith(textBuffer, bom.buffer));
}
function xmlEncoding(xmlBuffer) {
var detectedEncoding;
var xmlDeclFound;
var xmlDeclEncoding
const bom = getBOM(xmlBuffer);
if (bom) {
xmlBuffer = xmlBuffer.slice(bom.buffer.length);
detectedEncoding = bom.encoding;
} else {
detectedEncoding = getXMLDeclTagEncoding(xmlBuffer);
xmlDeclFound = !!detectedEncoding;
}
if (!detectedEncoding) {
return null;
}
if (xmlDeclFound) {
xmlDeclEncoding = normalizeEncoding(getEncodingAttr(getXMLDeclaration(xmlBuffer, detectedEncoding)), detectedEncoding);
}
// We should check if xmlDeclEncoding and detectedEncoding match, for now we
// give precedence to the encoding in the xml declaration if it exists
return xmlDeclEncoding ? xmlDeclEncoding : detectedEncoding;
}
function bufferToString(xmlBuffer, options) {
if (!Buffer.isBuffer(xmlBuffer)) {
throw new Error('buffer expected, found: ' + typeof xmlBuffer);
}
options = options || {};
const encoding = xmlEncoding(xmlBuffer);
const defaultEncoding = iconv.encodingExists(options.defaultEncoding) ? options.defaultEncoding : 'utf8';
return iconv.decode(xmlBuffer, iconv.encodingExists(encoding) ? encoding : defaultEncoding);
}
module.exports = bufferToString;
module.exports.xmlEncoding = xmlEncoding; |
var debug = require('debug')('crawler:main');
debug('welcome to zf'); |
/*
* spa.shell.js
* Shell module for SPA
*/
/*jslint browser : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars : false,
white : true
*/
/*global $, spa */
spa.shell = (function () {
var
configMap = {
anchor_schema_map : {
news : {
new_01 : true, new_02 : true, new_03 : true, new_04 : true,
new_05 : true, new_06 : true, new_07 : true, new_08 : true,
new_09 : true, new_10 : true, new_11 : true, new_12 : true
},
page : {
save_love : true, save_marriage : true,
separate_mistress : true, custom_love : true,
emotion_forum : true, mentor_team : true,
service_intro : true, about_us : true
}
},
main_html : String()
+ '<header class="spa-header"></header>'
+ '<div class="spa-preface"></div>'
+ '<div class="spa-main"></div>'
+ '<footer class="spa-footer"></footer>'
+ '<div class="spa-slide"></div>'
+ '<div class="spa-modal"></div>',
news_detail : {},
page_detail : {}
},
stateMap = {
$container : null,
anchor_map : {}
},
jqueryMap = {},
root_ele, device_width,
setJqueryMap, mergeConfigMap,
fontAutomatic, loadCommonModule,
checkAnchor, loadPage,
onHashchange, initModule;
// Start : setJqueryMap()
// 功能 : 缓存 jQuery 集合
//
setJqueryMap = function () {
var $container = stateMap.$container;
jqueryMap = {
$container : $container,
$header : $container.find('.spa-header'),
$preface : $container.find('.spa-preface'),
$main : $container.find('.spa-main'),
$footer : $container.find('.spa-footer'),
$slide : $container.find('.spa-slide'),
$modal : $container.find('.spa-modal')
};
};
// End : jqueryMap()
// Start : mergeConfigMap()
// 合并配置项,用于检查
//
mergeConfigMap = function () {
var news_detail = spa.data.news.configMap;
news_detail = $.extend(true, configMap.news_detail, news_detail);
};
// End : mergeConfigMap()
// Start fontAutomatic()
// 功能 :
// * 动态调整字体大小
// 返回值 :none
// 说明 :
// * root_ele - html 元素
// * device_width - 设备宽度
//
fontAutomatic = function () {
root_ele = document.documentElement;
device_width = root_ele.clientWidth;
// 根元素字体大小 - 以 iPhone6 为准
root_ele.style.fontSize = device_width / 7.5 + 'px';
// 当页面缩放时,动态更改字体大小
window.onresize = function () {
root_ele = document.documentElement;
device_width = root_ele.clientWidth;
root_ele.style.fontSize = device_width / 7.5 + 'px';
};
};
// End fontAutoMatic()
// Start : loadCommonModule() - 加载公共模块
// 功能 : 加载公共模块
//
loadCommonModule = function () {
spa.shell.header.initModule(jqueryMap.$header);
spa.shell.preface.initModule(jqueryMap.$preface);
spa.shell.footer.initModule(jqueryMap.$footer);
spa.shell.slide.initModule(jqueryMap.$slide);
};
// End : loadCommonModule();
// Start : checkAnchor()
// 功能 :
// * 用于检查地址栏的哈西片段是否有对应的页面检查如果所检查的哈西片段没有对应
// 页面,则返回首页
//
checkAnchor = function (key_name) {
var anchor_map = $.uriAnchor.makeAnchorMap();
delete anchor_map['_s_' + key_name];
if (key_name === 'news') {
spa.data.news.initModule(anchor_map[key_name]);
}
else if (key_name === 'page') {
switch (anchor_map[key_name]) {
case 'save_love' : // 挽回爱情
spa.slove.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'save_marriage' : // 挽救婚姻
spa.smarriage.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'separate_mistress' : // 分离小三
spa.smistress.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'custom_love' : // 定制爱情
spa.clove.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'emotion_forum' : // 情感论坛
spa.forum.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'mentor_team' : // 权威专家
spa.mentor.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'service_intro' : // 服务介绍
spa.service.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'about_us' : // 关于我们
spa.about.initModule(jqueryMap.$container, jqueryMap.$main);
break;
case 'book' : // 嘉伟导师十本好书推荐
spa.book.initModule(jqueryMap.$container, jqueryMap.$main);
break;
default:
break;
}
}
else if (key_name === 'video') {
spa.video.initModule(jqueryMap.$main);
}
else if (key_name === 'case') {
spa.data.case.initModule(jqueryMap.$main);
}
return false;
};
// End : checkAnchor()
// Start : loadPage()
// 功能 : 加载子页面
//
loadPage = function (arg_map) {
var is_key_name_exist = false, key_name, preface_img;
for (key_name in arg_map) {
if (arg_map.hasOwnProperty(key_name)) {
is_key_name_exist = true;
delete arg_map['_s_' + key_name];
}
}
if (is_key_name_exist) {
// 通过地址栏中的哈西片段定位到对应页面
switch (key_name) {
case 'news' :
checkAnchor(key_name);
break;
case 'page' :
checkAnchor(key_name);
break;
case 'video' :
checkAnchor(key_name);
break;
case 'case' :
checkAnchor(key_name);
break;
default:
$.uriAnchor.setAnchor({});
break;
}
}
// 若地址栏中的哈西片段没有对应的页面,加载首页
if (!is_key_name_exist) {
preface_img = jqueryMap.$container.find('.spa-preface img');
spa.index.initModule( jqueryMap.$main );
preface_img.attr('src', 'images/index/preface.png');
}
};
// End : loadPage()
// Start : onHashchange()
// 功能 : 监听地址栏哈西片段
//
onHashchange = function () {
var anchor_map = $.uriAnchor.makeAnchorMap();
$(document).scrollTop(0);
loadPage(anchor_map);
// 每当 URI 变化时,并且当加载完 js 后,加载左侧导航
document.getElementsByTagName('script').onload = (function () {
spa.shell.slide.toggleSlide(false);
}());
};
// End : onHashchange()
// initModule() - 初始化模块
initModule = function ($container) {
stateMap.$container = $container;
$container.html(configMap.main_html);
setJqueryMap();
mergeConfigMap();
fontAutomatic();
loadCommonModule();
// 加载首页主内容区域
spa.index.initModule(jqueryMap.$main);
// // 加载左侧导航
// spa.shell.slide.initModule(jqueryMap.$container);
$(window)
.bind('hashchange', onHashchange)
.trigger('hashchange');
};
// 导出公开方法
return { initModule : initModule };
}());
|
'use strict';
const { expect } = require('chai');
const { View, Property, Method } = require('..');
View.init(__dirname, 0, 0);
const loop = () => {
const timer = setInterval(View.update, 10);
return () => clearInterval(timer);
};
describe('Qml', function () {
this.timeout(4000);
let l;
before(() => { l = loop(); });
after(() => { l(); l = null; });
it('contains class View', () => {
expect(View).to.exist;
});
it('contains class Property', () => {
expect(Property).to.exist;
});
it('contains class Method', () => {
expect(Method).to.exist;
});
describe('View', () => {
it('has all static methods', () => {
['init', 'libs', 'plugins', 'style', 'update'].forEach(
name => expect(View).to.have.property(name)
);
});
it('can be created', () => {
expect(new View()).to.be.an.instanceOf(View);
});
it('has all dynamic methods', () => {
const view = new View();
[
'load', 'destroy', 'toString', 'mousedown', 'mouseup',
'mousemove', 'keydown', 'keyup',
].forEach(
name => expect(view).to.respondTo(name)
);
});
it('has all properties', () => {
const view = new View();
[
'width', 'height',
'w', 'h',
'wh',
'size',
'textureId',
'isLoaded',
].forEach(
name => expect(view).to.have.property(name)
);
});
it('eventually loads a QML file', async () => {
const view = new View({ file: 'test.qml' });
const loaded = await new Promise(
res => view.on('load', () => res(true))
);
expect(loaded).to.be.equal(true);
});
it('eventually creates a texture', () => {
const view = new View({ file: 'test.qml' });
return new Promise(res => view.on('reset', textureId => {
expect(textureId).to.exist;
res();
}));
});
});
describe('Property', () => {
const view = new View({ file: 'test.qml', silent: true });
const opts = { view, name: 'obj1', key: 'prop1' };
view.on('error', () => {});
it('can be created', () => {
expect(new Property(opts)).to.be.an.instanceOf(Property);
});
it('has all properties', () => {
const prop = new Property(opts);
['opts', 'value'].forEach(
name => expect(prop).to.have.property(name)
);
});
it('reads a value from QML', () => {
const prop = new Property(opts);
expect(prop.value).to.be.equal('value1');
});
it('changes a QML value', async () => {
const prop = new Property(opts);
const changed = await new Promise(res => {
view.on('p1c', () => res(true));
prop.value = 11;
});
expect(changed).to.be.equal(true);
});
it('reads non-existent object\'s property as null', () => {
const prop = new Property({ ...opts, name: 'awdaldaklwd23' });
expect(prop.value).to.be.equal(null);
});
it('reads non-existent property as null', () => {
const prop = new Property({ ...opts, key: 'awdaldaklwd23' });
expect(prop.value).to.be.equal(null);
});
});
describe('Method', () => {
const view = new View({ file: 'test.qml', silent: true });
const opts = { view, name: 'obj1', key: 'method1' };
view.on('error', () => {});
it('can be created', () => {
expect(new Method(opts)).to.be.a('function');
});
it('has all properties', () => {
const method = new Method(opts);
['opts'].forEach(
name => expect(method).to.have.property(name)
);
});
it('calls QML method1', async () => {
const method1 = new Method(opts);
const called = await new Promise(res => {
view.on('m1c', () => res(true));
method1();
});
expect(called).to.be.equal(true);
});
it('calls QML method2', async () => {
const method2 = new Method({ ...opts, key: 'method2' });
const called = await new Promise(res => {
view.on('m2c', () => res(true));
method2(10);
});
expect(called).to.be.equal(true);
});
it('calls non-existent object\'s method, and gets null', () => {
const method = new Method({ ...opts, name: 'awdaldaklwd23' });
expect(method()).to.be.equal(null);
});
it('calls non-existent method, and gets null', () => {
const method = new Method({ ...opts, key: 'awdaldaklwd23' });
expect(method()).to.be.equal(null);
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:d46bba17b272accbad7bfb4be8e3b20eb2e33ed28b0a7560558df4d9df2be1ad
size 8904
|
const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const TARGET = process.env.npm_lifecycle_event;
const PATHS = {
app: path.join(__dirname, 'client'),
build: path.join(__dirname, 'build')
};
process.env.BABEL_ENV = TARGET;
const common = {
entry: {
app: './client/index.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: PATHS.build,
filename: 'bundle.js'
},
externals: {
lodash: '_',
React: 'react',
ReactDOM: 'react-dom'
},
module: {
loaders: [
{
test: /\.css$/,
loaders: ['style', 'css'],
include: PATHS.app
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.js?$/,
loaders: ['babel?cacheDirectory'],
include: PATHS.app
}
]
}
};
if(TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
devtool: 'eval-source-map',
devServer: {
contentBase: PATHS.build,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
// display only errors to reduce the amount of output
stats: 'errors-only',
// parse host and port from env so this is easy
// to customize
host: process.env.HOST,
port: process.env.PORT
},
plugins: [
new webpack.HotModuleReplacementPlugin()
//new NpmInstallPlugin({
// save: false // --save
//})
]
});
}
if(TARGET === 'build') {
module.exports = merge(common, {});
} |
define([],function(){
'use strict';
var ctlr = ['$scope','SurveyService', function($scope, SurveyService){
SurveyService.query({page:'1', count:'10'},function(surveys){
$scope.surveys = surveys.surveys;
});
}];
return ctlr;
});
|
S_A_counter = 0;//counting number of changes
S_B_interval= [];
S_D_currentPos = 0;
S_D_numSeconds = 0;
function checkTextAtKeyPress(e) {
var givenText = "S_D_1";
var typedText = "S_D_2";
var timerLog = "S_D_3";
var textToType = document.getElementById(givenText).value;
//we reached the end, do nothing
if(S_D_currentPos>=textToType.length) {return;}
var nextChar = textToType.charAt(S_D_currentPos);
var keyPressed = String.fromCharCode(e.which);
//correct key was pressed
if(nextChar==keyPressed) {
document.getElementById(typedText).style.backgroundColor="rgb(255,255,255)";
document.getElementById(typedText).value = textToType.substring(0,S_D_currentPos+1);
S_D_currentPos++;
//first time key was pressed, start counter
if(S_D_currentPos==1) {
S_B_interval[timerLog]=setInterval(function(){incrementSB(timerLog, " seconds");}, 1000);
}
//we reached the end
if(S_D_currentPos==textToType.length) {
clearInterval(S_B_interval[timerLog]);
document.getElementById(timerLog).style.color="orange";
}
}
//incorrect key
else {
document.getElementById(typedText).style.backgroundColor="rgb(255,100,100)";
}
}
function movingTheMouseWithin(e) {
var box = document.getElementById("S_C_6");
box.style.top = (e.clientY)+"px";
box.style.left = (e.clientX)+"px";
box.innerHTML="X="+e.clientX+", Y="+e.clientY;
box.style.visibility = "visible";
}
function movingTheMouseOutside(e) {
var box = document.getElementById("S_C_6");
box.style.visibility = "hidden";
}
function updateNuggets() {
var n1 = document.getElementById('S_C_2').value;
var n2 = document.getElementById('S_C_3').value;
var n3 = document.getElementById('S_C_4').value;
var selected = null;
var myTextArea = document.getElementById('S_C_1');
if (myTextArea.selectionStart != undefined)
{
var p1 = myTextArea.selectionStart;
var p2 = myTextArea.selectionEnd;
selected = myTextArea.value.substring(p1, p2);
console.log("selected: "+ selected);
}
if(selected==n1) {document.getElementById('S_C_2').value = "";}
else if(selected==n2){document.getElementById('S_C_3').value = "";}
else if(selected==n3){document.getElementById('S_C_4').value = "";}
else if(n1.length==0){document.getElementById('S_C_2').value = selected;}
else if(n2.length==0){document.getElementById('S_C_3').value = selected;}
else if(n3.length==0)
{
document.getElementById('S_C_4').value = selected;
document.getElementById('S_C_5').classList.add("pure-button");
document.getElementById('S_C_5').classList.add("pure-button-secondary");
delete document.getElementById('S_C_5').hidden;
}
else {
alert('You have selected three information nuggets. Either unselect one or manually empty text box.')}
}
//reads a number from the element; tries first value and then innerHTML
//increments the number
//writes it back to the element (possible with some additional text)
function incrementSB ( elementIDString, addonText ) {
console.log("Entering incrementSB with "+elementIDString+", " + addonText);
var thisElement = document.getElementById(elementIDString);
console.log("thisElement: "+thisElement.toString());
var num;
if( thisElement.value!=undefined && thisElement.value.length > 0 ) {
num = parseInt(thisElement.value,10);
}
else if( thisElement.innerHTML!=undefined && thisElement.innerHTML.length > 0 ) {
num = parseInt(thisElement.innerHTML,10);
}
else {
console.log("Error at incrementSB - expected value/innerHTML property");
return;
}
if(num==null) {
console.log("Error at incrementSB - expected numerical value to parse");
return;
}
num++;
if( thisElement.value!=undefined && thisElement.value.length > 0) {
thisElement.value = num+addonText;
}
else if(thisElement.innerHTML!=undefined) {
thisElement.innerHTML = num+addonText;
}
}
function S_B_mouseover(elementID, timeout, addonText) {
//S_B_interval[elementID]=setInterval(function(){incrementSB(elementID, addonText);}, timeout);
S_B_interval[elementID]=setInterval(incrementSB, timeout,elementID, addonText);
}
function S_B_mouseout(elementID, addonText)
{
clearInterval(S_B_interval[elementID]);
var thisElement = document.getElementById(elementID);
if( thisElement.value.length > 0) {
thisElement.value = "0"+addonText;
}
else {
thisElement.innerHTML = "0"+addonText;
}
}
|
var Chaff;
(function (Chaff) {
var Mock = (function () {
function Mock(ConstructorFunction) {
this.ConstructorFunction = ConstructorFunction;
}
Mock.prototype.With = function (mutator) {
mutator(this.MakeSubject());
return this;
};
Mock.prototype.ConstructWith = function (Args) {
this.Args = Args;
return this;
};
Mock.prototype.Private = function (mutator) {
mutator(this.MakeSubject());
return this;
};
Mock.prototype.Create = function () {
return this.MakeSubject();
};
Mock.prototype.MakeSubject = function () {
if (!this.CreatedType) {
this.CreatedType = this.MakeType(this.Args || []);
}
return this.CreatedType;
};
Mock.prototype.MakeType = function (Args) {
var holder = new this.ConstructorFunction();
this.ConstructorFunction.apply(holder, Args);
return holder;
};
return Mock;
})();
Chaff.Mock = Mock;
})(Chaff || (Chaff = {}));
var Person = (function () {
function Person(Age, name) {
this.Age = Age;
this.Name = name;
}
Person.prototype.Older = function () {
return this.Age++;
};
Person.prototype.GetName = function () {
return this.Name;
};
return Person;
})();
var ChaffTests = (function () {
function ChaffTests() {
var _this = this;
this.Mock = new Chaff.Mock(Person);
describe("Public Properties Tests", function () {
it("Should Assign 4 to a Persons Age", function () {
var person = _this.Mock.With(function (x) {
return x.Age = 4;
}).Create();
expect(person.Age).toBe(4);
});
});
describe("Private Properties Tests", function () {
it("Should Assign 'Adam' to a Persons Name", function () {
var person = _this.Mock.Private(function (x) {
return x.Name = "Adam";
}).Create();
expect(person.GetName()).toBe("Adam");
});
});
describe("Arguments being passed in upon initialisation", function () {
it("Should pass the provided args array object into the constructor", function () {
var person = new Chaff.Mock(Person).ConstructWith([4, "Adam"]).Create();
expect(person.Age).toBe(4);
expect(person.GetName()).toBe("Adam");
});
});
describe("Generic Chaff Tests", function () {
it("Should return a object with no 'With' call", function () {
var person = new Chaff.Mock(Person).Create();
expect(person).toNotBe(null);
expect(person).toNotBe(undefined);
expect(person.Age).toBe(undefined);
expect(person.GetName()).toBe(undefined);
});
});
}
return ChaffTests;
})();
(function () {
return new ChaffTests();
})();
|
const round = (value, precision = 2) => {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
};
export default round;
|
import React, {Component} from "react";
import {observer} from "mobx-react";
import {render, unmountComponentAtNode} from "react-dom";
import {observable} from "mobx";
import {Dropdown, Menu, Alert} from "antd";
import event from "~/utils/event";
@observer
class Alerts extends Component {
@observable alerts = [];
disposers = [];
componentDidMount = () => {
this.disposers.push(event.on("Alerts.addAlert", this.addAlert));
};
componentWillUnMount = () => {
this.disposers.map((disposer) => disposer());
};
addAlert = (type, message, description) => {
this.alerts.push({type, message, description})
};
render = () => {
return <div style={{position: "fixed", top: 0, left: "50%", transform: "translate(-50%)"}}>
{this.alerts.map((alert, i) =>
<Alert style={{marginTop: "16px"}} key={i} type={alert.type} message={alert.message} description={alert.description} closable showIcon/>)}
</div>
};
}
const target = document.createElement("div");
document.body.appendChild(target);
render(<Alerts/>, target);
function alert(type, message, description) {
event.emit("Alerts.addAlert", type, message, description)
}
function success(message, description) {
alert("success", message, description)
}
function info(message, description) {
alert("info", message, description)
}
function warning(message, description) {
alert("warning", message, description)
}
function error(message, description) {
alert("error", message, description)
}
export default {success, info, warning, error} |
//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: http://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: http://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
// By VitoShadow from StackOverflow: http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity
|
var consts = {
}, lists = {
'1': '#list-inbox',
'2': '#list-urgent',
'3': '#list-today'
};
var Database = {
addTODO: function() {
}
};
var TODO = {
init: function() {
$('.todo-input').keydown(this.add.bind(this));
},
add: function(e) {
if($('.todo-input').val() && e.keyCode === 13) {
var title = $('.todo-input').val();
var id = new Date().getTime();
TODO.appendTODOHTML(title, id, 0, 1);
$('.todo-input').val(""); //인풋이 많으니 골라 지워
}
},
appendTODOHTML: function(title, id, completed, listId) {
var parent = $(lists[listId])
var source = $("#todo-template").html();
var template = Handlebars.compile(source);
var data = {
id: id,
listId: "1",
title : title,
completed: completed
};
$(parent).append(template(data));
},
/*
generateElement({
id: "1440490127007", //스타트 데이트가 들어감 "5/9/2015",
listId: "1", //리스트 이름
title: "빨래하기",
completed: '0' // 컴플릿 하면 "5/10/2015"처럼 들어감
});
*/
remove: function(id) {
}
}
TODO.init();
|
const Config = require('./webpack.base.config')
const Webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const Dashboard = require('webpack-dashboard')
const DashboardPlugin = require('webpack-dashboard/plugin')
const dashboard = new Dashboard()
Config.entry.app.unshift('webpack-dev-server/client?http://localhost:8080/', 'webpack/hot/dev-server')
Config.output.filename = '[name].[hash:7].js'
Config.output.chunkFilename = '[name].[hash:7].js'
Config.module.rules.forEach((loader) => {
if (loader.use[0].loader === 'url') {
loader.use[0].options.name = '[name].[hash:7].[ext]'
}
})
Config.output.publicPath = '/'
Config.plugins = (Config.plugins || []).concat([
new ExtractTextWebpackPlugin({
filename: '[name].[hash:7].css'
}),
new Webpack.HotModuleReplacementPlugin(),
new DashboardPlugin(dashboard.setData),
new Webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"dev"'
}
})
])
Config.devtool = 'source-map'
const compiler = Webpack(Config)
const server = new WebpackDevServer(compiler, {
historyApiFallback: {
index: '/app.html'
},
hot: true,
inline: true,
quiet: true,
proxy: {
'/api': {
changeOrigin: true,
host: '172.16.0.186:8000',
target: 'http://172.16.0.186:8000',
secure: false,
pathRewrite: { '^/api': '' }
}
}
})
server.listen(8080, (err) => {
if (err) {
console.log(err)
}
console.log('listen at localhost:8080')
})
|
module.exports = ST;
var Ship = require('./ship.js');
var Asteroid = require('./asteroid.js');
var Alien = require('./alien.js');
var Laser = require('./laser.js');
var Shield = require('./shield.js');
var Mine = require('./mine.js');
function ST (canvas, context, game) {
this.canvas = canvas;
this.context = context;
this.game = game;
this.ship = new Ship(this.canvas.width/2, this.canvas.height/2, 10, 10, context, this);
this.asteroids = [];
this.aliens = [];
this.lasers = [];
this.alienLasers = [];
this.shields = [];
this.mines = [];
this.initialAsteroids(game.asteroidQuantity);
this.initialAliens(game.alienQuantity);
};
ST.prototype.drawAll = function () {
this.detectSides();
this.ship.moveShip().draw();
this.drawAsteroids();
this.drawAliens();
this.detectShipCollision();
this.drawLasers();
this.drawAlienLasers();
this.drawMines();
this.drawShield(this.ship);
this.game.updateScore();
this.game.updateLives();
this.game.updateShield();
};
ST.prototype.initialAsteroids = function (numberOfAsteroids) {
for (var i = 0; i < numberOfAsteroids; i++) {
this.asteroids.push(new Asteroid(getRandom(0,this.canvas.width),getRandom(0,this.canvas.height),getRandom(20,50),getRandom(20,50),this.context,this.game.asteroidVelocity));
}
};
ST.prototype.initialAliens = function (numberOfAliens) {
for (var i = 0; i < numberOfAliens; i++) {
this.aliens.push(new Alien(getRandom(0,this.canvas.width/4),getRandom(10,this.canvas.height - 10),this.context,this));
}
};
ST.prototype.drawAsteroids = function () {
if (this.asteroids.length === 0) {
this.game.levelUp();
} else {
this.asteroids.forEach(function (asteroid) {
asteroid.move().draw();
})
}
};
ST.prototype.drawAliens = function () {
this.aliens.forEach(function (alien) {
if(Math.abs(alien.x - this.ship.x) < 5) {
alien.move().draw().shoot();
}
else {
alien.move().draw();
}
},this);
};
ST.prototype.drawLasers = function () {
this.lasers.forEach(function (laser) {
laser.draw(this);
this.detectLaserCollision(laser);
},this);
};
ST.prototype.drawAlienLasers = function () {
this.alienLasers.forEach(function (laser) {
laser.draw();
this.detectAlienLaserCollision(laser);
},this);
};
ST.prototype.drawMines = function () {
var spaceTime = this;
if (this.mines.length > 0) {
this.mines.forEach(function (mine) {
mine.draw();
spaceTime.detectLaserCollision(mine);
})
}
};
ST.prototype.drawShield = function (ship) {
var spaceTime = this;
if (this.shields.length > 0) {
this.shields.forEach(function (shield) {
shield.draw(ship);
spaceTime.detectShieldCollision(shield);
})
}
};
ST.prototype.fireLaser = function () {
this.lasers.push(new Laser(this.ship, this.context));
this.game.score -= 5;
};
ST.prototype.activeShield = function () {
this.shields.push(new Shield(this.ship, this.context));
};
ST.prototype.layMine = function () {
this.mines.push(new Mine(this.ship, this.context));
};
ST.prototype.detectLaserCollision = function (laser) {
this.asteroids.forEach( function (asteroid) {
if (asteroidCollidesWith(laser, asteroid)) {
asteroid.hit_count += 1;
if(asteroid.hit_count === 3) {
this.asteroids = this.asteroids.filter(function (a) {
return a !== asteroid;
});
if (asteroid.width > 30) {
this.asteroids.push(new Asteroid(asteroid.x, asteroid.y, asteroid.width / 2, asteroid.height / 2, this.context, this.game.asteroidVelocity));
this.asteroids.push(new Asteroid(asteroid.x + asteroid.width / 2, asteroid.y + asteroid.height / 2, asteroid.width / 2, asteroid.height / 2, this.context, this.game.asteroidVelocity));
}
}
this.lasers = this.lasers.filter(function (l) {
return l !== laser;
});
this.game.scorePoints(asteroid);
}
}, this);
this.aliens.forEach( function (alien) {
if (alienCollidesWith(laser, alien)) {
this.aliens = this.aliens.filter(function (a) {
return a !== alien;
});
this.game.scorePoints(alien);
}
}, this);
};
ST.prototype.detectAlienLaserCollision = function (laser) {
var spaceTime = this;
var ship = this.ship;
if (asteroidCollidesWith(laser, ship)) {
spaceTime.alienLasers = [];
ship.dead = true;
spaceTime.game.die();
setTimeout(function() {
ship.dead = false;
ship.x = spaceTime.canvas.width/2;
ship.y = spaceTime.canvas.height/2;
ship.velocity = 0;
}, 300);
}
};
ST.prototype.detectShieldCollision = function (shield) {
this.asteroids.forEach( function (asteroid) {
if (shieldCollidesWith(shield, asteroid)) {
this.asteroids = this.asteroids.filter(function (a) {
return a !== asteroid;
});
this.shields = this.shields.filter(function (s) {
return s !== shield;
});
this.game.scorePoints(asteroid);
}
}, this);
};
ST.prototype.detectShipCollision = function () {
var ship = this.ship;
var spaceTime = this;
this.asteroids.forEach( function (asteroid) {
if (asteroidCollidesWith(ship, asteroid)) {
spaceTime.asteroids = spaceTime.asteroids.filter(function (a) {
return a !== asteroid;
});
spaceTime.ship.dead = true;
spaceTime.game.die();
setTimeout(function() {
spaceTime.ship.dead = false;
ship.x = spaceTime.canvas.width/2;
ship.y = spaceTime.canvas.height/2;
ship.velocity = 0;
}, 300);
}
});
};
ST.prototype.detectSides = function () {
this.asteroids.forEach( function (asteroid) {
if(asteroid.x > this.canvas.width) {
asteroid.x -= this.canvas.width;
}
else if(asteroid.x < 0) {
asteroid.x += this.canvas.width;
}
else if(asteroid.y > this.canvas.height) {
asteroid.y -= this.canvas.height;
}
else if(asteroid.y < 0) {
asteroid.y += this.canvas.height;
}
}, this);
var ship = this.ship;
this.aliens.forEach( function (alien) {
if(alien.x > this.canvas.width) {
alien.x -= this.canvas.width;
}
else if(alien.x < 0) {
alien.x += this.canvas.width;
}
else if(alien.y > this.canvas.height) {
alien.y -= this.canvas.height;
}
else if(alien.y < 0) {
alien.y += this.canvas.height;
}
}, this);
this.lasers.forEach( function (laser) {
if(laser.x > this.canvas.width) {
this.lasers = this.lasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.x < 0) {
this.lasers = this.lasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.y > this.canvas.height) {
this.lasers = this.lasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.y < 0) {
this.lasers = this.lasers.filter(function (l) {
return l !== laser;
});
}
}, this);
this.alienLasers.forEach( function (laser) {
if(laser.x > this.canvas.width) {
this.alienLasers = this.alienLasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.x < 0) {
this.alienLasers = this.alienLasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.y > this.canvas.height) {
this.alienLasers = this.alienLasers.filter(function (l) {
return l !== laser;
});
}
else if(laser.y < 0) {
this.alienLasers = this.alienLasers.filter(function (l) {
return l !== laser;
});
}
}, this);
if(ship.x + ship.width > this.canvas.width) {
ship.x -= this.canvas.width;
}
else if(ship.x - ship.width < 0) {
ship.x += this.canvas.width;
}
else if(ship.y > this.canvas.height) {
ship.y -= this.canvas.height;
}
else if(ship.y < 0) {
ship.y += this.canvas.height;
}
};
function asteroidCollidesWith (object, asteroid) {
if(object.y <= asteroid.y + asteroid.height && object.y >= asteroid.y) {
if(object.x <= asteroid.x + asteroid.width && object.x >= asteroid.x){
return true
}
}
}
function alienCollidesWith (object, alien) {
if(object.y <= alien.y + alien.radius && object.y >= alien.y) {
if(object.x <= alien.x + alien.radius && object.x >= alien.x){
return true
}
}
}
function shieldCollidesWith (object, asteroid) {
var distX = Math.abs(object.x - (asteroid.x + asteroid.width/2));
var distY = Math.abs(object.y - (asteroid.y + asteroid.height/2));
if (distX > (asteroid.width/2 + object.radius)) { return false; }
if (distY > (asteroid.height/2 + object.radius)) { return false; }
if (distX <= (asteroid.width/2)) { return true; }
if (distY <= (asteroid.height/2)) { return true; }
}
function getRandom(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
} |
'use strict';
var webtestDriver = require('../src/web-test-driver');
const RE_STR = '["]?([^\"]+)["]?'; // e.g. foo.bar, "foo.bar", or "foo bar"
const RE_STR_WITH_QUOTE = '[\'"]?([\\s\\S]*)[\'"]?'; //e.g. 'foo bar', "foo bar"
module.exports = {
name: 'set element value',
help: 'set element <selector> value "<string>"',
regExp: new RegExp(`^set element ${RE_STR} value [as ]*${RE_STR_WITH_QUOTE}$`),
/** must return a Promise, so that it can be chained with next command*/
func: function(selector, value) {
let cssSelector = `${selector}, [placeholder='${selector}']`;
value = value || "";
return webtestDriver.driver.wait( function() {
return webtestDriver.driver.findElement({css: cssSelector})
.then(element => {
return webtestDriver.driver.executeScript(`
arguments[0].value = '${value}';
arguments[0].setAttribute('value', '${value}');
arguments[0].dispatchEvent(new Event('change'));
return true;
`, element);
})
}, webtestDriver.config.timeout);
}
};
|
define({main:{"sr-Cyrl-RS":{identity:{version:{_cldrVersion:"24",_number:"$Revision: 9061 $"},generation:{_date:"$Date: 2013-07-20 12:27:45 -0500 (Sat, 20 Jul 2013) $"},language:"root",script:"Cyrl",territory:"RS"},dates:{calendars:{gregorian:{months:{format:{abbreviated:{1:"јан",2:"феб",3:"мар",4:"апр",5:"мај",6:"јун",7:"јул",8:"авг",9:"сеп",10:"окт",11:"нов",12:"дец"},narrow:{1:"ј",2:"ф",3:"м",4:"а",5:"м",6:"ј",7:"ј",8:"а",9:"с",10:"о",11:"н",12:"д"},wide:{1:"јануар",2:"фебруар",3:"март",4:"април",
5:"мај",6:"јун",7:"јул",8:"август",9:"септембар",10:"октобар",11:"новембар",12:"децембар"}},"stand-alone":{abbreviated:{1:"јан",2:"феб",3:"мар",4:"апр",5:"мај",6:"јун",7:"јул",8:"авг",9:"сеп",10:"окт",11:"нов",12:"дец"},narrow:{1:"ј",2:"ф",3:"м",4:"а",5:"м",6:"ј",7:"ј",8:"а",9:"с",10:"о",11:"н",12:"д"},wide:{1:"јануар",2:"фебруар",3:"март",4:"април",5:"мај",6:"јун",7:"јул",8:"август",9:"септембар",10:"октобар",11:"новембар",12:"децембар"}}},days:{format:{abbreviated:{sun:"нед",mon:"пон",tue:"уто",
wed:"сре",thu:"чет",fri:"пет",sat:"суб"},narrow:{sun:"н",mon:"п",tue:"у",wed:"с",thu:"ч",fri:"п",sat:"с"},wide:{sun:"недеља",mon:"понедељак",tue:"уторак",wed:"среда",thu:"четвртак",fri:"петак",sat:"субота"}},"stand-alone":{abbreviated:{sun:"нед",mon:"пон",tue:"уто",wed:"сре",thu:"чет",fri:"пет",sat:"суб"},narrow:{sun:"н",mon:"п",tue:"у",wed:"с",thu:"ч",fri:"п",sat:"с"},wide:{sun:"недеља",mon:"понедељак",tue:"уторак",wed:"среда",thu:"четвртак",fri:"петак",sat:"субота"}}},dayPeriods:{format:{wide:{am:"пре подне",
pm:"поподне"}}},eras:{eraAbbr:{0:"п. н. е.",1:"н. е."}},dateFormats:{full:"EEEE, dd. MMMM y.","long":"dd. MMMM y.",medium:"dd.MM.y.","short":"d.M.yy."},timeFormats:{full:"HH.mm.ss zzzz","long":"HH.mm.ss z",medium:"HH.mm.ss","short":"HH.mm"},dateTimeFormats:{full:"{1} {0}","long":"{1} {0}",medium:"{1} {0}","short":"{1} {0}",availableFormats:{d:"d",Ed:"E d.",Ehm:"E, h:mm a",EHm:"E, HH:mm",Ehms:"E, h:mm:ss a",EHms:"E, HH:mm:ss",Gy:"y. G",GyMMM:"MMM y. G",GyMMMd:"d. MMM y. G",GyMMMEd:"E, d. MMM y. G",
h:"hh a",H:"HH",hm:"hh.mm a",Hm:"HH.mm",hms:"hh.mm.ss a",Hms:"HH.mm.ss",M:"L",Md:"d/M",MEd:"E, M-d",MMdd:"MM-dd",MMM:"LLL",MMMd:"d. MMM",MMMdd:"dd.MMM",MMMEd:"E d. MMM",MMMMd:"d. MMMM",MMMMdd:"dd. MMMM",MMMMEd:"E d. MMMM",ms:"mm.ss",y:"y.",yM:"y-M",yMd:"d. M. y.",yMEd:"E, d. M. y.",yMM:"MM.y",yMMdd:"dd.MM.y",yMMM:"MMM y.",yMMMd:"d. MMM y.",yMMMEd:"E, d. MMM y.",yMMMM:"MMMM y.",yQQQ:"QQQ. y",yQQQQ:"QQQQ. y"}}}},fields:{era:{displayName:"ера"},year:{displayName:"година","relative-type--1":"Прошле године",
"relative-type-0":"Ове године","relative-type-1":"Следеће године"},month:{displayName:"месец","relative-type--1":"Прошлог месеца","relative-type-0":"Овог месеца","relative-type-1":"Следећег месеца"},week:{displayName:"недеља","relative-type--1":"Прошле недеље","relative-type-0":"Ове недеље","relative-type-1":"Следеће недеље"},day:{displayName:"дан","relative-type--1":"јуче","relative-type-0":"данас","relative-type-1":"сутра"},weekday:{displayName:"дан у недељи"},dayperiod:{displayName:"пре подне/поподне"},
hour:{displayName:"час"},minute:{displayName:"минут"},second:{displayName:"секунд"},zone:{displayName:"зона"}}},numbers:{defaultNumberingSystem:"latn",otherNumberingSystems:{"native":"latn"},"symbols-numberSystem-latn":{decimal:",",group:".",list:";",percentSign:"%",plusSign:"+",minusSign:"-",exponential:"E",perMille:"‰",infinity:"∞",nan:"NaN"},"decimalFormats-numberSystem-latn":{standard:"#,##0.###","long":{decimalFormat:{"1000-count-one":"0 хиљада","1000-count-few":"0 хиљаде","1000-count-other":"0 хиљада",
"10000-count-one":"00 хиљада","10000-count-few":"00 хиљаде","10000-count-other":"00 хиљада","100000-count-one":"000 хиљада","100000-count-few":"000 хиљаде","100000-count-other":"000 хиљада","1000000-count-one":"0 милион","1000000-count-few":"0 милиона","1000000-count-other":"0 милиона","10000000-count-one":"00 милион","10000000-count-few":"00 милиона","10000000-count-other":"00 милиона","100000000-count-one":"000 милион","100000000-count-few":"000 милиона","100000000-count-other":"000 милиона","1000000000-count-one":"0 милијарда",
"1000000000-count-few":"0 милијарде","1000000000-count-other":"0 милијарди","10000000000-count-one":"00 милијарда","10000000000-count-few":"00 милијарде","10000000000-count-other":"00 милијарди","100000000000-count-one":"000 милијарда","100000000000-count-few":"000 милијарде","100000000000-count-other":"000 милијарди","1000000000000-count-one":"0 трилион","1000000000000-count-few":"0 трилиона","1000000000000-count-other":"0 трилиона","10000000000000-count-one":"00 трилион","10000000000000-count-few":"00 трилиона",
"10000000000000-count-other":"00 трилиона","100000000000000-count-one":"000 трилион","100000000000000-count-few":"000 трилиона","100000000000000-count-other":"000 трилиона"}},"short":{decimalFormat:{"1000-count-one":"0","1000-count-few":"0","1000-count-other":"0","10000-count-one":"00 хиљ","10000-count-few":"00K","10000-count-other":"00 хиљ","100000-count-one":"000 хиљ","100000-count-few":"000K","100000-count-other":"000 хиљ","1000000-count-one":"0 мил","1000000-count-few":"0 мил","1000000-count-other":"0 мил",
"10000000-count-one":"00 мил","10000000-count-few":"00 мил","10000000-count-other":"00 мил","100000000-count-one":"000 мил","100000000-count-few":"000 мил","100000000-count-other":"000 мил","1000000000-count-one":"0 млрд","1000000000-count-few":"0 млрд","1000000000-count-other":"0 млрд","10000000000-count-one":"00 млрд","10000000000-count-few":"00 млрд","10000000000-count-other":"00 млрд","100000000000-count-one":"000 млрд","100000000000-count-few":"000 млрд","100000000000-count-other":"000 млрд",
"1000000000000-count-one":"0 бил","1000000000000-count-few":"0 бил","1000000000000-count-other":"0 бил","10000000000000-count-one":"00 бил","10000000000000-count-few":"00 бил","10000000000000-count-other":"00 бил","100000000000000-count-one":"000 бил","100000000000000-count-few":"000 бил","100000000000000-count-other":"000 бил"}}},"percentFormats-numberSystem-latn":{standard:"#,##0%"},"currencyFormats-numberSystem-latn":{standard:"#,##0.00 ¤","unitPattern-count-one":"{0} {1}","unitPattern-count-few":"{0} {1}",
"unitPattern-count-other":"{0} {1}"},currencies:{AUD:{displayName:"Аустралијски долар",symbol:"A$"},BRL:{displayName:"Бразилски Реал",symbol:"R$"},CAD:{displayName:"Канадски долар",symbol:"CA$"},CHF:{displayName:"Швајцарски франак",symbol:"CHF"},CNY:{displayName:"Кинески јуан ренминби",symbol:"CN¥"},DKK:{displayName:"Данска круна",symbol:"DKK"},EUR:{displayName:"Евро",symbol:"€"},GBP:{displayName:"Британска фунта стерлинга",symbol:"£"},HKD:{displayName:"Хонгконшки долар",symbol:"HK$"},IDR:{displayName:"Индонежанска рупија",
symbol:"IDR"},INR:{displayName:"Индијска рупија",symbol:"₹"},JPY:{displayName:"Јапански јен",symbol:"¥"},KRW:{displayName:"Јужнокорејски Вон",symbol:"₩"},MXN:{displayName:"Мексички пезо",symbol:"MX$"},NOK:{displayName:"Норвешка круна",symbol:"NOK"},PLN:{displayName:"Пољски злот",symbol:"зл"},RUB:{displayName:"Руска рубља",symbol:"RUB"},SAR:{displayName:"Саудијски ријал",symbol:"SAR"},SEK:{displayName:"Шведска круна",symbol:"SEK"},THB:{displayName:"Таи бахт",symbol:"฿"},TRY:{displayName:"Турска лира",
symbol:"Тл"},TWD:{displayName:"Нови тајвански долар",symbol:"NT$"},USD:{displayName:"Амерички долар",symbol:"US$"},ZAR:{displayName:"Јужно-афрички ранд",symbol:"ZAR"}}}}}}); |
/*!
* DevExtreme (dx.messages.cs.js)
* Version: 20.2.9 (build 21293-1110)
* Build date: Wed Oct 20 2021
*
* Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define(function(require) {
factory(require("devextreme/localization"))
})
} else {
if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}
}(this, function(localization) {
localization.loadMessages({
cs: {
Yes: "Ano",
No: "Ne",
Cancel: "Zru\u0161it",
Clear: "Smazat",
Done: "Hotovo",
Loading: "Nahr\xe1v\xe1n\xed...",
Select: "V\xfdb\u011br...",
Search: "Hledat",
Back: "Zp\u011bt",
OK: "OK",
"dxCollectionWidget-noDataText": "\u017d\xe1dn\xe1 data k zobrazen\xed",
"dxDropDownEditor-selectLabel": "V\xfdb\u011br",
"validation-required": "povinn\xe9",
"validation-required-formatted": "{0} je povinn\xfdch",
"validation-numeric": "Hodnota mus\xed b\xfdt \u010d\xedslo",
"validation-numeric-formatted": "{0} mus\xed b\xfdt \u010d\xedslo",
"validation-range": "Hodnota je mimo rozsah",
"validation-range-formatted": "{0} je mimo rozsah",
"validation-stringLength": "D\xe9lka textov\xe9ho \u0159etezce nen\xed spr\xe1vn\xe1",
"validation-stringLength-formatted": "D\xe9lka textu {0} nen\xed spr\xe1vn\xe1",
"validation-custom": "Neplatn\xe1 hodnota",
"validation-custom-formatted": "{0} je neplatn\xfdch",
"validation-async": "Neplatn\xe1 hodnota",
"validation-async-formatted": "{0} je neplatn\xfdch",
"validation-compare": "Hodnoty se neshoduj\xed",
"validation-compare-formatted": "{0} se neshoduje",
"validation-pattern": "Hodnota neodpov\xedd\xe1 vzoru",
"validation-pattern-formatted": "{0} neodpov\xedd\xe1 vzoru",
"validation-email": "Neplatn\xfd email",
"validation-email-formatted": "{0} nen\xed platn\xfd",
"validation-mask": "Hodnota nen\xed platn\xe1",
"dxLookup-searchPlaceholder": "Minim\xe1ln\xed po\u010det znak\u016f: {0}",
"dxList-pullingDownText": "St\xe1hn\u011bte dol\u016f pro obnoven\xed...",
"dxList-pulledDownText": "Uvoln\u011bte pro obnoven\xed...",
"dxList-refreshingText": "Obnovuji...",
"dxList-pageLoadingText": "Nahr\xe1v\xe1m...",
"dxList-nextButtonText": "V\xedce",
"dxList-selectAll": "Vybrat v\u0161e",
"dxListEditDecorator-delete": "Smazat",
"dxListEditDecorator-more": "V\xedce",
"dxScrollView-pullingDownText": "St\xe1hn\u011bte dol\u016f pro obnoven\xed...",
"dxScrollView-pulledDownText": "Uvoln\u011bte pro obnoven\xed...",
"dxScrollView-refreshingText": "Obnovuji...",
"dxScrollView-reachBottomText": "Nahr\xe1v\xe1m...",
"dxDateBox-simulatedDataPickerTitleTime": "Vyberte \u010das",
"dxDateBox-simulatedDataPickerTitleDate": "Vyberte datum",
"dxDateBox-simulatedDataPickerTitleDateTime": "Vyberte datum a \u010das",
"dxDateBox-validation-datetime": "Hodnota mus\xed b\xfdt datum nebo \u010das",
"dxFileUploader-selectFile": "Vyberte soubor",
"dxFileUploader-dropFile": "nebo p\u0159eneste soubor sem",
"dxFileUploader-bytes": "byt\u016f",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "Nahr\xe1t",
"dxFileUploader-uploaded": "Nahr\xe1no",
"dxFileUploader-readyToUpload": "P\u0159ipraveno k nahr\xe1n\xed",
"dxFileUploader-uploadAbortedMessage": "TODO",
"dxFileUploader-uploadFailedMessage": "Nahr\xe1v\xe1n\xed selhalo",
"dxFileUploader-invalidFileExtension": "",
"dxFileUploader-invalidMaxFileSize": "",
"dxFileUploader-invalidMinFileSize": "",
"dxRangeSlider-ariaFrom": "Od",
"dxRangeSlider-ariaTill": "Do",
"dxSwitch-switchedOnText": "ZAP",
"dxSwitch-switchedOffText": "VYP",
"dxForm-optionalMark": "voliteln\xfd",
"dxForm-requiredMessage": "{0} je vy\u017eadov\xe1no",
"dxNumberBox-invalidValueMessage": "Hodnota mus\xed b\xfdt \u010d\xedslo",
"dxNumberBox-noDataText": "\u017d\xe1dn\xe1 data",
"dxDataGrid-columnChooserTitle": "V\xfdb\u011br sloupc\u016f",
"dxDataGrid-columnChooserEmptyText": "P\u0159esu\u0148te sloupec zde pro skyt\xed",
"dxDataGrid-groupContinuesMessage": "Pokra\u010dovat na dal\u0161\xed stran\u011b",
"dxDataGrid-groupContinuedMessage": "Pokra\u010dov\xe1n\xed z p\u0159edchoz\xed strany",
"dxDataGrid-groupHeaderText": "Slou\u010dit sloupce",
"dxDataGrid-ungroupHeaderText": "Odd\u011blit",
"dxDataGrid-ungroupAllText": "Odd\u011blit v\u0161e",
"dxDataGrid-editingEditRow": "Upravit",
"dxDataGrid-editingSaveRowChanges": "Ulo\u017eit",
"dxDataGrid-editingCancelRowChanges": "Zru\u0161it",
"dxDataGrid-editingDeleteRow": "Smazat",
"dxDataGrid-editingUndeleteRow": "Obnovit",
"dxDataGrid-editingConfirmDeleteMessage": "Opravdu chcete smazat tento z\xe1znam?",
"dxDataGrid-validationCancelChanges": "Zru\u0161it zm\u011bny",
"dxDataGrid-groupPanelEmptyText": "P\u0159eneste hlavi\u010dku sloupce zde pro slou\u010den\xed",
"dxDataGrid-noDataText": "\u017d\xe1dn\xe1 data",
"dxDataGrid-searchPanelPlaceholder": "Hled\xe1n\xed...",
"dxDataGrid-filterRowShowAllText": "(V\u0161e)",
"dxDataGrid-filterRowResetOperationText": "Reset",
"dxDataGrid-filterRowOperationEquals": "Rovn\xe1 se",
"dxDataGrid-filterRowOperationNotEquals": "Nerovn\xe1 se",
"dxDataGrid-filterRowOperationLess": "Men\u0161\xed",
"dxDataGrid-filterRowOperationLessOrEquals": "Men\u0161\xed nebo rovno",
"dxDataGrid-filterRowOperationGreater": "V\u011bt\u0161\xed",
"dxDataGrid-filterRowOperationGreaterOrEquals": "V\u011bt\u0161\xed nebo rovno",
"dxDataGrid-filterRowOperationStartsWith": "Za\u010d\xedn\xe1 na",
"dxDataGrid-filterRowOperationContains": "Obsahuje",
"dxDataGrid-filterRowOperationNotContains": "Neobsahuje",
"dxDataGrid-filterRowOperationEndsWith": "Kon\u010d\xed na",
"dxDataGrid-filterRowOperationBetween": "Mezi",
"dxDataGrid-filterRowOperationBetweenStartText": "Za\u010d\xedn\xe1",
"dxDataGrid-filterRowOperationBetweenEndText": "Kon\u010d\xed",
"dxDataGrid-applyFilterText": "Pou\u017e\xedt filtr",
"dxDataGrid-trueText": "Plat\xed",
"dxDataGrid-falseText": "Neplat\xed",
"dxDataGrid-sortingAscendingText": "Srovnat vzestupn\u011b",
"dxDataGrid-sortingDescendingText": "Srovnat sestupn\u011b",
"dxDataGrid-sortingClearText": "Zru\u0161it rovn\xe1n\xed",
"dxDataGrid-editingSaveAllChanges": "Ulo\u017eit zm\u011bny",
"dxDataGrid-editingCancelAllChanges": "Zru\u0161it zm\u011bny",
"dxDataGrid-editingAddRow": "P\u0159idat \u0159\xe1dek",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Min {1} je {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Max {1} je {0}",
"dxDataGrid-summaryAvg": "Pr\u016fm.: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Pr\u016fm\u011br ze {1} je {0}",
"dxDataGrid-summarySum": "Suma: {0}",
"dxDataGrid-summarySumOtherColumn": "Suma {1} je {0}",
"dxDataGrid-summaryCount": "Po\u010det: {0}",
"dxDataGrid-columnFixingFix": "Uchytit",
"dxDataGrid-columnFixingUnfix": "Uvolnit",
"dxDataGrid-columnFixingLeftPosition": "Vlevo",
"dxDataGrid-columnFixingRightPosition": "Vpravo",
"dxDataGrid-exportTo": "Export",
"dxDataGrid-exportToExcel": "Export do se\u0161itu Excel",
"dxDataGrid-exporting": "Export...",
"dxDataGrid-excelFormat": "soubor Excel",
"dxDataGrid-selectedRows": "Vybran\xe9 \u0159\xe1dky",
"dxDataGrid-exportSelectedRows": "Export vybran\xfdch \u0159\xe1dk\u016f",
"dxDataGrid-exportAll": "Exportovat v\u0161echny z\xe1znamy",
"dxDataGrid-headerFilterEmptyValue": "(pr\xe1zdn\xe9)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "Zru\u0161it",
"dxDataGrid-ariaColumn": "Sloupec",
"dxDataGrid-ariaValue": "Hodnota",
"dxDataGrid-ariaFilterCell": "Filtrovat bu\u0148ku",
"dxDataGrid-ariaCollapse": "Sbalit",
"dxDataGrid-ariaExpand": "Rozbalit",
"dxDataGrid-ariaDataGrid": "Datov\xe1 m\u0159\xed\u017eka",
"dxDataGrid-ariaSearchInGrid": "Hledat v datov\xe9 m\u0159\xed\u017ece",
"dxDataGrid-ariaSelectAll": "Vybrat v\u0161e",
"dxDataGrid-ariaSelectRow": "Vybrat \u0159\xe1dek",
"dxDataGrid-filterBuilderPopupTitle": "Tvorba Filtru",
"dxDataGrid-filterPanelCreateFilter": "Vytvo\u0159it Filtr",
"dxDataGrid-filterPanelClearFilter": "Smazat",
"dxDataGrid-filterPanelFilterEnabledHint": "Povolit Filtr",
"dxTreeList-ariaTreeList": "Tree list",
"dxTreeList-editingAddRowToNode": "P\u0159idat",
"dxPager-infoText": "Strana {0} ze {1} ({2} polo\u017eek)",
"dxPager-pagesCountText": "ze",
"dxPager-pageSizesAllText": "V\u0161e",
"dxPivotGrid-grandTotal": "Celkem",
"dxPivotGrid-total": "{0} Celkem",
"dxPivotGrid-fieldChooserTitle": "V\xfdb\u011br pole",
"dxPivotGrid-showFieldChooser": "Zobrazit v\xfdb\u011br pole",
"dxPivotGrid-expandAll": "Rozbalit v\u0161e",
"dxPivotGrid-collapseAll": "Sbalit v\u0161e",
"dxPivotGrid-sortColumnBySummary": 'Srovnat "{0}" podle tohoto sloupce',
"dxPivotGrid-sortRowBySummary": 'Srovnat "{0}" podle tohoto \u0159\xe1dku',
"dxPivotGrid-removeAllSorting": "Odstranit ve\u0161ker\xe9 t\u0159\xedd\u011bn\xed",
"dxPivotGrid-dataNotAvailable": "nedostupn\xe9",
"dxPivotGrid-rowFields": "Pole \u0159\xe1dk\u016f",
"dxPivotGrid-columnFields": "Pole sloupc\u016f",
"dxPivotGrid-dataFields": "Pole dat",
"dxPivotGrid-filterFields": "Filtrovat pole",
"dxPivotGrid-allFields": "V\u0161echna pole",
"dxPivotGrid-columnFieldArea": "Zde vlo\u017ete pole sloupc\u016f",
"dxPivotGrid-dataFieldArea": "Zde vlo\u017ete pole dat",
"dxPivotGrid-rowFieldArea": "Zde vlo\u017ete pole \u0159\xe1dk\u016f",
"dxPivotGrid-filterFieldArea": "Zde vlo\u017ete filtr pole",
"dxScheduler-editorLabelTitle": "P\u0159edm\u011bt",
"dxScheduler-editorLabelStartDate": "Po\u010d\xe1te\u010dn\xed datum",
"dxScheduler-editorLabelEndDate": "Koncov\xe9 datum",
"dxScheduler-editorLabelDescription": "Popis",
"dxScheduler-editorLabelRecurrence": "Opakovat",
"dxScheduler-openAppointment": "Otev\u0159\xedt sch\u016fzku",
"dxScheduler-recurrenceNever": "Nikdy",
"dxScheduler-recurrenceMinutely": "Minutely",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "Denn\u011b",
"dxScheduler-recurrenceWeekly": "T\xfddn\u011b",
"dxScheduler-recurrenceMonthly": "M\u011bs\xed\u010dn\u011b",
"dxScheduler-recurrenceYearly": "Ro\u010dn\u011b",
"dxScheduler-recurrenceRepeatEvery": "Ka\u017ed\xfd",
"dxScheduler-recurrenceRepeatOn": "Repeat On",
"dxScheduler-recurrenceEnd": "Konec opakov\xe1n\xed",
"dxScheduler-recurrenceAfter": "Po",
"dxScheduler-recurrenceOn": "Zap",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "dn\xed",
"dxScheduler-recurrenceRepeatWeekly": "t\xfddn\u016f",
"dxScheduler-recurrenceRepeatMonthly": "m\u011bs\xedc\u016f",
"dxScheduler-recurrenceRepeatYearly": "rok\u016f",
"dxScheduler-switcherDay": "Den",
"dxScheduler-switcherWeek": "T\xfdden",
"dxScheduler-switcherWorkWeek": "Pracovn\xed t\xfdden",
"dxScheduler-switcherMonth": "M\u011bs\xedc",
"dxScheduler-switcherAgenda": "Agenda",
"dxScheduler-switcherTimelineDay": "\u010casov\xe1 osa den",
"dxScheduler-switcherTimelineWeek": "\u010casov\xe1 osa t\xfdden",
"dxScheduler-switcherTimelineWorkWeek": "\u010casov\xe1 osa pracovn\xed t\xfdden",
"dxScheduler-switcherTimelineMonth": "\u010casov\xe1 osa m\u011bs\xedc",
"dxScheduler-recurrenceRepeatOnDate": "na den",
"dxScheduler-recurrenceRepeatCount": "v\xfdskyt\u016f",
"dxScheduler-allDay": "Cel\xfd den",
"dxScheduler-confirmRecurrenceEditMessage": "Chcete upravit pouze tuto sch\u016fzku nebo celou s\xe9rii?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Chcete smazat pouze tuto sch\u016fzku nebo celou s\xe9rii?",
"dxScheduler-confirmRecurrenceEditSeries": "Upravit s\xe9rii",
"dxScheduler-confirmRecurrenceDeleteSeries": "Smazat s\xe9rii",
"dxScheduler-confirmRecurrenceEditOccurrence": "Upravit sch\u016fzku",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Smazat sch\u016fzku",
"dxScheduler-noTimezoneTitle": "Bez \u010dasov\xe9 z\xf3ny",
"dxScheduler-moreAppointments": "{0} nav\xedc",
"dxCalendar-todayButtonText": "Dnes",
"dxCalendar-ariaWidgetName": "Kalend\xe1\u0159",
"dxColorView-ariaRed": "\u010cerven\xe1",
"dxColorView-ariaGreen": "Zelen\xe1",
"dxColorView-ariaBlue": "Modr\xe1",
"dxColorView-ariaAlpha": "Pr\u016fhledn\xe1",
"dxColorView-ariaHex": "K\xf3d barvy",
"dxTagBox-selected": "{0} vybr\xe1no",
"dxTagBox-allSelected": "V\u0161e vybr\xe1no ({0})",
"dxTagBox-moreSelected": "{0} nav\xedc",
"vizExport-printingButtonText": "Tisk",
"vizExport-titleMenuText": "Export/import",
"vizExport-exportButtonText": "{0} soubor\u016f",
"dxFilterBuilder-and": "A",
"dxFilterBuilder-or": "NEBO",
"dxFilterBuilder-notAnd": "NAND",
"dxFilterBuilder-notOr": "NOR",
"dxFilterBuilder-addCondition": "P\u0159idat podm\xednku",
"dxFilterBuilder-addGroup": "P\u0159idat skupinu",
"dxFilterBuilder-enterValueText": "<vlo\u017ete hodnotu>",
"dxFilterBuilder-filterOperationEquals": "Rovn\xe1 se",
"dxFilterBuilder-filterOperationNotEquals": "Nerovn\xe1 se",
"dxFilterBuilder-filterOperationLess": "Men\u0161\xed ne\u017e",
"dxFilterBuilder-filterOperationLessOrEquals": "Men\u0161\xed nebo rovno ne\u017e",
"dxFilterBuilder-filterOperationGreater": "V\u011bt\u0161\xed ne\u017e",
"dxFilterBuilder-filterOperationGreaterOrEquals": "V\u011bt\u0161\xed nebo rovno ne\u017e",
"dxFilterBuilder-filterOperationStartsWith": "Za\u010d\xedn\xe1 na",
"dxFilterBuilder-filterOperationContains": "Obsahuje",
"dxFilterBuilder-filterOperationNotContains": "Neobsahuje",
"dxFilterBuilder-filterOperationEndsWith": "Kon\u010d\xed na",
"dxFilterBuilder-filterOperationIsBlank": "Je pr\xe1zdn\xe9",
"dxFilterBuilder-filterOperationIsNotBlank": "Nen\xed pr\xe1zdn\xe9",
"dxFilterBuilder-filterOperationBetween": "Mezi",
"dxFilterBuilder-filterOperationAnyOf": "Libovoln\xfd z",
"dxFilterBuilder-filterOperationNoneOf": "\u017d\xe1dn\xfd z",
"dxHtmlEditor-dialogColorCaption": "!TODO!",
"dxHtmlEditor-dialogBackgroundCaption": "!TODO!",
"dxHtmlEditor-dialogLinkCaption": "!TODO!",
"dxHtmlEditor-dialogLinkUrlField": "!TODO!",
"dxHtmlEditor-dialogLinkTextField": "!TODO!",
"dxHtmlEditor-dialogLinkTargetField": "!TODO!",
"dxHtmlEditor-dialogImageCaption": "!TODO!",
"dxHtmlEditor-dialogImageUrlField": "!TODO!",
"dxHtmlEditor-dialogImageAltField": "!TODO!",
"dxHtmlEditor-dialogImageWidthField": "!TODO!",
"dxHtmlEditor-dialogImageHeightField": "!TODO!",
"dxHtmlEditor-dialogInsertTableRowsField": "!TODO",
"dxHtmlEditor-dialogInsertTableColumnsField": "!TODO",
"dxHtmlEditor-dialogInsertTableCaption": "!TODO",
"dxHtmlEditor-heading": "!TODO!",
"dxHtmlEditor-normalText": "!TODO!",
"dxFileManager-newDirectoryName": "TODO",
"dxFileManager-rootDirectoryName": "TODO",
"dxFileManager-errorNoAccess": "TODO",
"dxFileManager-errorDirectoryExistsFormat": "TODO",
"dxFileManager-errorFileExistsFormat": "TODO",
"dxFileManager-errorFileNotFoundFormat": "TODO",
"dxFileManager-errorDirectoryNotFoundFormat": "TODO",
"dxFileManager-errorWrongFileExtension": "TODO",
"dxFileManager-errorMaxFileSizeExceeded": "TODO",
"dxFileManager-errorInvalidSymbols": "TODO",
"dxFileManager-errorDefault": "TODO",
"dxFileManager-errorDirectoryOpenFailed": "TODO",
"dxDiagram-categoryGeneral": "TODO",
"dxDiagram-categoryFlowchart": "TODO",
"dxDiagram-categoryOrgChart": "TODO",
"dxDiagram-categoryContainers": "TODO",
"dxDiagram-categoryCustom": "TODO",
"dxDiagram-commandExportToSvg": "TODO",
"dxDiagram-commandExportToPng": "TODO",
"dxDiagram-commandExportToJpg": "TODO",
"dxDiagram-commandUndo": "TODO",
"dxDiagram-commandRedo": "TODO",
"dxDiagram-commandFontName": "TODO",
"dxDiagram-commandFontSize": "TODO",
"dxDiagram-commandBold": "TODO",
"dxDiagram-commandItalic": "TODO",
"dxDiagram-commandUnderline": "TODO",
"dxDiagram-commandTextColor": "TODO",
"dxDiagram-commandLineColor": "TODO",
"dxDiagram-commandLineWidth": "TODO",
"dxDiagram-commandLineStyle": "TODO",
"dxDiagram-commandLineStyleSolid": "TODO",
"dxDiagram-commandLineStyleDotted": "TODO",
"dxDiagram-commandLineStyleDashed": "TODO",
"dxDiagram-commandFillColor": "TODO",
"dxDiagram-commandAlignLeft": "TODO",
"dxDiagram-commandAlignCenter": "TODO",
"dxDiagram-commandAlignRight": "TODO",
"dxDiagram-commandConnectorLineType": "TODO",
"dxDiagram-commandConnectorLineStraight": "TODO",
"dxDiagram-commandConnectorLineOrthogonal": "TODO",
"dxDiagram-commandConnectorLineStart": "TODO",
"dxDiagram-commandConnectorLineEnd": "TODO",
"dxDiagram-commandConnectorLineNone": "TODO",
"dxDiagram-commandConnectorLineArrow": "TODO",
"dxDiagram-commandFullscreen": "TODO",
"dxDiagram-commandUnits": "TODO",
"dxDiagram-commandPageSize": "TODO",
"dxDiagram-commandPageOrientation": "TODO",
"dxDiagram-commandPageOrientationLandscape": "TODO",
"dxDiagram-commandPageOrientationPortrait": "TODO",
"dxDiagram-commandPageColor": "TODO",
"dxDiagram-commandShowGrid": "TODO",
"dxDiagram-commandSnapToGrid": "TODO",
"dxDiagram-commandGridSize": "TODO",
"dxDiagram-commandZoomLevel": "TODO",
"dxDiagram-commandAutoZoom": "TODO",
"dxDiagram-commandFitToContent": "TODO",
"dxDiagram-commandFitToWidth": "TODO",
"dxDiagram-commandAutoZoomByContent": "TODO",
"dxDiagram-commandAutoZoomByWidth": "TODO",
"dxDiagram-commandSimpleView": "TODO",
"dxDiagram-commandCut": "TODO",
"dxDiagram-commandCopy": "TODO",
"dxDiagram-commandPaste": "TODO",
"dxDiagram-commandSelectAll": "TODO",
"dxDiagram-commandDelete": "TODO",
"dxDiagram-commandBringToFront": "TODO",
"dxDiagram-commandSendToBack": "TODO",
"dxDiagram-commandLock": "TODO",
"dxDiagram-commandUnlock": "TODO",
"dxDiagram-commandInsertShapeImage": "TODO",
"dxDiagram-commandEditShapeImage": "TODO",
"dxDiagram-commandDeleteShapeImage": "TODO",
"dxDiagram-commandLayoutLeftToRight": "TODO",
"dxDiagram-commandLayoutRightToLeft": "TODO",
"dxDiagram-commandLayoutTopToBottom": "TODO",
"dxDiagram-commandLayoutBottomToTop": "TODO",
"dxDiagram-unitIn": "TODO",
"dxDiagram-unitCm": "TODO",
"dxDiagram-unitPx": "TODO",
"dxDiagram-dialogButtonOK": "TODO",
"dxDiagram-dialogButtonCancel": "TODO",
"dxDiagram-dialogInsertShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageSelectButton": "TODO",
"dxDiagram-dialogEditShapeImageLabelText": "TODO",
"dxDiagram-uiExport": "TODO",
"dxDiagram-uiProperties": "TODO",
"dxDiagram-uiSettings": "TODO",
"dxDiagram-uiShowToolbox": "TODO",
"dxDiagram-uiSearch": "TODO",
"dxDiagram-uiStyle": "TODO",
"dxDiagram-uiLayout": "TODO",
"dxDiagram-uiLayoutTree": "TODO",
"dxDiagram-uiLayoutLayered": "TODO",
"dxDiagram-uiDiagram": "TODO",
"dxDiagram-uiText": "TODO",
"dxDiagram-uiObject": "TODO",
"dxDiagram-uiConnector": "TODO",
"dxDiagram-uiPage": "TODO",
"dxDiagram-shapeText": "TODO",
"dxDiagram-shapeRectangle": "TODO",
"dxDiagram-shapeEllipse": "TODO",
"dxDiagram-shapeCross": "TODO",
"dxDiagram-shapeTriangle": "TODO",
"dxDiagram-shapeDiamond": "TODO",
"dxDiagram-shapeHeart": "TODO",
"dxDiagram-shapePentagon": "TODO",
"dxDiagram-shapeHexagon": "TODO",
"dxDiagram-shapeOctagon": "TODO",
"dxDiagram-shapeStar": "TODO",
"dxDiagram-shapeArrowLeft": "TODO",
"dxDiagram-shapeArrowUp": "TODO",
"dxDiagram-shapeArrowRight": "TODO",
"dxDiagram-shapeArrowDown": "TODO",
"dxDiagram-shapeArrowUpDown": "TODO",
"dxDiagram-shapeArrowLeftRight": "TODO",
"dxDiagram-shapeProcess": "TODO",
"dxDiagram-shapeDecision": "TODO",
"dxDiagram-shapeTerminator": "TODO",
"dxDiagram-shapePredefinedProcess": "TODO",
"dxDiagram-shapeDocument": "TODO",
"dxDiagram-shapeMultipleDocuments": "TODO",
"dxDiagram-shapeManualInput": "TODO",
"dxDiagram-shapePreparation": "TODO",
"dxDiagram-shapeData": "TODO",
"dxDiagram-shapeDatabase": "TODO",
"dxDiagram-shapeHardDisk": "TODO",
"dxDiagram-shapeInternalStorage": "TODO",
"dxDiagram-shapePaperTape": "TODO",
"dxDiagram-shapeManualOperation": "TODO",
"dxDiagram-shapeDelay": "TODO",
"dxDiagram-shapeStoredData": "TODO",
"dxDiagram-shapeDisplay": "TODO",
"dxDiagram-shapeMerge": "TODO",
"dxDiagram-shapeConnector": "TODO",
"dxDiagram-shapeOr": "TODO",
"dxDiagram-shapeSummingJunction": "TODO",
"dxDiagram-shapeContainerDefaultText": "TODO",
"dxDiagram-shapeVerticalContainer": "TODO",
"dxDiagram-shapeHorizontalContainer": "TODO",
"dxDiagram-shapeCardDefaultText": "TODO",
"dxDiagram-shapeCardWithImageOnLeft": "TODO",
"dxDiagram-shapeCardWithImageOnTop": "TODO",
"dxDiagram-shapeCardWithImageOnRight": "TODO",
"dxGantt-dialogTitle": "TODO",
"dxGantt-dialogStartTitle": "TODO",
"dxGantt-dialogEndTitle": "TODO",
"dxGantt-dialogProgressTitle": "TODO",
"dxGantt-dialogResourcesTitle": "TODO",
"dxGantt-dialogResourceManagerTitle": "TODO",
"dxGantt-dialogTaskDetailsTitle": "TODO",
"dxGantt-dialogEditResourceListHint": "TODO",
"dxGantt-dialogEditNoResources": "TODO",
"dxGantt-dialogButtonAdd": "TODO",
"dxGantt-contextMenuNewTask": "TODO",
"dxGantt-contextMenuNewSubtask": "TODO",
"dxGantt-contextMenuDeleteTask": "TODO",
"dxGantt-contextMenuDeleteDependency": "TODO",
"dxGantt-dialogTaskDeleteConfirmation": "TODO",
"dxGantt-dialogDependencyDeleteConfirmation": "TODO",
"dxGantt-dialogResourcesDeleteConfirmation": "TODO",
"dxGantt-dialogConstraintCriticalViolationMessage": "TODO",
"dxGantt-dialogConstraintViolationMessage": "TODO",
"dxGantt-dialogCancelOperationMessage": "TODO",
"dxGantt-dialogDeleteDependencyMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO",
"dxGantt-undo": "TODO",
"dxGantt-redo": "TODO",
"dxGantt-expandAll": "TODO",
"dxGantt-collapseAll": "TODO",
"dxGantt-addNewTask": "TODO",
"dxGantt-deleteSelectedTask": "TODO",
"dxGantt-zoomIn": "TODO",
"dxGantt-zoomOut": "TODO",
"dxGantt-fullScreen": "TODO"
}
})
});
|
import {READ_BREWSESSION_STARTED, READ_BREWSESSION_SUCCEEDED, READ_BREWSESSION_FAILED,
BREWSESSION_STARTSTOP_STARTED, BREWSESSION_STARTSTOP_SUCCEEDED, BREWSESSION_STARTSTOP_FAILED,
READ_BREWSESSION_DATA_STARTED, READ_BREWSESSION_DATA_SUCCEEDED, READ_BREWSESSION_DATA_FAILED,
UPDATE_BREWSESSIONSTATUS_FIELD} from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
export default function brewSessionStatusReducer(state = initialState.brewSessionStatus, action) {
let newState;
switch (action.type) {
case READ_BREWSESSION_STARTED:
return state;
case READ_BREWSESSION_SUCCEEDED:
newState = objectAssign({}, state);
newState.isBrewSessionRunning = action.status.isBrewSessionRunning;
if (newState.isBrewSessionRunning) {
newState.sessionName = action.status.sessionName;
newState.mashTemp = Math.round(Number(action.status.mashTemp * 9/5 + 32).toFixed(2));
newState.mashHoldTime = action.status.mashHoldTime;
}
return newState;
case READ_BREWSESSION_FAILED:
newState = objectAssign({}, state);
newState.isBrewSessionRunning = false;
// TODO: set some kind of error message to return and show
return newState;
case BREWSESSION_STARTSTOP_STARTED:
return state;
case BREWSESSION_STARTSTOP_SUCCEEDED:
// newState = objectAssign({}, state);
// if (action.status.action == 'start') {
// newState.isBrewSessionRunning = false;
// }
// else {
// newState.isBrewSessionRunning = true;
// }
// return newState;
// We're already updating the status on a timer anyway.
// Not sure we need to do anything here.
return state;
case BREWSESSION_STARTSTOP_FAILED:
// TODO: set some kind of error message to return and show
console.log('BREWSESSION_STARTSTOP_FAILED ERROR');
return state;
case READ_BREWSESSION_DATA_STARTED:
return state;
case READ_BREWSESSION_DATA_SUCCEEDED:
newState = objectAssign({}, state);
newState.data = action.data;
return newState;
case READ_BREWSESSION_DATA_FAILED:
// TODO: set some kind of error message to return and show
console.log('READ_BREWSESSION_DATA_FAILED ERROR');
return state;
case UPDATE_BREWSESSIONSTATUS_FIELD:
newState = objectAssign({}, state);
newState[action.fieldName] = action.value;
return newState;
default:
return state;
}
} |
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import LoadingIcon from '../components/LoadingIcon';
class LoginRedirect extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const loginRedirectUrl = localStorage.getItem('loginRedirectUrl') || '%2F';
browserHistory.replace(loginRedirectUrl);
}
render() {
return (
<div>
<LoadingIcon />
重新導向中
</div>
);
}
}
export default LoginRedirect;
|
var renderer;
$(function () {
var dashStyles = [
'Solid',
'ShortDash',
'ShortDot',
'ShortDashDot',
'ShortDashDotDot',
'Dot',
'Dash',
'LongDash',
'DashDot',
'LongDashDot',
'LongDashDotDot'
];
renderer = new Highcharts.Renderer(
$('#container')[0],
400,
400
);
$.each(dashStyles, function (i, dashStyle) {
renderer.text(dashStyle, 10, 30 * i + 20)
.add();
renderer.path(['M', 10, 30 * i + 23, 'L', 390, 30 * i + 23])
.attr({
'stroke-width': 2,
stroke: 'black',
dashstyle: dashStyle
})
.add();
});
}); |
(function() {
var app = angular.module('dashboardController', ['dashboardService', 'dashboardFactory']); //creating new module
/*create new controller; [] is a list of dependencies to fetch, and pass them all into a constructor function*/
app.controller('DashboardController', [ '$scope', 'DashboardService', 'DashboardFactory', 'EventService', function($scope, DashboardService, DashboardFactory, EventService) {
//put all logic in controller
//$scope will stores data
//$scope.message = "A new message";
//$scope.event = {startTimeDate:"string"} //will store startTimeDate inside of event, and it will store event inside of scope
//$scope.event = {startTimeDate: event.startTimeDate}; //will store startTimeDate inside of event, and it will store event inside of scope
this.selectedTab = "yourEvents";
$scope.currentDate = new Date(); //returns current date and time
// Call service function with a callback. The first argument
// is the data you want to pass to the Http request, and the
// second argument is a function to be called when the Http
// request returns with a successful status code. Then reassign
// $scope.event to the new event object we receive from the Http
// response.
/* EventService.getEvent({id: 1}, function(response) {
$scope.event = response.event;
});
EventService.getEvent({startTimeDate: event.startTimeDate}, function(response){
$scope.event = response.event;
}); */
// $scope.user = {
// firstName : "",
// middleName : "",
// lastName : "",
// description : "",
// picture: "",
// email : "",
// birthday : "",
// age : "",
// city : "",
// state : "",
// zipCode : "",
// phoneNum : "",
// googlePlus : "",
// facebook : "",
// linkedIn : "",
// twitter : "",
// volunteeredTo : [{id: ""}, {id: ""}],
// creatorOf : [{id: ""}, {id: ""}],
// organizerOf : [{id: ""}, {id: ""}],
// subscribedTo : [{id: ""}, {id: ""}],
// interests : [{type: ""}, {type: ""}]
// };
$scope.user = {
firstName : "",
middleName : "",
lastName : "",
description : "",
picture: "",
email : "",
birthday : "",
age : "",
city : "",
state : "",
zipCode : "",
phoneNum : "",
googlePlus : "",
facebook : "",
linkedIn : "",
twitter : "",
volunteeredTo : [//yourGroupEvents: [{groupEventTitle: 'Event 1', time: 'Time 1', date: 'Date 1'},
//{groupEventTitle: 'Event 2', time: 'Time 2', date: 'Date 2'}]
{picture : "//placekitten.com/g/500/500/",
//volunteered: null,
startTimeDate: "2015-08-26T18:50:10.111Z",
endTimeDate: "2015-09-26T18:50:10.111Z",
name: 'Event 2', volunteers: [{id: '49', firstName: 'Kris', lastName: 'Tadlok', picture: 'https://pbs.twimg.com/profile_images/2382660015/ducati_dog_profile.gif'}, {id: '50', firstName: 'Vadzim', lastName: 'Savenok', picture: 'https://lh3.googleusercontent.com/-fBggJD3y3Go/UgAEKqWlLkI/AAAAAAAAAAo/tjfjrjykw3Q/s426/BigDog_GooglePlusProfile.jpg'}],
maxVolunteers: '25', interests: [{type: "Animals"}, {type: "Education"}, {type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]},
{picture : "//placekitten.com/g/501/500/",
startTimeDate: "2016-08-26T18:50:10.111Z",
endTimeDate: "2016-09-26T18:50:10.111Z",
name: 'Event 3', volunteers: [{name: 'Anthony'}, {name: 'Huy'}, {name: 'Shane'}, {name: 'John'}, {name: 'Vadzim'}, {name: 'Kris'}],
maxVolunteers: '35', interests: [{type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]}],
creatorOf : [{id: ""}, {id: ""}],
organizerOf : [{id: ""}, {id: ""}],
subscribedTo : [//yourGroupEvents: [{groupEventTitle: 'Event 1', time: 'Time 1', date: 'Date 1'},
//{groupEventTitle: 'Event 2', time: 'Time 2', date: 'Date 2'}]
{picture : "//placekitten.com/g/500/500/",
startTimeDate: "2015-08-26T18:50:10.111Z",
endTimeDate: "2015-09-26T18:50:10.111Z",
name: 'Event 1', volunteers: [{id: '49', firstName: 'Kris', lastName: 'Tadlok', picture: 'https://pbs.twimg.com/profile_images/2382660015/ducati_dog_profile.gif'}, {id: '50', firstName: 'Vadzim', lastName: 'Savenok', picture: 'https://lh3.googleusercontent.com/-fBggJD3y3Go/UgAEKqWlLkI/AAAAAAAAAAo/tjfjrjykw3Q/s426/BigDog_GooglePlusProfile.jpg'}],
maxVolunteers: '25', interests: [{type: "Animals"}, {type: "Education"}, {type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]},
{picture : "//placekitten.com/g/501/500/",
startTimeDate: "2015-08-26T18:50:10.111Z",
endTimeDate: "2015-09-26T18:50:10.111Z",
name: 'Event 2', volunteers: [{id: '49', firstName: 'Kris', lastName: 'Tadlok', picture: 'https://pbs.twimg.com/profile_images/2382660015/ducati_dog_profile.gif'}, {id: '50', firstName: 'Vadzim', lastName: 'Savenok', picture: 'https://lh3.googleusercontent.com/-fBggJD3y3Go/UgAEKqWlLkI/AAAAAAAAAAo/tjfjrjykw3Q/s426/BigDog_GooglePlusProfile.jpg'}],
maxVolunteers: '25', interests: [{type: "Animals"}, {type: "Education"}, {type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]},
{picture : "//placekitten.com/g/501/500/",
startTimeDate: "2016-08-26T18:50:10.111Z",
endTimeDate: "2016-09-26T18:50:10.111Z",
name: 'Event 3', volunteers: [{name: 'Anthony'}, {name: 'Huy'}, {name: 'Shane'}, {name: 'John'}, {name: 'Vadzim'}, {name: 'Kris'}],
maxVolunteers: '35', interests: [{type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]}],
interests : [{type: ""}, {type: ""}]
};
$scope.upcomingEvents = [//yourGroupEvents: [{groupEventTitle: 'Event 1', time: 'Time 1', date: 'Date 1'},
//{groupEventTitle: 'Event 2', time: 'Time 2', date: 'Date 2'}]
{picture : "//placekitten.com/g/500/500/",
startTimeDate: "2015-08-26T18:50:10.111Z",
endTimeDate: "2015-09-26T18:50:10.111Z",
name: 'Event 1', volunteers: [{id: '49', firstName: 'Kris', lastName: 'Tadlok', picture: 'https://pbs.twimg.com/profile_images/2382660015/ducati_dog_profile.gif'}, {id: '50', firstName: 'Vadzim', lastName: 'Savenok', picture: 'https://lh3.googleusercontent.com/-fBggJD3y3Go/UgAEKqWlLkI/AAAAAAAAAAo/tjfjrjykw3Q/s426/BigDog_GooglePlusProfile.jpg'}],
maxVolunteers: '25', interests: [{type: "Animals"}, {type: "Education"}, {type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]},
{picture : "//placekitten.com/g/501/500/",
startTimeDate: "2016-08-26T18:50:10.111Z",
endTimeDate: "2016-09-26T18:50:10.111Z",
name: 'Event 2', volunteers: [{name: 'Anthony'}, {name: 'Huy'}, {name: 'Shane'}, {name: 'John'}, {name: 'Vadzim'}, {name: 'Kris'}],
maxVolunteers: '35', interests: [{type: "Environment"}, {type: "People"}, {type: "Recreation"}, {type: "Technology"}, {type: "Youth"}]}];
/***************************************************************************
* Functions that controls tabs for searching
**************************************************************************/
$scope.setCurrentTab = function(category) {
this.selectedTab = category;
}
$scope.getCurrentTab = function(category) {
if (this.selectedTab === category)
return true;
else
return false;
}
/*
* Checks if there are more than 1 upcoming events, the view will display
* arrows to move across events if that is the case.
*/
$scope.hasMultipleEvents = function() {
if ($scope.upcomingEvents != null){
if ($scope.upcomingEvents.length >= 2)
return true;
else
return false;
}
else
return false;
}
/*
* Checks if the gorup has a picture, the view will display a default
* picture if no picture is found.
*/
$scope.hasPicture = function(type1, index1, type2, index2) {
switch(type1){
case "group":
if ($scope.group.picture != null){
if ($scope.group.picture.length > 0)
return true;
else
return false;
}
else{
if ($scope.loaded == false)
return true;
else
return false;
}
case "organizer":
if ($scope.group.organizersBuilt != null){
if ($scope.group.organizersBuilt[index1].organizers[index2].picture != null){
if ($scope.group.organizersBuilt[index1].organizers[index2].picture.length > 0)
return true;
else
return false;
}
else
return false;
}
case "organizerXS":
if ($scope.group.organizersBuiltXS != null){
if ($scope.group.organizersBuiltXS[index1].organizers[index2].picture != null){
if ($scope.group.organizersBuiltXS[index1].organizers[index2].picture.length > 0)
return true;
else
return false;
}
else
return false;
}
case "subscriber":
if ($scope.group.subscribers != null){
if ($scope.group.subscribers[index1].picture != null){
if ($scope.group.subscribers[index1].picture.length > 0)
return true;
else
return false;
}
else
return false;
}
case "event":
if ($scope.upcomingEvents != null){
if (type2 != null) {
switch(type2){
case "volunteer":
if ($scope.upcomingEvents[index1].volunteers[index2].picture != null) {
if ($scope.upcomingEvents[index1].volunteers[index2].picture.length > 0)
return true;
else
return false;
}
}
}
else{
if ($scope.upcomingEvents[index1].picture != null){
if ($scope.upcomingEvents[index1].picture.length > 0)
return true;
else
return false;
}
else
return false;
}
}
}
}
}]);
})();
/*
user: {
firstName : String,
middleName : String,
lastName : String,
description : String,
picture: String,
email : String,
birthday : Date,
age : Number,
location : {city: String, state: String, zipcode: String},
phoneNum : Number,
googlePlus : String,
facebook : String,
linkedIn : String,
twitter : String,
volunteeredTo : [{id: String}, {id: String}, ...],
creatorOf : [{id: String}, {id: String}, ...],
organizerOf : [{id: String}, {id: String}, ...],
subscribedTo : [{id: String}, {id: String}, ...],
interests : [{type: String}, {type: String}, ...]
}
*/
/*
group: {
id : String,
name : String,
picture : String,
creationDate : String,
location : [{city: String, state: String, zipcode: String}, ...],
description : String,
googlePlusURL : String,
facebookURL : String,
linkInURL : String,
twitterURL: String,
personalWebsiteURL: String,
events: [{id: String}, {id: String}, ...],
organizers: [{id: String}, {id: String}, ...],
subscribers: [{id: String}, {id: String}, ...],
interests: [{type: String}, {type: String}, ...]
}
*/
/*
event: {
id: String,
creatorId: String,
groupId: String,
name: String,
description: String,
picture: String,
creationDate: DateTime,
startTimeDate: DateTime,
endTimeDate: DateTime,
location : {street: String, city: String, state: String, zipcode: String},
maxVolunteers: Number,
volunteers: [{id: String}, {id: String}, ...],
interests: [{type: String}, {type: String}, ...]
}
*/
|
/**
* @author Garrett Johnson / http://gkjohnson.github.io/
* https://github.com/gkjohnson/ply-exporter-js
*
* Usage:
* var exporter = new THREE.PLYExporter();
*
* // second argument is a list of options
* exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ] });
*
* Format Definition:
* http://paulbourke.net/dataformats/ply/
*/
THREE.PLYExporter = function () {};
THREE.PLYExporter.prototype = {
constructor: THREE.PLYExporter,
parse: function ( object, onDone, options ) {
if ( onDone && typeof onDone === 'object' ) {
console.warn( 'THREE.PLYExporter: The options parameter is now the third argument to the "parse" function. See the documentation for the new API.' );
options = onDone;
onDone = undefined;
}
// Iterate over the valid meshes in the object
function traverseMeshes( cb ) {
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
var mesh = child;
var geometry = mesh.geometry;
if ( geometry.isGeometry === true ) {
geometry = geomToBufferGeom.get( geometry );
}
if ( geometry.isBufferGeometry === true ) {
if ( geometry.getAttribute( 'position' ) !== undefined ) {
cb( mesh, geometry );
}
}
}
} );
}
// Default options
var defaultOptions = {
binary: false,
excludeAttributes: [] // normal, uv, color, index
};
options = Object.assign( defaultOptions, options );
var excludeAttributes = options.excludeAttributes;
var geomToBufferGeom = new WeakMap();
var includeNormals = false;
var includeColors = false;
var includeUVs = false;
var includeIndices = true;
// count the vertices, check which properties are used,
// and cache the BufferGeometry
var vertexCount = 0;
var faceCount = 0;
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
var mesh = child;
var geometry = mesh.geometry;
if ( geometry.isGeometry === true ) {
var bufferGeometry = geomToBufferGeom.get( geometry ) || new THREE.BufferGeometry().setFromObject( mesh );
geomToBufferGeom.set( geometry, bufferGeometry );
geometry = bufferGeometry;
}
if ( geometry.isBufferGeometry === true ) {
var vertices = geometry.getAttribute( 'position' );
var normals = geometry.getAttribute( 'normal' );
var uvs = geometry.getAttribute( 'uv' );
var colors = geometry.getAttribute( 'color' );
var indices = geometry.getIndex();
if ( vertices === undefined ) {
return;
}
vertexCount += vertices.count;
faceCount += indices ? indices.count / 3 : vertices.count / 3;
if ( normals !== undefined ) includeNormals = true;
if ( uvs !== undefined ) includeUVs = true;
if ( colors !== undefined ) includeColors = true;
}
}
} );
includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1;
includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1;
includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1;
includeIndices = includeIndices && excludeAttributes.indexOf( 'index' ) === - 1;
if ( includeIndices && faceCount !== Math.floor( faceCount ) ) {
// point cloud meshes will not have an index array and may not have a
// number of vertices that is divisble by 3 (and therefore representable
// as triangles)
console.error(
'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' +
'number of indices is not divisible by 3.'
);
return null;
}
// get how many bytes will be needed to save out the faces
// so we can use a minimal amount of memory / data
var indexByteCount = 1;
if ( vertexCount > 256 ) { // 2^8 bits
indexByteCount = 2;
}
if ( vertexCount > 65536 ) { // 2^16 bits
indexByteCount = 4;
}
var header =
'ply\n' +
`format ${ options.binary ? 'binary_big_endian' : 'ascii' } 1.0\n` +
`element vertex ${vertexCount}\n` +
// position
'property float x\n' +
'property float y\n' +
'property float z\n';
if ( includeNormals === true ) {
// normal
header +=
'property float nx\n' +
'property float ny\n' +
'property float nz\n';
}
if ( includeUVs === true ) {
// uvs
header +=
'property float s\n' +
'property float t\n';
}
if ( includeColors === true ) {
// colors
header +=
'property uchar red\n' +
'property uchar green\n' +
'property uchar blue\n';
}
if ( includeIndices === true ) {
// faces
header +=
`element face ${faceCount}\n` +
`property list uchar uint${ indexByteCount * 8 } vertex_index\n`;
}
header += 'end_header\n';
// Generate attribute data
var vertex = new THREE.Vector3();
var normalMatrixWorld = new THREE.Matrix3();
var result = null;
if ( options.binary === true ) {
// Binary File Generation
var headerBin = new TextEncoder().encode( header );
// 3 position values at 4 bytes
// 3 normal values at 4 bytes
// 3 color channels with 1 byte
// 2 uv values at 4 bytes
var vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) );
// 1 byte shape desciptor
// 3 vertex indices at ${indexByteCount} bytes
var faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0;
var output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) );
new Uint8Array( output.buffer ).set( headerBin, 0 );
var vOffset = headerBin.length;
var fOffset = headerBin.length + vertexListLength;
var writtenVertices = 0;
traverseMeshes( function ( mesh, geometry ) {
var vertices = geometry.getAttribute( 'position' );
var normals = geometry.getAttribute( 'normal' );
var uvs = geometry.getAttribute( 'uv' );
var colors = geometry.getAttribute( 'color' );
var indices = geometry.getIndex();
normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
for ( var i = 0, l = vertices.count; i < l; i ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
vertex.applyMatrix4( mesh.matrixWorld );
// Position information
output.setFloat32( vOffset, vertex.x );
vOffset += 4;
output.setFloat32( vOffset, vertex.y );
vOffset += 4;
output.setFloat32( vOffset, vertex.z );
vOffset += 4;
// Normal information
if ( includeNormals === true ) {
if ( normals != null ) {
vertex.x = normals.getX( i );
vertex.y = normals.getY( i );
vertex.z = normals.getZ( i );
vertex.applyMatrix3( normalMatrixWorld );
output.setFloat32( vOffset, vertex.x );
vOffset += 4;
output.setFloat32( vOffset, vertex.y );
vOffset += 4;
output.setFloat32( vOffset, vertex.z );
vOffset += 4;
} else {
output.setFloat32( vOffset, 0 );
vOffset += 4;
output.setFloat32( vOffset, 0 );
vOffset += 4;
output.setFloat32( vOffset, 0 );
vOffset += 4;
}
}
// UV information
if ( includeUVs === true ) {
if ( uvs != null ) {
output.setFloat32( vOffset, uvs.getX( i ) );
vOffset += 4;
output.setFloat32( vOffset, uvs.getY( i ) );
vOffset += 4;
} else if ( includeUVs !== false ) {
output.setFloat32( vOffset, 0 );
vOffset += 4;
output.setFloat32( vOffset, 0 );
vOffset += 4;
}
}
// Color information
if ( includeColors === true ) {
if ( colors != null ) {
output.setUint8( vOffset, Math.floor( colors.getX( i ) * 255 ) );
vOffset += 1;
output.setUint8( vOffset, Math.floor( colors.getY( i ) * 255 ) );
vOffset += 1;
output.setUint8( vOffset, Math.floor( colors.getZ( i ) * 255 ) );
vOffset += 1;
} else {
output.setUint8( vOffset, 255 );
vOffset += 1;
output.setUint8( vOffset, 255 );
vOffset += 1;
output.setUint8( vOffset, 255 );
vOffset += 1;
}
}
}
if ( includeIndices === true ) {
// Create the face list
var faceIndexFunc = `setUint${indexByteCount * 8}`;
if ( indices !== null ) {
for ( var i = 0, l = indices.count; i < l; i += 3 ) {
output.setUint8( fOffset, 3 );
fOffset += 1;
output[ faceIndexFunc ]( fOffset, indices.getX( i + 0 ) + writtenVertices );
fOffset += indexByteCount;
output[ faceIndexFunc ]( fOffset, indices.getX( i + 1 ) + writtenVertices );
fOffset += indexByteCount;
output[ faceIndexFunc ]( fOffset, indices.getX( i + 2 ) + writtenVertices );
fOffset += indexByteCount;
}
} else {
for ( var i = 0, l = vertices.count; i < l; i += 3 ) {
output.setUint8( fOffset, 3 );
fOffset += 1;
output[ faceIndexFunc ]( fOffset, writtenVertices + i );
fOffset += indexByteCount;
output[ faceIndexFunc ]( fOffset, writtenVertices + i + 1 );
fOffset += indexByteCount;
output[ faceIndexFunc ]( fOffset, writtenVertices + i + 2 );
fOffset += indexByteCount;
}
}
}
// Save the amount of verts we've already written so we can offset
// the face index on the next mesh
writtenVertices += vertices.count;
} );
result = output.buffer;
} else {
// Ascii File Generation
// count the number of vertices
var writtenVertices = 0;
var vertexList = '';
var faceList = '';
traverseMeshes( function ( mesh, geometry ) {
var vertices = geometry.getAttribute( 'position' );
var normals = geometry.getAttribute( 'normal' );
var uvs = geometry.getAttribute( 'uv' );
var colors = geometry.getAttribute( 'color' );
var indices = geometry.getIndex();
normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
// form each line
for ( var i = 0, l = vertices.count; i < l; i ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
vertex.applyMatrix4( mesh.matrixWorld );
// Position information
var line =
vertex.x + ' ' +
vertex.y + ' ' +
vertex.z;
// Normal information
if ( includeNormals === true ) {
if ( normals != null ) {
vertex.x = normals.getX( i );
vertex.y = normals.getY( i );
vertex.z = normals.getZ( i );
vertex.applyMatrix3( normalMatrixWorld );
line += ' ' +
vertex.x + ' ' +
vertex.y + ' ' +
vertex.z;
} else {
line += ' 0 0 0';
}
}
// UV information
if ( includeUVs === true ) {
if ( uvs != null ) {
line += ' ' +
uvs.getX( i ) + ' ' +
uvs.getY( i );
} else if ( includeUVs !== false ) {
line += ' 0 0';
}
}
// Color information
if ( includeColors === true ) {
if ( colors != null ) {
line += ' ' +
Math.floor( colors.getX( i ) * 255 ) + ' ' +
Math.floor( colors.getY( i ) * 255 ) + ' ' +
Math.floor( colors.getZ( i ) * 255 );
} else {
line += ' 255 255 255';
}
}
vertexList += line + '\n';
}
// Create the face list
if ( includeIndices === true ) {
if ( indices !== null ) {
for ( var i = 0, l = indices.count; i < l; i += 3 ) {
faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`;
faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`;
faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`;
}
} else {
for ( var i = 0, l = vertices.count; i < l; i += 3 ) {
faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`;
}
}
faceCount += indices ? indices.count / 3 : vertices.count / 3;
}
writtenVertices += vertices.count;
} );
result = `${ header }${vertexList}\n${ includeIndices ? `${faceList}\n` : '' }`;
}
if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) );
return result;
}
};
|
/**
* Created by granted on 15.04.14.
*/
define(
function () {
"use strict";
var topic = {
feed: {},
subscribe: function (message, callback) {
if (!topic.feed[message]) {
topic.feed[message] = [];
}
var id = topic.feed[message].push(callback);
return function () {
topic.unsubscribe(message, id - 1);
};
},
publish: function (message, data) {
var count = 0;
if (topic.feed[message]) {
topic.feed[message].forEach(function (callback) {
count++;
callback(data || []);
});
}
return count;
},
unsubscribe: function (message, id) {
topic.feed[message].splice(id, 1);
},
clear: function (message) {
if (message) {
if (topic.feed[message]) {
delete topic.feed[message];
}
} else {
topic.feed = {};
}
}
};
return topic;
}
); |
define(['fraction'], function(Fraction) {
describe("Fraction less than", function() {
it("should compare two fractions", function() {
var a = new Fraction(1, 4);
var b = new Fraction(1, 2);
expect(a.lt(b))
.toBe(true);
expect(b.lt(a))
.toBe(false);
});
it("should compare a fraction to an integer", function() {
var a = new Fraction(1, 4);
expect(a.lt(1))
.toBe(true);
expect(a.lt(0))
.toBe(false);
});
it("should compare a fraction to an float", function() {
var a = new Fraction(1, 4);
expect(a.lt(0.5))
.toBe(true);
expect(a.lt(0.1))
.toBe(false);
});
});
});
|
/*!
* devextreme-angular
* Version: 16.2.5
* Build date: Tue Feb 28 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file in the root of the project for details.
*
* https://github.com/DevExpress/devextreme-angular
*/
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var core_1 = require('@angular/core');
var nested_option_1 = require('../../core/nested-option');
var nested_option_2 = require('../../core/nested-option');
var DxoPagerComponent = (function (_super) {
__extends(DxoPagerComponent, _super);
function DxoPagerComponent(parentOptionHost, optionHost) {
_super.call(this);
parentOptionHost.setNestedOption(this);
optionHost.setHost(this, this._fullOptionPath.bind(this));
}
Object.defineProperty(DxoPagerComponent.prototype, "allowedPageSizes", {
get: function () {
return this._getOption('allowedPageSizes');
},
set: function (value) {
this._setOption('allowedPageSizes', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "infoText", {
get: function () {
return this._getOption('infoText');
},
set: function (value) {
this._setOption('infoText', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "showInfo", {
get: function () {
return this._getOption('showInfo');
},
set: function (value) {
this._setOption('showInfo', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "showNavigationButtons", {
get: function () {
return this._getOption('showNavigationButtons');
},
set: function (value) {
this._setOption('showNavigationButtons', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "showPageSizeSelector", {
get: function () {
return this._getOption('showPageSizeSelector');
},
set: function (value) {
this._setOption('showPageSizeSelector', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "visible", {
get: function () {
return this._getOption('visible');
},
set: function (value) {
this._setOption('visible', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxoPagerComponent.prototype, "_optionPath", {
get: function () {
return 'pager';
},
enumerable: true,
configurable: true
});
DxoPagerComponent.decorators = [
{ type: core_1.Component, args: [{
selector: 'dxo-pager',
template: '',
styles: [''],
providers: [nested_option_1.NestedOptionHost]
},] },
];
DxoPagerComponent.ctorParameters = function () { return [
{ type: nested_option_1.NestedOptionHost, decorators: [{ type: core_1.SkipSelf }, { type: core_1.Host },] },
{ type: nested_option_1.NestedOptionHost, decorators: [{ type: core_1.Host },] },
]; };
DxoPagerComponent.propDecorators = {
'allowedPageSizes': [{ type: core_1.Input },],
'infoText': [{ type: core_1.Input },],
'showInfo': [{ type: core_1.Input },],
'showNavigationButtons': [{ type: core_1.Input },],
'showPageSizeSelector': [{ type: core_1.Input },],
'visible': [{ type: core_1.Input },],
};
return DxoPagerComponent;
}(nested_option_2.NestedOption));
exports.DxoPagerComponent = DxoPagerComponent;
var DxoPagerModule = (function () {
function DxoPagerModule() {
}
DxoPagerModule.decorators = [
{ type: core_1.NgModule, args: [{
declarations: [
DxoPagerComponent
],
exports: [
DxoPagerComponent
],
},] },
];
DxoPagerModule.ctorParameters = function () { return []; };
return DxoPagerModule;
}());
exports.DxoPagerModule = DxoPagerModule;
//# sourceMappingURL=pager.js.map |
/**
* Copyright (c) 2014 brian@bevey.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* @author brian@bevey.org
* @fileoverview Unit test for devices/enviro/parser.js
*/
exports.enviroParserTest = {
parser : function (test) {
'use strict';
var enviroParser = require(__dirname + '/../../../../devices/enviro/parser'),
markup = '<h1>Foo</h1> <ul>{{ENVIRO_DYNAMIC}}</ul>',
value = { report : [
{ type : 'dogs', value : 2.2, units : 'dgs', max : 5, high : 2, time : 1283273077000 },
{ type : 'cats', value : 1.2, units : 'cts', max : 2.5, high : 1, time : 1283273077000 },
{ type : 'falcons', value : 500, units : 'flk', max : 1000, high : 200, time : 1283273077000 }
]},
fragments = { report : '<li>{{ENVIRO_TYPE}}: {{ENVIRO_VALUE}}{{ENVIRO_UNITS}}</li>',
graph : '<span>{{MAX_VALUE}} : {{PERCENT_QUALITY}}</span>' },
goodMarkup = enviroParser.enviro('dummy', markup, 'ok', value, fragments),
noValue = enviroParser.enviro('dummy', markup, 'ok', 'API Choked', fragments);
test.strictEqual(goodMarkup.indexOf('{{'), -1, 'All values replaced');
test.notStrictEqual(goodMarkup.indexOf('<li>dogs: 2.2dgs'), -1, 'Passed markup validated 1');
test.notStrictEqual(goodMarkup.indexOf('<li>cats: 1.2cts'), -1, 'Passed markup validated 2');
test.notStrictEqual(goodMarkup.indexOf('<li>falcons: 500flk'), -1, 'Passed markup validated 3');
test.strictEqual(noValue.indexOf('{{'), -1, 'All values replaced');
test.done();
}
};
|
//This is title screen function
//Basically
game.TitleScreen = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function () {
me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('title-screen')), -10);
me.game.world.addChild(new (me.Renderable.extend({
init: function () {
this._super(me.Renderable, 'init', [270, 240, 300, 50]);
this.font = new me.Font("PolybiusCPU", 46, "White");
me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true);
},
draw: function (renderer) {
this.font.draw(renderer.getContext(), ">Start a new game", this.pos.x, this.pos.y);
},
update: function (dt) {
return true;
},
newGame: function () {
me.input.releasePointerEvent('pointerdown', this);
me.state.change(me.state.NEW);
}
})));
me.game.world.addChild(new (me.Renderable.extend({
init: function () {
this._super(me.Renderable, 'init', [380, 340, 250, 50]);
this.font = new me.Font("PolybiusCPU", 46, "White");
me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true);
},
draw: function (renderer) {
this.font.draw(renderer.getContext(), ">Continue", this.pos.x, this.pos.y);
},
update: function (dt) {
return true;
},
newGame: function () {
me.input.releasePointerEvent('pointerdown', this);
me.state.change(me.state.LOAD);
}
})));
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function () {
}
});
|
var reduction__base_8h =
[
[ "intrusive_ptr_add_ref", "namespacehryky_1_1reduction.html#ab59dece4af8e91c10781e3b092c06d1b", null ],
[ "intrusive_ptr_release", "namespacehryky_1_1reduction.html#ab54d3281488314c37ed3906b45c8f866", null ],
[ "operator<<", "namespacestd.html#a8da2f2d5fa728f80513c463b31415f89", null ]
]; |
var app = require('express')(),
wizard = require('hmpo-form-wizard'),
steps = require('./steps'),
fields = require('./fields');
app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' }));
app.use(wizard(steps, fields, {
controller: require('../../../controllers/form'),
templatePath: 'prototype_171127/overseas-not-eligible' }));
module.exports = app;
|
version https://git-lfs.github.com/spec/v1
oid sha256:2cd487fcdcaa1f3fbc0c07b3108e563a79a40af008f4973858abe26314de4160
size 2036
|
// flow-typed signature: 1b1ded04c0f4cac847f8e4e7bd14dc0a
// flow-typed version: <<STUB>>/eslint-config-airbnb_v14.1.0/flow_v0.40.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-config-airbnb'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'eslint-config-airbnb' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'eslint-config-airbnb/base' {
declare module.exports: any;
}
declare module 'eslint-config-airbnb/legacy' {
declare module.exports: any;
}
declare module 'eslint-config-airbnb/rules/react-a11y' {
declare module.exports: any;
}
declare module 'eslint-config-airbnb/rules/react' {
declare module.exports: any;
}
declare module 'eslint-config-airbnb/test/test-base' {
declare module.exports: any;
}
declare module 'eslint-config-airbnb/test/test-react-order' {
declare module.exports: any;
}
// Filename aliases
declare module 'eslint-config-airbnb/base.js' {
declare module.exports: $Exports<'eslint-config-airbnb/base'>;
}
declare module 'eslint-config-airbnb/index' {
declare module.exports: $Exports<'eslint-config-airbnb'>;
}
declare module 'eslint-config-airbnb/index.js' {
declare module.exports: $Exports<'eslint-config-airbnb'>;
}
declare module 'eslint-config-airbnb/legacy.js' {
declare module.exports: $Exports<'eslint-config-airbnb/legacy'>;
}
declare module 'eslint-config-airbnb/rules/react-a11y.js' {
declare module.exports: $Exports<'eslint-config-airbnb/rules/react-a11y'>;
}
declare module 'eslint-config-airbnb/rules/react.js' {
declare module.exports: $Exports<'eslint-config-airbnb/rules/react'>;
}
declare module 'eslint-config-airbnb/test/test-base.js' {
declare module.exports: $Exports<'eslint-config-airbnb/test/test-base'>;
}
declare module 'eslint-config-airbnb/test/test-react-order.js' {
declare module.exports: $Exports<'eslint-config-airbnb/test/test-react-order'>;
}
|
(function (window, undefined) {
'use strict';
// Copyright 2011, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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.
var threshold = -27; // dB
var headroom = 21; // dB
function e4(x, k) {
return 1.0 - Math.exp(-k * x);
}
function dBToLinear(db) {
return Math.pow(10.0, 0.05 * db);
}
function shape(x) {
var linearThreshold = dBToLinear(threshold);
var linearHeadroom = dBToLinear(headroom);
var maximum = 1.05 * linearHeadroom * linearThreshold;
var kk = (maximum - linearThreshold);
var sign = x < 0 ? -1 : +1;
var absx = Math.abs(x);
var shapedInput = absx < linearThreshold ? absx : linearThreshold + kk * e4(absx - linearThreshold, 1.0 / kk);
shapedInput *= sign;
return shapedInput;
}
function generateColortouchCurve(curve) {
var n = 65536;
var n2 = n / 2;
for (var i = 0; i < n2; ++i) {
var x = i / n2;
x = shape(x);
curve[n2 + i] = x;
curve[n2 - i - 1] = -x;
}
return curve;
}
function generateMirrorCurve(curve) {
var n = 65536;
var n2 = n / 2;
for (var i = 0; i < n2; ++i) {
x = i / n2;
x = shape(x);
curve[n2 + i] = x;
curve[n2 - i - 1] = x;
}
return curve;
}
function createShaperCurve() {
var driveShaper = new Float32Array(4096);
for (var i = 0; i < 1024; i++) {
// "bottom" half of response curve is flat
driveShaper[2048 + i] = driveShaper[2047 - i] = i / 2048;
// "top" half of response curve is log
driveShaper[3072 + i] = driveShaper[1023 - i] = Math.sqrt((i + 1024) / 1024) / 2;
}
return driveShaper;
}
function WaveShaper(context) {
this.context = context;
var waveshaper = context.createWaveShaper();
var preGain = context.createGain();
var postGain = context.createGain();
preGain.connect(waveshaper);
waveshaper.connect(postGain);
this.input = preGain;
this.output = postGain;
this.waveshaper = waveshaper;
var curve = new Float32Array(65536); // FIXME: share across instances
generateColortouchCurve(curve);
waveshaper.curve = curve;
// waveshaper.curve = createShaperCurve();
}
WaveShaper.prototype.setDrive = function (drive) {
this.input.gain.value = drive;
var postDrive = Math.pow(1 / drive, 0.6);
this.output.gain.value = postDrive;
}
window.WaveShaper = WaveShaper;
})(window); |
import expect from 'expect';
import { fromJS } from 'immutable';
import appMenuContainerReducer from '../reducer';
describe('appMenuContainerReducer', () => {
it('returns the initial state', () => {
expect(appMenuContainerReducer(undefined, {})).toEqual(fromJS({
menu: [],
}));
});
});
|
'use strict'
var assert = require('assert')
var realFoo = require('./samples/foo')
var stubs = {
path: {
extname: function () {},
basename: function () {}
}
}
describe('api', function () {
describe('default export', function () {
var proxyquire = require('..')
it('proxyquire can load', function () {
var proxiedFoo = proxyquire.load('./samples/foo', stubs)
assert.strictEqual(typeof proxiedFoo, 'object')
assert.notStrictEqual(realFoo, proxiedFoo)
})
it('proxyquire can callThru and then load', function () {
var proxiedFoo = proxyquire.callThru().load('./samples/foo', stubs)
assert.strictEqual(typeof proxiedFoo, 'object')
assert.notStrictEqual(realFoo, proxiedFoo)
})
it('proxyquire can noCallThru and then load', function () {
var proxiedFoo = proxyquire.noCallThru().load('./samples/foo', stubs)
assert.strictEqual(typeof proxiedFoo, 'object')
assert.notStrictEqual(realFoo, proxiedFoo)
})
})
})
|
"use strict";
var helpers = require("../../helpers/helpers");
exports["US/Samoa"] = {
"1911" : helpers.makeTestYear("US/Samoa", [
["1911-01-01T11:22:47+00:00", "23:59:59", "LMT", 40968 / 60],
["1911-01-01T11:22:48+00:00", "23:52:48", "SAMT", 690]
]),
"1950" : helpers.makeTestYear("US/Samoa", [
["1950-01-01T11:29:59+00:00", "23:59:59", "SAMT", 690],
["1950-01-01T11:30:00+00:00", "00:30:00", "NST", 660]
]),
"1967" : helpers.makeTestYear("US/Samoa", [
["1967-04-01T10:59:59+00:00", "23:59:59", "NST", 660],
["1967-04-01T11:00:00+00:00", "00:00:00", "BST", 660]
]),
"1983" : helpers.makeTestYear("US/Samoa", [
["1983-11-30T10:59:59+00:00", "23:59:59", "BST", 660],
["1983-11-30T11:00:00+00:00", "00:00:00", "SST", 660]
])
}; |
var through = require('through2');
var gutil = require('gulp-util');
var read = require('read-file');
var PluginError = gutil.PluginError;
const PLUGIN_NAME = 'gulp-append-prepend';
function filesGetContents(filepaths){
if (!(filepaths instanceof Array)) {
filepaths = [filepaths];
}
var filesContents = [];
for(i = 0; i < filepaths.length; i++){
filesContents.push(read.sync(filepaths[i], 'utf8'));
}
return filesContents;
}
function insert(texts, separator, type) {
if(!texts){
throw new PluginError(PLUGIN_NAME, 'Missing text or path !');
}
if (!(texts instanceof Array)) {
texts = [texts];
}
if (type != "append" && type != "prepend") {
throw new PluginError(PLUGIN_NAME, 'Missing type !');
}
if (!separator) {
separator = "\n";
}
var buffers = [];
for (i = 0; i < texts.length; i++) {
if (type == "prepend") {
buffers.push(new Buffer(texts[i].trim()+separator));
}else if(type == "append") {
buffers.push(new Buffer(separator+texts[i].trim()));
}
}
var stream = through.obj(function(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
return cb();
}
if (file.isBuffer()) {
var concat = [];
if (type == "append") {
concat.push(file.contents);
}
for(i = 0; i < buffers.length; i++){
concat.push(buffers[i]);
}
if (type == "prepend") {
concat.push(file.contents);
}
file.contents = Buffer.concat(concat);
}
this.push(file);
cb();
});
return stream;
}
module.exports.appendFile = function(filepath, separator) {
return insert(filesGetContents(filepath), separator, "append");
};
module.exports.prependFile = function(filepath, separator) {
return insert(filesGetContents(filepath), separator, "prepend");
};
module.exports.appendText = function(text, separator) {
return insert(text, separator, "append");
};
module.exports.prependText = function(text, separator) {
return insert(text, separator, "prepend");
}; |
var casper = require('casper').create();
casper.start('http://google.com');
casper.then(function () {
this.clickLabel('தமிழ்', 'a');
});
casper.then(function () {
this.capture('google-lucky.png', {
top: 100,
left: 100,
width: 500,
height: 400
});
});
casper.run();
|
var path = require('path')
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
externals: [
/^animated_gif(\/.+)?$/,
'data-uri-to-blob',
],
}
|
(function($, Drupal)
{
Drupal.behaviors.profilecmd = {
attach: function(context, settings) {
var base_path = Drupal.settings.basePath;
$.getJSON(base_path + 'ReventlovGetProfile',
function(data) {
var selected = [];
var dt = $('#tableprofile').DataTable( {
data: data,
"bFilter" : false,
//"bJQueryUI" : true,
"sPaginationType" : "full_numbers",
"bPaginate": false,
"bInfo": false,
columns: [
//{ title: "select" },
{ title: "profileid" },
{ title: "profilename" },
{ title: "information" },
{ title: "content" },
],
"rowCallback": function( row, data ) {
if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
$(row).addClass('selected');
}
},
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ){
$(nRow).css('color', '#1487d4');
}
});
$('#tableprofile tbody').on('click', 'tr', function() {
console.log(dt.rows('.selected').data());
//$('#testid').text("lili");
});
});
}
};
}(jQuery, Drupal));
|
/*
* grunt-gaps
* https://github.com/cwarden/grunt-gaps
*
* Copyright (c) 2015 Christian G. Warden
* Licensed under the MIT license.
*/
'use strict';
var tmp = require('temporary');
var gaps = require('node-google-apps-script');
var del = require('del');
var fs = require('fs-extra');
var _ = require('underscore');
var fetch = function(projectId, dest) {
var fetchDir = new tmp.Dir();
var buildPath = fetchDir.path;
return gaps.download(projectId, buildPath)
.then(function(project) {
var projectPath = project.path;
fs.emptyDirSync(dest);
fs.copySync(projectPath, dest, { clobber: true });
fs.removeSync(buildPath);
});
};
var pushWithoutManifest = function(projectId, srcDir) {
var fetchDir = new tmp.Dir();
var buildPath = fetchDir.path;
// Fetch project and create manifest; overwrite fetched project with srcDir;
// and re-upload.
return fetch(projectId, buildPath)
.then(function(project) {
var toDelete = buildPath + '/*.{js,html}';
del.sync([toDelete], { force: true });
fs.copySync(srcDir, buildPath);
return gaps.upload(buildPath);
})
.then(_.partial(fs.removeSync, buildPath));
};
module.exports = function(grunt) {
grunt.registerMultiTask('gapspull', 'Download Google Apps Script Project', function() {
var projectId = this.data.projectId;
var destDir = this.data.dest;
grunt.log.writeln('Getting ' + projectId + ' to ' + destDir);
var done = this.async();
fetch(projectId, destDir)
.then(done);
});
grunt.registerMultiTask('gapspush', 'Upload Google Apps Script Project', function() {
var projectId = this.data.projectId;
var srcDir = this.data.src;
var done = this.async();
if (projectId) {
grunt.log.writeln('Uploading ' + projectId + ' from ' + srcDir);
return pushWithoutManifest(projectId, srcDir)
.done(done);
} else {
grunt.log.writeln('Uploading ' + srcDir);
return gaps.upload(srcDir)
.done(done);
}
grunt.log.writeln('No src defined');
done();
});
};
|
/**
* Point (on secp256k1)
* ====================
*
* A point is a point on the secp256k1 curve which is the elliptic curve used
* by bitcoin. This code is a wrapper for Fedor Indutny's Point class from his
* elliptic library. This code adds a few minor conveniences, but is mostly the
* same. Since Fedor's code returns points and big numbers that are instances
* of his point and big number classes, we have to wrap all the methods such as
* getX() to return the fullnode point and big number types.
*/
"use strict";
let dependencies = {
BN: require('./bn'),
elliptic: require('elliptic')
};
function inject(deps) {
let BN = deps.BN;
let elliptic = deps.elliptic;
let ec = elliptic.curves.secp256k1;
let _point = ec.curve.point();
let _Point = _point.constructor;
function Point(x, y, isRed) {
if (!(this instanceof Point))
return new Point(x, y, isRed);
_Point.call(this, ec.curve, x, y, isRed);
};
Point.prototype = Object.create(_Point.prototype);
Point.prototype.constructor = Point;
Point.fromX = function(isOdd, x) {
let _point = ec.curve.pointFromX.call(ec.curve, isOdd, x);
let point = Object.create(Point.prototype);
return point.copyFrom(_point);
};
Point.prototype.copyFrom = function(point) {
if (!(point instanceof _Point))
throw new Error('point should be an external point');
Object.keys(point).forEach(function(key) {
this[key] = point[key]
}.bind(this));
return this;
};
Point.prototype.add = function(p) {
p = _Point.prototype.add.call(this, p);
let point = Object.create(Point.prototype);
return point.copyFrom(p);
};
Point.prototype.mul = function(bn) {
let p = _Point.prototype.mul.call(this, bn);
let point = Object.create(Point.prototype);
return point.copyFrom(p);
};
Point.prototype.mulAdd = function(bn1, point, bn2) {
let p = _Point.prototype.mulAdd.call(this, bn1, point, bn2);
point = Object.create(Point.prototype);
return point.copyFrom(p);
};
Point.prototype.getX = function() {
let _x = _Point.prototype.getX.call(this);
let x = Object.create(BN.prototype);
_x.copy(x);
return x;
};
Point.prototype.getY = function() {
let _y = _Point.prototype.getY.call(this);
let y = Object.create(BN.prototype);
_y.copy(y);
return y;
};
Point.prototype.fromX = function(isOdd, x) {
let point = Point.fromX(isOdd, x);
return this.copyFrom(point);
};
// note that this overrides the elliptic point toJSON method
Point.prototype.toJSON = function() {
return {
isOdd: this.getX().isOdd(),
x: this.getX().toString()
};
};
Point.prototype.fromJSON = function(json) {
let point = Point().fromX(json.isOdd, BN().fromString(json.x));
return this.copyFrom(point);
};
Point.prototype.toString = function() {
return JSON.stringify(this.toJSON());
};
Point.prototype.fromString = function(str) {
let json = JSON.parse(str);
let p = Point().fromJSON(json);
return this.copyFrom(p);
};
Point.getG = function() {
let _g = ec.curve.g;
let g = Object.create(Point.prototype);
return g.copyFrom(_g);
};
Point.getN = function() {
return BN(ec.curve.n.toArray());
};
//https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf
Point.prototype.validate = function() {
let p2 = Point.fromX(this.getY().isOdd(), this.getX());
if (!(p2.getY().cmp(this.getY()) === 0))
throw new Error('Invalid y value of public key');
if (!(this.getX().gt(-1) && this.getX().lt(Point.getN()))
||!(this.getY().gt(-1) && this.getY().lt(Point.getN())))
throw new Error('Point does not lie on the curve');
if (!(this.mul(Point.getN()).isInfinity()))
throw new Error('Point times N must be infinity');
return this;
};
return Point;
}
inject = require('./injector')(inject, dependencies);
let Point = inject();
module.exports = Point;
|
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var sinon = require('sinon');
var sinonChai = require("sinon-chai");
var util = require('util');
var Q = require('q');
var Item = require('../models/item').Item;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;
var config = require('../config');
var listRoutes = require('../routes/list');
chai.should();
chai.use(chaiAsPromised);
chai.use(sinonChai);
var staticConfig = config.get();
config.get = function() {
return staticConfig;
}
describe('routes.list', function() {
var item;
var res;
beforeEach(function () {
item = { type : 'movie' };
Item.setupMethods(item);
item.save = sinon.spy(item.save);
item.planNextCheck = sinon.spy(item.planNextCheck);
Item.find = function(condition, sort) {
return Object.getOwnPropertyNames(condition).length === 0 ? Q([item]) : Q([]);
};
Item.save = sinon.stub().returns(Q(this));
res = {
render : sinon.spy(),
redirect : sinon.spy()
};
util.error = sinon.spy();
});
it('should add item', function() {
return listRoutes.add({query : { name : 'Test', type : 'movie', year : 2015, externalId : 'tt000000' } }, res).should.be.fulfilled.then(function() {
return Item.save.should.have.been.calledWithMatch({ name : 'Test', state : ItemStates.wanted });
}).then(function() {
return res.redirect.should.have.been.calledWith('/');
});
});
it('should list items', function() {
return listRoutes.list({}, res).should.be.fulfilled.then(function() {
return res.render.should.have.been.calledWith('list', {
items : [ item ],
icons : require('../models/item').ItemTypeIcons
});
});
});
}); |
import _ from 'lodash';
import QueryParameter from '../exception/QueryParameter';
/**
* Cleans and defaults query parameter
*
* This will only consider attributes, sort and order
*
* @author Selcuk Kekec <skekec@kekecmed.com>
* @param ctx
* @param next
*/
export default async function (ctx, next) {
// Check method first
if (ctx.request.method == 'GET') {
const parameters = ctx.query;
// Check attributes
if (parameters.attributes) {
if (_.isString(parameters.attributes)) {
if (parameters.attributes.indexOf(',') != -1) {
// Attributes are provided as a comma seperated list -> Make a array
parameters.attributes = parameters.attributes.split(',');
} else {
// Attributes include only one entry -> Make a array
parameters.attributes = [parameters.attributes];
}
} else if (!_.isArray(parameters.attributes)) {
throw new QueryParameter('Parameter attributes should be a comma seperated list or an array of attributes.');
}
}
// Check order
if (parameters.order) {
if (!_.isString(parameters.order)) {
throw new QueryParameter('Parameter order should be a string');
}
}
// Check limit
if (parameters.limit) {
if (_.isNaN(_.parseInt(parameters.limit))) {
throw new QueryParameter('Parameter limit should be a integer');
}
parameters.limit = _.parseInt(parameters.limit);
}
// Check offset
if (parameters.offset) {
if (_.isNaN(_.parseInt(parameters.offset))) {
throw new QueryParameter('Parameter offset should be a integer');
}
parameters.offset = _.parseInt(parameters.offset);
}
// Check relations
if (parameters.relations) {
if (parameters.relations === 'true') {
parameters.relations = true;
} else if (parameters.relations === 'false') {
parameters.relations = false;
} else {
throw new QueryParameter('Parameter relations should be one of {true,false}');
}
} else {
// Load relations by default
parameters.relations = true;
}
} else {
throw new Error('cleanQueryString should only used for GET Requests.');
}
await next();
} |
import mockServer from "./fixture-socket-server";
import mockContributionMonths from 'bitcentive/models/fixtures/contribution-months';
import mockOsProjects from 'bitcentive/models/fixtures/os-project';
import mockClientProjects from 'bitcentive/models/fixtures/client-project';
import mockContributor from 'bitcentive/models/fixtures/contributor';
import mockUser from 'bitcentive/models/fixtures/user';
mockContributionMonths( mockServer );
mockOsProjects( mockServer );
mockClientProjects( mockServer );
mockContributor( mockServer );
mockUser( mockServer );
|
'use strict';
describe('Guestbook controllers', function() {
beforeEach(module('guestBook'));
beforeEach(module('guestBook.controllers'));
beforeEach(module('guestBook.services'));
describe('mainController', function() {
var scope, ctrl, $httpBackend,
postObj = {"from":"Author", "text":"Some text", "date":"2012-12-23T12:16:00.582Z"};
beforeEach(inject(function($rootScope, $controller, _$httpBackend_) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
scope.message = { $valid: true };
ctrl = $controller('mainController', {$scope: scope});
}));
it('should post new message', function() {
$httpBackend.when('POST', '/api/messages', postObj).respond([postObj]);
$httpBackend.when('GET', '/partials/messages').respond();
scope.newMessage = {"from":"Author", "text":"Some text", "date":"2012-12-23T12:16:00.582Z"};
scope.postNewMessage();
$httpBackend.flush();
expect(scope.messages).toEqual([postObj]);
});
it('should hide validations after and before post', function() {
expect(scope.showValidationMessage).toBe(false);
scope.postNewMessage();
expect(scope.showValidationMessage).toBe(false);
});
it('new message window inputs should be cleared after post', function() {
$httpBackend.when('POST', '/api/messages', postObj).respond([postObj]);
$httpBackend.when('GET', '/partials/messages').respond();
scope.newMessage = {"from":"Author", "text":"Some text", "date":"2012-12-23T12:16:00.582Z"};
scope.postNewMessage();
$httpBackend.flush();
expect(scope.newMessage.from).toBe('');
expect(scope.newMessage.text).toBe('');
});
it('should hide message window on cancel', function() {
scope.cancelNewMessage();
expect(scope.newMessage.show).toBe(false);
expect(scope.showValidationMessage).toBe(false);
});
});
describe('showMessages', function() {
var scope, ctrl, $httpBackend,
getObj = {"from":"Author", "text":"Some text", "date":"2012-12-23T12:16:00.582Z"};
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
ctrl = $controller('showMessages', {$scope: scope});
}));
it('messages should be empty before fetching data', function() {
expect(scope.messages).toEqual([]);
});
it('messages should be ordered by date descending order', function() {
expect(scope.orderMessages).toBe('-date');
});
it('should fetch message data', function() {
$httpBackend.expectGET('/api/messages').respond([getObj]);
$httpBackend.flush();
scope.getMessages();
expect(scope.messages).toEqual([getObj]);
});
});
describe('adminController', function() {
var scope, admCtrl, showMsgCtrl, $httpBackend,
testObj = {"id":"0","from":"Author", "text":"Some text", "date":"2012-12-23T12:16:00.582Z"};
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
admCtrl = $controller('adminController', {$scope: scope});
showMsgCtrl = $controller('showMessages', {$scope: scope});
}));
it('should delete message with id 0', function() {
scope.messages = [testObj];
$httpBackend.expectDELETE('/api/message/0').respond();
$httpBackend.when('GET', '/partials/messages').respond();
$httpBackend.when('GET', '/api/messages').respond([]);
scope.delete(0);
$httpBackend.flush();
expect(scope.messages).toEqual([]);
});
});
}); |
'use strict'
const httpServer = require('http-server')
let cache = 3600
if (process.env.NODE_ENV === 'production') {
console.log('running in production mode(with caching)-make sure you have "Disable cache (while DevTools is open)" checked in the browser to see the changes while developing')
} else {
cache = -1
}
const server = httpServer.createServer({
root: 'public',
cache: cache,
robots: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
}
})
require('chokidar-socket-emitter')({app: server.server})
server.listen(29017)
|
var minimatch = require("minimatch");
/**
* Factory function for creating a matcher that works against an array of patterns.
* Uses minimatch syntax.
*
* @param patterns Array of patterns to compare against
* @returns {Function} Function will take a single string argument.
* It will return true if the argument matches any of the given patterns.
* It will return false if no patterns match or if any negated pattern matches.
*/
module.exports = function(patterns) {
patterns = patterns || [];
var include = patterns.filter(function(pattern) {
return pattern.charAt(0) != "!";
});
var exclude = patterns.filter(function(pattern) {
return pattern.charAt(0) == "!";
});
return function(test) {
var included = include.some(function(pattern) {
return minimatch(test, pattern, {
nocomment: true
});
});
var excluded = exclude.some(function(pattern) {
return minimatch(test, pattern, {
nocomment: true,
flipNegate: true
});
});
return included && !excluded;
};
}; |
"use strict";
(function() {
Dagaz.AI.PIECE_MASK = 0x1F;
Dagaz.AI.TYPE_MASK = 0xF;
Dagaz.AI.PLAYERS_MASK = 0x30;
Dagaz.AI.COUNTER_SIZE = 3;
Dagaz.AI.TYPE_SIZE = 4;
Dagaz.AI.STALMATED = true;
Dagaz.AI.colorBlack = 0x20;
Dagaz.AI.colorWhite = 0x10;
var pieceEmpty = 0x00;
var piecePawn = 0x01;
var pieceAdvisor = 0x02;
var pieceMandarin = 0x03;
var pieceSoldier = 0x04;
var pieceBishop = 0x05;
var pieceElephant = 0x06;
var pieceKnight = 0x07;
var pieceHorse = 0x08;
var pieceCannon = 0x09;
var pieceGun = 0x0A;
var pieceRook = 0x0B;
var pieceChariot = 0x0C;
var pieceGeneral = 0x0D;
var pieceKing = 0x0E;
var pieceNo = 0x80;
var moveflagPromotion = 0x10 << 16;
var g_lastSquare;
var g_moveUndoStack = new Array();
var g_mobUnit;
var materialTable = [0, 800, 800, 1000, 1200, 1500, 2500, 3350, 3550, 4000, 5000, 5500, 5700, 600000, 600000];
Dagaz.AI.pieceAdj = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceEmpty
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
],
[ 10, 20, 30, 100, 100, 100, 30, 20, 10, // piecePawn
10, 40, 60, 200, 200, 200, 60, 40, 10,
20, 40, 50, 100, 100, 100, 50, 40, 20,
20, 30, 40, 50, 50, 50, 40, 30, 20,
10, 20, 30, 40, 40, 40, 30, 20, 10,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceAdvisor
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 10, 0, 10, 0, 0, 0,
0, 0, 0, 0, 15, 0, 0, 0, 0,
0, 0, 0, 10, 0, 10, 0, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceMandarin
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 10, 0, 10, 0, 0, 0,
0, 0, 0, 0, 15, 0, 0, 0, 0,
0, 0, 0, 10, 0, 10, 0, 0, 0
],
[ 10, 20, 30, 100, 100, 100, 30, 20, 10, // pieceSoldier
10, 40, 60, 200, 200, 200, 60, 40, 10,
20, 40, 50, 100, 100, 100, 50, 40, 20,
20, 30, 40, 50, 50, 50, 40, 30, 20,
10, 20, 30, 40, 40, 40, 30, 20, 10,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceBishop
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 10, 0, 0, 0, 10, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 20, 0, 0, 0, 10,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 10, 0, 0, 0, 10, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceElephant
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 10, 0, 3, 0, 10, 0, 1,
0, 3, 0, 5, 0, 5, 0, 3, 0,
10, 0, 3, 0, 20, 0, 3, 0, 10,
0, 5, 0, 5, 0, 5, 0, 5, 0,
1, 0, 10, 0, 1, 0, 10, 0, 1
],
[-200, -100, -50, -50, -50, -50, -50, -100, -200, // pieceKnight
-100, 0, 0, 0, 0, 0, 0, 0, -100,
-50, 0, 60, 60, 60, 60, 60, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 30, 30, 30, 30, 0, -50,
-100, 0, 0, 0, 0, 0, 0, 0, -100,
-200, -50, -25, -25, -25, -25, -25, -50, -200
],
[-200, -100, -50, -50, -50, -50, -50, -100, -200, // pieceHorse
-100, 0, 0, 0, 0, 0, 0, 0, -100,
-50, 0, 60, 60, 60, 60, 60, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 60, 60, 60, 30, 0, -50,
-50, 0, 30, 30, 30, 30, 30, 0, -50,
-100, 0, 0, 0, 0, 0, 0, 0, -100,
-200, -50, -25, -25, -25, -25, -25, -50, -200
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceCannon
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceGun
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
],
[ -60, -30, -10, 20, 20, 20, -10, -30, -60, // pieceRook
40, 70, 90, 120, 120, 120, 90, 70, 40,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60
],
[ -60, -30, -10, 20, 20, 20, -10, -30, -60, // pieceChariot
40, 70, 90, 120, 120, 120, 90, 70, 40,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, 20, -10, -30, -60
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceGeneral
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5, 10, 5, 0, 0, 0,
0, 0, 0, 10, 10, 10, 0, 0, 0,
0, 0, 0, 5, 10, 5, 0, 0, 0
],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, // pieceKing
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5, 10, 5, 0, 0, 0,
0, 0, 0, 10, 10, 10, 0, 0, 0,
0, 0, 0, 5, 10, 5, 0, 0, 0
]];
var pieceSquareAdj = new Array(16);
var flipTable = new Array(256);
var g_seeValues = [0, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 5, 5, 900, 900, 0,
0, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 5, 5, 900, 900, 0];
function FormatSquare(square) {
var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
return letters[(square & 0xF) - 4] + (((Dagaz.Model.HEIGHT + 1) - (square >> 4)) + 1);
}
Dagaz.AI.FormatMove = function(move, color) {
var result = FormatSquare(move & 0xFF) + ' - ' + FormatSquare((move >> 8) & 0xFF);
return result;
}
function Mobility(color) {
var result = 0;
var from, to, pos, mob, pieceIdx;
var enemy = color == Dagaz.AI.colorWhite ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
var mobUnit = color == Dagaz.AI.colorWhite ? g_mobUnit[0] : g_mobUnit[1];
var mask = enemy | pieceNo;
var friend = color == Dagaz.AI.colorWhite ? Dagaz.AI.colorWhite : Dagaz.AI.colorBlack;
// Knight mobility
mob = -3;
pieceIdx = (color | pieceKnight) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos - 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from + 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from - 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 17; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 15; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from + 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 65 * mob;
// Horse mobility
mob = -3;
pieceIdx = (color | pieceHorse) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos - 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from + 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos + 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from - 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 17; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 15; mob += mobUnit[Dagaz.AI.g_board[to]];
}
pos = from + 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; mob += mobUnit[Dagaz.AI.g_board[to]];
to = pos + 17; mob += mobUnit[Dagaz.AI.g_board[to]];
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 65 * mob;
// Rook mobility
mob = -4;
pieceIdx = (color | pieceRook) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { to--; mob++;} if (Dagaz.AI.g_board[to] & enemy) mob++;
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { to++; mob++; } if (Dagaz.AI.g_board[to] & enemy) mob++;
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; mob++; } if (Dagaz.AI.g_board[to] & enemy) mob++;
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; mob++; } if (Dagaz.AI.g_board[to] & enemy) mob++;
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 25 * mob;
// Chariot mobility
mob = -4;
pieceIdx = (color | pieceChariot) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while ((Dagaz.AI.g_board[to] & mask) == 0) { to--; mob++;}
to = from + 1; while ((Dagaz.AI.g_board[to] & mask) == 0) { to++; mob++; }
to = from + 16; while ((Dagaz.AI.g_board[to] & mask) == 0) { to += 16; mob++; }
to = from - 16; while ((Dagaz.AI.g_board[to] & mask) == 0) { to -= 16; mob++; }
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 25 * mob;
// Cannon mobility
mob = -4;
pieceIdx = (color | pieceCannon) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { to--; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to--; while (Dagaz.AI.g_board[to] == 0) { to--; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { to++; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to++; while (Dagaz.AI.g_board[to] == 0) { to++; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to -= 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to += 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 25 * mob;
// Gun mobility
mob = -4;
pieceIdx = (color | pieceGun) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 17;
if (Dagaz.AI.g_board[to] & friend) {
to -= 17;
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from - 15;
if (Dagaz.AI.g_board[to] & friend) {
to -= 15;
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 17;
if (Dagaz.AI.g_board[to] & friend) {
to += 17;
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 15;
if (Dagaz.AI.g_board[to] & friend) {
to += 15;
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { to--; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to--; while (Dagaz.AI.g_board[to] == 0) { to--; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { to++; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to++; while (Dagaz.AI.g_board[to] == 0) { to++; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to -= 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; mob++;}
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to += 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; }
if (Dagaz.AI.g_board[to] & enemy) mob++;
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
result += 25 * mob;
return result;
}
Dagaz.AI.Evaluate = function() {
var curEval = Dagaz.AI.g_baseEval;
var evalAdjust = 0;
// Black bishop pair
if (Dagaz.AI.g_pieceCount[pieceBishop] + Dagaz.AI.g_pieceCount[pieceElephant] >= 2)
evalAdjust -= 500;
// White bishop pair
if (Dagaz.AI.g_pieceCount[pieceBishop | Dagaz.AI.colorWhite] + Dagaz.AI.g_pieceCount[pieceElephant | Dagaz.AI.colorWhite] >= 2)
evalAdjust += 500;
var mobility = Mobility(Dagaz.AI.colorWhite) - Mobility(0);
if (Dagaz.AI.g_toMove == 0) {
// Black
curEval -= mobility;
curEval -= evalAdjust;
} else {
curEval += mobility;
curEval += evalAdjust;
}
return curEval;
}
Dagaz.AI.ScoreMove = function(move){
var moveTo = (move >> 8) & 0xFF;
var captured = Dagaz.AI.g_board[moveTo] & Dagaz.AI.TYPE_MASK;
var piece = Dagaz.AI.g_board[move & 0xFF];
var score;
if (captured != pieceEmpty) {
var pieceType = piece & Dagaz.AI.TYPE_MASK;
score = (captured << 5) - pieceType;
} else {
score = Dagaz.AI.historyTable[piece & Dagaz.AI.PIECE_MASK][moveTo];
}
return score;
}
Dagaz.AI.IsHashMoveValid = function(hashMove) {
var from = hashMove & 0xFF;
var to = (hashMove >> 8) & 0xFF;
var ourPiece = Dagaz.AI.g_board[from];
var pieceType = ourPiece & Dagaz.AI.TYPE_MASK;
if (pieceType < piecePawn || pieceType > pieceKing) return false;
// Can't move a piece we don't control
if (Dagaz.AI.g_toMove != (ourPiece & Dagaz.AI.colorWhite)) return false;
// Can't move to a square that has something of the same color
if (Dagaz.AI.g_board[to] != 0 && (Dagaz.AI.g_toMove == (Dagaz.AI.g_board[to] & Dagaz.AI.colorWhite))) return false;
// This validates that this piece type can actually make the attack
return IsSquareAttackableFrom(to, from);
}
Dagaz.AI.isNoZugzwang = function() {
return true;
}
function MakeSquare(row, column) {
return ((row + 2) << 4) | (column + 4);
}
function MakeTable(table) {
var result = new Array(256);
for (var i = 0; i < 256; i++) {
result[i] = 0;
}
for (var row = 0; row < Dagaz.Model.HEIGHT; row++) {
for (var col = 0; col < Dagaz.Model.WIDTH; col++) {
result[MakeSquare(row, col)] = table[row * Dagaz.Model.WIDTH + col];
}
}
return result;
}
var ResetGame = Dagaz.AI.ResetGame;
Dagaz.AI.ResetGame = function() {
ResetGame();
for (var row = 0; row < Dagaz.Model.HEIGHT; row++) {
for (var col = 0; col < Dagaz.Model.WIDTH; col++) {
var square = MakeSquare(row, col);
flipTable[square] = MakeSquare((Dagaz.Model.HEIGHT - 1) - row, col);
}
}
pieceSquareAdj[pieceEmpty] = MakeTable(Dagaz.AI.pieceAdj[pieceEmpty]);
pieceSquareAdj[piecePawn] = MakeTable(Dagaz.AI.pieceAdj[piecePawn]);
pieceSquareAdj[pieceSoldier] = MakeTable(Dagaz.AI.pieceAdj[pieceSoldier]);
pieceSquareAdj[pieceKnight] = MakeTable(Dagaz.AI.pieceAdj[pieceKnight]);
pieceSquareAdj[pieceHorse] = MakeTable(Dagaz.AI.pieceAdj[pieceHorse]);
pieceSquareAdj[pieceBishop] = MakeTable(Dagaz.AI.pieceAdj[pieceBishop]);
pieceSquareAdj[pieceElephant] = MakeTable(Dagaz.AI.pieceAdj[pieceElephant]);
pieceSquareAdj[pieceRook] = MakeTable(Dagaz.AI.pieceAdj[pieceRook]);
pieceSquareAdj[pieceChariot] = MakeTable(Dagaz.AI.pieceAdj[pieceChariot]);
pieceSquareAdj[pieceAdvisor] = MakeTable(Dagaz.AI.pieceAdj[pieceAdvisor]);
pieceSquareAdj[pieceMandarin] = MakeTable(Dagaz.AI.pieceAdj[pieceMandarin]);
pieceSquareAdj[pieceCannon] = MakeTable(Dagaz.AI.pieceAdj[pieceCannon]);
pieceSquareAdj[pieceGun] = MakeTable(Dagaz.AI.pieceAdj[pieceGun]);
pieceSquareAdj[pieceGeneral] = MakeTable(Dagaz.AI.pieceAdj[pieceGeneral]);
pieceSquareAdj[pieceKing] = MakeTable(Dagaz.AI.pieceAdj[pieceKing]);
InitializeEval();
}
function InitializeEval() {
g_mobUnit = new Array(2);
for (var i = 0; i < 2; i++) {
g_mobUnit[i] = new Array();
var enemy = i == 0 ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
var friend = i == 0 ? Dagaz.AI.colorWhite : Dagaz.AI.colorBlack;
g_mobUnit[i][0] = 1;
g_mobUnit[i][pieceNo] = 0;
g_mobUnit[i][enemy | piecePawn] = 1;
g_mobUnit[i][enemy | pieceSoldier] = 1;
g_mobUnit[i][enemy | pieceKnight] = 2;
g_mobUnit[i][enemy | pieceHorse] = 2;
g_mobUnit[i][enemy | pieceBishop] = 1;
g_mobUnit[i][enemy | pieceElephant] = 1;
g_mobUnit[i][enemy | pieceRook] = 5;
g_mobUnit[i][enemy | pieceChariot] = 5;
g_mobUnit[i][enemy | pieceAdvisor] = 1;
g_mobUnit[i][enemy | pieceMandarin] = 1;
g_mobUnit[i][enemy | pieceCannon] = 4;
g_mobUnit[i][enemy | pieceGun] = 4;
g_mobUnit[i][enemy | pieceGeneral] = 6;
g_mobUnit[i][enemy | pieceKing] = 6;
g_mobUnit[i][friend | piecePawn] = 0;
g_mobUnit[i][friend | pieceSoldier] = 0;
g_mobUnit[i][friend | pieceKnight] = 0;
g_mobUnit[i][friend | pieceHorse] = 0;
g_mobUnit[i][friend | pieceBishop] = 0;
g_mobUnit[i][friend | pieceElephant] = 0;
g_mobUnit[i][friend | pieceRook] = 0;
g_mobUnit[i][friend | pieceChariot] = 0;
g_mobUnit[i][friend | pieceAdvisor] = 0;
g_mobUnit[i][friend | pieceMandarin] = 0;
g_mobUnit[i][friend | pieceCannon] = 0;
g_mobUnit[i][friend | pieceGun] = 0;
g_mobUnit[i][friend | pieceGeneral] = 0;
g_mobUnit[i][friend | pieceKing] = 0;
}
}
Dagaz.AI.InitializeFromFen = function(fen) {
var chunks = fen.split('_');
for (var i = 0; i < 256; i++)
Dagaz.AI.g_board[i] = pieceNo;
var row = 0;
var col = 0;
var pieces = chunks[0];
for (var i = 0; i < pieces.length; i++) {
var c = pieces.charAt(i);
if (c == '/') {
row++;
col = 0;
}
else {
if (c >= '0' && c <= '9') {
for (var j = 0; j < parseInt(c); j++) {
Dagaz.AI.g_board[MakeSquare(row, col)] = 0;
col++;
}
}
else {
var isBlack = c >= 'a' && c <= 'z';
var piece = isBlack ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
if (!isBlack)
c = pieces.toLowerCase().charAt(i);
switch (c) {
case 'p':
piece |= piecePawn;
break;
case 's':
piece |= pieceSoldier;
break;
case 'n':
piece |= pieceKnight;
break;
case 'h':
piece |= pieceHorse;
break;
case 'b':
piece |= pieceBishop;
break;
case 'e':
piece |= pieceElephant;
break;
case 'r':
piece |= pieceRook;
break;
case 'f':
piece |= pieceChariot;
break;
case 'a':
piece |= pieceAdvisor;
break;
case 'm':
piece |= pieceMandarin;
break;
case 'c':
piece |= pieceCannon;
break;
case 'j':
piece |= pieceGun;
break;
case 'g':
piece |= pieceGeneral;
break;
case 'k':
piece |= pieceKing;
break;
}
if (piece & Dagaz.AI.TYPE_MASK) {
Dagaz.AI.g_board[MakeSquare(row, col)] = piece;
}
col++;
}
}
}
Dagaz.AI.InitializePieceList();
Dagaz.AI.g_toMove = chunks[1].charAt(0) == 'w' ? Dagaz.AI.colorWhite : 0;
var them = Dagaz.AI.colorWhite - Dagaz.AI.g_toMove;
g_lastSquare = -1;
if (chunks[2].indexOf('-') == -1) {
var col = chunks[2].charAt(0).charCodeAt() - 'a'.charCodeAt();
var row = Dagaz.Model.HEIGHT - (chunks[2].charAt(1).charCodeAt() - '0'.charCodeAt());
g_lastSquare = MakeSquare(row, col);
}
var hashResult = Dagaz.AI.SetHash();
Dagaz.AI.g_hashKeyLow = hashResult.hashKeyLow;
Dagaz.AI.g_hashKeyHigh = hashResult.hashKeyHigh;
Dagaz.AI.g_baseEval = 0;
for (var i = 0; i < 256; i++) {
if (Dagaz.AI.g_board[i] & Dagaz.AI.colorWhite) {
Dagaz.AI.g_baseEval += pieceSquareAdj[Dagaz.AI.g_board[i] & Dagaz.AI.TYPE_MASK][i];
Dagaz.AI.g_baseEval += materialTable[Dagaz.AI.g_board[i] & Dagaz.AI.TYPE_MASK];
} else if (Dagaz.AI.g_board[i] & Dagaz.AI.colorBlack) {
Dagaz.AI.g_baseEval -= pieceSquareAdj[Dagaz.AI.g_board[i] & Dagaz.AI.TYPE_MASK][flipTable[i]];
Dagaz.AI.g_baseEval -= materialTable[Dagaz.AI.g_board[i] & Dagaz.AI.TYPE_MASK];
}
}
if (!Dagaz.AI.g_toMove) Dagaz.AI.g_baseEval = -Dagaz.AI.g_baseEval;
Dagaz.AI.g_move50 = 0;
var kingPos = Dagaz.AI.g_pieceList[(Dagaz.AI.g_toMove | pieceGeneral) << Dagaz.AI.COUNTER_SIZE];
if (kingPos == 0) {
kingPos = Dagaz.AI.g_pieceList[(Dagaz.AI.g_toMove | pieceKing) << Dagaz.AI.COUNTER_SIZE];
}
Dagaz.AI.g_inCheck = false;
if (kingPos != 0) {
Dagaz.AI.g_inCheck = IsSquareAttackable(kingPos, them);
}
// Check for king capture (invalid FEN)
kingPos = Dagaz.AI.g_pieceList[(them | pieceGeneral) << Dagaz.AI.COUNTER_SIZE]
if (kingPos == 0) {
kingPos = Dagaz.AI.g_pieceList[(them | pieceKing) << Dagaz.AI.COUNTER_SIZE]
}
if ((kingPos != 0) && IsSquareAttackable(kingPos, Dagaz.AI.g_toMove)) {
return 'Invalid FEN: Can capture king';
}
// Checkmate/stalemate
if (GenerateValidMoves().length == 0) {
return Dagaz.AI.g_inCheck ? 'Checkmate' : 'Stalemate';
}
return '';
}
function UndoHistory(lastSquare, inCheck, baseEval, hashKeyLow, hashKeyHigh, move50, captured) {
this.lastSquare = lastSquare;
this.inCheck = inCheck;
this.baseEval = baseEval;
this.hashKeyLow = hashKeyLow;
this.hashKeyHigh = hashKeyHigh;
this.move50 = move50;
this.captured = captured;
}
Dagaz.AI.MakeMove = function(move) {
var me = Dagaz.AI.g_toMove >> Dagaz.AI.TYPE_SIZE;
var otherColor = Dagaz.AI.colorWhite - Dagaz.AI.g_toMove;
var flags = move & 0xFF0000;
var to = (move >> 8) & 0xFF;
var from = move & 0xFF;
var captured = Dagaz.AI.g_board[to];
var piece = Dagaz.AI.g_board[from];
g_moveUndoStack[Dagaz.AI.g_moveCount] = new UndoHistory(g_lastSquare, Dagaz.AI.g_inCheck, Dagaz.AI.g_baseEval, Dagaz.AI.g_hashKeyLow, Dagaz.AI.g_hashKeyHigh, Dagaz.AI.g_move50, captured);
Dagaz.AI.g_moveCount++;
g_lastSquare = to;
if (captured) {
// Remove our piece from the piece list
var capturedType = captured & Dagaz.AI.PIECE_MASK;
Dagaz.AI.g_pieceCount[capturedType]--;
var lastPieceSquare = Dagaz.AI.g_pieceList[(capturedType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[capturedType]];
Dagaz.AI.g_pieceIndex[lastPieceSquare] = Dagaz.AI.g_pieceIndex[to];
Dagaz.AI.g_pieceList[(capturedType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[lastPieceSquare]] = lastPieceSquare;
Dagaz.AI.g_pieceList[(capturedType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[capturedType]] = 0;
Dagaz.AI.g_baseEval += materialTable[captured & Dagaz.AI.TYPE_MASK];
Dagaz.AI.g_baseEval += pieceSquareAdj[captured & Dagaz.AI.TYPE_MASK][me ? flipTable[to] : to];
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristLow[to][capturedType];
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristHigh[to][capturedType];
Dagaz.AI.g_move50 = 0;
}
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristLow[from][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristHigh[from][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristLow[to][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristHigh[to][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristBlackLow;
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristBlackHigh;
Dagaz.AI.g_baseEval -= pieceSquareAdj[piece & Dagaz.AI.TYPE_MASK][me == 0 ? flipTable[from] : from];
// Move our piece in the piece list
Dagaz.AI.g_pieceIndex[to] = Dagaz.AI.g_pieceIndex[from];
Dagaz.AI.g_pieceList[((piece & Dagaz.AI.PIECE_MASK) << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[to]] = to;
if (flags & moveflagPromotion) {
var newPiece = piece & (~Dagaz.AI.TYPE_MASK);
if ((piece & Dagaz.AI.TYPE_MASK) == piecePawn) newPiece |= pieceSoldier;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceAdvisor) newPiece |= pieceMandarin;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceBishop) newPiece |= pieceElephant;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceKnight) newPiece |= pieceHorse;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceCannon) newPiece |= pieceGun;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceRook) newPiece |= pieceChariot;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceGeneral) newPiece |= pieceKing;
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristLow[to][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristHigh[to][piece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_board[to] = newPiece;
Dagaz.AI.g_hashKeyLow ^= Dagaz.AI.g_zobristLow[to][newPiece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_hashKeyHigh ^= Dagaz.AI.g_zobristHigh[to][newPiece & Dagaz.AI.PIECE_MASK];
Dagaz.AI.g_baseEval += pieceSquareAdj[newPiece & Dagaz.AI.TYPE_MASK][me == 0 ? flipTable[to] : to];
Dagaz.AI.g_baseEval -= materialTable[piecePawn];
Dagaz.AI.g_baseEval += materialTable[newPiece & Dagaz.AI.TYPE_MASK];
var pawnType = piece & Dagaz.AI.PIECE_MASK;
var promoteType = newPiece & Dagaz.AI.PIECE_MASK;
Dagaz.AI.g_pieceCount[pawnType]--;
var lastPawnSquare = Dagaz.AI.g_pieceList[(pawnType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[pawnType]];
Dagaz.AI.g_pieceIndex[lastPawnSquare] = Dagaz.AI.g_pieceIndex[to];
Dagaz.AI.g_pieceList[(pawnType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[lastPawnSquare]] = lastPawnSquare;
Dagaz.AI.g_pieceList[(pawnType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[pawnType]] = 0;
Dagaz.AI.g_pieceIndex[to] = Dagaz.AI.g_pieceCount[promoteType];
Dagaz.AI.g_pieceList[(promoteType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[to]] = to;
Dagaz.AI.g_pieceCount[promoteType]++;
} else {
Dagaz.AI.g_board[to] = Dagaz.AI.g_board[from];
Dagaz.AI.g_baseEval += pieceSquareAdj[piece & Dagaz.AI.TYPE_MASK][me == 0 ? flipTable[to] : to];
}
Dagaz.AI.g_board[from] = pieceEmpty;
Dagaz.AI.g_toMove = otherColor;
Dagaz.AI.g_baseEval = -Dagaz.AI.g_baseEval;
var kingPos = Dagaz.AI.g_pieceList[(pieceGeneral | (Dagaz.AI.colorWhite - Dagaz.AI.g_toMove)) << Dagaz.AI.COUNTER_SIZE];
if (kingPos == 0) {
kingPos = Dagaz.AI.g_pieceList[(pieceKing | (Dagaz.AI.colorWhite - Dagaz.AI.g_toMove)) << Dagaz.AI.COUNTER_SIZE];
}
if ((kingPos != 0) && IsSquareAttackable(kingPos, otherColor)) {
Dagaz.AI.UnmakeMove(move);
return false;
}
Dagaz.AI.g_inCheck = false;
/* var theirKingPos = Dagaz.AI.g_pieceList[(pieceGeneral | Dagaz.AI.g_toMove) << Dagaz.AI.COUNTER_SIZE];
if (theirKingPos == 0) {
theirKingPos = Dagaz.AI.g_pieceList[(pieceKing | Dagaz.AI.g_toMove) << Dagaz.AI.COUNTER_SIZE];
}
if (theirKingPos != 0) {
Dagaz.AI.g_inCheck = IsSquareAttackable(theirKingPos, Dagaz.AI.g_toMove);
}*/
Dagaz.AI.g_repMoveStack[Dagaz.AI.g_moveCount - 1] = Dagaz.AI.g_hashKeyLow;
Dagaz.AI.g_move50++;
return true;
}
Dagaz.AI.UnmakeMove = function(move) {
Dagaz.AI.g_toMove = Dagaz.AI.colorWhite - Dagaz.AI.g_toMove;
Dagaz.AI.g_baseEval = -Dagaz.AI.g_baseEval;
Dagaz.AI.g_moveCount--;
g_lastSquare = g_moveUndoStack[Dagaz.AI.g_moveCount].lastSquare;
Dagaz.AI.g_inCheck = g_moveUndoStack[Dagaz.AI.g_moveCount].inCheck;
Dagaz.AI.g_baseEval = g_moveUndoStack[Dagaz.AI.g_moveCount].baseEval;
Dagaz.AI.g_hashKeyLow = g_moveUndoStack[Dagaz.AI.g_moveCount].hashKeyLow;
Dagaz.AI.g_hashKeyHigh = g_moveUndoStack[Dagaz.AI.g_moveCount].hashKeyHigh;
Dagaz.AI.g_move50 = g_moveUndoStack[Dagaz.AI.g_moveCount].move50;
var otherColor = Dagaz.AI.colorWhite - Dagaz.AI.g_toMove;
var me = Dagaz.AI.g_toMove >> Dagaz.AI.TYPE_SIZE;
var them = otherColor >> Dagaz.AI.TYPE_SIZE;
var flags = move & 0xFF0000;
var captured = g_moveUndoStack[Dagaz.AI.g_moveCount].captured;
var to = (move >> 8) & 0xFF;
var from = move & 0xFF;
var piece = Dagaz.AI.g_board[to];
if (flags & moveflagPromotion) {
var newPiece = piece & (~Dagaz.AI.TYPE_MASK);
if ((piece & Dagaz.AI.TYPE_MASK) == pieceSoldier) newPiece |= piecePawn;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceMandarin) newPiece |= pieceAdvisor;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceElephant) newPiece |= pieceBishop;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceHorse) newPiece |= pieceKnight;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceGun) newPiece |= pieceCannon;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceChariot) newPiece |= pieceRook;
if ((piece & Dagaz.AI.TYPE_MASK) == pieceKing) newPiece |= pieceGeneral;
Dagaz.AI.g_board[from] = newPiece;
var pawnType = Dagaz.AI.g_board[from] & Dagaz.AI.PIECE_MASK;
var promoteType = Dagaz.AI.g_board[to] & Dagaz.AI.PIECE_MASK;
Dagaz.AI.g_pieceCount[promoteType]--;
var lastPromoteSquare = Dagaz.AI.g_pieceList[(promoteType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[promoteType]];
Dagaz.AI.g_pieceIndex[lastPromoteSquare] = Dagaz.AI.g_pieceIndex[to];
Dagaz.AI.g_pieceList[(promoteType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[lastPromoteSquare]] = lastPromoteSquare;
Dagaz.AI.g_pieceList[(promoteType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[promoteType]] = 0;
Dagaz.AI.g_pieceIndex[to] = Dagaz.AI.g_pieceCount[pawnType];
Dagaz.AI.g_pieceList[(pawnType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[to]] = to;
Dagaz.AI.g_pieceCount[pawnType]++;
} else {
Dagaz.AI.g_board[from] = Dagaz.AI.g_board[to];
}
Dagaz.AI.g_board[to] = captured;
// Move our piece in the piece list
Dagaz.AI.g_pieceIndex[from] = Dagaz.AI.g_pieceIndex[to];
Dagaz.AI.g_pieceList[((piece & Dagaz.AI.PIECE_MASK) << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceIndex[from]] = from;
if (captured) {
// Restore our piece to the piece list
var captureType = captured & Dagaz.AI.PIECE_MASK;
Dagaz.AI.g_pieceIndex[to] = Dagaz.AI.g_pieceCount[captureType];
Dagaz.AI.g_pieceList[(captureType << Dagaz.AI.COUNTER_SIZE) | Dagaz.AI.g_pieceCount[captureType]] = to;
Dagaz.AI.g_pieceCount[captureType]++;
}
}
function IsSquareAttackableFrom(target, from) {
var to, pos, piece, pieceType, adj;
piece = Dagaz.AI.g_board[from];
pieceType = piece & Dagaz.AI.TYPE_MASK;
if (pieceType == pieceEmpty) return false;
var color = (piece & Dagaz.AI.colorWhite);
var enemy = color ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
var friend = color ? Dagaz.AI.colorWhite : Dagaz.AI.colorBlack;
var inc = color ? -16 : 16;
var me = color >> Dagaz.AI.TYPE_SIZE;
var mask = enemy | pieceNo;
if (pieceType == piecePawn) {
adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[from] : from];
if (from + inc == target) return true;
if (adj != 0) {
if (+from + 1 == target) return true;
if (+from - 1 == target) return true;
}
}
if (pieceType == pieceSoldier) {
if (from + inc == target) return true;
if (from + 1 == target) return true;
if (from - 1 == target) return true;
to = from - inc; adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[to] : to];
if (adj != 0) return true;
}
if ((pieceType == pieceAdvisor) || (pieceType == pieceKing)) {
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
if (pieceType == pieceMandarin) {
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
if ((pieceType == pieceBishop) || (pieceType == pieceElephant)) {
to = from + 15;
if (Dagaz.AI.g_board[to] == 0) {
to += 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
to = from + 17;
if (Dagaz.AI.g_board[to] == 0) {
to += 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
to = from - 15;
if (Dagaz.AI.g_board[to] == 0) {
to -= 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
to = from - 17;
if (Dagaz.AI.g_board[to] == 0) {
to -= 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
}
}
if (pieceType == pieceElephant) {
to = from - 17;
if (Dagaz.AI.g_board[to] == 0) {
to -= 17;
if (Dagaz.AI.g_board[to] == 0) {
to -= 17; adj = pieceSquareAdj[pieceElephant][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (to == target)) return true;
}
}
to = from - 15;
if (Dagaz.AI.g_board[to] == 0) {
to -= 15;
if (Dagaz.AI.g_board[to] == 0) {
to -= 15; adj = pieceSquareAdj[pieceElephant][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (to == target)) return true;
}
}
to = from + 17;
if (Dagaz.AI.g_board[to] == 0) {
to += 17;
if (Dagaz.AI.g_board[to] == 0) {
to += 17; adj = pieceSquareAdj[pieceElephant][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (to == target)) return true;
}
}
to = from + 15;
if (Dagaz.AI.g_board[to] == 0) {
to += 15;
if (Dagaz.AI.g_board[to] == 0) {
to += 15; adj = pieceSquareAdj[pieceElephant][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (to == target)) return true;
}
}
}
if (pieceType == pieceKnight) {
pos = from - 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (to == target) return true;
to = pos - 17; if (to == target) return true;
}
pos = from + 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; if (to == target) return true;
to = pos + 17; if (to == target) return true;
}
pos = from - 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; if (to == target) return true;
to = pos - 17; if (to == target) return true;
}
pos = from + 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (to == target) return true;
to = pos + 17; if (to == target) return true;
}
}
if (pieceType == pieceHorse) {
pos = from - 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (to == target) return true;
to = pos - 17; if (to == target) return true;
}
pos = from + 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos + 15; if (to == target) return true;
to = pos + 17; if (to == target) return true;
}
pos = from - 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos + 15; if (to == target) return true;
to = pos - 17; if (to == target) return true;
}
pos = from + 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (to == target) return true;
to = pos + 17; if (to == target) return true;
}
}
if (pieceType == pieceGun) {
to = from - 17;
if (Dagaz.AI.g_board[to] & friend) {
to -= 17;
if (to == target) return true;
}
to = from - 15;
if (Dagaz.AI.g_board[to] & friend) {
to -= 15;
if (to == target) return true;
}
to = from + 17;
if (Dagaz.AI.g_board[to] & friend) {
to += 17;
if (to == target) return true;
}
to = from + 15;
if (Dagaz.AI.g_board[to] & friend) {
to += 15;
if (to == target) return true;
}
}
if (((target & 0xF) != (from & 0xF)) && ((target & 0xF0) != (from & 0xF0))) return false;
if ((pieceType == pieceChariot) || (pieceType == pieceRook)) {
to = from; do { to++; if (to == target) return true; } while (Dagaz.AI.g_board[to] == 0);
to = from; do { to--; if (to == target) return true; } while (Dagaz.AI.g_board[to] == 0);
to = from; do { to += 16; if (to == target) return true; } while (Dagaz.AI.g_board[to] == 0);
to = from; do { to -= 16; if (to == target) return true; } while (Dagaz.AI.g_board[to] == 0);
}
if ((pieceType == pieceCannon) || (pieceType == pieceGun)) {
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { if (to == target) return true; to++; }
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to++; while (Dagaz.AI.g_board[to] == 0) { to++; }
if (to == target) return true;
}
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { if (to == target) return true; to--; }
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to--; while (Dagaz.AI.g_board[to] == 0) { to--; }
if (to == target) return true;
}
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { if (to == target) return true; to += 16; }
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to += 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; }
if (to == target) return true;
}
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { if (to == target) return true; to -= 16; }
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to -= 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; }
if (to == target) return true;
}
}
if ((pieceType == pieceGeneral) || (pieceType == pieceKing)) {
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (to == target) return true;
}
to = from + inc; while (Dagaz.AI.g_board[to] == 0) { to += inc; }
if (to != target) return false;
if ((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) == pieceGeneral) return true;
if ((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) == pieceKing) return (to != g_lastSquare) || (pieceType == pieceKing);
}
return false;
}
function IsSquareAttackable(target, color) {
for (var i = piecePawn; i <= pieceKing; i++) {
var index = (color | i) << Dagaz.AI.COUNTER_SIZE;
var square = Dagaz.AI.g_pieceList[index];
while (square != 0) {
if (IsSquareAttackableFrom(target, square)) return true;
square = Dagaz.AI.g_pieceList[++index];
}
}
return false;
}
function GenerateMove(from, to, flags) {
return from | (to << 8) | flags;
}
function GenerateValidMoves() {
var moveList = new Array();
var allMoves = new Array();
Dagaz.AI.GenerateCaptureMoves(allMoves, null);
Dagaz.AI.GenerateAllMoves(allMoves);
for (var i = allMoves.length - 1; i >= 0; i--) {
if (Dagaz.AI.MakeMove(allMoves[i])) {
moveList[moveList.length] = allMoves[i];
Dagaz.AI.UnmakeMove(allMoves[i]);
}
}
return moveList;
}
Dagaz.AI.GenerateAllMoves = function(moveStack) {
var adj, from, to, pos, piece, pieceIdx;
var me = Dagaz.AI.g_toMove >> Dagaz.AI.TYPE_SIZE;
var inc = (Dagaz.AI.g_toMove == Dagaz.AI.colorWhite) ? -16 : 16;
var enemy = Dagaz.AI.g_toMove == Dagaz.AI.colorWhite ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
var mask = enemy | pieceNo;
// Pawn quiet moves
pieceIdx = (Dagaz.AI.g_toMove | piecePawn) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from + inc; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[from] : from];
if (adj != 0) {
to = from - 1; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from + 1; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Soldier quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceSoldier) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from + inc; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from + 1; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from - 1; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from - inc; adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Advisor quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceAdvisor) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Mandarin quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceMandarin) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Bishop quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceBishop) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 15;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
pos = from - 17;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
pos = from + 15;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
pos = from + 17;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Elephant quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceElephant) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 15;
if (Dagaz.AI.g_board[to] == 0) {
to -= 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
to -= 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from - 17;
if (Dagaz.AI.g_board[to] == 0) {
to -= 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
to -= 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from + 15;
if (Dagaz.AI.g_board[to] == 0) {
to += 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
to += 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from + 17;
if (Dagaz.AI.g_board[to] == 0) {
to += 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
to += 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] == 0)) {
moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Knight quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceKnight) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos - 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from + 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from - 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from + 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Horse quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceHorse) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos - 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from + 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos + 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from - 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
pos = from + 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = pos + 17; if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Rook quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceRook) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to--; }
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to++; }
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to += 16; }
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to -= 16; }
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Chariot quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceChariot) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1;
while ((Dagaz.AI.g_board[to] & mask) == 0) {
if (Dagaz.AI.g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to--;
}
to = from + 1;
while ((Dagaz.AI.g_board[to] & mask) == 0) {
if (Dagaz.AI.g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to++;
}
to = from - 16;
while ((Dagaz.AI.g_board[to] & mask) == 0) {
if (Dagaz.AI.g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to -= 16;
}
to = from + 16;
while ((Dagaz.AI.g_board[to] & mask) == 0) {
if (Dagaz.AI.g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to += 16;
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Cannon quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceCannon) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to--; }
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to++; }
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to += 16; }
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to -= 16; }
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Gun quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceGun) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to--; }
to = from + 1; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to++; }
to = from + 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to += 16; }
to = from - 16; while (Dagaz.AI.g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to, 0); to -= 16; }
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// General quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceGeneral) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx];
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
// King quiet moves quiet moves
pieceIdx = (Dagaz.AI.g_toMove | pieceKing) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx];
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] == 0) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
function isCapturing(to, pieceType) {
var enemy = Dagaz.AI.g_toMove == Dagaz.AI.colorWhite ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
if ((to == g_lastSquare) && ((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) == pieceType)) return false;
return Dagaz.AI.g_board[to] & enemy;
}
Dagaz.AI.GenerateCaptureMoves = function(moveStack) {
var adj, from, to, pos, piece, pieceIdx;
var me = Dagaz.AI.g_toMove >> Dagaz.AI.TYPE_SIZE;
var enemy = Dagaz.AI.g_toMove == Dagaz.AI.colorWhite ? Dagaz.AI.colorBlack : Dagaz.AI.colorWhite;
var friend = Dagaz.AI.g_toMove == Dagaz.AI.colorWhite ? Dagaz.AI.colorWhite : Dagaz.AI.colorBlack;
var inc = (Dagaz.AI.g_toMove == Dagaz.AI.colorWhite) ? -16 : 16;
var mask = enemy | pieceNo;
// Pawn captures
pieceIdx = (Dagaz.AI.g_toMove | piecePawn) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from + inc; if (isCapturing(to, pieceSoldier)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[from] : from];
if (adj != 0) {
to = from - 1; if (isCapturing(to, pieceSoldier)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = from + 1; if (isCapturing(to, pieceSoldier)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Soldier captures
pieceIdx = (Dagaz.AI.g_toMove | pieceSoldier) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from + inc; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from + 1; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from - 1; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
to = from - inc; adj = pieceSquareAdj[piecePawn][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Advisor captures
pieceIdx = (Dagaz.AI.g_toMove | pieceAdvisor) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Mandarin captures
pieceIdx = (Dagaz.AI.g_toMove | pieceMandarin) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Bishop captures
pieceIdx = (Dagaz.AI.g_toMove | pieceBishop) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 15;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
}
pos = from - 17;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
}
pos = from + 15;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
}
pos = from + 17;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Elephant captures
pieceIdx = (Dagaz.AI.g_toMove | pieceElephant) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 15;
if (Dagaz.AI.g_board[to] == 0) {
to -= 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
if (Dagaz.AI.g_board[to] == 0) {
to -= 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] & enemy)) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from - 17;
if (Dagaz.AI.g_board[to] == 0) {
to -= 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
if (Dagaz.AI.g_board[to] == 0) {
to -= 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] & enemy)) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from + 15;
if (Dagaz.AI.g_board[to] == 0) {
to += 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
if (Dagaz.AI.g_board[to] == 0) {
to += 15; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] & enemy)) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
to = from + 17;
if (Dagaz.AI.g_board[to] == 0) {
to += 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
if (Dagaz.AI.g_board[to] == 0) {
to += 17; adj = pieceSquareAdj[pieceBishop][me == 0 ? flipTable[to] : to];
if ((adj != 0) && (Dagaz.AI.g_board[to] & enemy)) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Knight captures
pieceIdx = (Dagaz.AI.g_toMove | pieceKnight) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos - 17; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from + 16;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos + 15; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 17; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from - 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 17; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 15; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from + 1;
if (Dagaz.AI.g_board[pos] == 0) {
to = pos - 15; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 17; if (isCapturing(to, pieceHorse)) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Horse captures
pieceIdx = (Dagaz.AI.g_toMove | pieceHorse) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
pos = from - 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos - 17; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from + 16;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos + 15; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 17; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from - 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 17; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 15; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
pos = from + 1;
if ((Dagaz.AI.g_board[pos] & mask) == 0) {
to = pos - 15; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
to = pos + 17; if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Rook captures
pieceIdx = (Dagaz.AI.g_toMove | pieceRook) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from; do { to--; } while (Dagaz.AI.g_board[to] == 0); if (isCapturing(to, pieceChariot)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
to = from; do { to++; } while (Dagaz.AI.g_board[to] == 0); if (isCapturing(to, pieceChariot)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
to = from; do { to -= 16; } while (Dagaz.AI.g_board[to] == 0); if (isCapturing(to, pieceChariot)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
to = from; do { to += 16; } while (Dagaz.AI.g_board[to] == 0); if (isCapturing(to, pieceChariot)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Chariot captures
pieceIdx = (Dagaz.AI.g_toMove | pieceChariot) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from; do { to--; } while (Dagaz.AI.g_board[to] == 0); if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to = from; do { to++; } while (Dagaz.AI.g_board[to] == 0); if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to = from; do { to -= 16; } while (Dagaz.AI.g_board[to] == 0); if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
to = from; do { to += 16; } while (Dagaz.AI.g_board[to] == 0); if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Cannon captures
pieceIdx = (Dagaz.AI.g_toMove | pieceCannon) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from; do { to--; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to--; while (Dagaz.AI.g_board[to] == 0) { to--; }
if (isCapturing(to, pieceGun)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
}
to = from; do { to++; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to++; while (Dagaz.AI.g_board[to] == 0) { to++; }
if (isCapturing(to, pieceGun)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
}
to = from; do { to -= 16; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to -= 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; }
if (isCapturing(to, pieceGun)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
}
to = from; do { to += 16; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to += 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; }
if (isCapturing(to, pieceGun)) moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// Gun captures
pieceIdx = (Dagaz.AI.g_toMove | pieceGun) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx++];
while (from != 0) {
to = from - 17;
if (Dagaz.AI.g_board[to] & friend) {
to -= 17;
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from - 15;
if (Dagaz.AI.g_board[to] & friend) {
to -= 15;
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from + 17;
if (Dagaz.AI.g_board[to] & friend) {
to += 17;
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from + 15;
if (Dagaz.AI.g_board[to] & friend) {
to += 15;
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from; do { to--; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to--; while (Dagaz.AI.g_board[to] == 0) { to--; }
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from; do { to++; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to++; while (Dagaz.AI.g_board[to] == 0) { to++; }
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from; do { to -= 16; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to -= 16; while (Dagaz.AI.g_board[to] == 0) { to -= 16; }
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
to = from; do { to += 16; } while (Dagaz.AI.g_board[to] == 0);
if (Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) {
to += 16; while (Dagaz.AI.g_board[to] == 0) { to += 16; }
if (Dagaz.AI.g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to, 0);
}
from = Dagaz.AI.g_pieceList[pieceIdx++];
}
// General captures
pieceIdx = (Dagaz.AI.g_toMove | pieceGeneral) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx];
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, moveflagPromotion);}
}
// King captures
pieceIdx = (Dagaz.AI.g_toMove | pieceKing) << Dagaz.AI.COUNTER_SIZE;
from = Dagaz.AI.g_pieceList[pieceIdx];
to = from - 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 15; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 17; adj = pieceSquareAdj[pieceAdvisor][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 16; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from - 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
to = from + 1; adj = pieceSquareAdj[pieceKing][me == 0 ? flipTable[to] : to];
if (adj != 0) {
if (Dagaz.AI.g_board[to] & enemy) {moveStack[moveStack.length] = GenerateMove(from, to, 0);}
}
}
Dagaz.AI.See = function(move) {
var from = move & 0xFF;
var to = (move >> 8) & 0xFF;
var fromPiece = Dagaz.AI.g_board[from];
var fromValue = g_seeValues[fromPiece & Dagaz.AI.PIECE_MASK];
var toValue = g_seeValues[Dagaz.AI.g_board[to] & Dagaz.AI.PIECE_MASK];
if (fromValue <= toValue) {
return true;
}
var us = (fromPiece & Dagaz.AI.colorWhite) ? Dagaz.AI.colorWhite : 0;
var them = Dagaz.AI.colorWhite - us;
var themAttacks = new Array();
// Pawn attacks
// If any opponent pawns can capture back, this capture is probably not worthwhile (as we must be using knight or above).
if (SeeAddSliderAttacks(to, them, themAttacks, piecePawn)) {
return false;
}
// Knight attacks
// If any opponent knights can capture back, and the deficit we have to make up is greater than the knights value,
// it's not worth it. We can capture on this square again, and the opponent doesn't have to capture back.
var captureDeficit = fromValue - toValue;
// Slider attacks
Dagaz.AI.g_board[from] = 0;
for (var pieceType = pieceAdvisor; pieceType <= pieceChariot; pieceType++) {
if (SeeAddSliderAttacks(to, them, themAttacks, pieceType)) {
if (captureDeficit > g_seeValues[pieceType]) {
Dagaz.AI.g_board[from] = fromPiece;
return false;
}
}
}
var usAttacks = new Array();
// Pawn defenses
// At this point, we are sure we are making a "losing" capture. The opponent can not capture back with a
// pawn. They cannot capture back with a minor/major and stand pat either. So, if we can capture with
// a pawn, it's got to be a winning or equal capture.
if (SeeAddSliderAttacks(to, us, usAttacks, piecePawn)) {
Dagaz.AI.g_board[from] = fromPiece;
return true;
}
// King attacks
SeeAddSliderAttacks(to, them, themAttacks, pieceGeneral);
SeeAddSliderAttacks(to, them, themAttacks, pieceKing);
// Our attacks
for (var pieceType = pieceAdvisor; pieceType <= pieceKing; pieceType++) {
SeeAddSliderAttacks(to, us, usAttacks, pieceType);
}
Dagaz.AI.g_board[from] = fromPiece;
// We are currently winning the amount of material of the captured piece, time to see if the opponent
// can get it back somehow. We assume the opponent can capture our current piece in this score, which
// simplifies the later code considerably.
var seeValue = toValue - fromValue;
for (; ; ) {
var capturingPieceValue = 1000;
var capturingPieceIndex = -1;
// Find the least valuable piece of the opponent that can attack the square
for (var i = 0; i < themAttacks.length; i++) {
if (themAttacks[i] != 0) {
var pieceValue = g_seeValues[Dagaz.AI.g_board[themAttacks[i]] & Dagaz.AI.TYPE_MASK];
if (pieceValue < capturingPieceValue) {
capturingPieceValue = pieceValue;
capturingPieceIndex = i;
}
}
}
if (capturingPieceIndex == -1) {
// Opponent can't capture back, we win
return true;
}
// Now, if seeValue < 0, the opponent is winning. If even after we take their piece,
// we can't bring it back to 0, then we have lost this battle.
seeValue += capturingPieceValue;
if (seeValue < 0) {
return false;
}
var capturingPieceSquare = themAttacks[capturingPieceIndex];
themAttacks[capturingPieceIndex] = 0;
// Add any x-ray attackers
SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
// Our turn to capture
capturingPieceValue = 1000;
capturingPieceIndex = -1;
// Find our least valuable piece that can attack the square
for (var i = 0; i < usAttacks.length; i++) {
if (usAttacks[i] != 0) {
var pieceValue = g_seeValues[Dagaz.AI.g_board[usAttacks[i]] & Dagaz.AI.TYPE_MASK];
if (pieceValue < capturingPieceValue) {
capturingPieceValue = pieceValue;
capturingPieceIndex = i;
}
}
}
if (capturingPieceIndex == -1) {
// We can't capture back, we lose :(
return false;
}
// Assume our opponent can capture us back, and if we are still winning, we can stand-pat
// here, and assume we've won.
seeValue -= capturingPieceValue;
if (seeValue >= 0) {
return true;
}
capturingPieceSquare = usAttacks[capturingPieceIndex];
usAttacks[capturingPieceIndex] = 0;
// Add any x-ray attackers
SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
}
}
function SeeAddXrayAttack(target, square, us, usAttacks, themAttacks) {
var inc;
if ((target & 0xF) == (square & 0xF)) {
inc = (square > target) ? 16 : -16;
}
if ((target & 0xF0) == (square & 0xF0)) {
inc = (square > target) ? 1 : -1;
}
var to = square + inc; while (Dagaz.AI.g_board[to] == 0) { to += inc; }
if (((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) == pieceRook) || ((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) == pieceChariot)) {
if ((Dagaz.AI.g_board[to] & Dagaz.AI.colorWhite) == us) {
usAttacks[usAttacks.length] = to;
} else {
themAttacks[themAttacks.length] = to;
}
return;
}
if ((Dagaz.AI.g_board[to] & Dagaz.AI.PLAYERS_MASK) == 0) return;
to += inc; while (Dagaz.AI.g_board[to] == 0) { to += inc; }
if (((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) != pieceCannon) && ((Dagaz.AI.g_board[to] & Dagaz.AI.TYPE_MASK) != pieceGun)) return;
if ((Dagaz.AI.g_board[to] & Dagaz.AI.colorWhite) == us) {
usAttacks[usAttacks.length] = to;
} else {
themAttacks[themAttacks.length] = to;
}
}
function SeeAddSliderAttacks(target, us, attacks, pieceType) {
var pieceIdx = (us | pieceType) << Dagaz.AI.COUNTER_SIZE;
var attackerSq = Dagaz.AI.g_pieceList[pieceIdx++];
var hit = false;
while (attackerSq != 0) {
if (IsSquareAttackableFrom(target, attackerSq)) {
if (pieceType > piecePawn) {
attacks[attacks.length] = attackerSq;
}
hit = true;
}
attackerSq = Dagaz.AI.g_pieceList[pieceIdx++];
}
return hit;
}
})();
|
/*!
* # Semantic UI 2.1.8 - Popup
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.popup = function(parameters) {
var
$allModules = $(this),
$document = $(document),
$window = $(window),
$body = $('body'),
moduleSelector = $allModules.selector || '',
hasTouch = (true),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.popup.settings, parameters)
: $.extend({}, $.fn.popup.settings),
selector = settings.selector,
className = settings.className,
error = settings.error,
metadata = settings.metadata,
namespace = settings.namespace,
eventNamespace = '.' + settings.namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$target = (settings.target)
? $(settings.target)
: $module,
$popup,
$offsetParent,
searchDepth = 0,
triedPositions = false,
openedWithTouch = false,
element = this,
instance = $module.blocks(moduleNamespace),
elementNamespace,
id,
module
;
module = {
// binds events
initialize: function() {
module.debug('Initializing', $module);
module.createID();
module.bind.events();
if( !module.exists() && settings.preserve) {
module.create();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance', module);
instance = module;
$module
.blocks(moduleNamespace, instance)
;
},
refresh: function() {
if(settings.popup) {
$popup = $(settings.popup).eq(0);
}
else {
if(settings.inline) {
$popup = $target.nextAll(selector.popup).eq(0);
settings.popup = $popup;
}
}
if(settings.popup) {
$popup.addClass(className.loading);
$offsetParent = module.get.offsetParent();
$popup.removeClass(className.loading);
if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
module.debug('Moving popup to the same offset parent as activating element');
$popup
.detach()
.appendTo($offsetParent)
;
}
}
else {
$offsetParent = (settings.inline)
? module.get.offsetParent($target)
: module.has.popup()
? module.get.offsetParent($popup)
: $body
;
}
if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) {
module.debug('Setting page as offset parent');
$offsetParent = $body;
}
if( module.get.variation() ) {
module.set.variation();
}
},
reposition: function() {
module.refresh();
module.set.position();
},
destroy: function() {
module.debug('Destroying previous module');
// remove element only if was created dynamically
if($popup && !settings.preserve) {
module.removePopup();
}
// clear all timeouts
clearTimeout(module.hideTimer);
clearTimeout(module.showTimer);
// remove events
$window.off(elementNamespace);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
event: {
start: function(event) {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.show
: settings.delay
;
clearTimeout(module.hideTimer);
if(!openedWithTouch) {
module.showTimer = setTimeout(module.show, delay);
}
},
end: function() {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.hide
: settings.delay
;
clearTimeout(module.showTimer);
module.hideTimer = setTimeout(module.hide, delay);
},
touchstart: function(event) {
openedWithTouch = true;
module.show();
},
resize: function() {
if( module.is.visible() ) {
module.set.position();
}
},
hideGracefully: function(event) {
// don't close on clicks inside popup
if(event && $(event.target).closest(selector.popup).length === 0) {
module.debug('Click occurred outside popup hiding popup');
module.hide();
}
else {
module.debug('Click was inside popup, keeping popup open');
}
}
},
// generates popup html from metadata
create: function() {
var
html = module.get.html(),
title = module.get.title(),
content = module.get.content()
;
if(html || content || title) {
module.debug('Creating pop-up html');
if(!html) {
html = settings.templates.popup({
title : title,
content : content
});
}
$popup = $('<div/>')
.addClass(className.popup)
.blocks(metadata.activator, $module)
.html(html)
;
if(settings.inline) {
module.verbose('Inserting popup element inline', $popup);
$popup
.insertAfter($module)
;
}
else {
module.verbose('Appending popup element to body', $popup);
$popup
.appendTo( $context )
;
}
module.refresh();
module.set.variation();
if(settings.hoverable) {
module.bind.popup();
}
settings.onCreate.call($popup, element);
}
else if($target.next(selector.popup).length !== 0) {
module.verbose('Pre-existing popup found');
settings.inline = true;
settings.popups = $target.next(selector.popup).blocks(metadata.activator, $module);
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else if(settings.popup) {
$(settings.popup).blocks(metadata.activator, $module);
module.verbose('Used popup specified in settings');
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else {
module.debug('No content specified skipping display', element);
}
},
createID: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
},
// determines popup state
toggle: function() {
module.debug('Toggling pop-up');
if( module.is.hidden() ) {
module.debug('Popup is hidden, showing pop-up');
module.unbind.close();
module.show();
}
else {
module.debug('Popup is visible, hiding pop-up');
module.hide();
}
},
show: function(callback) {
callback = callback || function(){};
module.debug('Showing pop-up', settings.transition);
if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) {
if( !module.exists() ) {
module.create();
}
if(settings.onShow.call($popup, element) === false) {
module.debug('onShow callback returned false, cancelling popup animation');
return;
}
else if(!settings.preserve && !settings.popup) {
module.refresh();
}
if( $popup && module.set.position() ) {
module.save.conditions();
if(settings.exclusive) {
module.hideAll();
}
module.animate.show(callback);
}
}
},
hide: function(callback) {
callback = callback || function(){};
if( module.is.visible() || module.is.animating() ) {
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
module.remove.visible();
module.unbind.close();
module.restore.conditions();
module.animate.hide(callback);
}
},
hideAll: function() {
$(selector.popup)
.filter('.' + className.visible)
.each(function() {
$(this)
.blocks(metadata.activator)
.popup('hide')
;
})
;
},
exists: function() {
if(!$popup) {
return false;
}
if(settings.inline || settings.popup) {
return ( module.has.popup() );
}
else {
return ( $popup.closest($context).length >= 1 )
? true
: false
;
}
},
removePopup: function() {
if( module.has.popup() && !settings.popup) {
module.debug('Removing popup', $popup);
$popup.remove();
$popup = undefined;
settings.onRemove.call($popup, element);
}
},
save: {
conditions: function() {
module.cache = {
title: $module.attr('title')
};
if (module.cache.title) {
$module.removeAttr('title');
}
module.verbose('Saving original attributes', module.cache.title);
}
},
restore: {
conditions: function() {
if(module.cache && module.cache.title) {
$module.attr('title', module.cache.title);
module.verbose('Restoring original attributes', module.cache.title);
}
return true;
}
},
animate: {
show: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.set.visible();
$popup
.transition({
animation : settings.transition + ' in',
queue : false,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
onComplete : function() {
module.bind.close();
callback.call($popup, element);
settings.onVisible.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
},
hide: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
module.debug('Hiding pop-up');
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
$popup
.transition({
animation : settings.transition + ' out',
queue : false,
duration : settings.duration,
debug : settings.debug,
verbose : settings.verbose,
onComplete : function() {
module.reset();
callback.call($popup, element);
settings.onHidden.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
}
},
change: {
content: function(html) {
$popup.html(html);
}
},
get: {
html: function() {
$module.removeData(metadata.html);
return $module.blocks(metadata.html) || settings.html;
},
title: function() {
$module.removeData(metadata.title);
return $module.blocks(metadata.title) || settings.title;
},
content: function() {
$module.removeData(metadata.content);
return $module.blocks(metadata.content) || $module.attr('title') || settings.content;
},
variation: function() {
$module.removeData(metadata.variation);
return $module.blocks(metadata.variation) || settings.variation;
},
popup: function() {
return $popup;
},
popupOffset: function() {
return $popup.offset();
},
calculations: function() {
var
targetElement = $target[0],
targetPosition = (settings.inline || (settings.popup && settings.movePopup))
? $target.position()
: $target.offset(),
calculations = {},
screen
;
calculations = {
// element which is launching popup
target : {
element : $target[0],
width : $target.outerWidth(),
height : $target.outerHeight(),
top : targetPosition.top,
left : targetPosition.left,
margin : {}
},
// popup itself
popup : {
width : $popup.outerWidth(),
height : $popup.outerHeight()
},
// offset container (or 3d context)
parent : {
width : $offsetParent.outerWidth(),
height : $offsetParent.outerHeight()
},
// screen boundaries
screen : {
scroll: {
top : $window.scrollTop(),
left : $window.scrollLeft()
},
width : $window.width(),
height : $window.height()
}
};
// add in container calcs if fluid
if( settings.setFluidWidth && module.is.fluid() ) {
calculations.container = {
width: $popup.parent().outerWidth()
};
calculations.popup.width = calculations.container.width;
}
// add in margins if inline
calculations.target.margin.top = (settings.inline)
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
: 0
;
calculations.target.margin.left = (settings.inline)
? module.is.rtl()
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
: parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left') , 10)
: 0
;
// calculate screen boundaries
screen = calculations.screen;
calculations.boundary = {
top : screen.scroll.top,
bottom : screen.scroll.top + screen.height,
left : screen.scroll.left,
right : screen.scroll.left + screen.width
};
return calculations;
},
id: function() {
return id;
},
startEvent: function() {
if(settings.on == 'hover') {
return 'mouseenter';
}
else if(settings.on == 'focus') {
return 'focus';
}
return false;
},
scrollEvent: function() {
return 'scroll';
},
endEvent: function() {
if(settings.on == 'hover') {
return 'mouseleave';
}
else if(settings.on == 'focus') {
return 'blur';
}
return false;
},
distanceFromBoundary: function(offset, calculations) {
var
distanceFromBoundary = {},
popup,
boundary
;
offset = offset || module.get.offset();
calculations = calculations || module.get.calculations();
// shorthand
popup = calculations.popup;
boundary = calculations.boundary;
if(offset) {
distanceFromBoundary = {
top : (offset.top - boundary.top),
left : (offset.left - boundary.left),
right : (boundary.right - (offset.left + popup.width) ),
bottom : (boundary.bottom - (offset.top + popup.height) )
};
module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
}
return distanceFromBoundary;
},
offsetParent: function($target) {
var
element = ($target !== undefined)
? $target[0]
: $module[0],
parentNode = element.parentNode,
$node = $(parentNode)
;
if(parentNode) {
var
is2D = ($node.css('transform') === 'none'),
isStatic = ($node.css('position') === 'static'),
isHTML = $node.is('html')
;
while(parentNode && !isHTML && isStatic && is2D) {
parentNode = parentNode.parentNode;
$node = $(parentNode);
is2D = ($node.css('transform') === 'none');
isStatic = ($node.css('position') === 'static');
isHTML = $node.is('html');
}
}
return ($node && $node.length > 0)
? $node
: $()
;
},
positions: function() {
return {
'top left' : false,
'top center' : false,
'top right' : false,
'bottom left' : false,
'bottom center' : false,
'bottom right' : false,
'left center' : false,
'right center' : false
};
},
nextPosition: function(position) {
var
positions = position.split(' '),
verticalPosition = positions[0],
horizontalPosition = positions[1],
opposite = {
top : 'bottom',
bottom : 'top',
left : 'right',
right : 'left'
},
adjacent = {
left : 'center',
center : 'right',
right : 'left'
},
backup = {
'top left' : 'top center',
'top center' : 'top right',
'top right' : 'right center',
'right center' : 'bottom right',
'bottom right' : 'bottom center',
'bottom center' : 'bottom left',
'bottom left' : 'left center',
'left center' : 'top left'
},
adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'),
oppositeTried = false,
adjacentTried = false,
nextPosition = false
;
if(!triedPositions) {
module.verbose('All available positions available');
triedPositions = module.get.positions();
}
module.debug('Recording last position tried', position);
triedPositions[position] = true;
if(settings.prefer === 'opposite') {
nextPosition = [opposite[verticalPosition], horizontalPosition];
nextPosition = nextPosition.join(' ');
oppositeTried = (triedPositions[nextPosition] === true);
module.debug('Trying opposite strategy', nextPosition);
}
if((settings.prefer === 'adjacent') && adjacentsAvailable ) {
nextPosition = [verticalPosition, adjacent[horizontalPosition]];
nextPosition = nextPosition.join(' ');
adjacentTried = (triedPositions[nextPosition] === true);
module.debug('Trying adjacent strategy', nextPosition);
}
if(adjacentTried || oppositeTried) {
module.debug('Using backup position', nextPosition);
nextPosition = backup[position];
}
return nextPosition;
}
},
set: {
position: function(position, calculations) {
// exit conditions
if($target.length === 0 || $popup.length === 0) {
module.error(error.notFound);
return;
}
var
offset,
distanceAway,
target,
popup,
parent,
positioning,
popupOffset,
distanceFromBoundary
;
calculations = calculations || module.get.calculations();
position = position || $module.blocks(metadata.position) || settings.position;
offset = $module.blocks(metadata.offset) || settings.offset;
distanceAway = settings.distanceAway;
// shorthand
target = calculations.target;
popup = calculations.popup;
parent = calculations.parent;
if(target.width === 0 && target.height === 0 && !(target.element instanceof SVGGraphicsElement)) {
module.debug('Popup target is hidden, no action taken');
return false;
}
if(settings.inline) {
module.debug('Adding margin to calculation', target.margin);
if(position == 'left center' || position == 'right center') {
offset += target.margin.top;
distanceAway += -target.margin.left;
}
else if (position == 'top left' || position == 'top center' || position == 'top right') {
offset += target.margin.left;
distanceAway -= target.margin.top;
}
else {
offset += target.margin.left;
distanceAway += target.margin.top;
}
}
module.debug('Determining popup position from calculations', position, calculations);
if (module.is.rtl()) {
position = position.replace(/left|right/g, function (match) {
return (match == 'left')
? 'right'
: 'left'
;
});
module.debug('RTL: Popup position updated', position);
}
// if last attempt use specified last resort position
if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') {
position = settings.lastResort;
}
switch (position) {
case 'top left':
positioning = {
top : 'auto',
bottom : parent.height - target.top + distanceAway,
left : target.left + offset,
right : 'auto'
};
break;
case 'top center':
positioning = {
bottom : parent.height - target.top + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
top : 'auto',
right : 'auto'
};
break;
case 'top right':
positioning = {
bottom : parent.height - target.top + distanceAway,
right : parent.width - target.left - target.width - offset,
top : 'auto',
left : 'auto'
};
break;
case 'left center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
right : parent.width - target.left + distanceAway,
left : 'auto',
bottom : 'auto'
};
break;
case 'right center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
left : target.left + target.width + distanceAway,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom left':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom center':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom right':
positioning = {
top : target.top + target.height + distanceAway,
right : parent.width - target.left - target.width - offset,
left : 'auto',
bottom : 'auto'
};
break;
}
if(positioning === undefined) {
module.error(error.invalidPosition, position);
}
module.debug('Calculated popup positioning values', positioning);
// tentatively place on stage
$popup
.css(positioning)
.removeClass(className.position)
.addClass(position)
.addClass(className.loading)
;
popupOffset = module.get.popupOffset();
// see if any boundaries are surpassed with this tentative position
distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);
if( module.is.offstage(distanceFromBoundary, position) ) {
module.debug('Position is outside viewport', position);
if(searchDepth < settings.maxSearchDepth) {
searchDepth++;
position = module.get.nextPosition(position);
module.debug('Trying new position', position);
return ($popup)
? module.set.position(position, calculations)
: false
;
}
else {
if(settings.lastResort) {
module.debug('No position found, showing with last position');
}
else {
module.debug('Popup could not find a position to display', $popup);
module.error(error.cannotPlace, element);
module.remove.attempts();
module.remove.loading();
module.reset();
settings.onUnplaceable.call($popup, element);
return false;
}
}
}
module.debug('Position is on stage', position);
module.remove.attempts();
module.remove.loading();
if( settings.setFluidWidth && module.is.fluid() ) {
module.set.fluidWidth(calculations);
}
return true;
},
fluidWidth: function(calculations) {
calculations = calculations || module.get.calculations();
module.debug('Automatically setting element width to parent width', calculations.parent.width);
$popup.css('width', calculations.container.width);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation && module.has.popup() ) {
module.verbose('Adding variation to popup', variation);
$popup.addClass(variation);
}
},
visible: function() {
$module.addClass(className.visible);
}
},
remove: {
loading: function() {
$popup.removeClass(className.loading);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation) {
module.verbose('Removing variation', variation);
$popup.removeClass(variation);
}
},
visible: function() {
$module.removeClass(className.visible);
},
attempts: function() {
module.verbose('Resetting all searched positions');
searchDepth = 0;
triedPositions = false;
}
},
bind: {
events: function() {
module.debug('Binding popup events to module');
if(settings.on == 'click') {
$module
.on('click' + eventNamespace, module.toggle)
;
}
if(settings.on == 'hover' && hasTouch) {
$module
.on('touchstart' + eventNamespace, module.event.touchstart)
;
}
if( module.get.startEvent() ) {
$module
.on(module.get.startEvent() + eventNamespace, module.event.start)
.on(module.get.endEvent() + eventNamespace, module.event.end)
;
}
if(settings.target) {
module.debug('Target set to element', $target);
}
$window.on('resize' + elementNamespace, module.event.resize);
},
popup: function() {
module.verbose('Allowing hover events on popup to prevent closing');
if( $popup && module.has.popup() ) {
$popup
.on('mouseenter' + eventNamespace, module.event.start)
.on('mouseleave' + eventNamespace, module.event.end)
;
}
},
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
$context
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
}
if(settings.on == 'hover' && openedWithTouch) {
module.verbose('Binding popup close event to document');
$document
.on('touchstart' + elementNamespace, function(event) {
module.verbose('Touched away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Binding popup close event to document');
$document
.on('click' + elementNamespace, function(event) {
module.verbose('Clicked away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
}
},
unbind: {
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.off('scroll' + elementNamespace, module.hide)
;
$context
.off('scroll' + elementNamespace, module.hide)
;
}
if(settings.on == 'hover' && openedWithTouch) {
$document
.off('touchstart' + elementNamespace)
;
openedWithTouch = false;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Removing close event from document');
$document
.off('click' + elementNamespace)
;
}
}
},
has: {
popup: function() {
return ($popup && $popup.length > 0);
}
},
is: {
offstage: function(distanceFromBoundary, position) {
var
offstage = []
;
// return boundaries that have been surpassed
$.each(distanceFromBoundary, function(direction, distance) {
if(distance < -settings.jitter) {
module.debug('Position exceeds allowable distance from edge', direction, distance, position);
offstage.push(direction);
}
});
if(offstage.length > 0) {
return true;
}
else {
return false;
}
},
active: function() {
return $module.hasClass(className.active);
},
animating: function() {
return ($popup !== undefined && $popup.hasClass(className.animating) );
},
fluid: function() {
return ($popup !== undefined && $popup.hasClass(className.fluid));
},
visible: function() {
return ($popup !== undefined && $popup.hasClass(className.visible));
},
dropdown: function() {
return $module.hasClass(className.dropdown);
},
hidden: function() {
return !module.is.visible();
},
rtl: function () {
return $module.css('direction') == 'rtl';
}
},
reset: function() {
module.remove.visible();
if(settings.preserve) {
if($.fn.transition !== undefined) {
$popup
.transition('remove transition')
;
}
}
else {
module.removePopup();
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.popup.settings = {
name : 'Popup',
// module settings
debug : false,
verbose : false,
performance : true,
namespace : 'popup',
// callback only when element added to dom
onCreate : function(){},
// callback before element removed from dom
onRemove : function(){},
// callback before show animation
onShow : function(){},
// callback after show animation
onVisible : function(){},
// callback before hide animation
onHide : function(){},
// callback when popup cannot be positioned in visible screen
onUnplaceable: function(){},
// callback after hide animation
onHidden : function(){},
// when to show popup
on : 'hover',
// whether to add touchstart events when using hover
addTouchEvents : true,
// default position relative to element
position : 'top left',
// name of variation to use
variation : '',
// whether popup should be moved to context
movePopup : true,
// element which popup should be relative to
target : false,
// jq selector or element that should be used as popup
popup : false,
// popup should remain inline next to activator
inline : false,
// popup should be removed from page on hide
preserve : false,
// popup should not close when being hovered on
hoverable : false,
// explicitly set content
content : false,
// explicitly set html
html : false,
// explicitly set title
title : false,
// whether automatically close on clickaway when on click
closable : true,
// automatically hide on scroll
hideOnScroll : 'auto',
// hide other popups on show
exclusive : false,
// context to attach popups
context : 'body',
// position to prefer when calculating new position
prefer : 'opposite',
// specify position to appear even if it doesn't fit
lastResort : false,
// delay used to prevent accidental refiring of animations due to user error
delay : {
show : 50,
hide : 70
},
// whether fluid variation should assign width explicitly
setFluidWidth : true,
// transition settings
duration : 200,
transition : 'scale',
// distance away from activating element in px
distanceAway : 0,
// number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
jitter : 2,
// offset on aligning axis from calculated position
offset : 0,
// maximum times to look for a position before failing (9 positions total)
maxSearchDepth : 15,
error: {
invalidPosition : 'The position you specified is not a valid position',
cannotPlace : 'Popup does not fit within the boundaries of the viewport',
method : 'The method you called is not defined.',
noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
notFound : 'The target or popup you specified does not exist on the page'
},
metadata: {
activator : 'activator',
content : 'content',
html : 'html',
offset : 'offset',
position : 'position',
title : 'title',
variation : 'variation'
},
className : {
active : 'active',
animating : 'animating',
dropdown : 'dropdown',
fluid : 'fluid',
loading : 'loading',
popup : 'ui popup',
position : 'top left center bottom right',
visible : 'visible'
},
selector : {
popup : '.ui.popup'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
popup: function(text) {
var
html = '',
escape = $.fn.popup.settings.templates.escape
;
if(typeof text !== undefined) {
if(typeof text.title !== undefined && text.title) {
text.title = escape(text.title);
html += '<div class="header">' + text.title + '</div>';
}
if(typeof text.content !== undefined && text.content) {
text.content = escape(text.content);
html += '<div class="content">' + text.content + '</div>';
}
}
return html;
}
}
};
})( jQuery, window, document );
|
module.exports = (gulp, plugins, utilities) => {
return () => gulp.src(utilities.paths.TEST_FILES, {read: false})
.pipe(plugins.mocha({
compilers: {js: plugins.babel},
require: ['./lib/jsdom'] // Prepare environement for React/JSX testing
})).once('end', function () {
if (utilities.exitAfterTest) process.exit();
});
}; |
'use strict';
const assert = require('assert');
const RAND = require('../../../../src/sqlFunctions/basic/RAND');
const DataType = require('../../../../src/DataType');
describe('SQL function RAND()', () => {
it('data type', () => {
assert.strictEqual(RAND.dataType(), DataType.NUMBER);
});
it('result', () => {
const f = new RAND;
assert.strictEqual(typeof(f.call([])), 'number');
});
});
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Schedule Day Schema
*/
var ScheduleDaySchema = new Schema({
day: {
type: String,
enum: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
required: true
},
active: {
type: Boolean,
required: true
},
time: {
type: String,
match: /([1-9]|1[0-2]):[0-5][0-9](AM|PM)/,
required: true
},
target: {
type: Number,
min: 0,
max: 100,
required: true
}
});
/**
* Vehicle Schema
*/
var VehicleSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User',
index: true,
required: true
},
primary: {
// TODO: Set validation for only one primary
type: Boolean,
default: null
},
manufacturer: {
type: String,
required: true
},
model: {
type: String,
required: true
},
latestState: {
type: Number,
min: 0,
max: 120
},
currentCharge: {
type: Schema.ObjectId,
ref: 'Charge',
default: null,
},
/* // array to store velocity vector, which is re-computed daily
velocityVector: [Number],*/
// schedule generated in planning view (array of scheduleDays)
schedule: [ScheduleDaySchema]
});
/*// Validate that the velocity vector contains 100 positive values
VehicleSchema.path('velocityVector').validate(function(vector) {
var positive = true;
vector.forEach(function(element) {
if (element < 0) { positive = false; }
});
return positive && vector.length === 100;
}, 'Velocity vector incomplete or invalid');*/
// Validate that schedule includes each day of week only once
VehicleSchema.path('schedule').validate(function(schedule) {
// skip validation if no schedule has been made
if(schedule.length === 0) {
return true;
}
var weekDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var scheduleDays = _.pluck(schedule, 'day');
return (scheduleDays.length === 7 && _.difference(weekDays,scheduleDays).length === 0);
}, 'Schedule must include each day of the week');
mongoose.model('Vehicle', VehicleSchema);
|
/// <reference path="typings/globals/dc.framework/index.d.ts" />
(function () {
/**
* 通用帮助类
*/
function dcUtil() {
this.isArray = function (object) {
return object && typeof object === 'object' &&
Array == object.constructor;
};
this.isUrl = function (str) {
var regex = /^.*\/?\w*\.\w*\/?$/g;
return !regex.test(str);
};
var _isString = function (object) {
if (typeof (object) == 'string')
return true;
else
return false;
};
this.isString = _isString;
/**
* 日期格式化
* @param dateOrTimestamp js日期对象或者timestamp
* @param formatter 格式化,默认值 yyyy-MM-dd
*/
this.dateFormatter = function (dateOrTimestamp, formatter) {
//类型转换
var dateObj = dateOrTimestamp;
if (!isNaN(dateOrTimestamp))
dateObj = new Date(dateOrTimestamp);
if (_isString(dateOrTimestamp)) {
return dateOrTimestamp;
}
//formatter默认值
if (!formatter)
formatter = "yyyy-MM-dd";
var date = {
"M+": dateObj.getMonth() + 1,
"d+": dateObj.getDate(),
"h+": dateObj.getHours(),
"m+": dateObj.getMinutes(),
"s+": dateObj.getSeconds(),
"q+": Math.floor((dateObj.getMonth() + 3) / 3),
"S+": dateObj.getMilliseconds()
};
//主逻辑
var format = formatter;
if (/(y+)/i.test(format)) {
var year = dateObj.getFullYear();
if (year > 3000) {
year = dateObj.getYear();
}
format = format.replace(RegExp.$1, (year + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
//表示全局唯一标识符 (GUID)
var guid = function (g) {
var arr = new Array(); //存放32位数值的数组
if (typeof (g) == "string") { //如果构造函数的参数为字符串
InitByString(arr, g);
} else {
InitByOther(arr);
}
//返回一个值,该值指示 Guid 的两个实例是否表示同一个值。
this.Equals = function (o) {
if (o && o.IsGuid) {
return this.ToString() == o.ToString();
} else {
return false;
}
};
//Guid对象的标记
this.IsGuid = function () {
};
//返回 Guid 类的此实例值的 String 表示形式。
this.ToString = function (format) {
if (typeof (format) == "string") {
if (format == "N" || format == "D" || format == "B" || format == "P") {
return ToStringWithFormat(arr, format);
} else {
return ToStringWithFormat(arr, "D");
}
} else {
return ToStringWithFormat(arr, "D");
}
};
//由字符串加载
function InitByString(arr, g) {
g = g.replace(/\{|\(|\)|\}|-/g, "");
g = g.toLowerCase();
if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
InitByOther(arr);
} else {
for (var i = 0; i < g.length; i++) {
arr.push(g[i]);
}
}
}
//由其他类型加载
function InitByOther(arr) {
var i = 32;
while (i--) {
arr.push("0");
}
}
/*
根据所提供的格式说明符,返回此 Guid 实例值的 String 表示形式。
N 32 位: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
D 由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
B 括在大括号中、由连字符分隔的 32 位数字:{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
P 括在圆括号中、由连字符分隔的 32 位数字:(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
*/
function ToStringWithFormat(arr, format) {
switch (format) {
case "N":
return arr.toString().replace(/,/g, "");
case "D":
var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
str = str.replace(/,/g, "");
return str;
case "B":
var str = ToStringWithFormat(arr, "D");
str = "{" + str + "}";
return str;
case "P":
var str = ToStringWithFormat(arr, "D");
str = "(" + str + ")";
return str;
default:
return new Guid();
}
}
};
var GUID = {};
//Guid 类的默认实例,其值保证均为零。
GUID.empty = guid();
//初始化 Guid 类的一个新实例。
GUID.newGuid = function () {
/// <summary>初始化 Guid 类的一个新实例</summary>
var g = "";
var i = 32;
while (i--) {
g += Math.floor(Math.random() * 16.0).toString(16);
}
return new $.Guid(g);
};
this.GUID = GUID;
this.GUID = GUID;
/**
* 对象克隆属性,克隆对象b的属性至对象a的一个克隆
* @param obja 基础对象
* @param objb 需要克隆属性的对象
* @param iProArray 克隆忽略的属性
*/
this.cloneObjectPro = function (obja, objb, iProArray) {
iProArray = iProArray || [];
iProArray = iProArray.join(',');
var objc = {};
for (var a in obja) {
objc[a] = obja[a];
}
if (typeof (objb) == "object") {
for (var p in objb) {
if (iProArray.indexOf(p) >= 0) {
continue; //忽略,不拷贝
} else {
objc[p] = objb[p];
}
}
}
return objc;
};
/**
* 获取当前页面的网址,不包含页面的名称
* @returns string
*/
this.getUrl = function () {
var url = window.location.href;
return url.substring(0, url.lastIndexOf("/"));
};
/**
* 获取网站根路径(包含虚拟路径)
* @returns string
*/
this.getRootUrl = function () {
var strProtocol = window.location.protocol + "//";
var strFullPath = window.location.href;
strFullPath = strFullPath.replace(strProtocol, '');
var strPath = window.document.location.pathname;
var pos = strFullPath.indexOf(strPath);
var prePath = strFullPath.substring(0, pos);
var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
if (postPath.toLowerCase() == "/home") {
postPath = "";
}
if (postPath.toLowerCase() == "/importexport") {
postPath = "";
}
return (strProtocol + prePath + postPath);
}
/**
* 获取Url中的参数 Json
*/
this.getRequest = function () {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
theRequest.count = 0;
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
theRequest.count++;
}
}
return theRequest;
};
}
/**
* 提示框对象
*/
function dcInfo() {
/**
* 普通消息框
* @param msg 消息内容
* @param option 额外配置对象
*/
this.alert = function (msg, option) {
var title = "提示";
var fn = undefined;
if (option) {
if (option.title) {
title = option.title;
}
if (option.fn) {
fn = option.fn;
}
}
$.messager.alert(title, msg, 'info', fn);
};
/**
* 错误提示框
* @param msg 消息内容
* @param option 额外配置对象
*/
this.error = function (msg, option) {
var title = "错误";
var fn = undefined;
if (option) {
if (option.title) {
title = option.title;
}
if (option.fn) {
fn = option.fn;
}
}
$.messager.alert(title, msg, 'error', fn);
};
/**
* 警告框
* @param msg 消息内容
* @param option 额外配置对象
*/
this.warn = function (msg, option) {
var title = "警告";
var fn = undefined;
if (option) {
if (option.title) {
title = option.title;
}
if (option.fn) {
fn = option.fn;
}
}
$.messager.alert(title, msg, 'warning', fn);
};
/**
* 询问框
* @param msg 消息内容
* @param option 额外配置对象
*/
this.confirm = function (msg, option) {
var title = "询问";
var fn = undefined;
if (option) {
if (option.title) {
title = option.title;
}
if (option.fn) {
fn = option.fn;
}
}
$.messager.confirm(title, msg, fn);
};
/**
* 自动隐藏信息框
* @param msg 消息内容
* @param option 额外配置对象
*/
this.show = function (msg, option) {
var _option = {
showType: "slide",
title: "提示",
msg: msg,
timeout: 1000
}
_option = dc.util.cloneObjectPro(_option, option);
$.messager.show(_option);
};
}
/**
* 选项卡组对象
*/
function dcTabs() {
/**
* 添加新的tab
* @param id tabs的id
* @param tabObj 需要添加的tab对象
*/
this.add = function (id, tabObj) {
if (tabObj != undefined && typeof (tabObj) == "object") {
if (tabObj.id) {
if ($("#" + tabObj.id).length == 0) {
tabObj.content = "<iframe style='width:100%;height:100%;border:none;overflow:hidden' src='" + tabObj.href + "'></iframe>";
tabObj.href = undefined;
$("#" + id).tabs("add", tabObj);
} else {
throw "id为[" + tabObj.id + "]的tab已经存在";
}
} else {
throw "请设置tab的id";
}
}
}
/**
* 删除指定tab
* @param id tabs的id
* @param tabid 需要删除的选项的id
*/
this.close = function (id, tabid) {
var tab = $("#" + tabid);
if (tab.length == 0) {
throw "id为[" + tabid + "]的tab不存在";
} else {
var index = $("#" + id).tabs("getTabIndex", tab[0]);
$("#" + id).tabs("close", index);
}
}
/**
* 选中指定的tab
* @param id tabs的id
* @param tabid 需要选中的选项的id
*/
this.select = function (id, tabid) {
var tab = $("#" + tabid);
if (tab.length == 0) {
throw "id为[" + tabid + "]的tab不存在";
} else {
var index = $("#" + id).tabs("getTabIndex", tab[0]);
$("#" + id).tabs("select", index);
}
}
/**
* 刷新指定的tab
* @param id tabs的id
* @param tabid 需要刷新的选项的id
*/
this.refresh = function (id, tabid) {
var tab = $("#" + tabid);
if (tab.length == 0) {
throw "id为[" + tabid + "]的tab不存在";
} else {
$("#" + tabid).find("iframe").attr("src", $("#" + tabid).find("iframe").attr("src"));
}
}
/**
* 更新指定的tab
* @param id tabs的id
* @param tabid 需要更新的选项的id
* @param tabObj 面板更新对象,可设置三个属性,title,href,selected
*/
this.update = function (id, tabid, tabObj) {
var tab = $("#" + tabid);
if (tab.length == 0) {
console.error("id为[" + tabid + "]的tab不存在");
} else {
if (tabObj) {
tabObj.selected = tabObj.selected || false;
if (!tabObj.title) {
throw "请设置更新的标题";
}
if (!tabObj.href) {
throw "请设置更新的地址";
}
$("#" + id).tabs("update",
{
tab: tab,
options: {
title: tabObj.title
}
});
$("#" + tabid).find("iframe").attr("src", tabObj.href);
if (tabObj.selected) {
dc.tabs.select(id, tabid);
}
} else {
throw "请传入面板更新属性";
}
}
}
}
/**
* 弹框对象
*/
function dcDialog() {
/**
* 打开弹窗
* @param title 窗口标题
* @param url 页面地址
* @param dialogObj 弹窗对象
*/
this.open = function (title, href, dialogObj) {
var _option = {
title: title,
content: "<iframe style='height:100%;width:100%;border:none' src=" + href + "></ifarmae>",
width: 1200,
height: 600,
closed: false,
cache: true,
resizable: true,
maximizable: true,
modal: true,
onClose: function () {
var _dcDialog = window.top.dcDialog;
if (_dcDialog && _dcDialog.length > 0) {
_dcDialog.splice(_dcDialog.length - 1, 1);
} else {
throw "页面内不存在弹窗或页面内弹窗个数为0";
}
if (dialogObj && dialogObj.onClose) {
dialogObj.onClose();
}
}
};
_option = dc.util.cloneObjectPro(_option, dialogObj, ["onClose"]);
if (window.top.location.href != window.location.href) { //本页面不是最外层的页面
if (window.top.base) { //最外层window对象中是否存在base对象
if (_option.onBeforeClose) {
_option.beforeClose = _option.onBeforeClose;
}
if (_option.onClose) {
_option.closeCallback = _option.onClose;
}
window.top.base.openNewDialog(_option);
}
if (window.top.dc) {
window.top.dc.dialog.open(title, href, dialogObj);
}
else {
//弹窗对象全局唯一
window.top.dcDialog = window.top.dcDialog || [];
window.top.dcDialog.push($("<div></div>").dialog(_option));
}
}
else {
if (window.base) {//window对象中是否存在base对象
if (_option.onBeforeClose) {
_option.beforeClose = _option.onBeforeClose;
}
if (_option.onClose) {
_option.closeCallback = _option.onClose;
}
window.top.base.openNewDialog(_option);
}
if (window.dc) {
//弹窗对象全局唯一
window.top.dcDialog = window.top.dcDialog || [];
window.top.dcDialog.push($("<div></div>").dialog(_option));
}
}
}
/**
* 关闭弹窗
* @param result 如果外层有base对象,则此参数为关闭弹窗后的回调函数,否则可不传该参数
*/
this.close = function (result) {
var _dcDialog = window.top.dcDialog;
if (window.top.base) { //最外层window对象中是否存在base对象
window.top.base.closeNewDialog(result);
}
if (window.top.dc) {
if (_dcDialog && _dcDialog.length > 0) {
_dcDialog[_dcDialog.length - 1].dialog('close');
} else {
throw "页面内不存在弹窗或页面内弹窗个数为0";
}
}
}
}
/**
* easyui扩展
*/
$.extend($.fn.datagrid.methods, {
getValue: function (jq) {
var selects = jq.datagrid("getSelections");
var result = [];
if (selects.length > 0) {
var field = jq.datagrid('options').idField;
if (field) {
$.each(selects, function (index, value) {
var val = value[field];
if (val == undefined)
throw new Error("获取datagrid表格数据出错,没有字段:" + field);
result.push(val);
});
}
else
return null;
}
return result;
},
setValue: function (jq, value) {
var array = value;
//判断是否字符串
if (dcFramework.util.isString(value)) {
array = value.split(",");
}
//清空选择
jq.datagrid("clearSelections");
//赋值
$.each(array, function (index, v) {
var i = jq.datagrid("getRowIndex", v);
if (i > -1) {
jq.datagrid("selectRow", i);
}
});
}
});
$.extend($.fn.validatebox.defaults.rules,
{
length: {
validator: function (value, param) {
if (param.length == 1) {
param.splice(0, 0, 0);
}
if (param[0] <= value.length && value.length <= param[1]) {
return true;
} else {
return false;
}
},
message: '输入内容长度必须介于{0}和{1}之间'
},
int: {
validator: function (value, param) {
var regex = new RegExp(/^[\-\+]?\d+$/);
var res = regex.test(value);
if (res && param) {
if (value.length > param[0]) {
$.fn.validatebox.defaults.rules["int"].message = "整数最大" + param[0] + "位";
return false;
} else {
return true;
}
} else {
$.fn.validatebox.defaults.rules["int"].message = "不是有效的整数";
return res;
}
},
message: '不是有效的整数'
},
number: {
validator: function (value, param) {
var regex = new RegExp(/^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/);
var res = regex.test(value);
if (res && param) {
var intlength = value.length;
var decimalLength = 0;
if (value.indexOf('.') >= 0) {
intlength = value.indexOf('.');
decimalLength = value.length - 1 - intlength;
}
if (intlength <= param[0] && decimalLength <= param[1]) {
return true;
} else {
$.fn.validatebox.defaults.rules["number"]
.message = "整数位最大" + param[0] + "位,小数位最大" + param[1] + "位";
return false;
}
} else {
$.fn.validatebox.defaults.rules["number"].message = "不是有效的数字";
return res;
}
},
message: "不是有效的数字"
},
date: {
validator: function (value, param) {
if (value.indexOf('-') >= 0) {
var regex = new
RegExp(/^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$/);
return regex.test(value);
} else if (value.indexOf('/') >= 0) {
var regex2 = new
RegExp(/^[0-9]{4}\/(((0[13578]|(10|12))\/(0[1-9]|[1-2][0-9]|3[0-1]))|(02\/(0[1-9]|[1-2][0-9]))|((0[469]|11)\/(0[1-9]|[1-2][0-9]|30)))$/);
return regex2.test(value);
} else {
var regex3 = new RegExp(/^\d{8}$/);
return regex3.test(value);
}
},
message: "不是有效的日期"
},
datetime: {
validator: function (value, param) {
var regex = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/g;
return regex.test(value);
},
message: "不是有效的时间"
},
checklistbox: {
validator: function (value, param) {
return false;
},
message: "xxx"
}
});
/**
* 前端框架核心对象
*/
function dcjet() {
this.util = new dcUtil();
var _util = this.util;
this.info = new dcInfo();
this.tabs = new dcTabs();
this.dialog = new dcDialog();
//控件区************************************************************************************************************///
//公共配置信息,congfig对象中的属性只有框架有权限进行增加/删除,开发人员不可在config对象中增加/删除属性
this.config = {
control: {},
pageCode: "",
page: {},
fieldValid: {}
};
//私有全局配置
var _option = {
labelPosition: "before",
labelAlign: 'right',
width: "70%",
validateOnCreate: false,
validateOnBlur: true
};
//私有捷通控件默认配置
var _control = {
textbox: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
textarea: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: 1000,
multiline: true,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
password: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
type: "password",
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
intbox: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur,
validType: "int"
},
decimalbox: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
precision: 5,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur,
validType: "number"
},
datagrid: {
idField: "oid",
fitColumns: false,
rownumbers: false,
pagination: true,
pageNumber: 1,
fit: true,
queryParams: {},
pageSize: 15,
pageList: [10, 15, 20],
checkbox: true,
chkBindId: "" //checkbox绑定的字段名
},
select: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
editable: true,
limitToList: true,
textField: "text",
valueField: "value",
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
mselect: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
editable: false,
multiple: true,
limitToList: true,
textField: "text",
valueField: "value",
panelMinHeight: 20,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
autocomplete: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
editable: true,
multiple: false,
limitToList: true,
mode: "remote",
textField: "text",
valueField: "value",
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
fileupload: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: 300,
buttonText: "选择文件",
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
codeautocomplete: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
width: _option.width,
editable: true,
multiple: false,
limitToList: true,
mode: "remote",
valueField: "code",
textField: "name",
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
checkbox: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur
},
mcheckbox: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur,
textField: "text",
valueField: "value",
},
radio: {
labelPosition: _option.labelPosition,
labelAlign: _option.labelAlign,
validateOnCreate: _option.validateOnCreate,
validateOnBlur: _option.validateOnBlur,
textField: "text",
valueField: "value"
},
tabs: {
fit: true,
border: false
},
datebox: {
validType: "date"
},
datetimebox: {
validType: "datetime"
}
};
//控件id-easyui控件类型map对象
var _controlIdTypeMap = {};
/**
* 初始化控件
*/
this.init = function () {
//找到页面所以dcc控件
var controls = $("[dcc],[dc-control]");
$.each(controls, function (n, c) {
var id = c.id;
c = $(c);
var dcType = c.attr("dcc") || c.attr("dc-control");
var ecType = _getEasyUiColType(dcType);
_controlIdTypeMap[id] = ecType;
var option = _getControlOption(id, dcType.replace(/-/g, ""));
//执行特殊控件的初始化
var iscontinue = _specialInit(c, dcType, option);
if (iscontinue) {
//执行easyui控件的初始化
c[ecType](option);
}
});
if (dc.out.init) {//外部初始化
dc.out.init();
}
};
/**
* 获取dc控件继承的easyui控件类型
* @param dcType 捷通控件类型
*/
function _getEasyUiColType(dcType) {
var easyType = dcType;
switch (dcType) {
case "textbox":
{
easyType = "textbox";
break;
}
case "textarea":
{
easyType = "textbox";
break;
}
case "password":
{
easyType = "textbox";
break;
}
case "button":
{
easyType = "linkbutton";
break;
}
case "intbox":
{
easyType = "numberbox";
break;
}
case "decimalbox":
{
easyType = "numberbox";
break;
}
case "select":
{
easyType = "combobox";
break;
}
case "m-select":
{
easyType = "combobox";
break;
}
case "autocomplete":
{
easyType = "combobox";
break;
}
case "m-autocomplete":
{
easyType = "combobox";
break;
}
case "datagrid":
{
easyType = "datagrid";
break;
}
case "fileUpload":
{
easyType = "filebox";
break;
}
case "code-autocomplete":
{
easyType = "combobox";
break;
}
case "m-code-autocomplete":
{
easyType = "combobox";
break;
}
case "fileupload":
{
easyType = "filebox";
break;
}
case "datebox":
{
easyType = "datebox";
break;
}
case "datetimebox":
{
easyType = "datetimebox";
break;
}
case "tabs":
{
easyType = "tabs";
break;
}
case "checkbox":
{
easyType = "checkbox";
break;
}
case "m-checkbox":
{
easyType = "checklistbox";
break;
}
case "radio":
{
easyType = "radiobox";
break;
}
default:
{
throw easyType + "不是我们封装的控件";
}
}
return easyType;
}
/**
* 返回控件的配置信息,包含默认配置及用户自定义配置
*/
function _getControlOption(id, type) {
var option = _control[type] || {};//框架默认配置
option = dc.util.cloneObjectPro(option, dc.config.control[id]);
var dcm = $("#" + id).attr("dcm");
if (dcm) {
if (dc.config.fieldValid) {
option = dc.util.cloneObjectPro(option, dc.config.fieldValid[dcm]);
}
}
//判断是否跨域
if (dc.project.isCrossdomain) {
option.method = "get";
option.dataType = "jsonp";
}
//设置请求类型
else if (option.url && dc.util.isUrl(option.url)) {
if (!option.method)//用户未设置请求类型
{
option.method = "post";
}
} else {
if (!option.method)//用户未设置请求类型
{
option.method = "get";
}
}
//一些控件属性的特殊处理
switch (type) {
case "datagrid"://dc表格控件
{
var chkColumn = {};
option.frozenColumns = option.frozenColumns|| [[]];
//设置checkbox列
if (option.checkbox) {
chkColumn = { checkbox: true, field: "ck" };
option.frozenColumns[0].splice(0, 0, chkColumn);
}
if (option.columns) {
for (var c in option.columns[0]) {
option.columns[0][c].width = option.columns[0][c].width || 100;
}
}
}
break;
case "codeautocomplete":
{//dc 公共参数控件
if (dc.project.commonParamUrl) {
option.url = dc.project.commonParamUrl; //Apollo 公共参数路径
if (option.code) {
option.queryParams = {
"code": option.code
}
}
}
}
break;
}
return option;
}
/**
* 执行特殊控件的初始化
*/
function _specialInit(c, dcType, option) {
//是否继续执行easyui控件的初始化
var iscontinue = true;
var id;
switch (dcType) {
case "fileupload":
{
var _option = {
onSubmit: function () {
var file = $("#" + id).filebox("getValue");
if (file) {
return true;
} else {
dc.info.warn("请选择需要上传的文件!");
return false;
}
},
success: function (result) {
if (result == true || result == "true") {
dc.info.show("上传成功!");
} else {
dc.info.show("上传失败!");
}
}
};
id = c.prop("id");
var dcm = c.attr("dcm") || "";
c.after('<form id="' + id + '_fm" method="' + option.method + '" enctype="multipart/form-data"><input id="' + id + '" name="file" dcm="'+dcm+'" /> <a id="' + id + '_btnupload" >上传</a></form>').remove();
$("#" + id).filebox(option);
$("#" + id + "_btnupload").linkbutton({
width: 60,
height: 24,
onClick: function () {
$("#" + id + "_fm").form("submit",
{
url: option.url,
onSubmit: _option.onSubmit,
success: _option.success
});
}
});
iscontinue = false;
break;
}
case "tabs":
{
c.find("iframe").css({
height: "100%",
width: "100%",
border: "none",
overflow: "hidden"
});
iscontinue = true;
break;
}
case "datebox":
{
_specialDateInit(option);
iscontinue = true;
break;
}
}
return iscontinue;
}
/**
* 日期初始化,特殊处理,可变态输入日期,不加-或者/
* @param option 控件的配置对象
*/
function _specialDateInit(option) {
//to do 日期回车后会默认选择今天日期
option.formatter = function (date) {
option.dcformatter = option.dcformatter || "yyyy-MM-dd";
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
m = m < 10 ? ('0' + m) : m;
d = d < 10 ? ('0' + d) : d;
var value = option.dcformatter.replace("yyyy", y);
value = value.replace("MM", m);
value = value.replace("dd", d);
return value;
};
option.parser = function (s) {
if (!s) return new Date();
var y = 0, m = 0, d = 0;
if (s.indexOf('-') >= 0) {
var ss = s.split('-');
y = parseInt(ss[0], 10);
m = parseInt(ss[1], 10);
d = parseInt(ss[2], 10);
}
else if (s.indexOf('/') >= 0) {
var ss2 = s.split('/');
y = parseInt(ss2[0], 10);
m = parseInt(ss2[1], 10);
d = parseInt(ss2[2], 10);
} else {
y = parseInt(s.substring(0, 4), 10);
m = parseInt(s.substring(4, 6), 10);
d = parseInt(s.substring(6, 8), 10);
}
if (isNaN(m)) {
m = 1;
}
if (isNaN(d)) {
d = 1;
}
if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
return new Date(y, m - 1, d);
} else {
return new Date();
}
};
}
//取值赋值区************************************************************************************************************///
/**
* 根据控件获取
*/
var _getControlType = function (control) {
var cid = control.id || control[0].id;
if (!cid && dc.project.RunMode == dc.project.Enum.dev) {
console.log("获取控件类型时遇到问题 : 无法获取控件的id :" + control)
}
//通过初始化进行优化
if (cid) {
var type = _controlIdTypeMap[cid];
if (type)
return type;
}
if (!control.hasClass)
control = $(control);
if (control) {
var _type = null;
if (control.hasClass("easyui-textbox")) {
_type = "textbox";
}
else if (control.hasClass("easyui-combobox")) {
_type = "combobox";
}
else if (control.hasClass("easyui-numberbox")) {
_type = "numberbox";
}
else if (control.hasClass("datebox-f")) {
_type = "datebox";
}
else if (control.hasClass("datetimebox-f")) {
_type = "datetimebox";
}
else if (control.hasClass("easyui-tagbox")) {
_type = "tagbox";
}
else if (control.hasClass("easyui-passwordbox")) {
_type = "passwordbox";
}
else if (control.hasClass("easyui-filebox")) {
_type = "filebox";
}
else if (control.hasClass("datagrid-f")) {
_type = "datagrid";
}
else if (control.hasClass("easyui-checkbox")) {
_type = "checkbox";
}
else if (control.hasClass("easyui-checklistbox")) {
_type = "checklistbox";
}
else if (control.hasClass("easyui-radiobox")) {
_type = "radiobox";
}
return _type;
}
return null;
};
/**
* 获取控件类型
*/
this.getControlType = _getControlType;
/**
* 获取控件值
*/
var _getValue = function (control) {
if (!control) return null;
//正常取值
var type = _getControlType(control);
/*textbox
combobox
numberbox
datebox
datetimebox
tagbox
passwordbox
filebox
checkbox
m-checkbox
radio*/
var value = null;
switch (type) {
case "textbox":
value = control.textbox('getValue');
break;
case "combobox":
value = control.combobox('getValues');
break;
case "numberbox":
value = control.numberbox('getValue');
break;
case "datebox":
value = control.datebox('getValue');
break;
case "datetimebox":
value = control.datetimebox('getValue');
break;
case "tagbox":
value = control.tagbox('getValues');
break;
case "passwordbox":
value = control.passwordbox('getValue');
break;
case "datagrid":
value = control.datagrid('getValue');
break;
case "checkbox":
value = control.checkbox("getValue");
break;
case "checklistbox":
value = control.checklistbox('getValues');
break;
case "radiobox":
value = control.radiobox('getValue');
break;
case "filebox":
case "fileUpload":
value = control.filebox('getText');
break;
default:
if (control.val)
value = control.val();
break;
}
return value;
};
/**
* 获取值(数组)
* @param selectorOrArray 选择器或者数组,如 #id .class
*/
this.getValues = function (selectorOrArray) {
//数组时,返回map
if (this.util.isArray(selectorOrArray)) {
var map = {};
for (var i = 0; i < selectorOrArray.length; i++) {
map[selectorOrArray[i]] = this.getValues(selectorOrArray[i]);
}
return map;
}
else {
var values = new Array();
var controls = $(selectorOrArray);
controls.each(function () {
values.push(_getValue($(this)));
});
return values;
}
};
/**
* 获取值(多个值时,返回一个)
*/
this.getValue = function (selectorOrArray) {
//数组时,返回map
if (this.util.isArray(selectorOrArray)) {
var map = {};
for (var i = 0; i < selectorOrArray.length; i++) {
map[selectorOrArray[i]] = this.getValue(selectorOrArray[i]);
}
return map;
}
else {
var control = $(selectorOrArray);
return _getValue(control);
}
};
/**
* 内部赋值实现,只用于单纯的赋值,判断控件类型,进行赋值
*/
var _setValue = function (controls, value) {
var type = _getControlType(controls);
/*textbox
combobox
numberbox
datebox
datetimebox
tagbox
passwordbox
filebox
checkbox
m-checbox
radio*/
switch (type) {
case "textbox":
if (value)
controls.textbox('setValue', value);
else
controls.textbox('clear');
break;
case "combobox":
if (value) {
if (_util.isArray(value)) {
controls.combobox('setValues', value);
}
else {
controls.combobox('setValue', value);
}
}
else
controls.combobox('clear');
break;
case "numberbox":
if (value)
controls.numberbox('setValue', value);
else
controls.numberbox('clear');
break;
case "datebox":
if (value)
controls.datebox('setValue', _util.dateFormatter(value, dc.project.dateFormat));
else
controls.datebox('clear');
break;
case "datetimebox":
if (value)
controls.datetimebox('setValue', _util.dateFormatter(value, dc.project.datetimeFormat));
else
controls.datetimebox('clear');
break;
case "tagbox":
if (value) {
if (_util.isArray(value)) {
controls.tagbox('setValues', value);
}
else {
controls.tagbox('setValue', value);
}
}
else
controls.tagbox('clear');
break;
case "passwordbox":
if (value)
controls.passwordbox('setValue', value);
else
controls.passwordbox('clear');
break;
case "datagrid":
controls.datagrid('setValue', value);
break;
case "checkbox":
controls.checkbox("setValue", value);
break;
case "checklistbox":
controls.checklistbox('setValues', value);
break;
case "radiobox":
controls.radiobox('setValue', value);
break;
default:
//throw new Error("控件不能通过setValue来赋值");
}
};
/**
* 设置值 (可以是数组)
*/
this.setValue = function (selectorOrMap, value) {
if (!selectorOrMap) throw new Error("setValue 必须带参数");
//map赋值 没有Value值认为是map方式赋值
if (!value && selectorOrMap && typeof selectorOrMap != 'string') {
for (var key in selectorOrMap) {
if (key && selectorOrMap[key])
this.setValue(key, selectorOrMap[key]);
}
return;
}
//正常赋值
var controls = $(selectorOrMap);
//控件只有一个时,直接赋值
if (controls.length == 1) {
_setValue(controls, value);
}
else {
//判断值是否是数组,如果是数组,如果不是数组,遍历控件赋值相同,如果是数组,进行依次赋值
if (_util.isArray(value) == false || value == null) {
controls.each(function () {
_setValue($(this), value);
});
}
else {
if (controls.length != value.length) {
throw new Error("赋值时控件数量和数组值的数量应该一致:[" + controls.length + ":" + value.length + "]");
}
for (var i = 0; i < controls.length; i++) {
_setValue($(controls[i]), value[i]);
}
}
}
};
/**
* model赋值,只支持Id选择器
*/
this.setModel = function (idSelector, model) {
//找到容器中的对象,进行赋值取值
var controls = $(idSelector).find("[dcm],[dc-model]");
//增加清空功能
if (!model) {
$.each(controls, function (n, c) {
c = $(c);
var dcmVal = c.attr("dcm") || c.attr("dc-model");
if (dcmVal) {
_setValue(c, null);
}
});
}
var dcmControlMap = {};
//获取map
$.each(controls, function (n, c) {
c = $(c);
var dcmVal = c.attr("dcm") || c.attr("dc-model");
if (dcmVal) {
dcmControlMap[dcmVal] = $(c);
}
});
//遍历model,赋值
for (var key in model) {
var control = dcmControlMap[key];
if (control) {
_setValue(control, model[key]);
}
}
};
/**
* model 取值, 参数model可不传
*/
this.getModel = function (idSelector, model) {
//找到容器中的对象,进行赋值取值
var controls = $(idSelector).find("[dcm],[dc-model]");
var json = new Object();
//支持model
if (model) {
json = model;
}
//获取map
$.each(controls, function (n, c) {
c = $(c);
var dcmVal = c.attr("dcm") || c.attr("dc-model");
if (dcmVal) {
var val = _getValue($(c));
//数组自动转化
if (_util.isArray(val)) {
val = val.join(',');
}
json[dcmVal] = val;
}
});
return json;
};
/**
* Ajax post 封装
* @param url 请求的url
* @param data 请求传递的参数
* @param type 返回的数据类型
* @param successfn 请求成功后的回掉函数
* @param errorfn 请求失败后的回掉函数
*/
this.post = function (url, data, successfn, type, errorfn) {
if (!dc.util.isUrl(url)) {
throw "请传入url路径";
}
type = type || "json";
$.ajax({
url: url,
type: "post",
async: true,
data: data,
dataType: type,
success: successfn,
error: errorfn
});
}
/**
* Ajax get 封装
* @param url 请求的url
* @param data 请求传递的参数
* @param type 返回的数据类型
* @param successfn 请求成功后的回掉函数
* @param errorfn 请求失败后的回掉函数
*/
this.get = function (url, data, successfn, type, errorfn) {
if (!dc.util.isUrl(url)) {
throw "请传入url路径";
}
type = type || "json";
$.ajax({
url: url,
type: "get",
async: true,
data: data,
dataType: type,
success: successfn,
error: errorfn
});
}
/**
* Ajax post 同步封装
* @param url 请求的url
* @param data 请求传递的参数
* @param type 返回的数据类型
* @param successfn 请求成功后的回掉函数
* @param errorfn 请求失败后的回掉函数
*/
this.syncPost = function (url, data, type) {
if (!dc.util.isUrl(url)) {
throw "请传入url路径";
}
var res = null;
type = type || "json";
$.ajax({
url: url,
type: "post",
async: false,
data: data,
dataType: type,
success: function (data) {
res = data;
}
});
return res;
}
/**
* Ajax get 同步封装
* @param url 请求的url
* @param data 请求传递的参数
* @param successfn 请求成功后的回掉函数
* @param errorfn 请求失败后的回掉函数
*/
this.syncGet = function (url, data, type) {
if (!dc.util.isUrl(url)) {
throw "请传入url路径";
}
var res = null;
type = type || "json";
$.ajax({
url: url,
type: "get",
async: false,
data: data,
dataType: type,
success: function (data) {
res = data;
}
});
return res;
}
/**
* 获取选项列
* @param urlOrList url或者列表
* @param selectedItem 选中项 可空
* @param isHasPleaseSelect 是否有请选择 默认没有
*/
this.getSelectItemList = function (urlOrList, selectedItem, isHasPleaseSelect) {
if (!isHasPleaseSelect) {
isHasPleaseSelect = false;
}
//是列表情况时
if (!_util.isString(urlOrList)) {
var list = new Array();
var selectedCount = 0;
for (var val in urlOrList) {
var text = urlOrList[val];
var isSelected = false;
//暂时只支持一个选中项
if (selectedItem && selectedItem == val) {
isSelected = true;
selectedCount++;
}
list.push({
"value": val,
"text": text,
"selected": isSelected
});
}
if (isHasPleaseSelect) {
list.splice(0, 0, {
"value": "",
"text": "--请选择--",
"selected": selectedCount == 0
});
}
return list;
}
else {
//直接返回url的值
return _util.syncPost(url);
}
//{"selected":true,"text":"","value":""}
};
};
window.dc = new dcjet();
window.dcFramework = window.dc;
})(window);
/**
* 系统初始化ok后执行
* @type {null|Function}
*/
var dcReady = dcReady || null;
/**
* 当没有apolloFrontend 时,进行初始化
*/
if (!apolloFrontend) {
var apolloFrontend = apolloFrontend || {};
apolloFrontend.init = apolloFrontend.init || null;
var dcReady = dcReady || function (fn) {
apolloFrontend.init = fn;
}
//调用read
$(function () {
if (apolloFrontend.init) {
apolloFrontend.init();
}
});
}
//out 的框架定义
dc.out = dc.out || {};
/**
* 默认外部跳转,可重写
* @param url
* @param title
*/
dc.out.redirect = function (url, title) {
location.href = url;
};
/**
* 日期格式器
* @param value
* @param row
* @param index
* @returns {*}
*/
dc.out.datetimeFormatter = function (value, row, index) {
return dc.util.dateFormatter(value, dc.project.datetimeFormat);
};
dc.out.dateFormatter = function (value, row, index) {
return dc.util.dateFormatter(value, dc.project.dateFormat);
};
//项目默认值
dc.project = dc.project || {};
dc.project.dateFormat = "yyyy-MM-dd";
dc.project.datetimeFormat = "yyyy-MM-dd hh:mm:ss";
//项目枚举项
dc.project.Enum = dc.project.Enum || {};
dc.project.Enum = {
dev: "devMode",
develop: "devMode",
produce: "produceMode",
defaut: "produceMode",
run: "produceMode"
};
//运行模式,默认为生产模式
dc.project.RunMode = dc.project.Enum.defaut;
/**
* easyui扩展-checkbox控件
*/
(function ($) {
$.fn.checkbox = function (options, param) {
if (typeof options == 'string') {
var method = $.fn.checkbox.methods[options];
if (method) {
return method(this, param);
} else {
return this.textbox(options, param);
}
} else {
options = options || { value: false };//默认不选中
return this.each(function () {
var state = $.data(this, 'checkbox');
if (state) {
$.extend(state.options, options);
} else {
$.data(this, 'checkbox', {
options: $.extend({}, $.fn.checkbox.defaults, options)//用户配置覆盖默认配置
});
}
createbox(this);
});
}
};
/**
* 默认配置
*/
$.fn.checkbox.defaults = $.extend({}, $.fn.textbox.defaults, {
value: false
});
$.fn.checkbox.methods = {
options: function (jq) {
var copts = jq.combo('options');
return $.extend($.data(jq[0], 'Checkbox').options, {
width: copts.width,
height: copts.height,
originalValue: copts.originalValue,
disabled: copts.disabled,
readonly: copts.readonly
});
},
setValue: function (jq, value) {
return jq.each(function () {
setValue(this, value);
});
},
getValue: function (jq) {
return getValue(jq);
},
reset: function (jq) {
return jq.each(function () {
var opts = $(this).Checkbox('options');
$(this).Checkbox('setValue', opts.originalValue);
});
}
};
/**
* 控件初始化函数
* @param target 控件对象
*/
function createbox(target) {
var opts = $.data(target, 'checkbox').options;//获取配置对象
var chk = $(target);
var id = chk.attr("id") || "chk";
var checked = "";
chk.hide();
if (opts.value === true) {
checked = "checked='checked'";
} else {
checked = "";
}
if (opts.text) {
var html = "<sapn class='checkbox'><input id='chk_" + id + "' type='checkbox' " + checked + "/><label for='chk_" + id + "'>" + opts.text + "<label></sapn>";
$(target).after(html);
}
}
function getValue(target, remainText) {
var chk = $(target).next(".checkbox").find(":checkbox");
return chk.prop("checked");
}
function setValue(target, value, remainText) {
var chk = $(target).next(".checkbox").find(":checkbox");
if (value === true) {
chk.prop("checked", true);
} else {
chk.prop("checked", false);
}
}
})(jQuery);
/**
* easyui扩展-checklistbox控件
*/
(function ($) {
$.fn.checklistbox = function (options, param) {
if (typeof options == 'string') {
var method = $.fn.checklistbox.methods[options];
if (method) {
return method(this, param);
} else {
return this.combobox(options, param);
}
}
options = options || {};
return this.each(function () {
var state = $.data(this, 'checklistbox');
if (state) {
$.extend(state.options, options);
} else {
$.data(this, 'checklistbox', {
options: $.extend({}, $.fn.checklistbox.defaults, options)
});
}
checklistbox(this);
});
};
/**
* 默认配置
*/
$.fn.checklistbox.defaults = $.extend({}, $.fn.combobox.defaults, {
textField: "text",
valueField: "value",
method: "post",
dataType: "json"
});
$.fn.checklistbox.methods = {
getValues: function (jq) {
return getValues(jq);
},
getValue: function (jq) {
var res = getValues(jq);
if (res.length == 0) {
return undefined;
} else {
return res.join(',');
}
},
setValues: function (jq, value) {
return jq.each(function () {
clear(jq);
setValues(this, value);
});
},
setValue: function (jq, value) {
return jq.each(function () {
clear(jq);
setValue(this, value);
});
},
clear: function (jq) {
clear(jq);
}
};
/**
* 控件初始化函数
* @param target 控件对象
*/
function checklistbox(target) {
var state = $.data(target, 'checklistbox');
var opts = state.options;
var html = "";
var checked = "";
if (opts.url) {
$.ajax({
type: opts.method,
url: opts.url,
data: opts.queryParams,
dataType: opts.dataType,
beforeSend: function () {
if (data.onBeforeLoad) {
data.onBeforeLoad(data);
}
},
success: function (data) {
if (data.onLoadSuccess) {
data.onLoadSuccess(data);
}
opts.data = data;
},
error: function () {
if (data.onLoadError) {
data.onLoadError();
}
}
});
}
var chkl = $(target);
chkl.hide();
var id = chkl.prop("id") || "chkl";
for (var i = 0; i < opts.data.length; i++) {
var nid = id + "_" + i;
if (opts.value) {//如果设置了默认值,则选中不选中以默认值为准
if ((opts.value + ",").indexOf(opts.data[i][opts.valueField] + ",") >= 0) {
checked = "checked='checked'";
} else {
checked = "";
}
} else {//没有默认值,选中不选中以数据源为准
if (opts.data[i].selected === true) {
checked = "checked='checked'";
} else {
checked = "";
}
}
html += "<input id='" + nid + "' type='checkbox' value='" + opts.data[i][opts.valueField] + "' " + checked + "/>" +
"<label for='" + nid + "'>" + opts.data[i][opts.textField] + "</label>";
}
chkl.after('<span class="checklistbox">' + html + "</input></span>");
}
function setValues(target, value, remainText) {
var arrInput = $(target).next(".checklistbox");
if (dc.util.isString(value)) {
value=value.split(',');
}
if (value) {
$(value).each(function (n, d) {
arrInput.find("input[value='" + d + "']").prop("checked", true);
});
}
}
function setValue(target, value, remainText) {
var arrInput = $(target).next(".checklistbox").find(":checkbox");
$(arrInput).each(function (n, d) {
if (d.value == value) {
d.checked = true;
}
});
}
function getValues(target, remainText) {
var value = new Array();
var arrInput = $(target).next(".checklistbox").find(":checked");
$(arrInput).each(function () {
value.push($(this).val());
});
return value;
}
function clear(target) {
var arrInput = $(target).next(".checklistbox").find(":checked");
$(arrInput).each(function (n, d) {
d.checked = false;
});
}
})(jQuery);
/**
* easyui扩展-radiobox控件
*/
(function ($) {
$.fn.radiobox = function (options, param) {
if (typeof options == 'string') {
var method = $.fn.radiobox.methods[options];
if (method) {
return method(this, param);
} else {
return this.combobox(options, param);
}
}
options = options || {};
return this.each(function () {
var state = $.data(this, 'radiobox');
if (state) {
$.extend(state.options, options);
} else {
$.data(this, 'radiobox', {
options: $.extend({}, $.fn.radiobox.defaults, options)
});
}
radiobox(this);
});
};
/**
* 默认配置
*/
$.fn.radiobox.defaults = $.extend({}, $.fn.combobox.defaults, {
textField: "text",
valueField: "value"
});
$.fn.radiobox.methods = {
getValue: function (jq) {
return getValue(jq);
},
setValue: function (jq, value) {
return jq.each(function () {
clear(jq);
setValue(this, value);
});
},
clear: function (jq) {
clear(jq);
}
};
/**
* 控件初始化函数
* @param target 控件对象
*/
function radiobox(target) {
var state = $.data(target, 'radiobox');
var opts = state.options;
var html = "";
var checked = "";
if (opts.url) {
$.ajax({
type: opts.method,
url: opts.url,
data: opts.queryParams,
dataType: opts.dataType,
beforeSend: function () {
if (data.onBeforeLoad) {
data.onBeforeLoad(data);
}
},
success: function (data) {
if (data.onLoadSuccess) {
data.onLoadSuccess(data);
}
opts.data = data;
},
error: function () {
if (data.onLoadError) {
data.onLoadError();
}
}
});
}
var radio = $(target);
radio.hide();
var id = radio.prop("id") || "rad";
var name = id;
for (var i = 0; i < opts.data.length; i++) {
var nid = id + "_" + i;
if (opts.value) {//如果设置了默认值,则选中不选中以默认值为准
if ((opts.value + ",").indexOf(opts.data[i][opts.valueField] + ",") >= 0) {
checked = "checked='checked'";
} else {
checked = "";
}
}
else {//没有默认值,选中不选中以数据源为准
if (opts.data[i].selected===true) {
checked = "checked='checked'";
} else {
checked = "";
}
}
html += "<input id='" + nid + "' name=" + name + " type='radio' value='" + opts.data[i][opts.valueField] + "' " + checked + "/>" +
"<label for='" + nid + "'>" + opts.data[i][opts.textField] + "</label>";
}
radio.after('<span class="radiobox">' + html + "</span>");
}
function getValue(target, value, remainText) {
var arrInput = $(target).next(".radiobox").find(":checked");
if (arrInput) {
return arrInput[0].value;
} else {
return undefined;
}
}
function setValue(target, value, remainText) {
var arrInput = $(target).next(".radiobox").find(":radio");
$(arrInput).each(function (n, d) {
if (d.value == value) {
d.checked = true;
}
});
}
function clear(target) {
var arrInput = $(target).next(".radiobox").find(":checked");
$(arrInput).each(function (n, d) {
d.checked = false;
});
}
})(jQuery);
|
var gulp = require("gulp");
var rename = require('gulp-rename');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var babel = require("gulp-babel");
gulp.task('clean', function () {
return gulp.src(['src/**/*-compiled.js', 'test/**/*-compiled.js'], { read: false })
.pipe(clean());
});
gulp.task('compile', ['clean'], function () {
return gulp.src('src/**/*.js')
.pipe(babel())
.pipe(rename({ suffix: '-compiled'}))
.pipe(gulp.dest('src'));
});
gulp.task('build', ['compile'], function () {
return gulp.src('src/**/*-compiled.js')
.pipe(concat('aflowlib.js'))
.pipe(gulp.dest('dist'))
.pipe(rename({ suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('test', ['compile'], function () {
return gulp.src('test/**/*.js')
.pipe(babel())
.pipe(rename({ suffix: '-compiled'}))
.pipe(gulp.dest('test'));
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
|
module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/editor/insert-drive-file": require('material-ui/svg-icons/editor/insert-drive-file')
}
},
name: "EditorInsertDriveFile",
ports: {
input: {},
output: {
component: {
title: "EditorInsertDriveFile",
type: "Component"
}
}
}
} |
import { moduleFor, test } from 'ember-qunit';
moduleFor('service:firebase', 'Unit | Service | firebase', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
|
/*
* Copyright (c) 2015-2016 PointSource, LLC.
* MIT Licensed
*
* Captures the image loading event and displays a spinner while the image loads
*/
(function() {
'use strict';
angular
.module('app.directives')
.directive('imageLoader', ImageLoaderDirective);
ImageLoaderDirective.$inject = ['$parse'];
function ImageLoaderDirective($parse) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var fn = $parse(attrs.imageLoader);
elem.on('load', function(event) {
scope.$apply(function() {
fn(scope, {
$event: event
});
});
});
}
};
}
})();
|
// Sigma16: state.js
// Copyright (c) 2019 John T. O'Donnell. john.t.odonnell9@gmail.com
// License: GNU GPL Version 3 or later. Sigma16/ LICENSE.txt NOTICE.txt
// This file is part of Sigma16. Sigma16 is free software: you can
// redistribute it and/or modify it under the terms of the GNU General
// Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
// Sigma16 is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details. You should have received
// a copy of the GNU General Public License along with Sigma16. If
// not, see <https://www.gnu.org/licenses/>.
//-------------------------------------------------------------------------------
// state.js defines global state for the system, IDE, modules, and
// emulator
//-------------------------------------------------------------------------------
// The main components of the program avoid using global variables;
// instead the necessary state is organized into records and passed as
// needed to the functions. This module defines those records. The
// gui operations, defined in Sigma16.html, call the emulator's
// interface functios with the state, for example boot(emulatorState).
let highlightedRegisters = [];
// Update the display of all registers and memory (all of memory)
function displayFullState () {
console.log ('displayFullState');
clearRegisterHighlighting ();
refreshRegisters ();
memClearAccesses ();
memDisplayFull ();
}
//------------------------------------------------------------------------------
// Emulator state
//------------------------------------------------------------------------------
// This is the global emulator state. The functions in the emulator
// don't use it directly, in order to avoid excessive use of globals.
// The current emulator state is passed as needed to functions (the
// convention is that the parameter name is 'es').
let emulatorState =
{
// Processor
procStatus : "Reset",
nInstructionsExecuted : 0,
instrLooperDelay : 1000,
instrLooperShow : false,
breakEnabled : false,
breakPCvalue : 0,
// Instruction being executed
doInterrupt : 0,
ir_op : 0,
ir_d : 0,
ir_a : 0,
ir_b : 0,
ea : 0,
instrDisp : 0,
field_e : 0,
field_f : 0,
field_g : 0,
field_h : 0,
field_gh : 0,
instrOpCode : null,
instrCodeStr : "",
instrFmtStr : "",
instrOp : "",
instrArgs : "",
instrEA : null,
instrEAStr : "",
instrEffect : [],
// Tracking source lines corresponding to current instruction
curAsmap : [],
asmListingPlain : [], // plain listing shows address, code, source
asmListingDec : [], // decorated listing uses highlighting for fields
asmListingCurrent : [], // version of listing displayed in emulator pane
asmListingHeight : 0, // height in pixels of the listing
curInstrAddr : 0,
nextInstrAddr : 0,
curInstrLineNo : -1, // -1 indicates no line has been highlighted
nextInstrLineNo : -1,
saveCurSrcLine : "",
saveNextSrcLine : "",
// srcLinePlain : [],
// srcLineHighlightedFields : []
}
// Global variables for instruction decode; used in emulator
let displayInstrDecode = true;
let instrCode, instrDisp, instrCodeStr; // record the values
let instrFmtStr = "";
let instrOpStr = "";
let instrArgsStr = "";
let instrEA, instrEAStr;
let instrEffect = [];
//---------------------------------------------------------------------------
// State variables
// let st =
// { ir_op : 0,
// ir_d : 0,
// ir_a : 0,
// ir_b : 0
// }
// Is it better to keep registers, memory, etc, as globals? Or to
// make them fields in a state record? Changed ir_d to st.ir_d in
// state.js and emulator.js. Reconsider which approach is better, and
// make it consistent. ?????
// Processor elements: html elements for displaying instruction decode
let instrCodeElt;
let instrFmtElt;
let instrOpElt;
let instrArgsElt;
let instrEAElt;
let instrCCElt;
let instrEffect1Elt;
let instrEffect2Elt;
function initializeProcessorElements () {
console.log ('initializeProcessorElements');
instrCodeElt = document.getElementById("InstrCode");
instrFmtElt = document.getElementById("InstrFmt");
instrOpElt = document.getElementById("InstrOp");
instrArgsElt = document.getElementById("InstrArgs");
instrEAElt = document.getElementById("InstrEA");
instrCCElt = document.getElementById("InstrCC");
instrEffect1Elt = document.getElementById("InstrEffect1");
instrEffect2Elt = document.getElementById("InstrEffect2");
}
// Fields of the current instruction
var instr = 0;
var ir_op = 0, ir_d = 0, ir_a = 0, ir_b = 0; // instruction fields
// The value of the effective addresss pecified by an RX instruction
var ea = 0; // effective address
// Global variables for handling listing display as program runs.
// Uses global variables set by linker: exMod is executing module and
// curAsmap is map from addresses to source lines
var srcLine; // copy of source statements
// Keep track of the address of the currently executing instruction,
// the address of the next instruction, and the line numbers where
// these instructions appear in the assembly listing. -1 indicates no
// line has been highlighted
var curInstrAddr, curInstrLineNo, saveCurSrcLine;
var nextInstrAddr, nextInstrLineNo, saveNextSrcLine;
function initializeSubsystems () {
memDisplayModeFull = false;
document.getElementById('FullDisplayToggleButton').value = "Fast display";
}
function toggleFullDisplay () {
console.log ('toggleFullDisplay clicked');
memDisplayModeFull = ! memDisplayModeFull;
document.getElementById('FullDisplayToggleButton').value =
memDisplayModeFull ? "Full display" : "Fast display";
if (memDisplayModeFull) { memDisplayFull () }
else { memDisplayFast ()
} // loses info but makes tab switching faster
}
//----------------------------------------------------------------------
// Registers
//----------------------------------------------------------------------
// The registers are defined as global variables. These variables are
// declared here but their values are set only when window has been
// loaded, because the gui elements will exist at that time.
var modeHighlightAccess = true; // for tracing: highlight reg/mem that is accessed
// Define the control registers as global variables
var pc, ir, adr, dat, sysStat; // instruction control
var enable, mask, req, isys, ipc, handle; // interrupt control
var sEnable, sProg, sProgEnd, sDat, sDatEnd; // segmentation control
var ctlRegIndexOffset = 0; // update in gui.js when registers are created
var regFile = []; // register file R0,..., R15
var nRegisters = 0; // total number of registers
var sysCtlRegIdx = 0; // index of first system control reg
function showSysStat (s) {
return s===0 ? 'Usr' : 'Sys'
}
// Instructions refer to the system control registers by a 4-bit
// index, but the system control register that has instruction index 0
// will actually have a higher index (16) in the emulator's array of
// registers. To refer to sysctl reg i, it can be accessed as
// register [sysCtlRegIdx + i].
// Global variables for accessing the registers
var register = []; // all the registers, control and regfile
var registerIndex = 0; // unique index for each reg
var regStored = [];
var regFetched = [];
// Each register is represented by an object that contains its current
// value, as well as methods to get and set the value, and to refresh
// the display. The mkReg function makes a register corresponding to
// a gui element. To remove highlight, use refresh.
// Arguments
// regName is the name of the register, e.g. "pc"
// eltName is the html id of the gui element
// show(x) converts a value x to a string that can be displayed
// Set by creation loop
// regIdx is the unique index in the array of all registers
// Local state
// val is the current contents of the register
// elt is gui element used to display the register
// put(x) discards current val and replaces it with x (highlight if mode set)
// get() returns current val (highlight if mode set)
// refresh() puts the current val into display, without any highlighting
function testReg1 () {
console.log("testReg1");
regClearAccesses();
pc.put(3);
console.log ("ir = " + ir.get());
console.log ("pc = " + pc.get());
regShowAccesses();
}
function testReg2 () {
console.log("testReg1");
regClearAccesses();
console.log ("ir = " + ir.get());
console.log ("pc = " + pc.get());
adr.put(20);
regShowAccesses();
}
// The registers are actually created in gui.js in the window.onload
// function, because they need the gui display elements to be created
// first
function mkReg (rn,eltName,showfcn) {
r = Object.create({
regIdx : 0, // will be overwritten with actual index
regName : rn,
show : showfcn,
val : 0,
elt : document.getElementById(eltName),
put : function (x) {
this.val = x;
console.log (`reg put rn=${rn} idx=${this.regIdx} x=${x}`);
if (this.regIdx<16) {
// record regfile put
instrEffect.push (["R", this.regIdx, x, this.regName]);
console.log (`mkReg put recording effect 0 ${instrEffect[0]}`);
console.log (`mkReg put recording effect 1 ${instrEffect[1]}`);
}
if (modeHighlight) { regStored.push(this) } },
get : function () {
x = this.val;
if (modeHighlight) { regFetched.push(this) };
return x },
refresh : function() {
console.log (`refresh register ${rn}`);
this.elt.innerHTML = this.show(this.val);
},
showNameVal: function() {return this.regName + '=' + this.show(this.val);}
});
// register[nRegisters] = this;
nRegisters++;
return r;
}
// R0 is special: it always contains 0 and cannot be changed
function mkReg0 (rn,eltName,showfcn) {
r = Object.create({
regName : rn,
show : showfcn,
val : 0,
elt : document.getElementById(eltName),
put : function (x) { },
get : function () { return 0 },
refresh : function() {this.elt.innerHTML = this.show(this.val);},
showNameVal: function() {return this.regName + '=' + this.show(this.val);}
});
nRegisters++;
return r;
}
function regShowAccesses () {
let i, r;
for (i = 0; i < regFetched.length; i++) {
r = regFetched[i];
r.elt.innerHTML = highlightText(r.show(r.val),'GET')
}
for (i = 0; i < regStored.length; i++) {
r = regStored[i];
r.elt.innerHTML = highlightText(r.show(r.val),'PUT')
}
}
function regClearAccesses () {
let r;
for (let i = 0; i < regFetched.length; i++) {
regFetched[i].refresh();
}
for (let i = 0; i <regStored.length; i++) {
regStored[i].refresh();
}
regFetched = [];
regStored = [];
}
// Resetting the registers sets them all to 0,
function resetRegisters () {
console.log('Resetting registers');
for (var i = 0; i < nRegisters; i++) {
register[i].val = 0;
register[i].refresh();
}
}
// Refresh all the registers. This ensures the display corresponds to the
// current values, and it also removes any highlighting of the registers.
function refreshRegisters() {
console.log('Refreshing registers');
for (var i = 0; i < nRegisters; i++) {
register[i].refresh();
}
}
// ------------------------------------------------------------------------
// Highlighting registers to indicate accesses
// When a register is accessed, its display in the gui is highlighted
// by setting the text color. If the register has not been used it
// has the default color black, if it has been read but not written
// its color is READ, and if it has been written its color is WRITE.
// The meanings of the tags for syntax highlighting are defined in
// Sigma16gui.css. Normally we would use blue for READ and red for
// WRITE.
var modeHighlight = true; // indicate get/put by setting text color
function setModeHighlight (x) {
if (x) {
console.log('Setting modeHighlight to True');
modeHighlight = true;
}
else {
console.log('Setting modeHighlight to False');
modeHighlight = false;
refreshRegisters();
}
}
function highlightText (txt,tag) {
return "<span class='" + tag + "'>" + txt + "</span>";
}
function clearRegisterHighlighting () {
let n = highlightedRegisters.length;
var r;
for (var i = 0; i < n; i++) {
r = highlightedRegisters[i];
console.log('clear highlight ' + i + ' reg = ' + r.regName);
r.refresh();
};
highlightedRegisters = [];
}
//----------------------------------------------------------------------
// Memory
//----------------------------------------------------------------------
// Usage
// General operations
// memInitialize get html elements, clear refresh, display
// memClear () set each location to 0
// memRefresh () recalculate the memory strings
// During instruction execution
// memClearAccesses () remove get/put highligting
// ir = memFetchInstr (a) instruction fetch
// adr = memFetchData (a) data fetch
// memStore (a,x) store
// memShowAccesses () update array of hex strings
// memDisplayFast () render html elements showing only accessed area
// memDisplayFull () render html elements showing full memory
// memDisplay () use display mode to select fast or full
// The memory is represented as array of words (represented as an
// integer between 0 and 2^16-q) and a corresponding array of strings
// showing each word as a hex number. There are html elements for
// displaying the memory contents, and two arrays to track memory
// accesses (fetches and stores) in order to generate the displays.
var memSize = 65536; // number of memory locations = 2^16
var memory = []; // the memory contents, indexed by address
var memString = []; // a string for each location, to be displayed
var memElt1, memElt2; // html elements for two views into the memory
var memFetchInstrLog = [];
var memFetchDataLog = [];
var memStoreLog = [];
var memDisplayModeFull = false; // show entire memory? or just a little of it?
var memDisplayFastWindow = 16; // how many locations to show in fast mode
var memDispOffset = 3; // how many locations above highligted one
// Must wait until onload event
function memInitialize () {
memElt1 = document.getElementById('MemDisplay1');
memElt2 = document.getElementById('MemDisplay2');
memClear(); // set each location to 0
memRefresh(); // generate a string showing each location
memDisplay(); // put the strings into the gui display elements
}
// There are two primary memory accesses: fetch and store. These
// functions record the operation to enable the user interface to show
// the access by using colors to highlight the accessed location.
// There is just one memory, but the gui contains two windows into the
// memory: by convention, display 1 shows instruction fetches and
// display 2 shows data fetches and stores. In the hardware (the
// digital circuit that implements the processor) there may be no
// distinction between memory and data accesses (although there could
// be if the machine has separate instruction and data caches).
// All memory stores are considered to be data stores. Howver, there
// are two variants of fetch: instruction fetch and data fetch. Both
// of these record the operation in the array memFetchInstrLog, but
// they record the address in separate scalar vairables to enable the
// gui to scroll the two displays to show the instruction access in
// disply 1 and the data access in display 2.
// Set all memory locations to 0
function memClear () {
for (var i = 0; i < memSize; i++) {
memory[i] = 0;
}
memFetchInstrLog = [];
memFetchDataLog = [];
memStoreLog = [];
memRefresh ();
}
// Refresh all the memory strings; the memString array should be accurate
// but this function will recalculate all elements of that array
// Note on data structure. I tried having a preliminary element [0]
// containing just "<pre class='HighlightedTextAsHtml'>", so address a
// is shown in memString[a+1]. The indexing was fine but the
// scrolling didn't work, possibly because of this dummy element with
// its newline inserted when the array is joined up.
function memRefresh () {
memString = []; // clear out and collect any existing elements
// memString[0] = "hello"; // "<pre class='HighlightedTextAsHtml'>"
for (var i = 0; i < memSize; i++) {
setMemString(i);
}
// memString.push("bye"); // "</pre>");
}
// Create a string to represent a memory location; the actual value is
// in the memory array, and the string is placed in the memString
// array. memString[0] = <pre class="HighlightedTextAsHtml"> and
// mem[a] corresponds to memString[a+1].
function setMemString(a) {
memString[a] = wordToHex4(a) + ' ' + wordToHex4(memory[a]);
}
// Fetch and return a word from memory at address a, and record the
// address so the display can show this access.
function memFetchInstr (a) {
memFetchInstrLog.push(a);
return memory[a];
}
function memFetchData (a) {
memFetchDataLog.push(a);
return memory[a];
}
// Store a word x into memory at address a, and record the address so
// the display can show this access.
function memStore (a,x) {
memStoreLog.push(a);
instrEffect.push(["M", a, x]);
memory[a] = x;
}
// Update the memory string for each location that has been accessed,
// so that it contains an html div element which can be used to
// highlight the memory location. Do the fetches first, then the
// stores: this ensures that if a location has both been fetched and
// stored, the highlighting for the store will take precedence.
function memShowAccesses () {
let i, a;
for (i = 0; i < memFetchInstrLog.length; i++) {
a = memFetchInstrLog[i];
highlightMemString(a,"GET");
}
for (i = 0; i < memFetchDataLog.length; i++) {
a = memFetchDataLog[i];
highlightMemString(a,"GET");
}
for (i = 0; i < memStoreLog.length; i++) {
a = memStoreLog[i];
highlightMemString(a,"PUT");
}
}
// Remove the highlighting for the memory locations that have been accessed
function memClearAccesses () {
let a;
for (i=0; i<memFetchInstrLog.length; i++) {
a = memFetchInstrLog[i];
setMemString(a);
}
for (i=0; i<memFetchDataLog.length; i++) {
a = memFetchDataLog[i];
setMemString(a);
}
for (i=0; i<memStoreLog.length; i++) {
a = memStoreLog[i];
setMemString(a);
}
memFetchInstrLog = [];
memFetchDataLog = [];
memStoreLog = [];
}
// Create a string with a span class to represent a memory location
// with highlighting; the actual value is in the memory array, and the
// string is placed in the memString array.
function highlightMemString(a,highlight) {
memString[a] =
"<span class='" + highlight + "'>"
+ wordToHex4(a) + " " + wordToHex4(memory[a])
+ "</span>";
}
// Set the memory displays, using the memString array. Check mode to
// determine whether the display should be partial and fast or
// complete but slow.
function memDisplay () {
if (memDisplayModeFull) { memDisplayFull () }
else { memDisplayFast () }
}
// Set the memory displays, showing only part of the memory to save time
function memDisplayFast () {
// console.log ('memDisplayFast');
let xa, xb, xs1, xs, yafet, yasto, ya, yb, ys1, ys;
xa = (memFetchInstrLog.length===0) ? 0 : (memFetchInstrLog[0] - memDispOffset);
xa = xa < 0 ? 0 : xa;
xb = xa + memDisplayFastWindow;
xs = "<pre class='CodePre'><code class='HighlightedTextAsHtml'>"
+ memString.slice(xa,xb).join('\n')
+ "</code></pre>";
// xs = "<pre><code class='HighlightedTextAsHtml'>TEST</code></pre>";
// xs = "<pre><code>TEST</code></pre>";
// xs = "<code>TEST</code>";
// xs = "<pre>TEST</pre>";
console.log (' xa=' + xa + ' xb=' + xb);
memElt1.innerHTML = xs;
yafet = (memFetchDataLog.length===0) ? 0 : (memFetchDataLog[0] - memDispOffset);
yasto = (memStoreLog.length===0) ? 0 :(memStoreLog[0] - memDispOffset);
ya = yafet > 0 && yafet < yasto ? yafet : yasto;
ya = ya < 0 ? 0 : ya;
yb = ya + memDisplayFastWindow;
ys = "<pre class='CodePre'><code class='HighlightedTextAsHtml'>"
+ memString.slice(ya,yb).join('\n')
+ "</code></pre>";
console.log (' ya=' + ya + ' yb=' + yb);
memElt2.innerHTML = ys;
}
// Set the memory displays, showing the full memory
// Need <pre> to get the formatting correct with line breaks. but
// <pre> prevents scrolling from working. Could try not using pre,
// but putting <br> after each line, but that still wouldn't work
// because multiple spaces in code wouldn't work.. Try <code>; With
// <code class=... scrolling works, but the line breaks aren't
// there.. Is there a problem with HighlightedTextAsHtml?
// THE RIGHT WAY TO DO IT: code inside pre; class defined in code:
// xs = "<pre><code class='HighlightedTextAsHtml'>"
// + memString.join('\n')
// + "</code></pre>";
function memDisplayFull () {
let xs; // display text
let xt, xo; // display 1 targets and offsets
let yafet, yasto, ya, yo
console.log ('memDisplayFull');
xs = "<pre class='CodePre'><code class='HighlightedTextAsHtml'>"
+ memString.join('\n')
+ "</code></pre>";
memElt1.innerHTML = xs;
xt = (memFetchInstrLog.length===0)? 0 : memFetchInstrLog[0] - memDispOffset;
xo = xt * pxPerChar;
console.log(' target1 xt = ' + xt + ' offset1 = ' + xo);
memElt1.scroll(0,xo);
memElt2.innerHTML = xs;
yafet = (memFetchDataLog.length===0) ? 0 : (memFetchDataLog[0] - memDispOffset);
yasto = (memStoreLog.length===0) ? 0 :(memStoreLog[0] - memDispOffset);
yt = (yasto > 0 ? yasto : yafet) - memDispOffset;
yt = yt < 0 ? 0 : yt;
yo = yt * pxPerChar;
console.log(' yafet=' + yafet + ' yasto=' + yasto
+ ' target1 yt = ' + yt + ' offset1 = ' + yo);
memElt2.scroll(0,yo);
}
function memTest1a () {
console.log('testMem1a');
memClear ();
memStore(3,7);
memStore(6,2);
memShowAccesses ();
memDisplay ();
}
function memTest1b () {
console.log('testMem1b');
memClearAccesses ();
let y = memFetchInstr(6);
memStore(300,20);
memShowAccesses();
memDisplay ();
// console.log('testMem1 x = ' + x); // should be 0, highlight Fetch
// console.log('testMem1 y = ' + y); // should be 7, highlight Store
}
function memTest2 () {
console.log('testMem2');
memClear ();
let y = memFetchInstr (32768);
let q = memFetchData (50);
memStore (65520, 7);
memShowAccesses ();
memDisplay ();
}
|
import React from 'react'
import { TagButton } from './index'
import { VisaIcon } from 'kitten'
import { DocsPage } from 'storybook/docs-page'
export default {
title: 'Action/TagButton',
component: TagButton,
parameters: {
docs: {
page: () => <DocsPage filepath={__filename} importString="TagButton" />,
},
},
decorators: [
story => (
<div className="story-Container story-Grid story-Grid--large">
<div>{story()}</div>
</div>
),
],
argTypes: {
size: { control: 'radio', options: ['tiny', 'regular', 'big', 'huge'] },
active: { control: 'boolean' },
children: { control: 'text' },
},
args: {
size: 'regular',
active: false,
children: 'My Tag',
},
}
export const Default = args => <TagButton {...args} />
export const WithIcon = args => (
<TagButton {...args} icon>
<VisaIcon />
</TagButton>
)
|
const chai = require('chai');
const chaiHttp = require('chai-http');
const cheerio = require('cheerio');
const nock = require('nock');
const constants = require('../../app/lib/constants');
const getSampleResponse = require('../resources/getSampleResponse');
const iExpect = require('../lib/expectations');
const postcodesIOURL = require('../lib/constants').postcodesIOURL;
const server = require('../../server');
const nockRequests = require('../lib/nockRequests');
const queryBuilder = require('../../app/lib/queryBuilder');
const postcodeCoordinates = require('../resources/postcode-coordinates');
const expect = chai.expect;
const queryTypes = constants.queryTypes;
chai.use(chaiHttp);
const siteRoot = constants.siteRoot;
const resultsRoute = `${siteRoot}/results`;
function expectStandardMetadata($) {
const canonicalUrl = `https://127.0.0.1${siteRoot}/`;
expect($('link[rel="canonical"]').attr('href')).to.equal(canonicalUrl);
expect($('meta[property="og:description"]').attr('content')).to.equal(constants.app.description);
expect($('meta[property="og:image"]').attr('content')).to.equal(`${canonicalUrl}images/opengraph-image.png`);
expect($('meta[property="og:image:alt"]').attr('content')).to.equal('nhs.uk');
expect($('meta[property="og:image:height"]').attr('content')).to.equal('630');
expect($('meta[property="og:image:width"]').attr('content')).to.equal('1200');
expect($('meta[property="og:locale"]').attr('content')).to.equal(constants.app.locale);
expect($('meta[property="og:site_name"]').attr('content')).to.equal(constants.app.siteName);
expect($('meta[property="og:title"]').attr('content')).to.equal(`${constants.app.title} - NHS`);
expect($('meta[property="og:type"]').attr('content')).to.equal('website');
expect($('meta[property="og:url"]').attr('content')).to.equal(`https://127.0.0.1${siteRoot}/`);
expect($('meta[property="twitter:card"]').attr('content')).to.equal('summary_large_image');
expect($('meta[property="twitter:creator"]').attr('content')).to.equal('@nhsuk');
expect($('meta[property="twitter:site"]').attr('content')).to.equal('@nhsuk');
}
describe('Metadata', () => {
const location = 'Midsomer';
afterEach('clean nock', () => {
nock.cleanAll();
});
describe('the search page', () => {
it('should include the standard properties', async () => {
const res = await chai.request(server).get(siteRoot);
iExpect.htmlWith200Status(res);
const $ = cheerio.load(res.text);
expectStandardMetadata($);
});
});
describe('the results page, when displaying results', () => {
it('should include the standard properties', async () => {
const searchOrigin = postcodeCoordinates.LS1;
const body = queryBuilder(searchOrigin, { queryType: queryTypes.nearby });
await nockRequests.serviceSearch(body, 200, 'organisations/LS1-as.json');
const res = await chai.request(server)
.get(resultsRoute)
.query({
latitude: searchOrigin.latitude,
location,
longitude: searchOrigin.longitude,
});
iExpect.htmlWith200Status(res);
const $ = cheerio.load(res.text);
expectStandardMetadata($);
});
});
describe('the results page, when there are no results', () => {
it('should include the standard properties', async () => {
const multiPlaceResponse = getSampleResponse('postcodesio-responses/multiplePlaceResult.json');
const multiPlaceTerm = 'multiresult';
nock(postcodesIOURL)
.get(`/places?limit=100&q=${multiPlaceTerm}`)
.times(1)
.reply(200, multiPlaceResponse);
const res = await chai.request(server)
.get(resultsRoute)
.query({ location: multiPlaceTerm });
iExpect.htmlWith200Status(res);
const $ = cheerio.load(res.text);
expectStandardMetadata($);
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.