code stringlengths 2 1.05M |
|---|
/*
* jQuery File Upload User Interface Plugin 5.0.12
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
/*jslint nomen: false, unparam: true, regexp: false */
/*global window, document, URL, webkitURL, FileReader, jQuery */
(function ($) {
'use strict';
// The UI version extends the basic fileupload widget and adds
// a complete user interface based on the given upload/download
// templates.
$.widget('blueimpUI.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: false,
// The following option limits the number of files that are
// allowed to be uploaded using this widget:
maxNumberOfFiles: 10,
// The maximum allowed file size:
maxFileSize: undefined,
// The minimum allowed file size:
minFileSize: 1,
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /^image\/(gif|jpeg|png)$/,
// The regular expression to define for which files a preview
// image is shown, matched against the file type:
previewFileTypes: /^image\/(gif|jpeg|png)$/,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// By default, preview images are displayed as canvas elements
// if supported by the browser. Set the following option to false
// to always display preview images as img elements:
previewAsCanvas: true,
// The file upload template that is given as first argument to the
// jQuery.tmpl method to render the file uploads:
uploadTemplate: $('#template-upload'),
// The file download template, that is given as first argument to the
// jQuery.tmpl method to render the file downloads:
downloadTemplate: $('#template-download'),
// The expected data type of the upload response, sets the dataType
// option of the $.ajax upload requests:
dataType: 'json',
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
var that = $(this).data('fileupload');
that._adjustMaxNumberOfFiles(-data.files.length);
data.isAdjusted = true;
data.isValidated = that._validate(data.files);
data.context = that._renderUpload(data.files)
.appendTo($(this).find('.files')).fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
}).data('data', data);
if ((that.options.autoUpload || data.autoUpload) &&
data.isValidated) {
data.jqXHR = data.submit();
}
},
// Callback for the start of each file upload request:
send: function (e, data) {
if (!data.isValidated) {
var that = $(this).data('fileupload');
if (!data.isAdjusted) {
that._adjustMaxNumberOfFiles(-data.files.length);
}
if (!that._validate(data.files)) {
return false;
}
}
if (data.context && data.dataType &&
data.dataType.substr(0, 6) === 'iframe') {
// Iframe Transport does not support progress events.
// In lack of an indeterminate progress bar, we set
// the progress to 100%, showing the full animated bar:
data.context.find('.ui-progressbar').progressbar(
'value',
parseInt(100, 10)
);
}
},
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('fileupload');
if (data.context) {
data.context.each(function (index) {
var file = ($.isArray(data.result) &&
data.result[index]) || {error: 'emptyResult'};
if (file.error) {
that._adjustMaxNumberOfFiles(1);
}
$(this).fadeOut(function () {
that._renderDownload([file])
.css('display', 'none')
.replaceAll(this)
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
});
});
} else {
that._renderDownload(data.result)
.css('display', 'none')
.appendTo($(this).find('.files'))
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
var that = $(this).data('fileupload');
that._adjustMaxNumberOfFiles(data.files.length);
if (data.context) {
data.context.each(function (index) {
$(this).fadeOut(function () {
if (data.errorThrown !== 'abort') {
var file = data.files[index];
file.error = file.error || data.errorThrown
|| true;
that._renderDownload([file])
.css('display', 'none')
.replaceAll(this)
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
} else {
data.context.remove();
}
});
});
} else if (data.errorThrown !== 'abort') {
that._adjustMaxNumberOfFiles(-data.files.length);
data.context = that._renderUpload(data.files)
.css('display', 'none')
.appendTo($(this).find('.files'))
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
}).data('data', data);
}
},
// Callback for upload progress events:
progress: function (e, data) {
if (data.context) {
data.context.find('.ui-progressbar').progressbar(
'value',
parseInt(data.loaded / data.total * 100, 10)
);
}
},
// Callback for global upload progress events:
progressall: function (e, data) {
$(this).find('.fileupload-progressbar').progressbar(
'value',
parseInt(data.loaded / data.total * 100, 10)
);
},
// Callback for uploads start, equivalent to the global ajaxStart event:
start: function () {
$(this).find('.fileupload-progressbar')
.progressbar('value', 0).fadeIn();
},
// Callback for uploads stop, equivalent to the global ajaxStop event:
stop: function () {
$(this).find('.fileupload-progressbar').fadeOut();
},
// Callback for file deletion:
destroy: function (e, data) {
var that = $(this).data('fileupload');
if (data.url) {
$.ajax(data)
.success(function () {
that._adjustMaxNumberOfFiles(1);
$(this).fadeOut(function () {
$(this).remove();
});
});
} else {
data.context.fadeOut(function () {
$(this).remove();
});
}
}
},
// Scales the given image (img HTML element)
// using the given options.
// Returns a canvas object if the canvas option is true
// and the browser supports canvas, else the scaled image:
_scaleImage: function (img, options) {
options = options || {};
var canvas = document.createElement('canvas'),
scale = Math.min(
(options.maxWidth || img.width) / img.width,
(options.maxHeight || img.height) / img.height
);
if (scale >= 1) {
scale = Math.max(
(options.minWidth || img.width) / img.width,
(options.minHeight || img.height) / img.height
);
}
img.width = parseInt(img.width * scale, 10);
img.height = parseInt(img.height * scale, 10);
if (!options.canvas || !canvas.getContext) {
return img;
}
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d')
.drawImage(img, 0, 0, img.width, img.height);
return canvas;
},
_createObjectURL: function (file) {
var undef = 'undefined',
urlAPI = (typeof window.createObjectURL !== undef && window) ||
(typeof URL !== undef && URL) ||
(typeof webkitURL !== undef && webkitURL);
return urlAPI ? urlAPI.createObjectURL(file) : false;
},
_revokeObjectURL: function (url) {
var undef = 'undefined',
urlAPI = (typeof window.revokeObjectURL !== undef && window) ||
(typeof URL !== undef && URL) ||
(typeof webkitURL !== undef && webkitURL);
return urlAPI ? urlAPI.revokeObjectURL(url) : false;
},
// Loads a given File object via FileReader interface,
// invokes the callback with a data url:
_loadFile: function (file, callback) {
if (typeof FileReader !== 'undefined' &&
FileReader.prototype.readAsDataURL) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
callback(e.target.result);
};
fileReader.readAsDataURL(file);
return true;
}
return false;
},
// Loads an image for a given File object.
// Invokes the callback with an img or optional canvas
// element (if supported by the browser) as parameter:
_loadImage: function (file, callback, options) {
var that = this,
url,
img;
if (!options || !options.fileTypes ||
options.fileTypes.test(file.type)) {
url = this._createObjectURL(file);
img = $('<img>').bind('load', function () {
$(this).unbind('load');
that._revokeObjectURL(url);
callback(that._scaleImage(img[0], options));
}).prop('src', url);
if (!url) {
this._loadFile(file, function (url) {
img.prop('src', url);
});
}
}
},
// Link handler, that allows to download files
// by drag & drop of the links to the desktop:
_enableDragToDesktop: function () {
var link = $(this),
url = link.prop('href'),
name = decodeURIComponent(url.split('/').pop())
.replace(/:/g, '-'),
type = 'application/octet-stream';
link.bind('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[type, name, url].join(':')
);
} catch (err) {}
});
},
_adjustMaxNumberOfFiles: function (operand) {
if (typeof this.options.maxNumberOfFiles === 'number') {
this.options.maxNumberOfFiles += operand;
if (this.options.maxNumberOfFiles < 1) {
this._disableFileInputButton();
} else {
this._enableFileInputButton();
}
}
},
_formatFileSize: function (file) {
if (typeof file.size !== 'number') {
return '';
}
if (file.size >= 1000000000) {
return (file.size / 1000000000).toFixed(2) + ' GB';
}
if (file.size >= 1000000) {
return (file.size / 1000000).toFixed(2) + ' MB';
}
return (file.size / 1000).toFixed(2) + ' KB';
},
_hasError: function (file) {
if (file.error) {
return file.error;
}
// The number of added files is subtracted from
// maxNumberOfFiles before validation, so we check if
// maxNumberOfFiles is below 0 (instead of below 1):
if (this.options.maxNumberOfFiles < 0) {
return 'maxNumberOfFiles';
}
// Files are accepted if either the file type or the file name
// matches against the acceptFileTypes regular expression, as
// only browsers with support for the File API report the type:
if (!(this.options.acceptFileTypes.test(file.type) ||
this.options.acceptFileTypes.test(file.name))) {
return 'acceptFileTypes';
}
if (this.options.maxFileSize &&
file.size > this.options.maxFileSize) {
return 'maxFileSize';
}
if (typeof file.size === 'number' &&
file.size < this.options.minFileSize) {
return 'minFileSize';
}
return null;
},
_validate: function (files) {
var that = this,
valid;
$.each(files, function (index, file) {
file.error = that._hasError(file);
valid = !file.error;
});
return valid;
},
_uploadTemplateHelper: function (file) {
file.sizef = this._formatFileSize(file);
return file;
},
_renderUploadTemplate: function (files) {
var that = this;
return $.tmpl(
this.options.uploadTemplate,
$.map(files, function (file) {
return that._uploadTemplateHelper(file);
})
);
},
_renderUpload: function (files) {
var that = this,
options = this.options,
tmpl = this._renderUploadTemplate(files);
if (!(tmpl instanceof $)) {
return $();
}
tmpl.css('display', 'none');
// .slice(1).remove().end().first() removes all but the first
// element and selects only the first for the jQuery collection:
tmpl.find('.progress div').slice(1).remove().end().first()
.progressbar();
tmpl.find('.start button').slice(
this.options.autoUpload ? 0 : 1
).remove().end().first()
.button({
text: false,
icons: {primary: 'ui-icon-circle-arrow-e'}
});
tmpl.find('.cancel button').slice(1).remove().end().first()
.button({
text: false,
icons: {primary: 'ui-icon-cancel'}
});
tmpl.find('.preview').each(function (index, node) {
that._loadImage(
files[index],
function (img) {
$(img).hide().appendTo(node).fadeIn();
},
{
maxWidth: options.previewMaxWidth,
maxHeight: options.previewMaxHeight,
fileTypes: options.previewFileTypes,
canvas: options.previewAsCanvas
}
);
});
return tmpl;
},
_downloadTemplateHelper: function (file) {
file.sizef = this._formatFileSize(file);
return file;
},
_renderDownloadTemplate: function (files) {
var that = this;
return $.tmpl(
this.options.downloadTemplate,
$.map(files, function (file) {
return that._downloadTemplateHelper(file);
})
);
},
_renderDownload: function (files) {
var tmpl = this._renderDownloadTemplate(files);
if (!(tmpl instanceof $)) {
return $();
}
tmpl.css('display', 'none');
tmpl.find('.delete button').button({
text: false,
icons: {primary: 'ui-icon-trash'}
});
tmpl.find('a').each(this._enableDragToDesktop);
return tmpl;
},
_startHandler: function (e) {
e.preventDefault();
var tmpl = $(this).closest('.template-upload'),
data = tmpl.data('data');
if (data && data.submit && !data.jqXHR) {
data.jqXHR = data.submit();
$(this).fadeOut();
}
},
_cancelHandler: function (e) {
e.preventDefault();
var tmpl = $(this).closest('.template-upload'),
data = tmpl.data('data') || {};
if (!data.jqXHR) {
data.errorThrown = 'abort';
e.data.fileupload._trigger('fail', e, data);
} else {
data.jqXHR.abort();
}
},
_deleteHandler: function (e) {
e.preventDefault();
var button = $(this);
e.data.fileupload._trigger('destroy', e, {
context: button.closest('.template-download'),
url: button.attr('data-url'),
type: button.attr('data-type'),
dataType: e.data.fileupload.options.dataType
});
},
_initEventHandlers: function () {
$.blueimp.fileupload.prototype._initEventHandlers.call(this);
var filesList = this.element.find('.files'),
eventData = {fileupload: this};
filesList.find('.start button')
.live(
'click.' + this.options.namespace,
eventData,
this._startHandler
);
filesList.find('.cancel button')
.live(
'click.' + this.options.namespace,
eventData,
this._cancelHandler
);
filesList.find('.delete button')
.live(
'click.' + this.options.namespace,
eventData,
this._deleteHandler
);
},
_destroyEventHandlers: function () {
var filesList = this.element.find('.files');
filesList.find('.start button')
.die('click.' + this.options.namespace);
filesList.find('.cancel button')
.die('click.' + this.options.namespace);
filesList.find('.delete button')
.die('click.' + this.options.namespace);
$.blueimp.fileupload.prototype._destroyEventHandlers.call(this);
},
_initFileUploadButtonBar: function () {
var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
filesList = this.element.find('.files'),
ns = this.options.namespace;
fileUploadButtonBar
.addClass('ui-widget-header ui-corner-top');
this.element.find('.fileinput-button').each(function () {
var fileInput = $(this).find('input:file').detach();
$(this).button({icons: {primary: 'ui-icon-plusthick'}})
.append(fileInput);
});
fileUploadButtonBar.find('.start')
.button({icons: {primary: 'ui-icon-circle-arrow-e'}})
.bind('click.' + ns, function (e) {
e.preventDefault();
filesList.find('.start button').click();
});
fileUploadButtonBar.find('.cancel')
.button({icons: {primary: 'ui-icon-cancel'}})
.bind('click.' + ns, function (e) {
e.preventDefault();
filesList.find('.cancel button').click();
});
fileUploadButtonBar.find('.delete')
.button({icons: {primary: 'ui-icon-trash'}})
.bind('click.' + ns, function (e) {
e.preventDefault();
filesList.find('.delete button').click();
});
},
_destroyFileUploadButtonBar: function () {
this.element.find('.fileupload-buttonbar')
.removeClass('ui-widget-header ui-corner-top');
this.element.find('.fileinput-button').each(function () {
var fileInput = $(this).find('input:file').detach();
$(this).button('destroy')
.append(fileInput);
});
this.element.find('.fileupload-buttonbar button')
.unbind('click.' + this.options.namespace)
.button('destroy');
},
_enableFileInputButton: function () {
this.element.find('.fileinput-button input:file:disabled')
.each(function () {
var fileInput = $(this),
button = fileInput.parent();
fileInput.detach().prop('disabled', false);
button.button('enable').append(fileInput);
});
},
_disableFileInputButton: function () {
this.element.find('.fileinput-button input:file:enabled')
.each(function () {
var fileInput = $(this),
button = fileInput.parent();
fileInput.detach().prop('disabled', true);
button.button('disable').append(fileInput);
});
},
_initTemplates: function () {
// Handle cases where the templates are defined
// after the widget library has been included:
if (this.options.uploadTemplate instanceof $ &&
!this.options.uploadTemplate.length) {
this.options.uploadTemplate = $(
this.options.uploadTemplate.selector
);
}
if (this.options.downloadTemplate instanceof $ &&
!this.options.downloadTemplate.length) {
this.options.downloadTemplate = $(
this.options.downloadTemplate.selector
);
}
},
_create: function () {
$.blueimp.fileupload.prototype._create.call(this);
this._initTemplates();
this.element
.addClass('ui-widget');
this._initFileUploadButtonBar();
this.element.find('.fileupload-content')
.addClass('ui-widget-content ui-corner-bottom');
this.element.find('.fileupload-progressbar')
.hide().progressbar();
},
destroy: function () {
this.element.find('.fileupload-progressbar')
.progressbar('destroy');
this.element.find('.fileupload-content')
.removeClass('ui-widget-content ui-corner-bottom');
this._destroyFileUploadButtonBar();
this.element.removeClass('ui-widget');
$.blueimp.fileupload.prototype.destroy.call(this);
},
enable: function () {
$.blueimp.fileupload.prototype.enable.call(this);
this.element.find(':ui-button').not('.fileinput-button')
.button('enable');
this._enableFileInputButton();
},
disable: function () {
this.element.find(':ui-button').not('.fileinput-button')
.button('disable');
this._disableFileInputButton();
$.blueimp.fileupload.prototype.disable.call(this);
}
});
}(jQuery)); |
import { ensureLogin, containsErrorMessage } from '../utils/HelpUtil';
import { waitInSeconds } from '../utils/WaitUtil';
import ClientHistoryRequest from '../utils/ClientHistoryRequest';
import * as mock from '../mock';
import permissionsMessages from '../../modules/RolesAndPermissions/permissionsMessages';
const authzProfileBody = require('../mock/data/authzProfile');
export default (auth, client, accountInfo, account, alert) => {
describe('AccountInfo:', () => {
this.timeout(20000);
mock.mockClient(client);
let isLoginSuccess;
const clientHistoryRequest = new ClientHistoryRequest(new Map(), client);
afterEach(async () => {
if (auth.loggedIn) {
await auth.logout();
}
await waitInSeconds(1);
});
it('Should load info successfully', async () => {
mock.restore();
mock.mockForLogin();
isLoginSuccess = await ensureLogin(auth, account);
if (!isLoginSuccess) {
console.error(
'Skip test case as failed to login with credential ',
account,
);
this.skip();
}
this.retries(2);
await waitInSeconds(1);
expect(accountInfo.info.id).equal(208594004);
});
it('Should show insufficientPrivilege when no ReadCompanyInfo', async () => {
mock.restore();
mock.mockForLogin({ mockAuthzProfile: false });
mock.authzProfile({
permissions: authzProfileBody.permissions.filter(
(p) => p.permission.id !== 'ReadCompanyInfo',
),
});
await auth.login({
...account,
});
await waitInSeconds(5);
expect(auth.loggedIn).equal(false);
expect(
containsErrorMessage(
alert.state.messages,
permissionsMessages.insufficientPrivilege,
),
).to.not.equal(undefined);
});
});
};
|
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Category, Type;
return {
setters:[],
execute: function() {
(function (Category) {
Category[Category["Item"] = 0] = "Item";
Category[Category["Chemistry"] = 1] = "Chemistry";
})(Category || (Category = {}));
exports_1("Category", Category);
(function (Type) {
Type[Type["Item"] = 0] = "Item";
Type[Type["Fluid"] = 1] = "Fluid";
})(Type || (Type = {}));
exports_1("Type", Type);
}
}
});
//# sourceMappingURL=recipe.js.map |
// @flow
import React from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import Routes from '../routes';
require('jquery');
// import "bootstrap-material-design/dist/css/bootstrap-material-design.css";
// import "bootstrap-material-design/dist/css/ripples.css";
type RootType = {
store: {},
history: {}
};
export default function Root({ store, history }: RootType) {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>
);
}
|
const template = require('./login.html');
const mainSong = require('../../public/music/Main.ogg');
export const LoginCtrlName = 'LoginCtrl';
export const LoginCtrlState = {
url: '/login',
template,
controller: LoginCtrlName,
controllerAs: 'login',
params: {
errorMessage: null
}
};
export const LoginCtrl = [
'$scope',
'UserServices',
'$state',
'$stateParams',
'$rootScope',
'SoundService',
'TimerService',
class LoginCtrl {
constructor($scope,
UserServices,
$state,
$stateParams,
$rootScope,
SoundService,
TimerService) {
'ngInject';
this.UserServices = UserServices;
TimerService.resetGame();
if (SoundService.currentSong._src !== mainSong) {
SoundService.setCurrentSong(mainSong);
}
$scope.userName = '';
$scope.password = '';
$scope.checkCredentials = () =>{
UserServices.getUsers({username: $scope.userName, password: $scope.password})
.success(response => {
if (response.success) {
$rootScope.user = response.username;
$rootScope.visible = true;
} else {
$scope.userName = '';
$scope.password = '';
}
})
};
$scope.errorMessage = $stateParams.errorMessage;
}
}
]; |
/*jslint indent:2*/
'use strict';
// this will be dictionary containing
// - key: a string
// - all possible words with the characters of the key
var memory = {},
callsToFunction = 0;
// find all posible strings that can be formed with
// n characters, without repeating characters
// @param string {String} The initial String to use to generate all combinations
// @memoization {bool} Whether or not you want to use memoization
function findAllWords(string, memoization) {
var allWords = [],
i,
prefix = '',
wordsWithSubstring,
wordsWithPrefix,
remainingChars;
// count the number calls to this function
callsToFunction = callsToFunction + 1;
// if we've already seen this word and have
// calculated it's combinations, then just
// return it
if ('true' === memoization // only use memoization when set to true
&& memory.hasOwnProperty(string)) {
// return the array of all the possible words
// formed with the chars of `string`
return memory[string];
}
// if there's only one char in the string
// there's only one word tha can be formed
if (1 === string.length) {
return [string];
}
function getAllWordsWithPrefix(prefix, words) {
var result = [];
words.forEach(function (item) {
result.push(prefix + item);
});
return result;
}
// the string has at least 2 characters
// chose one char and put that in the first position
for (i = 0; i < string.length; i = i + 1) {
// fix the first character
prefix = string.charAt(i);
// then recursively find all posible words with the
// remaining characters
remainingChars = string.substr(0, i) + string.substr(i + 1);
wordsWithSubstring = findAllWords(remainingChars, memoization);
// add all words that begin with the `prefix`
wordsWithPrefix = getAllWordsWithPrefix(prefix, wordsWithSubstring);
allWords = allWords.concat(wordsWithPrefix);
}
if ('true' === memoization) {
// add all the words to our dictionary
memory[string] = allWords;
}
return allWords;
}
var myWord = 'a',
prompt = require('prompt'),
sizeof = require('../gists/sizeof/sizeof');
console.log('Setup:');
prompt.get(['string', 'memoization'], function (err, result) {
var found;
if (err) {
console.log(err);
} else {
found = findAllWords(result.string, result.memoization);
console.log(found);
console.log(found.length + ' words found.');
console.log('Calls to `findAllWords`:' + callsToFunction);
console.log('Memory used: ' + sizeof(memory));
callsToFunction = 0;
}
}); |
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
/**
* Gets a value from the querystring (or returns "")
* @param {string} name the name of the querystring parameter
* @param {string} [url] when omitted, the current location.url is assumed
*/
function getQueryStringParam(name, url) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
if( url == undefined && name == "village" ) {
return game_data.village.id;
} else {
var results = regex.exec(url == undefined ? window.location.href : url);
if (results == null) {
return "";
} else {
return results[1];
}
}
}
/**
* Get a TW url taking account sitting etc in account
* @param {string} url provide the url starting from &screen=
* @param {number} [villageId] when omitted the current village is assumed
*/
function getUrlString(url, villageId) {
if (url.indexOf("?") == -1) {
var link = location.href.substr(0, location.href.indexOf("?"));
link += "?village=" + (villageId ? villageId : getQueryStringParam("village"));
var isSit = getQueryStringParam("t");
if (isSit) {
link += "&t=" + isSit;
}
if (url.indexOf("=") == -1) {
return link + "&screen=" + url;
} else {
return link + "&" + url;
}
} else {
return url;
}
}
/**
* Perform an ajax call (if the server allows it)
* @param {string} screen passed to getUrlString. (start from &screen=)
* @param {function} strategy executed on success. Has parameter text (content of the parameter depends on opts.contentValue)
* @param {object} [opts] object with properties
* {false|number} [villageId] passed to getUrlString. Default is false which defaults to current village. Otherwise pass a village id.
* {boolean=true} [contentValue] true (default): only return the #content_value. false: return entire DOM HTML
* {boolean=true} [async] defaults to true
*/
function ajax(screen, strategy, opts) {
if (!server_settings.ajaxAllowed) {
alert("Ajax is not allowed on this server.");
return;
}
opts = $.extend({}, { villageId: false, contentValue: true, async: false }, opts);
$.ajax({
url: getUrlString(screen, opts.villageId),
async: server_settings.asyncAjaxAllowed ? opts.async : false,
success: function(text) {
text = opts.contentValue ? $("#content_value", text) : text;
strategy(text);
}
});
}
/**** TribalWarsLibrary.js ****/
if (typeof window.twLib === 'undefined') {
window.twLib = {
queues: null,
init: function() {
if (this.queues === null) {
this.queues = this.queueLib.createQueues(5);
}
},
queueLib: {
maxAttempts: 3,
Item: function (action, arg, promise = null) {
this.action = action;
this.arguments = arg;
this.promise = promise;
this.attempts = 0;
},
Queue: function() {
this.list = [];
this.working = false;
this.length = 0;
this.doNext = function () {
let item = this.dequeue();
let self = this;
if (item.action == 'openWindow') {
window.open(...item.arguments).addEventListener('DOMContentLoaded', function() {
self.start();
});
} else {
$[item.action](...item.arguments).done(function () {
item.promise.resolve.apply(null, arguments);
self.start();
}).fail(function () {
item.attempts += 1;
if (item.attempts < twLib.queueLib.maxAttempts) {
self.enqueue(item, true);
} else {
item.promise.reject.apply(null, arguments);
}
self.start();
});
}
};
this.start = function () {
if (this.length) {
this.working = true;
this.doNext();
} else {
this.working = false;
}
};
this.dequeue = function () {
this.length -= 1;
return this.list.shift();
};
this.enqueue = function (item, front = false) {
(front) ? this.list.unshift(item) : this.list.push(item);
this.length += 1;
if (!this.working) {
this.start();
}
};
},
createQueues: function(amount) {
let arr = [];
for (let i = 0; i < amount; i++) {
arr[i] = new twLib.queueLib.Queue();
}
return arr;
},
addItem: function(item) {
let leastBusyQueue = twLib.queues.map(q => q.length).reduce((next, curr) => (curr < next) ? curr : next, 0);
twLib.queues[leastBusyQueue].enqueue(item);
},
orchestrator: function(type, arg) {
let promise = $.Deferred();
let item = new twLib.queueLib.Item(type, arg, promise);
twLib.queueLib.addItem(item);
return promise;
}
},
ajax: function() {
return twLib.queueLib.orchestrator('ajax', arguments);
},
get: function() {
return twLib.queueLib.orchestrator('get', arguments);
},
post: function() {
return twLib.queueLib.orchestrator('post', arguments);
},
openWindow: function() {
let item = new twLib.queueLib.Item('openWindow', arguments);
twLib.queueLib.addItem(item);
}
};
twLib.init();
}
function spSpeedCookie(setter) {
if (setter == undefined) {
var speedCookie = pers.get("targetVillageSpeed");
if (speedCookie == '') {
speedCookie = 'ram';
}
return speedCookie;
} else {
if (setter.indexOf('_') == 4) {
setter = setter.substr(setter.indexOf('_') + 1);
}
pers.set("targetVillageSpeed", setter);
return setter;
}
}
function spTargetVillageCookie(setter) {
if (setter == undefined) {
return pers.get("targetVillageCoord");
} else {
pers.set("targetVillageCoord", setter);
return setter;
}
}
function getDistance(x1, x2, y1, y2, speed) {
var dist = {};
dist.fields = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
dist.travelTime = dist.fields * (speed == '' ? world_data.unitsSpeed.unit_ram : world_data.unitsSpeed['unit_' + speed]);
dist.arrivalTime = getDateFromTW($("#serverTime").text(), true);
dist.arrivalTime.setTime(dist.arrivalTime.getTime() + (dist.travelTime * 60 * 1000));
dist.isNightBonus = isDateInNightBonus(dist.arrivalTime);
if (speed == 'snob' && dist.travelTime > world_config.maxNobleWalkingTime) {
dist.html = "<font color='" + user_data.colors.error + "'><b>" + twDurationFormat(dist.travelTime) + "</b></font>";
dist.isNightBonus = true;
} else {
var displayTime = twDateFormat(dist.arrivalTime);
if (speed != 'merchant' && dist.isNightBonus) {
displayTime = "<font color='" + user_data.colors.error + "'><b>" + displayTime + "</b></font>";
}
dist.html = user_data.walkingTimeDisplay
.replace("{duration}", twDurationFormat(dist.travelTime))
.replace("{arrival}", displayTime);
}
if (dist.fields == 0) {
dist.html = "";
}
return dist;
}
// _gaq.push(['b._setAccount', 'UA-30075487-3']);
/**
* Send click to google analytics
* @param {string} action
*/
function trackClickEvent(action) {
trackEvent("ButtonClick", action);
}
/**
* google analytics event tracking
*/
function trackEvent(category, action, label) {
// category: clicks (downloads, ...)
// action: which button clicked
if (typeof label === 'undefined') {
label = getQueryStringParam("screen");
var mode = getQueryStringParam("mode");
if (mode) label += "-" + mode;
}
//_gaq.push(['b._setAccount', 'UA-30075487-3']);
//_gaq.push(['b._trackPageview']);
// _gat._getTrackerByName('b')._trackEvent("SanguPackage", "Loaded", "withGetB");
// try
// {
// _gat._getTrackerByName('b')._trackEvent(category, action, label);
// }
// catch (e) {
// // no crash report for this
// }
}
function fillRallyPoint(units) {
var script = "";
$.each(world_data.units, function (i, v) {
if (units[v] != undefined && units[v] > 0) {
script += "document.forms[0]." + v + ".value=\"" + units[v] + "\";";
} else {
script += "document.forms[0]." + v + ".value=\"\";";
}
});
return script;
}
/**
* Tries to find village coords in str and convert it to a 'village' object
* @param {string} str the string to be converted to a village object
* @param {true|} looseMatch !!!Do not provide a value for looseMatch when converting a real village name.!!!
* It should be set to true when it was the user that provided the input str. When true,
* a str like 456-789 would also match. (so that Sangu Package users don't have to use | but can instead
* use anything to seperate the 2 coordinates).
* @returns {object} object with parameters isValid: false when the string could not be matched and true with extra properties
* x, y, coord, validName (=html friendly id name) and continent
*/
function getVillageFromCoords(str, looseMatch) {
// if str is "villageName (X|Y) C54" then the villageName could be something like "456-321"
// the regex then thinks that the villageName are the coords
// looseMatch
var targetMatch = looseMatch != undefined ? str.match(/(\d+)\D(\d+)/g) : str.match(/(\d+)\|(\d+)/g);
if (targetMatch != null && targetMatch.length > 0) {
var coordMatch = targetMatch[targetMatch.length - 1].match(/(\d+)\D(\d+)/);
var village = { "isValid": true, "coord": coordMatch[1] + '|' + coordMatch[2], "x": coordMatch[1], "y": coordMatch[2] };
village.validName = function () { return this.x + '_' + this.y; };
village.continent = function () { return this.y.substr(0, 1) + this.x.substr(0, 1); };
return village;
}
return { "isValid": false };
}
function buildAttackString(villageCoord, unitsSent, player, isSupport, minimum, haulDescription) {
var seperator = " ";
if (minimum == undefined) {
minimum = 0;
}
var totalPop = 0;
var renamed = villageCoord == null ? "" : villageCoord + seperator;
var sent = "";
$.each(world_data.units, function (i, val) {
var amount = unitsSent[val];
if (amount != 0) {
if (val == "snob") {
renamed += trans.tw.units.names[val] + "! ";
}
else if (amount >= minimum) {
sent += ", " + trans.tw.units.shortNames[val] + "=" + amount;
}
totalPop += amount * world_data.unitsPositionSize[i];
}
});
if (player) {
renamed += '(' + player + ')' + seperator;
}
if (sent.length > 2) {
sent = sent.substr(2);
}
if (isSupport) {
sent += seperator + "(" + trans.sp.all.populationShort + ": " + formatNumber(totalPop) + ")";
}
if (user_data.attackAutoRename.addHaul && typeof haulDescription !== 'undefined') {
sent += " (" + trans.tw.command.haul + " " + haulDescription + ")";
}
return renamed + sent;
}
function calcTroops(units) {
// units is an array of numbers; keys are the unit names (without unit_)
var x = {};
x.totalDef = 0;
function removeElement(arr, element) {
var idx = arr.indexOf(element);
if (idx != -1) {
arr.splice(idx, 1);
}
return arr;
}
// heavy doesn't count in determining whether the village is def/off (since you got some crazy guys using hc as offense and defense:)
$.each(removeElement(world_data.units_def, 'heavy'), function (i, v) { x.totalDef += units[v] * world_data.unitsSize['unit_' + v]; });
x.totalOff = 0;
$.each(removeElement(world_data.units_off, 'heavy'), function (i, v) { x.totalOff += units[v] * world_data.unitsSize['unit_' + v]; });
x.isDef = x.totalDef > x.totalOff;
x.isScout = units.spy * world_data.unitsSize.unit_spy > x.totalDef + x.totalOff;
x.isMatch = function (type) { return (type == 'all' || (type == 'def' && this.isDef) || (type == 'off' && !this.isDef)); };
x.getSlowest =
function () {
var slowest_unit = null;
$.each(world_data.units, function (i, v) {
if (units[v] > 0 && (slowest_unit == null || world_data.unitsSpeed["unit_" + slowest_unit] < world_data.unitsSpeed["unit_" + v])) {
slowest_unit = v;
}
});
return slowest_unit;
};
x.colorIfNotRightAttackType =
function (cell, isAttack) {
var isSet = false;
if (units.snob != undefined && units.snob > 0) {
if (isAttack) {
if (units.snob > 1) {
isSet = true;
cell.css("background-color", user_data.colors.error).css("border", "1px solid black");
cell.animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 5000, function () {
// Animation complete.
});
} else {
return;
}
} else {
isSet = true;
}
}
else if (x.totalDef + x.totalOff < user_data.command.filterFakeMaxPop) {
// fake
return;
}
if (!isSet && (x.isScout || x.isMatch(isAttack ? 'off' : 'def'))) {
return;
}
cell.css("background-color", user_data.colors.error);
};
return x;
}
function minimalTroops(unit, nobleValue) {
return Math.ceil((game_data.village.points * world_config.minFake - nobleValue) / world_data.unitsSize["unit_" + unit])
}
// Tagger rename function
function executeRename(id, value) {
if (server_settings.ajaxAllowed) {
return twLib.ajax({
url: game_data.link_base_pure + 'info_command&ajaxaction=edit_other_comment&id=' + id + '&h=' + game_data.csrf,
type: 'POST',
async: true,
data: {text: value},
success: function () {
$('span.quickedit[data-id="' + id + '"]').find('span.quickedit-label').text(value);
}
});
}
}
function stackDisplay(totalFarm, stackOptions) {
// TODO: this function is only used on main village overview
if (stackOptions == undefined) {
stackOptions = {};
}
var farmSize = game_data.village.buildings.farm * world_config.farmLimit;
var stackDesc = '<b>' + formatNumber(totalFarm);
if (stackOptions.showFarmLimit && world_config.farmLimit > 0) {
stackDesc += ' / ' + formatNumber(farmSize);
}
if (stackOptions.percentage) {
stackDesc += ' (' + stackOptions.percentage + ')</b>';
}
var bgColor = getStackColor(totalFarm, farmSize);
if (stackOptions.cell == undefined) {
return {
color: bgColor,
desc: stackDesc,
cssColor: "style='background-color:" + bgColor + "'"
};
} else {
if (stackOptions.appendToCell) {
stackOptions.cell.append(" » " + stackDesc);
} else {
stackOptions.cell.html(stackDesc);
}
if (!stackOptions.skipColoring) {
stackOptions.cell.css("background-color", bgColor);
}
}
}
/**
* Gets the configured stack backgroundcolor for the given stackTotal
* @param stackTotal {number}
* @returns {color}
*/
function getStackColor(stackTotal) {
var color = null,
arrayToIterate,
farmLimitModifier;
if (world_config.farmLimit > 0) {
arrayToIterate = user_data.farmLimit.acceptableOverstack;
farmLimitModifier = 30 * world_config.farmLimit;
} else {
arrayToIterate = user_data.farmLimit.unlimitedStack;
farmLimitModifier = 1; // = No modifier
}
if (arrayToIterate.length > 0) {
$.each(arrayToIterate, function (index, configValue) {
if (color == null && stackTotal < farmLimitModifier * configValue) {
if (index === 0) {
color = "";
} else {
color = user_data.farmLimit.stackColors[index - 1];
//q(stackTotal +"<"+ farmLimitModifier +"*"+ configValue);
//q("return " + (index - 1) + "->" + color);
}
return false;
}
});
if (color != null) {
//q(stackTotal + " -> " + color);
return color;
}
return user_data.farmLimit.stackColors[user_data.farmLimit.stackColors.length - 1];
}
return "";
}
|
var test = require('tape');
var isValidZip = require('../is-valid-zip');
test('is valid zip', function (t) {
t.plan(7);
t.equal(isValidZip(11743), true);
t.equal(isValidZip('11743-6961'), true);
t.equal(isValidZip('11743-6'), false);
t.equal(isValidZip(11743344), false);
t.equal(isValidZip(144), false);
t.equal(isValidZip({}), false);
t.equal(isValidZip(), false);
});
|
'use strict'
const fs = require('fs-extra')
const path = require('path')
const prune = require('../prune')
const test = require('ava')
const util = require('./_util')
function checkDependency (t, resourcesPath, moduleName, moduleExists) {
const assertion = moduleExists ? 'should' : 'should NOT'
const message = `module dependency '${moduleName}' ${assertion} exist under app/node_modules`
const modulePath = path.join(resourcesPath, 'app', 'node_modules', moduleName)
return fs.pathExists(modulePath)
.then(exists => t.is(moduleExists, exists, message))
.then(() => modulePath)
}
function assertDependencyExists (t, resourcesPath, moduleName) {
return checkDependency(t, resourcesPath, moduleName, true)
.then(modulePath => fs.stat(modulePath))
.then(stats => t.true(stats.isDirectory(), 'module is a directory'))
}
function createPruneOptionTest (t, baseOpts, prune, testMessage) {
const opts = Object.assign({}, baseOpts, {
name: 'pruneTest',
dir: util.fixtureSubdir('basic'),
prune: prune
})
let resourcesPath
return util.packageAndEnsureResourcesPath(t, opts)
.then(generatedResourcesPath => {
resourcesPath = generatedResourcesPath
return assertDependencyExists(t, resourcesPath, 'run-series')
}).then(() => assertDependencyExists(t, resourcesPath, '@types/node'))
.then(() => checkDependency(t, resourcesPath, 'run-waterfall', !prune))
.then(() => checkDependency(t, resourcesPath, 'electron-prebuilt', !prune))
}
util.testSinglePlatform('prune test', (t, baseOpts) => {
return createPruneOptionTest(t, baseOpts, true, 'package.json devDependency should NOT exist under app/node_modules')
})
util.testSinglePlatform('prune electron in dependencies', (t, baseOpts) => {
const opts = Object.assign({}, baseOpts, {
name: 'pruneElectronTest',
dir: util.fixtureSubdir('electron-in-dependencies')
})
return util.packageAndEnsureResourcesPath(t, opts)
.then(resourcesPath => checkDependency(t, resourcesPath, 'electron', false))
})
util.testSinglePlatform('prune: false test', createPruneOptionTest, false,
'package.json devDependency should exist under app/node_modules')
test('isModule only detects modules inside a node_modules parent folder', t =>
prune.isModule(util.fixtureSubdir(path.join('prune-is-module', 'node_modules', 'module')))
.then(isModule => {
t.true(isModule, 'module folder should be detected as module')
return prune.isModule(util.fixtureSubdir(path.join('prune-is-module', 'node_modules', 'module', 'not-module')))
}).then(isModule => t.false(isModule, 'not-module folder should not be detected as module'))
)
|
define([
'model/CodeCollection',
'text!tinyschemer/intro.scm',
'text!tinyschemer/values.scm',
'text!tinyschemer/lists.scm',
'text!tinyschemer/functioncalls.scm',
'text!tinyschemer/listfunctions.scm',
'text!tinyschemer/define.scm',
'text!tinyschemer/recursionintro.scm',
'text!tinyschemer/sum.scm',
'text!tinyschemer/sumAnswer.scm',
'text!tinyschemer/count-in.scm',
'text!tinyschemer/count-inAnswer.scm'
], function (CodeCollection, intro, values, lists, functioncalls,
listfunctions, define, recursionintro, sum, sumAnswer,
countIn, countInAnswer) {
return new CodeCollection([
{ name: 'Intro', code: intro },
{ name: 'Values', code: values },
{ name: 'Lists', code: lists },
{ name: 'Function calls', code: functioncalls },
{ name: 'List functions', code: listfunctions },
{ name: 'Defining variables and functions', code: define },
{ name: 'Recursive functions', code: recursionintro},
{ name: 'sum exercise', code: sum},
{ name: 'sum answer', code: sumAnswer},
{ name: 'count-in exercise', code: countIn},
{ name: 'count-in answer', code: countInAnswer}
]);
});
|
const enums =
{
PlayerBan: 'playerBans',
PlayerKick: 'playerKicks',
PlayerMute: 'playerMutes',
PlayerNote: 'playerNotes',
PlayerWarning: 'playerWarnings'
}
module.exports = (type) => enums[type]
|
module.exports = {
name:'setup',
description:'Runs clone and then install to get your environment ready for action.',
example:'bosco setup',
cmd:cmd
}
function cmd(bosco, args) {
var clone = require('./clone');
var install = require('./install');
var team = require('./team');
var link = require('./link');
team.cmd(bosco, ['sync'], function() {
team.cmd(bosco, ['setup'], function() {
clone.cmd(bosco, [], function() {
link.cmd(bosco, [], function() {
install.cmd(bosco, args);
});
});
});
});
}
|
//
// Basic array functions that javascript annoyingly doesn't have
//
// a is an array. Return an array of the elements of a for which f returns true
var filter = function(a,f) {
var r = [];
var l = a.length;
for(var i=0; i<l; ++i) {
var e = a[i];
if (f(e)) {
r.push(e);
}
}
return r;
};
// Return a shallow copy of the array a
var arrayClone = function(a) { return filter(a,function() {return true;}); };
// Returns true if the value e is somewhere in the array a
var contains = function(a,e) {
var l = a.length;
for(var i=0; i<l; ++i) {
if (a[i] == e)
return true;
}
return false;
}
// Backfill Object.keys for browsers that don't already have it.
// Copied from Andy E at http://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object/3937321#3937321
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
DontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
DontEnumsLength = DontEnums.length;
return function (o) {
if (typeof o != "object" && typeof o != "function" || o === null)
throw new TypeError("Object.keys called on a non-object");
var result = [];
for (var name in o) {
if (hasOwnProperty.call(o, name))
result.push(name);
}
if (hasDontEnumBug) {
for (var i = 0; i < DontEnumsLength; i++) {
if (hasOwnProperty.call(o, DontEnums[i]))
result.push(DontEnums[i]);
}
}
return result;
};
})();
//
// The "meat" functions are below
//
// songs is an object { song name: [ list of songs it can segue to ] }
// numSongs is how many songs you want in the setlist
// randGen is a function that should return random integers >= 0 and < the integer passed in
function generateSetlist(songs, numSongs, randGen) {
if (numSongs < 1) {
throw "number of songs must be at least 1: got "+numSongs;
}
return (function(availableSongs, setList) {
var result;
var numAvail = availableSongs.length;
var firstSongIndex = randGen(numAvail);
for (var i = firstSongIndex; (!result) && (i-firstSongIndex)<numAvail; ++i) {
var nsi = i % numAvail;
var newSong = availableSongs[nsi];
var newSetList = arrayClone(setList);
newSetList.push(newSong);
if (newSetList.length == numSongs) {
result = newSetList;
} else {
var newAvailableSongs = filter(songs[newSong], function(x) { return !contains(newSetList,x); });
if (newAvailableSongs.length) {
result = arguments.callee(newAvailableSongs, newSetList);
}
}
// At this point either we've set result (in which case we'll drop
// out of the loop and return it) or we go on to the next song
// in the available list
}
return result;
})(
Object.keys(songs), // initial availableSongs
[] // initial setList
);
}
// The idea here is to make the minimal changes necessary to change the list of song names in a songs/transitions object
// suitable for generateSetlist. I.e. if there is a song in the list not in the current one, add it with an empty transitions list.
// For any songs in the object not in the new list, remove it from the main object and from all transitions lists.
// Leave all other songs and transitions as they are. If the song name list is empty, return undefined
// This should return a brand new object and not change the one passed in
function changeSongNameList(oldSongs, newSongNames) {
var nsnl=newSongNames.length;
if (nsnl == 0) {
return undefined;
}
var curNames = (oldSongs ? Object.keys(oldSongs) : []);
var cnl = curNames.length;
var result = {};
for(var i=0; i<cnl; ++i) {
var oldName = curNames[i];
if (contains(newSongNames,oldName)) {
result[oldName] = filter(oldSongs[oldName], function(song) { return contains(newSongNames,song); });
}
}
for(var i=0; i<nsnl; ++i) {
var newSong = newSongNames[i];
if (!oldSongs || !Object.prototype.hasOwnProperty.call(oldSongs,newSong)) {
result[newSong] = [];
}
}
return result;
} |
// TODO(wuhf): AMD/CMD加载器
// ========================================================
;(function ($, global) {
var modules = {
'armer': {
exports: $
},
require: {exports: require},
exports: {exports: {}},
module: {exports: {}}
};
modules.jQuery = modules.jquery = modules.zepto = modules.armer;
function getFnRegExp(requireS) {
return RegExp('(?:[^\\w\\d$_]|^)' + requireS + '\\s*\\(([^)]*)\\)', 'g')
}
var requestUrl = null;
// 这个变量用于储存require的时候当前请求的位置来确定依赖的位置
var requesting = {};
// 通过require正在请求的模块
var defaults = {
autoWrap: true, // xhr环境下支持无define的commonJS模式
//linkStyleAsModule: true, // 自动分析link下的css,作为已加载的模块
fireNoRequestingModel: true, // 允许匿名模块,当使用define来定义未被请求的匿名模块,设为false会被
useXhr: false,
baseUrl : location.href,
ext : 'js',
paths : {},
shim: {},
map: {},
method: 'auto',
namespace: 'default',
collector: [
// 分析 require
function (deps, factory){
var withCMD = -1, i;
for (i = 0; i < deps.length; i++) {
// 看deps里是否有require,是则找出其index
if (deps[i] == 'require') {
withCMD = i;
}
}
// CMD分析require
if (typeof factory == "function" && !!~withCMD) {
var requireS, fn = factory.toString();
var args = fn.match(/^function[^(]*\(([^)]*)\)/)[1];
if ($.trim(args) != '') {
args = args.split(',');
requireS = $.trim(args[withCMD]);
fn.replace(getFnRegExp(requireS), function(_, dep){
// try 一下,确保不会把奇奇怪怪的东西放进去
try {
dep = eval.call(null, dep);
if (typeof dep == 'string') deps.push(dep);
} catch(e) {}
})
}
}
},
// 分析 __inline
function(deps, factory){
var s = ['__inline'], fn = factory.toString();
$.each(s, function(_, item){
fn.replace(getFnRegExp(item), function(_, dep){
dep = eval.call(null, dep);
if (typeof dep == 'string') deps.push(item + '!' + dep);
})
});
}
],
plugins: {
// domready 插件
domready: {
config: function(){
var mod = {
dfd: $.Deferred(),
exports: $,
method: 'domready'
};
$(function(){
mod.dfd.resolveWith(mod, [mod]);
});
return mod;
}
},
auto: {
config: function(config){
var url;
if ($.type(this.url) == 'string') {
url = $.URL(this.url, this.parent);
} else if (this.url) {
url = this.url;
} else {
url = $.URL(this.name, this.parent);
}
this.ext = url.extension();
if (!this.ext) {
url.extension(defaults.ext);
this.ext = defaults.ext;
} else if (!$.ajax.ext2Type[this.ext]) {
url.extension(defaults.ext, true);
this.ext = defaults.ext;
}
if (this.ext == defaults.ext) {
this.name = url.fileNameWithoutExt()
} else {
this.name = url.fileName()
}
url.search('callback', 'define');
this.url = url.toString();
this.type = $.ajax.ext2Type[this.ext];
},
callback: function(){
if (this.type !== 'script') {
this.exports = this.originData;
} else if (this.factory) {
var exports = this.factory.apply(this, getExports(arguments))
if (exports != null)
this.exports = exports
else if (this.exports == null)
this.exports = modules.exports.exports
} else if (this.exports == null)
this.exports = modules.exports.exports
}
}
}
};
// 构造模块
require.Model = function Model(config, url){
$.extend(this, config);
//throw Error(this.id)
modules[this.id] = this;
if (url != null) this.url = url;
//if (this.url) modules[this.method + this.url] = this;
//else if (this.id) modules[this.id] = this;
};
require.Model.prototype = {
// 处理模块
fire: function(data){
// 使用shim模式
var mod = this;
var shim = defaults.shim[mod.name] || {};
if ($.isArray(shim))
shim = {
deps: shim
}
mod.deps = mod.deps || shim.deps
mod.originData = data;
var success = function(){
modules.module.exports = mod;
modules.exports.exports = {};
if (shim.exports)
modules.exports.exports = eval('(function(){return ' + shim.exports + '})()');
mod.factory = mod.factory || shim.init;
var args = arguments
require.rebase(mod.url, function(){
if (defaults.plugins[mod.method].callback.apply(mod, args) !== false) {
mod.dfd.resolveWith(mod, [mod]);
}
});
modules.module.exports = null;
}
if (mod.deps && mod.deps.length) {
require.rebase(mod.url, function(){
innerRequire(mod.deps).done(success).fail(function(){
mod.dfd.rejectWith(mod, arguments);
});
});
} else
// 避免加载过快 parseDep 时currentUrl的出错
$.nextTick(function(){success()}, 0);
// 这两个是为CMD服务的,只读
mod.dependencies = mod.deps;
mod.uri = mod.url;
},
error: function(errState){
this.err = errState
this.dfd.rejectWith(this, [this]);
},
resolve: function(url){
url = $.URL(url, this.url);
if (url.extension() == '') url.extension(defaults.ext);
return url.toString();
}
}
function getExports(mods){
var arr = [], i;
for (i = 0; i < mods.length; i++) {
arr.push(mods[i].exports);
}
return arr;
}
function parseDep(config, currentUrl) {
var mod, tmp;
if (typeof config == 'string') {
// 存在同名模块
tmp = id2Config(config, currentUrl);
if (!(mod = modules[tmp.id] || modules[config])) {
config = tmp
}
}
//如果有mod证明已经通过同名模块的if分支
if (!mod) {
if ($.isDeferred(config)) {
var id;
if (config.modelName && modules[config.modelName])
mod = modules[config.modelName];
else {
// 如果是一个dfd,则通过dfd产生一个匿名模块
id = 'anonymousModel' + $.now();
mod = new require.Model({dfd: config, id: id});
config.modelName = id;
}
}
else if (typeof config == 'object') {
// 处理同样地址同样方式加载但不同name的模块
if (!(mod = modules[config.id]))
mod = new require.Model(config);
// 模块作为参数情况
} else if (typeof config == 'string')
mod = new require.Model({url: config})
}
return mod;
}
/**
* 请求模块
* @param deps 依赖列表
* @param parent 当前路径
* @returns {$.Deferred.promise}
*/
function innerRequire(deps) {
if (!$.isArray(deps)) deps = [deps];
var mDps = [], mod;
for (var i = 0; i < deps.length; i++) {
mod = parseDep(deps[i], requestUrl);
// 当不存在dfd的时候证明这个模块没有初始化
// 当存在状态为rejected的模块,则重新请求
if (!mod.dfd || mod.dfd.state() == 'rejected') {
mod.dfd = $.Deferred();
// 如果factory或者exports没有定义,那么可以判断出是通过异步加载已存在但未请求成功的模块
// TODO:这个判断貌似不太准确
if (!mod.factory && !('exports' in mod))
(function(mod){
requesting[mod.url] = mod;
var options = {
url: mod.url,
cache: true,
crossDomain: defaults.useXhr && defaults.charset ? true : void 0,
//crossDomain: true,
dataType: mod.type || $.ajax.ext2Type[defaults.ext],
scriptCharset: defaults.charset,
success: function(data) {
var bmod;
if (requesting[mod.url]) {
// 处理bmods
if (requesting[mod.url].bmods) {
if (requesting[mod.url].exports == null && requesting[mod.url].factory == null) {
bmod = requesting[mod.url].bmods.pop();
var dfd = mod.dfd;
$.extend(mod, bmod);
mod.dfd = dfd;
modules[bmod.id] = mod;
if (defaults.fireNoRequestingModel) $.each(requesting[mod.url].bmods, function(bmod){
bmod.fire(data)
})
}
}
delete requesting[mod.url]
}
mod.fire(data);
},
error: function(){
mod.error(arguments);
delete requesting[mod.url];
},
converters: {
"text script": function(text) {
require.rebase(mod.url, function(){
if (defaults.autoWrap && !getFnRegExp('define').test(text)) {
text = 'define(function(require, exports, module){' + text + '})';
}
$.globalEval(text);
});
return text;
}
}
};
$.ajax(options);
})(mod);
// 如果factory或者exports已经定义过,那么就直接处理该模块
else if (mod.fire)
mod.fire();
// 一些特殊的模块,只包括exports的
else mod.dfd.resolveWith(mod, [mod])
}
mDps.push(mod.dfd);
}
return $.when.apply($, mDps);
}
function require(deps, callback, errorCallback){
// 兼容CMD模式
if (!callback && !$.isArray(deps)) {
var mod, currentUrl = requestUrl || $.URL.current();
if (mod = modules[id2Config(deps, currentUrl).id] || modules[deps])
return mod.exports;
else {
throw Error('this module is not define');
}
}
return require.rebase($.URL.current(), function(){
return innerRequire(deps).done(function(){
callback && callback.apply(this, getExports(arguments))
}).fail(errorCallback).promise();
});
}
/**
*
* @param name 模块name用于记录缓存这个模块
* @param [deps] 依赖列表,这个模块需要依赖那些模块
* @param factory 工厂,用于处理返回的模块
* @returns {Model}
*/
function define(name, deps, factory){
if (typeof name != 'string') {
factory = deps;
deps = name;
name = null;
}
if (factory === undefined) {
factory = deps;
deps = ['require', 'exports', 'module'];
}
var mod, config;
var currentUrl = requestUrl || $.URL.current();
// 如果正在请求这个js
if (mod = requesting[currentUrl]) {
if (name && (config = id2Config(name, currentUrl)).id !== mod.id) {
// 如果define的名字不一样,记录bmod作为后备模块,当文件请求完毕仍然没有同名模块,则最后一个后备模块为该模块
mod = new require.Model(config, currentUrl);
requesting[currentUrl].bmods = requesting[currentUrl].bmods || [];
requesting[currentUrl].bmods.push(mod);
} else
mod.anonymous = true;
} else {
//如果没有请求这个js
if (!name) {
mod = new require.Model(id2Config(currentUrl, location.href));
mod.anonymous = true;
}
else mod = new require.Model(id2Config(name, currentUrl))
if (defaults.fireNoRequestingModel) {
mod.dfd = $.Deferred();
mod.fire();
}
}
mod.deps = deps;
mod.type = 'script';
if (mod.anonymous == null) mod.anonymous = false;
$.each(defaults.collector, function(i, item){
item(mod.deps, factory);
});
if (typeof factory == 'function')
mod.factory = factory;
else
mod.exports = factory;
return mod;
}
function id2Config(name, parent) {
var s, c = {name: name};
s = name.split('!');
// 分析处理方法
if (s.length == 2) {
c.method = s[0];
c.name = s[1];
} else if (!!~name.indexOf('!')) {
c.method = s[0];
} else {
c.method = defaults.method;
c.name = s[0];
}
if (!~c.name.indexOf('://')) {
s = c.name.split(':');
if (/:\/\//.test(c.name) && s.length == 2 || s.length == 1)
c.namespace = defaults.namespace;
else
c.namespace = s.shift();
c.name = s[s.length - 1];
}
c.parent = parent;
//别名机制
var tmpExt = '.' + defaults.ext;
var path;
if (name.indexOf(tmpExt) == name.length - tmpExt.length) {
path = defaults.paths[name.substr(name.length)]
} else {
path = defaults.paths[name + tmpExt];
}
if (defaults.paths[name] || path) {
c.url = defaults.paths[name] || path
}
c = defaults.plugins[c.method].config.call(c) || c;
c.id = c.id || c.method + '!' + (c.namespace ? (c.namespace + ':') : '') + c.url;
return c;
}
define.amd = define.cmd = modules;
require.defaults = defaults;
require.config = function(options){
if ($.isPlainObject(options)) {
options = $.mixOptions({}, options);
if (options.paths) $.each(options.paths, function(i, item){
if ($.type(item) == 'string') {
options.paths[i] = $.URL(item);
}
});
$.mixOptions(this.defaults, options);
} else return defaults[options];
};
/**
* 默认require会在当前js运行的环境下找相对require的路径,但如果要特定require相对路径查找的位置,需要运行这个方法
* @param url 给出的url
* @param callback
* @returns {*}
*/
require.rebase = function(url, callback){
var ret
requestUrl = url;
ret = callback();
requestUrl = null;
return ret;
};
// CMD的async方法实际是就是AMD的require
require.async = require;
require.resolve = function(url){
return modules.module.exports.resolve(url);
};
require.requesting = requesting;
require.register = define;
$.require = require;
$.define = define;
$.use = function(deps){
return require(deps, $.noop);
}
defaults.plugins.domReady = defaults.plugins.ready = defaults.plugins.domready;
$.each(['js', 'css', 'text', 'html'], function(i, item){
defaults.plugins[item] = {
config: function(){
var url;
if ($.type(this.url) == 'string') {
url = $.URL(this.url, this.parent);
} else if (this.url) {
url = this.url;
} else {
url = $.URL(this.name, this.parent);
}
this.ext = url.extension();
if (this.ext == defaults.ext) {
this.name = url.fileNameWithoutExt()
} else {
this.name = url.fileName()
}
url.search('callback', 'define');
this.url = url.toString();
this.type = $.ajax.ext2Type[item] || item;
},
callback: defaults.plugins.auto.callback
}
});
defaults.plugins['__inline'] = {
config: function(){
var url;
if ($.type(this.url) == 'string') {
url = $.URL(this.url, this.parent);
} else if (this.url) {
url = this.url;
} else {
url = $.URL(this.name, this.parent);
}
this.ext = url.extension();
if (this.ext == defaults.ext)
this.name = url.fileNameWithoutExt();
else
this.name = url.fileName();
if (this.ext == 'js')
this.type = 'script'
else
this.type = 'text'
url.search('callback', 'define');
this.url = url.toString();
},
callback: defaults.plugins.auto.callback
};
var nodes = document.getElementsByTagName("script");
defaults = $.mixOptions(defaults, window.require, $(nodes[nodes.length - 1]).data());
if (!window.require) window.require = require;
if (!window.define) window.define = define;
window.__inline = function(url){
return require('__inline!' + url);
}
window.__uri = window.__uid = window.__uril = function(url){
return $.URL(url, requestUrl || $.URL.current()).toString()
}
// 之前版本写错单词
defaults.plusin = defaults.plugins;
if (defaults.main)
$(function(){
require.rebase(location.href, function(){
innerRequire(defaults.main);
})
});
})(armer, window);
|
// Could implement other Array methods, like some(), filter(), etc.
function PropertyMapper () {
}
PropertyMapper.prototype.mapOwnEnumerables = function (cb) {
};
PropertyMapper.prototype.mapOwnNonenumerables = function (cb) {
};
PropertyMapper.prototype.mapOwnEnumerablesAndNonenumerables = function (cb) {
};
PropertyMapper.prototype.mapPrototypeEnumerables = function (cb) {
};
PropertyMapper.prototype.mapPrototypeNonenumerables = function (cb) {
};
PropertyMapper.prototype.mapPrototypeEnumerablesAndNonenumerables = function (cb) {
};
PropertyMapper.prototype.mapOwnAndPrototypeEnumerables = function (cb) {
var obj = this.obj;
var ret = [];
for (var prop in obj) {
ret.push(cb(obj[prop], prop, obj));
}
return ret;
};
PropertyMapper.prototype.mapOwnAndPrototypeNonenumerables = function (cb) {
};
PropertyMapper.prototype.mapOwnAndPrototypeEnumerablesAndNonenumerables = function (cb) {
}; |
app.directive('desoslide', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).desoSlide(scope.$eval(attrs.options));
}
};
});
|
this.NesDb = this.NesDb || {};
NesDb[ '974BA6A6C95551FF5B5F8842D876BA02A827A778' ] = {
"$": {
"name": "Stealth ATF",
"class": "Licensed",
"catalog": "NES-LH-USA",
"publisher": "Activision",
"developer": "Imagineering",
"region": "USA",
"players": "2",
"date": "1989-10"
},
"cartridge": [
{
"$": {
"system": "NES-NTSC",
"crc": "C6DD7E69",
"sha1": "974BA6A6C95551FF5B5F8842D876BA02A827A778",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2005-12-17"
},
"board": [
{
"$": {
"type": "NES-SLROM",
"pcb": "NES-SLROM-04",
"mapper": "1"
},
"prg": [
{
"$": {
"name": "NES-LH-0 PRG",
"size": "128k",
"crc": "21D7517A",
"sha1": "F1746813AB4F247E33448603908F2EBDFE2A693D"
}
}
],
"chr": [
{
"$": {
"name": "NES-LH-0 CHR",
"size": "128k",
"crc": "BBA9A33D",
"sha1": "4EB2F19E79DFA9D8D655BFA4D8C696161A7DB62F"
}
}
],
"chip": [
{
"$": {
"type": "MMC1B2"
}
}
],
"cic": [
{
"$": {
"type": "6113B1"
}
}
]
}
]
}
],
"gameGenieCodes": [
{
"name": "Infinite missiles",
"codes": [
[
"SZVZSSVK"
]
]
},
{
"name": "Start with double missiles",
"codes": [
[
"AOUXXEAA"
]
]
},
{
"name": "No damage taken from enemy's bullets",
"codes": [
[
"SZVPXNVV"
]
]
},
{
"name": "Start with less fuel",
"codes": [
[
"AVUXNAVP"
]
]
},
{
"name": "More enemy planes on the screen",
"codes": [
[
"AEKZZLZE"
]
]
}
]
};
|
#!/usr/bin/env node
/**
*
* SCRIPTS: resources
*
*
* DESCRIPTION:
* - Retrieves metric resources.
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. kgryte@gmail.com. 2014.
*
*/
(function() {
'use strict';
// MODULES //
var fs = require( 'fs' ),
path = require( 'path' ),
request = require( 'request' );
// RESOURCES //
var resources = {};
// VARIABLES //
var filepath = path.resolve( __dirname, '../docs' );
// FUNCTIONS //
/**
* FUNCTION: getResources()
* Retrieves the latest resources.
*
* @private
*/
function getResources() {
var keys = Object.keys( resources );
if ( !fs.existsSync( filepath ) ) {
fs.mkdirSync( filepath );
}
for ( var i = 0; i < keys.length; i++ ) {
request({
'method': 'GET',
'uri': resources[ keys[i] ]
}, onResponse( keys[i] ) );
}
} // end FUNCTION getResources()
/**
* FUNCTION: onResponse( name )
* Returns an HTTP response handler.
*
* @private
* @param {String} name - resource name
* @returns {Function} response handler
*/
function onResponse( name ) {
var filename = path.join( filepath, name+'.json' );
/**
* FUNCTION: onResponse( error, response, body )
* Handler for HTTP response.
*
* @private
* @param {Object} error - error object
* @param {Object} response - HTTP response object
* @param {Object} body - response body
*/
return function onResponse( error, response, body ) {
if ( error ) {
throw new Error( error );
}
if ( !body ) {
throw new Error( 'Error when retrieving metric resource: ' + name + '.' );
}
try {
JSON.parse( body );
} catch ( err ) {
console.log( body );
throw new Error( 'Unable to parse body content as JSON for metric resource: ' + name + '.' );
}
fs.writeFile( filename, body, 'utf8', function onError( error ) {
if ( error ) {
throw new Error( error );
}
});
}; // end FUNCTION onResponse()
} // end FUNCTION onResponse()
// RUN //
getResources();
})(); |
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
dist: ['dist', 'docs']
},
jshint: {
options: {
node: true,
browser: true,
bitwise: true,
camelcase: true,
curly: true,
eqeqeq: true,
immed: true,
indent: 4,
latedef: true,
newcap: true,
noarg: true,
quotmark: 'single',
undef: true,
unused: true,
strict: true,
trailing: true,
'-W098': true, // ignore defined parameters that are never used in methods
globals: {
}
},
src: ['src/{,*/}*.js'],
grunt: {
options: {
indent: 2
},
src: ['Gruntfile.js']
},
package: {
options: {
indent: 2,
quotmark: 'double'
},
src: ['package.json']
}
},
copy: {
dist: {
src: 'src/PG.js',
dest: 'dist/PG.js'
}
},
replace: {
src: {
src: ['dist/PG.js'],
overwrite: true,
replacements: [{
from: /{{ VERSION }}/g,
to: '<%= pkg.version %>'
}]
}
},
uglify: {
dist: {
files: {
'dist/PG.min.js': [
'dist/PG.js'
]
}
}
},
jsdoc: {
basic: {
src: ['src/{,*/}*.js'],
options: {
destination: 'docs/basic',
private: false
}
}
}
});
grunt.registerTask('default', ['clean', 'jshint', 'copy', 'replace', 'uglify']);
grunt.registerTask('build', ['copy', 'replace', 'uglify']);
grunt.registerTask('docs', ['jsdoc']);
};
|
// server.js
var express = require('express'),
mysql = require('mysql'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
config = require('./config'),
compression = require('compression'),
fs = require('fs')
;
var connection = mysql.createConnection(config.db);
var app = express();
// body parser
app.use( bodyParser.json( ) );
// urlencoded
app.use( bodyParser.urlencoded(
{
extended: true
} ) );
// compression
app.use( compression( ) );
// static File Server
app.use( express.static( config.htmlDir,
{
maxAge: 86400000
} ) );
app.use( cookieParser( ) );
app.once( 'error', function( err )
{
if ( err.code === 'ERRADDRINUSE' )
{
console.error( 'Port ' + config.port + ' is already in use.' );
process.exit( );
}
else
{
console.log( 'ERROR: ', err );
}
} );
// routes
app.get('/', function( req, res ) {
res.type('html');
res.send(fs.readFileSync('./views/index.html'));
});
// End routes
connection.connect( function( err )
{
if ( err )
{
console.error( 'Mysql Connection error: ' + err.stack );
return;
}
console.log( 'connected on thread#' + connection.threadId );
} );
app.listen( config.port, function( )
{
console.log( 'Server listening on port ' + config.port, 'PID: ' + process.pid );
} );
|
import React from 'react';
class Button extends React.Component {
render() {
return (
<div>
<button onClick={this.props.openPop}>Open</button>
</div>
)
};
}
export default Button;
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Utenti = mongoose.model('Utenti');
/**
* Globals
*/
var user, utenti;
/**
* Unit tests
*/
describe('Utenti Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
utenti = new Utenti({
name: 'Utenti Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return utenti.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
utenti.name = '';
return utenti.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Utenti.remove().exec();
User.remove().exec();
done();
});
}); |
const fa_toggle_down = 'M1273 675q18 35-5 66l-320 448q-19 27-52 27t-52-27l-320-448q-23-31-5-66 17-35 57-35h640q40 0 57 35zm135 701v-960q0-13-9.5-22.5t-22.5-9.5h-960q-13 0-22.5 9.5t-9.5 22.5v960q0 13 9.5 22.5t22.5 9.5h960q13 0 22.5-9.5t9.5-22.5zm256-960v960q0 119-84.5 203.5t-203.5 84.5h-960q-119 0-203.5-84.5t-84.5-203.5v-960q0-119 84.5-203.5t203.5-84.5h960q119 0 203.5 84.5t84.5 203.5z'
export default fa_toggle_down |
/*
Script: Booking form script
Author: Smart
Varsion: 1.1
*/
//includeScript ('jquery-ui-1.10.3.custom.min.js');
//includeScript ('jquery.fancyform.js');
//includeScript ('jquery.placeholder.js');
//includeScript ('regula.js');
(function($){
$.fn.bookingForm=function(options){
return this.each(function(){
var $this = $(this),
data = $this.data('bookingForm'),
object = {
url: 'bat/booking.php', // php-script url
sender: '', // sender for header in e-mail
ownerEmail:'support@template-help.com', // destination e-mail, message will be send on this e-mail
validate:true, // validate or not
errorMessageClass:'.error-message', // error-message class
successMessageClass:'.success-message', // success-message class
invalidClass:'.invalid', // invalid class
inputClass: '.tmInput', // input class
textareaClass: '.tmTextarea', // textarea class
selectClass: '.tmSelect', // select class
checkboxClass: '.tmCheckbox', // checkbox class
radioClass: '.tmRadio', // radiobutton class
datepickerClass: '.tmDatepicker', // datepicker class
wrapperClass: '.controlHolder', // wrapper class, all elements will be wrapped in div with this class
successMessage: "Your order has been sent! We'll be in touch soon!", // success message
// private fields
form: null,
fields: [],
types: {input: 'input', textarea: 'textarea', select: 'select', checkbox: 'checkbox', radio: 'radio', datepicker: 'datepicker'},
init: function () {
object.createCustomFileds();
object.fillFields();
(object.validate) && regula.bind();
object.addListeners();
object.form.find('input, textarea').placeholder();
},
createCustomFileds: function (){
var wrapper = '<div class="'+String(object.wrapperClass).substr(1)+'"></div>';
object.form = $(object.data[0]);
object.form
.find(object.inputClass)
.wrap(wrapper).end()
.find(object.textareaClass)
.wrap(wrapper).end()
.find(object.selectClass)
.wrap(wrapper)
.each(function (ind, elem) {
var $elem = $(elem),
manual = false,
dClass = String(object.selectClass).substr(1),
tempClass,
autocomplete;
var tempClass = $elem.attr('data-class');
if (tempClass) dClass=tempClass;
$elem.hasClass('manual') ? manual=true : dClass+=' auto';
autocomplete = $elem.hasClass('autocomplete');
$elem.transformSelect({
dropDownClass: dClass,
acceptManualInput : manual,
useManualInputAsFilter: autocomplete,
showFirstItemInDrop : false
})
})
.end()
.find(object.datepickerClass)
.wrap(wrapper)
.find('input')
.datepicker({
showButtonPanel: true
}).end().end()
.find(object.checkboxClass)
.wrap(wrapper)
.find("input:checkbox")
.transformCheckbox({
base : "class"
}).end().end()
.find(object.radioClass)
.wrap(wrapper)
.find("input:radio")
.transformRadio({
});
},
checked: function($obj) {
return $obj.hasClass('checked');
},
// serialize fields of form {name, value, filed}
fillFields: function (){
object.form
// serialize input
.find(object.inputClass)
.each(function(ind, el){
var inp = $(el).find('input');
object.fields.push({type: object.types.input,
name: inp.attr('name'),
value: inp.val(),
field: inp[0],
input: inp,
wrapper: inp.parents(object.wrapperClass)});
})
.end()
// serialize textarea
.find(object.textareaClass)
.each(function(ind, el){
var inp = $(el).find('textarea');
object.fields.push({type: object.types.textarea,
name: inp.attr('name'),
value: inp.val(),
field: inp[0],
input: inp,
wrapper: inp.parents(object.wrapperClass)});
})
.end()
// serialize selects
.find('select'+object.selectClass)
.each(function(ind, el){
var $el = $(el),
wpr = $el.parents(object.wrapperClass),
inp = wpr.find('input'),
ul = wpr.find('input+ul'),
sel = wpr.find('select');
if (sel.hasClass('auto')) {
ul = wpr.find('ul ul')
inp = sel;
}
object.fields.push({type: object.types.select,
name: inp.attr('name'),
value: ul.find('.checked').text(),
defValue: ul.siblings('span').text(),
field: ul[0],
input: inp,
wrapper: wpr});
})
.end()
// serialize checkboxes
.find(object.checkboxClass)
.each(function(ind, el){
var $el = $(el),
inp = $el.find('input'),
span = $el.find('span').eq(0);
object.fields.push({type: object.types.checkbox,
name: inp.attr('name'),
value: object.readValueCheckbox(span),
field: span[0],
input: inp,
wrapper: span.parents(object.wrapperClass)});
})
.end()
// serialize radiobuttons
.find(object.radioClass)
.each(function(ind, el){
var $el = $(el),
inp = $el.find('input').toArray(),
wpr = $el.parents(object.wrapperClass);
object.fields.push({type: object.types.radio,
name: inp[0].name,
value: object.readValueRadio(wpr),
field: $el.find('strong').toArray(),
input: $(inp[0]),
wrapper: wpr});
})
.end()
// serialize datepickeres
.find(object.datepickerClass)
.each(function(ind, el){
var inp = $(el).find('input');
object.fields.push({type: object.types.datepicker,
name: inp.attr('name'),
value: inp.attr('value'),
field: inp[0],
input: inp,
wrapper: inp.parents(object.wrapperClass)});
});
// save default values to defValue property
$.each(object.fields, function (ind, el) {
el['defValue'] = el['defValue'] ? el['defValue'] : el.value;
});
},
readValueCheckbox: function (span){
return object.checked(span)?'Yes':'No';
},
writeValueCheckbox: function (span, value){
if (value === 'Yes'){
!object.checked(span) && span.trigger('click');
} else if (value === 'No'){
object.checked(span) && span.trigger('click');
}
},
readValueRadio: function(wpr){
return wpr.find('strong.checked+*').text();
},
writeValueRadio: function(wpr, value){
wpr.find('strong+*').each(function(){
var $th = $(this);
if ($th.text() === value) {
$th.siblings('strong')
.removeClass('checked')
.eq(parseInt($th.index()/3)-1).addClass('checked');
}
});
},
// read fields data
readFieldsData: function (){
$.each(object.fields, function (ind, el) {
switch (el.type) {
case object.types.input:
el.value = $(el.field).attr('value');
break;
case object.types.textarea:
el.value = $(el.field).val();
break;
case object.types.select:
el.value = $(el.field).find('.checked').text();
var wpr = el.wrapper;
if (wpr.find('.manual').length) {
var inp = wpr.find('input');
wpr.find('.transformSelectDropdown li').each(function (index, elem) {
(inp.val() === $(elem).text()) && $(elem).trigger('click');
});
}
break;
case object.types.checkbox:
el.value = object.readValueCheckbox($(el.field));
break;
case object.types.radio:
el.value= object.readValueRadio(el.wrapper);
break;
case object.types.datepicker:
el.value = $(el.field).attr('value');
break;
}
})
},
// white fields with data
writeFieldsDataDefaults: function (){
$.each(object.fields, function (ind, el) {
switch (el.type) {
case object.types.input:
$(el.field).attr('value', el.defValue).trigger('blur');
break;
case object.types.textarea:
$(el.field).val(el.defValue).trigger('blur');
break;
case object.types.select:
var wpr = el.wrapper;
wpr
.find('.transformSelectDropdown li').removeClass('checked');
if (wpr.find('.manual').length) {
wpr.find('input').val('').trigger('blur');
} else {
wpr.find('span').eq(0).text(el.defValue);
}
el.value = el.defValue;
break;
case object.types.checkbox:
object.writeValueCheckbox($(el.field), el.defValue);
break;
case object.types.radio:
el.value = el.defValue;
object.writeValueRadio(el.wrapper, el.defValue);
break;
case object.types.datepicker:
$(el.field).attr('value', el.defValue).trigger('blur');
break;
}
})
},
// validate data
validateData: function(){
var validationResults = regula.validate();
$this.trigger('reset');
$.each(validationResults, function(i, r) {
var wpr = $(validationResults[i].failingElements[0]).parents(object.wrapperClass);
if (!wpr.hasClass(className(object.invalidClass))) {
wpr
.addClass(className(object.invalidClass))
.append('<strong class="'+className(object.errorMessageClass)+'">'+validationResults[i].message+'</strong>')
.find(object.errorMessageClass)
.slideUp(0).slideDown();
}
});
},
// prepare data
prepareData: function () {
var data = {
owner_email: object.ownerEmail,
sender: (object.sender == '')?location.hostname:object.sender
}
$.each(object.fields, function(ind, el){
var val = object.fields[ind].value;
if (val == '') val = 'nope';
data[object.fields[ind].name] = val;
})
return data;
},
// submit data
submitData: function(){
$.ajax({
type: "POST",
url: object.url,
data: object.prepareData(),
success: function(results){
$this
.find(object.successMessageClass).remove().end()
.find('[data-type="submit"]').after('<p class="'+className(object.successMessageClass)+'">'+ object.successMessage +'</p>').end()
.find(object.successMessageClass).stop(true).slideUp(0).slideDown(object.writeFieldsDataDefaults).delay(4000).slideUp();
}
})
},
// addListebers to controls
addListeners: function () {
$this.on('reset', function (){
$.each(object.fields, function(ind, el){
el.wrapper
.removeClass(className(object.invalidClass))
.find(object.errorMessageClass).remove();
});
return false;
})
$this.find('a[data-type="submit"]').click(function(){
object.readFieldsData();
object.validateData();
if (!$this.find(object.invalidClass).length) {
object.submitData();
}
return false;
})
$this.find('a[data-type="reset"]').click(function(){
$this.trigger('reset');
})
}
}
data ? object=data : $this.data({bookingForm: object});
typeof options=='object' && $.extend(object, options);
object.data || object.init(object.data = $this);
})
return this;
}
})(jQuery);
// extrude class name
function className(className){
return String(className).substr(1);
}
function includeScript(url){
document.write('<script type="text/javascript" src="js/'+ url + '"></script>');
return false;
} |
define(function(require) {
var test = require('../../../test');
var n = 0;
// 404
var a;
try {
a = require('./a')
} catch (e) {
test.assert(e.toString().indexOf('module was broken:') > -1, '404 error msg ' + e);
n++
}
test.assert(a === void 0, '404 a');
// exec error
setTimeout(function() {
var b = require('./b')
}, 0);
require.async('./c', function(c) {
test.assert(c === void 0, '404 c');
done()
});
require.async('./e', function(e) {
test.assert(e === void 0, 'exec error e');
done()
});
seajs.use('./d', function(d) {
test.assert(d === void 0, '404 d');
done()
});
// 404 css
//require('./f.css')
function done() {
if (++n === 4) {
test.assert(w_errors.length > 0, w_errors.length);
// 0 for IE6-8
test.assert(s_errors.length === 0 || s_errors.length === 3, s_errors.length);
test.next()
}
}
});
|
Ext.define('Fiddle.Chart', {
extend: 'Ext.chart.CartesianChart',
requires: [
'Fiddle.ChartController'
],
controller: 'fiddlechart',
alias: 'widget.fiddlechart',
store: fiddleStore,
insetPadding: 40,
axes: [{
type: 'numeric',
position: 'left',
grid: true,
fields: ['Buy', 'Sell'],
label: {
renderer: 'onAxisLabelRender'
},
}, {
type: 'category',
position: 'bottom',
grid: true,
fields: ['MemberFirmId'],
label: {
rotate: {
degrees: -45
}
}
}],
series: [{
type: 'bar',
stacked: true,
xField: 'MemberFirmId',
yField: ['Buy', 'Sell'],
style: {
opacity: 0.80
},
highlightCfg: {
opacity: 1,
strokeStyle: 'black'
}
/*tooltip: {
trackMouse: true,
renderer: 'onSeriesTooltipRender'
}*/
}]
})
|
var ChildProcess = require('child_process'),
PassThrough = require('stream').PassThrough,
BaseFile = require('./base_arc_file'),
libpath = require('path'),
RarFile = require('./rar_file'),
TarFile = require('./tar_file'),
rimraf = require('rimraf'),
mmm = require('mmmagic'),
mkdirp = require('mkdirp'),
Magic = mmm.Magic,
magic = new Magic(mmm.MAGIC_MIME_TYPE),
fs = require('graceful-fs'),
ArcStream,
Blast,
Fn;
// Require protoblast (without native mods) if it isn't loaded yet
if (typeof __Protoblast == 'undefined') {
Blast = require('protoblast')(false);
} else {
Blast = __Protoblast;
}
Fn = Blast.Bound.Function;
/**
* The ArcStream class
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.4
*/
ArcStream = Fn.inherits('Informer', function ArcStream(config) {
if (!config) {
config = {};
}
// The type of archive we're extracting
this.type = null;
// The tempid
this.tempid = Date.now() + '-' + ~~(Math.random()*10e5);
// Where to store our temporary files
this.tempdir = config.tempdir || '/tmp';
// Clean up files on exit?
if (typeof config.cleanup == 'undefined') {
this.cleanup = true;
} else {
this.cleanup = config.cleanup;
}
// Debug mode
this.debugMode = config.debug || false;
// The temppath
this.temppath = null;
// The last used part
this.lastpart = null;
// The last queued part
this.lastqueue = null;
// Is this a multipart file
this.multipart = null;
// The added files
this.files = [];
// The extracted files
this.extracted = [];
// Copied file info
this.copiedInfo = {};
// Already seen requests
this.seenRequests = [];
// Extract nested archives by default
this.extractNested = true;
// Handle nested archives
this.subArchive = null;
// Is this archive corrupt?
this.corrupt = null;
});
/**
* Output debug message
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.3
* @version 0.1.3
*/
ArcStream.setMethod(function debug(dtest, info, args) {
if (this.debugMode) {
if (dtest == '__debug__') {
args = Array.prototype.slice.call(args);
args.unshift('[' + info + '] ');
} else {
args = Array.prototype.slice.call(arguments);
args.unshift('[ARCSTREAM] ');
}
console.log.apply(console, args);
return true;
}
return false;
});
/**
* Prepare a temporary folder
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.3
*
* @param {Function} callback
*/
ArcStream.setMethod(function getTemppath(callback) {
var that = this;
if (that.temppath) {
this.after('createdTempDir', function() {
callback(null, that.temppath);
});
return;
}
// Create a unique-ish id
this.temppath = libpath.resolve(this.tempdir, this.tempid);
mkdirp(this.temppath, function createdDir(err) {
that.emit('createdTempDir');
return callback(err, that.temppath);
});
// Make sure the temppath is removed on exit
process.on('exit', function onExit() {
if (that.temppath && that.cleanup) {
rimraf.sync(that.temppath);
}
});
});
/**
* Add an archive file to be extracted
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.3
*
* @param {Number} index Index of the file, first one is 0 (optional)
* @param {String|Stream} stream Path to archive or readstream
* @param {String} type Type of the archive
*/
ArcStream.setMethod(function addFile(index, stream, type) {
var that = this,
multipart;
if (typeof index != 'number') {
type = stream;
stream = index;
index = this.files.length;
}
if (typeof stream == 'string') {
stream = fs.createReadStream(stream);
}
this.files.push({stream: stream, type: type});
// Pause the read stream
stream.pause();
Fn.series(function getType(next) {
// Continue if the type has already been provided
if (type) {
return next();
}
// Attempt to get the mimetype from the first chunk of data
stream.once('data', function onFirstData(chunk) {
// Pause the stream again
stream.pause();
// Push this chunk back to the top
stream.unshift(chunk);
magic.detect(chunk, function gotType(err, result) {
if (err) {
return next(err);
}
type = result;
next();
});
});
stream.resume();
}, function checkMultipart(next) {
if (this.multipart != null) {
return next();
}
if (type.indexOf('rar') > -1) {
that.multipart = true;
that.type = 'rar';
} else {
that.multipart = false;
that.type = type;
}
next();
}, function copyMultiparts(next) {
if (!that.multipart) {
return next();
}
// Move the multipart file
that.getTemppath(function gotPath(err, dirpath) {
var tempname = 'p' + index + '.' + that.type,
path = dirpath + '/' + tempname,
writeStream;
that.files[index] = {path: path};
// Create the writestream
writeStream = fs.createWriteStream(path);
// Pipe the original stream into the writestream
stream.pipe(writeStream);
// Wait for the writestream (not the readstream) to be finished
writeStream.on('finish', function copied() {
that.debug('Archive part', index, 'has been written to disk as', tempname);
that.copiedInfo['copied-' + index] = {name: tempname, path: path};
that.emit('copied-' + index, tempname, path);
});
});
if (index == 0) {
that.queueNext();
}
}, function handleSinglepart(err) {
if (err) {
throw err;
}
if (that.multipart) {
return;
}
if (type.indexOf('tar') > -1) {
that.extractTar(stream);
} else if (type.indexOf('gzip') > -1) {
that.extractTar(stream, 'z');
} else if (type.indexOf('bzip2') > -1 || type.indexOf('bz2') > -1) {
that.extractTar(stream, 'j');
} else if (type.indexOf('zip') > -1) {
throw new Error('ZIP is not yet supported');
} else {
throw new Error('Unknown archive: ' + type);
}
});
});
/**
* Handle extracted files
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.1
* @version 0.1.1
*
* @param {ArcBaseFile} arcfile
*/
ArcStream.setMethod(function emitFile(arcfile) {
var that = this;
// Push this to the extracted files
this.extracted.push(arcfile);
// If the new file is in itself an archive, intercept it!
if (this.extractNested !== false && /bz2|gz|tgz|tar|rar|r\d\d/.exec(arcfile.extension)) {
if (!this.subArchive) {
this.subArchive = new ArcStream();
this.subArchive.nested = true;
this.subArchive.on('file', function onNestedFile(name, stream, subarc) {
that.emit('file', name, stream, subarc);
});
this.subArchive.on('error', function onSubError(err) {
that.emit('error', err);
});
}
return this.subArchive.addFile(arcfile.output, arcfile.extension);
}
this.emit('file', arcfile.name, arcfile.output, arcfile);
});
/**
* Emit the done event
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.4
* @version 0.1.4
*/
ArcStream.setMethod(function emitDone() {
if (this.done) {
return;
}
this.done = true;
this.emit('done', this.files);
});
/**
* Queue the next extraction (for multipart archives)
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.2
*
* @param {Function}
*/
ArcStream.setMethod(function queueNext(expectedName, callback) {
var that = this,
copyid,
index;
if (typeof expectedName == 'function') {
callback = expectedName;
expectedName = null;
}
if (this.lastqueue == null) {
this.lastqueue = 0;
} else {
this.lastqueue++;
}
if (expectedName && this.seenRequests.indexOf(expectedName) > -1) {
this.lastqueue--;
}
// Remember this request
this.seenRequests.push(expectedName);
index = this.lastqueue;
copyid = 'copied-' + index;
// Listen for the file to be done
this.after(copyid, function copiedFile() {
Fn.series(function checkNames(next) {
var filename = that.copiedInfo[copyid].name,
fullpath = that.copiedInfo[copyid].path;
if (filename == expectedName) {
return next();
}
// Create a symlink to the actual filename
fs.symlink(fullpath, libpath.resolve(libpath.dirname(fullpath), expectedName), function created(err) {
that.debug('Created symlink from', libpath.basename(fullpath), 'to expected name', expectedName);
next();
});
}, function done() {
if (index == 0) {
that.extractRar();
}
if (callback) {
return callback();
}
});
});
});
/**
* Extract tar files
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.0
*
* @param {Stream} input Readstream to tar file
* @param {String} arg Extra argument for tar command
*/
ArcStream.setMethod(function extractTar(input, arg) {
var that = this,
args,
path,
files,
prevbuf,
curfile,
extractor;
files = {};
args = ['xvvfO', '-', '--checkpoint'];
if (arg) {
args[0] += arg;
}
Fn.series(function getPath(next) {
that.getTemppath(function gotPath(err, temppath) {
path = temppath;
return next();
});
}, function done() {
// Create the TAR extractor process
extractor = ChildProcess.spawn('tar', args, {cwd: path});
// Listen to the tar output, where decompressed data will go to
extractor.stdout.on('data', function onExtractorData(data) {
// Sometimes file data comes before the filename
if (prevbuf) {
if (curfile) {
files[curfile].update(prevbuf);
} else {
prevbuf = Buffer.concat([prevbuf, data]);
return;
}
}
if (curfile) {
prevbuf = files[curfile].update(data);
} else {
prevbuf = data;
}
});
// Listen for messages on the stderr
extractor.stderr.on('data', function onStderr(data) {
var info = data.toString().trim();
if (info.indexOf('not recoverable') > -1 || info.indexOf('exiting now') > -1) {
throw new Error('TAR extractor encountered an error');
}
if (info.slice(0, 4) == 'tar:') {
// This is just a progress update
return;
}
// Extract expected filesize & filename
info = /.+?(\d+) \d+-\d+-\d+ \d\d\:\d\d (.+)\b/.exec(info);
if (!info) {
return;
}
if (curfile) {
prevbuf = files[curfile].end(prevbuf);
}
// Create new file
curfile = info[2];
files[curfile] = new TarFile(that, curfile, Number(info[1]));
});
// Listen for the end
extractor.stdout.on('end', function onEnd() {
// Tar extractor has finished, make sure the last file has ended
if (files[curfile]) {
files[curfile].end(prevbuf);
}
});
// Pipe the input stream into the tar process
input.pipe(extractor.stdin);
});
});
/**
* Extract rar files
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.1.0
* @version 0.1.4
*/
ArcStream.setMethod(function extractRar() {
var that = this,
args = ['-kb', '-vp', 'x', 'p0.rar'],
files = {},
temp = '',
outtemp = '',
curfile,
extractor;
// Create the extractor process
extractor = ChildProcess.spawn('unrar', args, {cwd: this.temppath});
// Listen to the unrar output
extractor.stdout.on('data', function onExtractorData(data) {
var output = data.toString(),
procent,
info;
// Look for percentages (indicating extraction progress)
procent = /\u0008{4}\W*(\d+)%/.exec(output);
// Sometimes procentages and filenames are on the same line
output = output.replace(/\u0008{4}\W*\d+%/g, '').trim();
if (!output && procent) {
if (procent[1]) {
that.emit('progress', Number(procent[1]));
}
outtemp = '';
if (curfile) files[curfile].update();
return;
}
outtemp += output;
// Look for a new message indicating a new file has started
info = /Extracting.+\n\nExtracting\W+(.*)/.exec(output);
if (!info) {
info = /Extracting (?!:from)\W+(.*)/.exec(output);
}
// Or for a continued file
if (!info) {
info = /\n\.\.\.\W+(.*)/.exec(output);
}
if (!info) {
// Probably "extracting from..." info
return;
}
// Trim the filename
info = info[1].trim();
// Remove possible \b characters
info = info.replace(/\u0008/g, ' ');
// Remove trailing "OK" message, if present
if (/\W{2,}OK$/.exec(info)) {
info = info.slice(0, -2).trim();
}
// Do nothing if the current file has not changes
if (curfile && curfile == info) {
return;
}
if (curfile) {
// End the stream
files[curfile].end();
}
// Create a new file
curfile = info;
files[curfile] = new RarFile(that, curfile);
});
// Listen for messages on the stderr
extractor.stderr.on('data', function onStderr(data) {
var nextName;
temp += data.toString();
// Look for wrong volume order error messages
if (temp.indexOf('previous volume') > -1) {
return that.emit('error', new Error(temp));
}
// Look for checksum errors
if (temp.indexOf('checksum error in') > -1) {
// Emit the error, but don't return yet.
// There could be an "insert disk" message in the data burst
that.emit('error', new Error('Checksum error: ' + temp));
}
// Ignore any non "insert-disk" messages
if (temp.indexOf('Insert disk') == -1) {
return;
}
// Get the expected name of the next archive
nextName = /with (.+) \[C\]ontinue,/.exec(temp);
if (nextName) {
nextName = nextName[1];
}
// We really need a next name to wait for
if (!nextName) {
return;
}
temp = '';
// Copy the next rar archive
that.queueNext(nextName, function gotNext() {
// Reset the outtemp string
outtemp = '';
// Once it's there, tell rar to keep on unrarring
extractor.stdin.write('C\n');
});
});
// Listen for the end signal
extractor.stdout.on('end', function onEnd() {
if (outtemp.indexOf('All OK') == -1) {
// Something went wrong during extraction
that.corrupt = true;
that.emit('corrupted', outtemp);
} else {
// Extraction succeeded!
that.corrupt = false;
}
// Extractor is done, make sure the last file has ended
if (curfile) files[curfile].end();
});
});
module.exports = ArcStream; |
'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/enviewtest',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'https://localhost:443/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
}; |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'codesnippet', 'ug', {
button: 'كود پارچىسى قىستۇرۇش',
codeContents: 'كود مەزمۇنى',
emptySnippetError: 'كود پارچىسى بوش قالمايدۇ',
language: 'تىل',
title: 'كود پارچىسى',
pathName: 'كود پارچىسى'
} );
|
self.port.on("show", function (c) {
document.getElementById("username").value = c.username;
document.getElementById("password").value = c.password;
});
document.getElementById("save").addEventListener("click", function () {
self.port.emit("save", { username: document.getElementById("username").value, password: document.getElementById("password").value });
});
document.getElementById("close").addEventListener("click", function () {
self.port.emit("close");
});
|
/* * ====================================================================
* About: This a a compressed JS file from the Sarissa library.
* see http://dev.abiss.gr/sarissa
*
* Copyright: Manos Batsis, http://dev.abiss.gr
*
* Licence:
* Sarissa is free software distributed under the GNU GPL version 2
* or higher, GNU LGPL version 2.1 or higher and Apache Software
* License 2.0 or higher. The licenses are available online see:
* http://www.gnu.org
* http://www.apache.org
*
* 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.
* ====================================================================*/
if(Sarissa._SARISSA_HAS_DOM_FEATURE&&document.implementation.hasFeature("XPath","3.0")){SarissaNodeList=function(i){this.length=i;};SarissaNodeList.prototype=[];SarissaNodeList.prototype.constructor=Array;SarissaNodeList.prototype.item=function(i){return(i<0||i>=this.length)?null:this[i];};SarissaNodeList.prototype.expr="";if(window.XMLDocument&&(!XMLDocument.prototype.setProperty)){XMLDocument.prototype.setProperty=function(x,y){};}
Sarissa.setXpathNamespaces=function(oDoc,sNsSet){oDoc._sarissa_useCustomResolver=true;var namespaces=sNsSet.indexOf(" ")>-1?sNsSet.split(" "):[sNsSet];oDoc._sarissa_xpathNamespaces=[];for(var i=0;i<namespaces.length;i++){var ns=namespaces[i];var colonPos=ns.indexOf(":");var assignPos=ns.indexOf("=");if(colonPos>0&&assignPos>colonPos+1){var prefix=ns.substring(colonPos+1,assignPos);var uri=ns.substring(assignPos+2,ns.length-1);oDoc._sarissa_xpathNamespaces[prefix]=uri;}else{throw"Bad format on namespace declaration(s) given";}}};XMLDocument.prototype._sarissa_useCustomResolver=false;XMLDocument.prototype._sarissa_xpathNamespaces=[];XMLDocument.prototype.selectNodes=function(sExpr,contextNode,returnSingle){var nsDoc=this;var nsresolver;if(this._sarissa_useCustomResolver){nsresolver=function(prefix){var s=nsDoc._sarissa_xpathNamespaces[prefix];if(s){return s;}
else{throw"No namespace URI found for prefix: '"+prefix+"'";}};}
else{this.createNSResolver(this.documentElement);}
var result=null;if(!returnSingle){var oResult=this.evaluate(sExpr,(contextNode?contextNode:this),nsresolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);var nodeList=new SarissaNodeList(oResult.snapshotLength);nodeList.expr=sExpr;for(var i=0;i<nodeList.length;i++){nodeList[i]=oResult.snapshotItem(i);}
result=nodeList;}
else{result=this.evaluate(sExpr,(contextNode?contextNode:this),nsresolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;}
return result;};Element.prototype.selectNodes=function(sExpr){var doc=this.ownerDocument;if(doc.selectNodes){return doc.selectNodes(sExpr,this);}
else{throw"Method selectNodes is only supported by XML Elements";}};XMLDocument.prototype.selectSingleNode=function(sExpr,contextNode){var ctx=contextNode?contextNode:null;return this.selectNodes(sExpr,ctx,true);};Element.prototype.selectSingleNode=function(sExpr){var doc=this.ownerDocument;if(doc.selectSingleNode){return doc.selectSingleNode(sExpr,this);}
else{throw"Method selectNodes is only supported by XML Elements";}};Sarissa.IS_ENABLED_SELECT_NODES=true;} |
//import $ from '../libs/jquery-2.1.4.min';
const $ = require('jquery');
function init() {
//_cacheDom();
//_bindEvents();
// ===========================================================
let devise = 0;
let backCall, order;
let id_device;
let id_model;
let id_repair;
let modelUrl;
$('.selectmodel').click(function() {
$('.selectmodel').removeClass('active');
$(this).addClass('active');
let model = $(this).data('model');
modelUrl = $(this).data('url');
id_model = parseInt($(this).data('id'));
$('#inputmodel').val(model);
if(devise == 1) {
$('.selectstep[data-step=2] .text').html(model.substr(5,model.length));
}
else if(devise == 2) {
$('.selectstep[data-step=2] .text').html(model.substr(7,model.length));
}
$('.selectstep[data-step=2]').fadeIn('slow').css('display', 'block');
$('#formstep2').fadeOut('slow',function() {
$('#formstep3').fadeIn('slow');
});
});
$('#formstep2 .back').click(function() {
$('.selectstep[data-step=1]').fadeOut('slow');
$('#formstep2').fadeOut('slow',function() {
$('#formstep1').fadeIn('slow');
});
});
$('#formstep3 .back').click(function() {
$('.selectstep[data-step=2]').fadeOut('slow');
$('.selectmodel').removeClass('active');
$('#formstep3').fadeOut('slow',function() {
$('#formstep2').fadeIn('slow');
});
});
$('#formstep4 .back').click(function() {
$('.selectstep[data-step=3]').fadeOut('slow');
$('.selectrepair').removeClass('active');
$('#formstep4').fadeOut('slow',function() {
$('#formstep3').fadeIn('slow');
});
});
$('.selectstep').click(function(){
let step = parseInt($(this).data('step'));
let index = $('.formstep:visible').index();
$('.formstep:visible').fadeOut('slow',function() {
for(i=index;i>=step;i--) $('.selectstep[data-step='+i+']').fadeOut('fast');
$('.selectrepair').removeClass('active');
$('.selectmodel').removeClass('active');
$('#formstep'+step).fadeIn('slow');
});
});
$('.selectrepair').click(function(){
$('.selectrepair').removeClass('active');
$(this).addClass('active');
id_repair = parseInt($(this).data('id'));
/*
let id_device;
let id_model;
let id_repair;
*/
let textEndForm;
$('#inputrepair').val($(this).data('repair'));
$('.selectstep[data-step=3] .text').html($(this).data('repair'));
if(id_device == 1) {
switch(id_repair){
case 1: {
textEndForm = "Замена сенсорного стекла вашего iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>1199 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>1199 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>1999 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>1999 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>1149 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>1149 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>1049 грн.</span>";
break;
}
}
break;
}
case 2: {
textEndForm = "Замена микрофона на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>799 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>699 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>699 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>799 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>599 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>599 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>499 грн.</span>";
break;
}
}
break;
}
case 3: {
textEndForm = "Замена аккумуляторной батареи на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>1499 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>1399 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>1999 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>1899 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>1399 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>1399 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>1199 грн.</span>";
break;
}
}
break;
}
case 4: {
textEndForm = "Замена кнопки вкл/выкл на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>649 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>649 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>799 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>899 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>599 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>599 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>549 грн.</span>";
break;
}
}
break;
}
case 5: {
textEndForm = "Замена кнопки меню на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>599 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>549 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>699 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>799 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>549 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>549 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>549 грн.</span>";
break;
}
}
break;
}
case 6: {
textEndForm = "Замена передней камеры на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>799 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>699 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>849 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>899 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>699 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>649 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>599 грн.</span>";
break;
}
}
break;
}
case 7: {
textEndForm = "Замена динамика на вашем iPad ";
switch(id_model){
case 1: {
textEndForm += "Mini Retina: <span class='price'>599 грн.</span>";
break;
}
case 2: {
textEndForm += "Mini: <span class='price'>599 грн.</span>";
break;
}
case 3: {
textEndForm += "Air: <span class='price'>699 грн.</span>";
break;
}
case 4: {
textEndForm += "mini 3: <span class='price'>699 грн.</span>";
break;
}
case 5: {
textEndForm += "4: <span class='price'>599 грн.</span>";
break;
}
case 6: {
textEndForm += "3: <span class='price'>599 грн.</span>";
break;
}
case 7: {
textEndForm += "2: <span class='price'>549 грн.</span>";
break;
}
}
break;
}
case 8: {
textEndForm = "Опишите проблему в текстовом сообщение или можете перейти на " + "<a href="+ modelUrl +">каталог наших цен.</a>";
$('#repair8').html('Если вы не знаете причину поломки мастер произведет бесплатную диагностику');
$('#textmsg').show();
break;
}
}
$('.selectstep[data-step=3]').fadeIn('slow').css('display', 'block');
$('#stepsforform').fadeOut('slow');
$('#stepsendform').fadeIn('slow');
} else {
switch(id_repair){
case 1: {
textEndForm = "Замена стекла вашего iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>1399 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>1199 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>799 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>699 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>4499 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>3999 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>2499 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>1999 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>799 грн.</span>";
break;
}
}
break;
}
case 2: {
textEndForm = "Замена микрофона на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>499 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>499 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>349 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>249 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>1099 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>899 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>799 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>699 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>399 грн.</span>";
break;
}
}
break;
}
case 3: {
textEndForm = "Замена аккумуляторной батареи на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>599 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>499 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>399 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>349 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>1599 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>1499 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>1199 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>999 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>399 грн.</span>";
break;
}
}
break;
}
case 4: {
textEndForm = "Замена кнопки вкл/выкл на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>499 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>449 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>349 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>249 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>999 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>799 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>599 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>599 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>399 грн.</span>";
break;
}
}
break;
}
case 5: {
textEndForm = "Замена кнопки меню на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>399 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>399 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>199 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>199 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>999 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>999 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>599 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>599 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>499 грн.</span>";
break;
}
}
break;
}
case 6: {
textEndForm = "Замена передней камеры на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>599 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>499 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>349 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>249 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>1599 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>1599 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>1299 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>1199 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>899 грн.</span>";
break;
}
}
break;
}
case 7: {
textEndForm = "Замена динамика на вашем iPhone";
switch(id_model){
case 1: {
textEndForm += " 6plus: <span class='price'>299 грн.</span>";
break;
}
case 2: {
textEndForm += " 6: <span class='price'>299 грн.</span>";
break;
}
case 3: {
textEndForm += " 5/5c/5s: <span class='price'>249 грн.</span>";
break;
}
case 6: {
textEndForm += " 4/4s: <span class='price'>199 грн.</span>";
break;
}
case 9: {
textEndForm += " 7plus: <span class='price'>699 грн.</span>";
break;
}
case 10: {
textEndForm += " 7: <span class='price'>699 грн.</span>";
break;
}
case 11: {
textEndForm += " 6plus: <span class='price'>399 грн.</span>";
break;
}
case 12: {
textEndForm += " 6s: <span class='price'>399 грн.</span>";
break;
}
case 13: {
textEndForm += " se: <span class='price'>249 грн.</span>";
break;
}
}
break;
}
case 8: {
textEndForm = "Опишите проблему в текстовом сообщение или можете перейти на " + "<a href="+ modelUrl +">каталог наших цен.</a>";
$('#repair8').html('Если вы не знаете причину поломки мастер произведет бесплатную диагностику');
$('#textmsg').show();
break;
}
}
$('#stepsforform').fadeOut('slow');
$('#stepsendform').fadeIn('slow');
}
$('.repair-msg').html(textEndForm);
$('#formstep3').fadeOut('slow',function() {
$('#formstep4').fadeIn('slow');
});
});
$('.choose-device').click(function(){
let index = parseInt($(this).data('index'));
id_device = parseInt($(this).data('index'));
if(index == 1) {
devise = 1;
$('.modeliphone').hide();
$('.modelipad').show();
$('.selectstep[data-step=1] .text').html('iPad');
}
else if(index == 2) {
devise = 2;
$('.modelipad').hide();
$('.modeliphone').show();
$('.selectstep[data-step=1] .text').html('iPhone');
}
$('#formstep1').fadeOut('slow',function() {
$('#formstep2').fadeIn('slow');
});
$('.selectstep[data-step=1]').fadeIn('slow').css('display', 'block');
});
let formParent = document.getElementById('formstep4'),
form = formParent.childNodes[0];
function sbmForm(e) {
e.preventDefault();
$('#rapair-info').val($('.repair-msg').text());
let formLength = form.length - 1,
data = '';
for (let i = 0; i < formLength; i++) {
data += form[i].getAttribute('name') + '=' + form[i].value + '&';
}
$.ajax({
type: 'POST',
url: '/call-courier',
data: data
}).done(function (res) {
if (res === 'success') {
formParent.innerHTML = '<h1 style="color: green; text-align:center;">Мы вам перезвоним в течении 3 мин! </h1>';
} else {
$(formParent).prepend('Opps something wend wrong');
}
});
}
form.addEventListener('submit', sbmForm);
}
// ===========================================================
export default {
init: init
}
|
define(function(){
/**
* A sound resource.
* @class
* @memberof thruster.content
* @param {Howler.Howl} howl A Howl object from Howler.js.
*/
var Sound = function(howl){
this.howl = howl;
};
/**
* Plays this sound.
* @public
*/
Sound.prototype.play = function(){
this.howl.play();
};
return Sound;
}); |
require.config({
shim: {
easel: {
exports: 'createjs'
}
},
paths: {
easel: './easel'
}
});
requirejs(['game'],
function() {
this.game = new Game('evacuationCanvas');
}
);
|
version https://git-lfs.github.com/spec/v1
oid sha256:76b7b5c2236b49dc4fb0d70de35fcd36746989d16668d9ce48905db3d026ea50
size 6056
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.updateOverrideContexts = updateOverrideContexts;
exports.createFullOverrideContext = createFullOverrideContext;
exports.updateOverrideContext = updateOverrideContext;
exports.getItemsSourceExpression = getItemsSourceExpression;
exports.unwrapExpression = unwrapExpression;
exports.isOneTime = isOneTime;
exports.updateOneTimeBinding = updateOneTimeBinding;
exports.indexOf = indexOf;
var _aureliaBinding = require('aurelia-binding');
var oneTime = _aureliaBinding.bindingMode.oneTime;
function updateOverrideContexts(views, startIndex) {
var length = views.length;
if (startIndex > 0) {
startIndex = startIndex - 1;
}
for (; startIndex < length; ++startIndex) {
updateOverrideContext(views[startIndex].overrideContext, startIndex, length);
}
}
function createFullOverrideContext(repeat, data, index, length, key) {
var bindingContext = {};
var overrideContext = (0, _aureliaBinding.createOverrideContext)(bindingContext, repeat.scope.overrideContext);
if (typeof key !== 'undefined') {
bindingContext[repeat.key] = key;
bindingContext[repeat.value] = data;
} else {
bindingContext[repeat.local] = data;
}
updateOverrideContext(overrideContext, index, length);
return overrideContext;
}
function updateOverrideContext(overrideContext, index, length) {
var first = index === 0;
var last = index === length - 1;
var even = index % 2 === 0;
overrideContext.$index = index;
overrideContext.$first = first;
overrideContext.$last = last;
overrideContext.$middle = !(first || last);
overrideContext.$odd = !even;
overrideContext.$even = even;
}
function getItemsSourceExpression(instruction, attrName) {
return instruction.behaviorInstructions.filter(function (bi) {
return bi.originalAttrName === attrName;
})[0].attributes.items.sourceExpression;
}
function unwrapExpression(expression) {
var unwrapped = false;
while (expression instanceof _aureliaBinding.BindingBehavior) {
expression = expression.expression;
}
while (expression instanceof _aureliaBinding.ValueConverter) {
expression = expression.expression;
unwrapped = true;
}
return unwrapped ? expression : null;
}
function isOneTime(expression) {
while (expression instanceof _aureliaBinding.BindingBehavior) {
if (expression.name === 'oneTime') {
return true;
}
expression = expression.expression;
}
return false;
}
function updateOneTimeBinding(binding) {
if (binding.call && binding.mode === oneTime) {
binding.call(_aureliaBinding.sourceContext);
} else if (binding.updateOneTimeBindings) {
binding.updateOneTimeBindings();
}
}
function indexOf(array, item, matcher, startIndex) {
if (!matcher) {
return array.indexOf(item);
}
var length = array.length;
for (var index = startIndex || 0; index < length; index++) {
if (matcher(array[index], item)) {
return index;
}
}
return -1;
} |
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
define(["require", "exports", "sitecore/shell/client/Speak/Assets/lib/core/1.2/SitecoreSpeak"], function(require, exports, Speak) {
var MetroListview = (function (_super) {
__extends(MetroListview, _super);
function MetroListview() {
_super.apply(this, arguments);
}
return MetroListview;
})(Speak.ControlBase);
Sitecore.Speak.component(["metro"], MetroListview, "MetroListview");
});
|
import assign from 'object-assign';
import prependChars from './prependChars';
import formatAngle from './formatAngle';
const defaultTemplate = '{degree}° {prime}′ {doublePrime}″ {direction}';
export default function formatLatitude(value, options) {
options = options || {};
const template = typeof options.template === 'string' ? options.template : defaultTemplate;
return formatAngle(value, assign({}, options, {
template,
customTokens: f => {
return {
degree: prependChars(f.degree, 2, '0'),
direction: f.sign >= 0 ? 'N' : 'S'
};
}
}));
}
|
(function ($, window, document, undefined) {
'use strict';
Foundation.libs.forms = {
name: 'forms',
version: '4.1.6',
cache: {},
settings: {
disable_class: 'no-custom',
last_combo : null
},
init: function (scope, method, options) {
if (typeof method === 'object') {
$.extend(true, this.settings, method);
}
if (typeof method != 'string') {
if (!this.settings.init) {
this.events();
}
this.assemble();
return this.settings.init;
} else {
return this[method].call(this, options);
}
},
assemble: function () {
$('form.custom input[type="radio"]', $(this.scope)).not('[data-customforms="disabled"]')
.each(this.append_custom_markup);
$('form.custom input[type="checkbox"]', $(this.scope)).not('[data-customforms="disabled"]')
.each(this.append_custom_markup);
$('form.custom select', $(this.scope))
.not('[data-customforms="disabled"]')
.not('[multiple=multiple]')
.each(this.append_custom_select);
},
events: function () {
var self = this;
$(this.scope)
.on('click.fndtn.forms', 'form.custom span.custom.checkbox', function (e) {
e.preventDefault();
e.stopPropagation();
self.toggle_checkbox($(this));
})
.on('click.fndtn.forms', 'form.custom span.custom.radio', function (e) {
e.preventDefault();
e.stopPropagation();
self.toggle_radio($(this));
})
.on('change.fndtn.forms', 'form.custom select:not([data-customforms="disabled"])', function (e, force_refresh) {
self.refresh_custom_select($(this), force_refresh);
})
.on('click.fndtn.forms', 'form.custom label', function (e) {
if ($(e.target).is('label')) {
var $associatedElement = $('#' + self.escape($(this).attr('for')) + ':not([data-customforms="disabled"])'),
$customCheckbox,
$customRadio;
if ($associatedElement.length !== 0) {
if ($associatedElement.attr('type') === 'checkbox') {
e.preventDefault();
$customCheckbox = $(this).find('span.custom.checkbox');
//the checkbox might be outside after the label or inside of another element
if ($customCheckbox.length == 0) {
$customCheckbox = $associatedElement.add(this).siblings('span.custom.checkbox').first();
}
self.toggle_checkbox($customCheckbox);
} else if ($associatedElement.attr('type') === 'radio') {
e.preventDefault();
$customRadio = $(this).find('span.custom.radio');
//the radio might be outside after the label or inside of another element
if ($customRadio.length == 0) {
$customRadio = $associatedElement.add(this).siblings('span.custom.radio').first();
}
self.toggle_radio($customRadio);
}
}
}
})
.on('mousedown.fndtn.forms', 'form.custom div.custom.dropdown', function () {
return false;
})
.on('click.fndtn.forms', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (e) {
var $this = $(this),
$dropdown = $this.closest('div.custom.dropdown'),
$select = getFirstPrevSibling($dropdown, 'select');
// make sure other dropdowns close
if (!$dropdown.hasClass('open')) $(self.scope).trigger('click');
e.preventDefault();
if (false === $select.is(':disabled')) {
$dropdown.toggleClass('open');
if ($dropdown.hasClass('open')) {
$(self.scope).on('click.fndtn.forms.customdropdown', function () {
$dropdown.removeClass('open');
$(self.scope).off('.fndtn.forms.customdropdown');
});
} else {
$(self.scope).on('.fndtn.forms.customdropdown');
}
return false;
}
})
.on('click.fndtn.forms touchend.fndtn.forms', 'form.custom div.custom.dropdown li', function (e) {
var $this = $(this),
$customDropdown = $this.closest('div.custom.dropdown'),
$select = getFirstPrevSibling($customDropdown, 'select'),
selectedIndex = 0;
e.preventDefault();
e.stopPropagation();
if (!$(this).hasClass('disabled')) {
$('div.dropdown').not($customDropdown).removeClass('open');
var $oldThis = $this.closest('ul')
.find('li.selected');
$oldThis.removeClass('selected');
$this.addClass('selected');
$customDropdown.removeClass('open')
.find('a.current')
.text($this.text());
$this.closest('ul').find('li').each(function (index) {
if ($this[0] == this) {
selectedIndex = index;
}
});
$select[0].selectedIndex = selectedIndex;
//store the old value in data
$select.data('prevalue', $oldThis.html());
$select.trigger('change');
}
});
$(window).on('keydown', function (e) {
var focus = document.activeElement,
self = Foundation.libs.forms,
dropdown = $('.custom.dropdown.open');
if (dropdown.length > 0) {
e.preventDefault();
if (e.which === 13) {
dropdown.find('li.selected').trigger('click');
}
if (e.which === 27) {
dropdown.removeClass('open');
}
if (e.which >= 65 && e.which <= 90) {
var next = self.go_to(dropdown, e.which),
current = dropdown.find('li.selected');
if (next) {
current.removeClass('selected');
self.scrollTo(next.addClass('selected'), 300);
}
}
if (e.which === 38) {
var current = dropdown.find('li.selected'),
prev = current.prev(':not(.disabled)');
if (prev.length > 0) {
prev.parent()[0].scrollTop = prev.parent().scrollTop() - self.outerHeight(prev);
current.removeClass('selected');
prev.addClass('selected');
}
} else if (e.which === 40) {
var current = dropdown.find('li.selected'),
next = current.next(':not(.disabled)');
if (next.length > 0) {
next.parent()[0].scrollTop = next.parent().scrollTop() + self.outerHeight(next);
current.removeClass('selected');
next.addClass('selected');
}
}
}
});
this.settings.init = true;
},
go_to: function (dropdown, character) {
var lis = dropdown.find('li'),
count = lis.length;
if (count > 0) {
for (var i = 0; i < count; i++) {
var first_letter = lis.eq(i).text().charAt(0).toLowerCase();
if (first_letter === String.fromCharCode(character).toLowerCase()) return lis.eq(i);
}
}
},
scrollTo: function (el, duration) {
if (duration < 0) return;
var parent = el.parent();
var li_height = this.outerHeight(el);
var difference = (li_height * (el.index())) - parent.scrollTop();
var perTick = difference / duration * 10;
this.scrollToTimerCache = setTimeout(function () {
if (!isNaN(parseInt(perTick, 10))) {
parent[0].scrollTop = parent.scrollTop() + perTick;
this.scrollTo(el, duration - 10);
}
}.bind(this), 10);
},
append_custom_markup: function (idx, sel) {
var $this = $(sel),
type = $this.attr('type'),
$span = $this.next('span.custom.' + type);
if (!$this.parent().hasClass('switch')) {
$this.addClass('hidden-field');
}
if ($span.length === 0) {
$span = $('<span class="custom ' + type + '"></span>').insertAfter($this);
}
$span.toggleClass('checked', $this.is(':checked'));
$span.toggleClass('disabled', $this.is(':disabled'));
},
append_custom_select: function (idx, sel) {
var self = Foundation.libs.forms,
$this = $(sel),
$customSelect = $this.next('div.custom.dropdown'),
$customList = $customSelect.find('ul'),
$selectCurrent = $customSelect.find(".current"),
$selector = $customSelect.find(".selector"),
$options = $this.find('option'),
$selectedOption = $options.filter(':selected'),
copyClasses = $this.attr('class') ? $this.attr('class').split(' ') : [],
maxWidth = 0,
liHtml = '',
$listItems,
$currentSelect = false;
if ($this.hasClass(self.settings.disable_class)) return;
if ($customSelect.length === 0) {
var customSelectSize = $this.hasClass('small') ? 'small' : $this.hasClass('medium') ? 'medium' : $this.hasClass('large') ? 'large' : $this.hasClass('expand') ? 'expand' : '';
$customSelect = $('<div class="' + ['custom', 'dropdown', customSelectSize].concat(copyClasses).filter(function (item, idx, arr) {
if (item == '') return false;
return arr.indexOf(item) == idx;
}).join(' ') + '"><a href="#" class="selector"></a><ul /></div>');
$selector = $customSelect.find(".selector");
$customList = $customSelect.find("ul");
liHtml = $options.map(function () {
return "<li>" + $(this).html() + "</li>";
}).get().join('');
$customList.append(liHtml);
$currentSelect = $customSelect
.prepend('<a href="#" class="current">' + $selectedOption.html() + '</a>')
.find(".current");
$this.after($customSelect)
.addClass('hidden-field');
} else {
liHtml = $options.map(function () {
return "<li>" + $(this).html() + "</li>";
})
.get().join('');
$customList.html('')
.append(liHtml);
} // endif $customSelect.length === 0
self.assign_id($this, $customSelect);
$customSelect.toggleClass('disabled', $this.is(':disabled'));
$listItems = $customList.find('li');
// cache list length
self.cache[$customSelect.data('id')] = $listItems.length;
$options.each(function (index) {
if (this.selected) {
$listItems.eq(index).addClass('selected');
if ($currentSelect) {
$currentSelect.html($(this).html());
}
}
if ($(this).is(':disabled')) {
$listItems.eq(index).addClass('disabled');
}
});
//
// If we're not specifying a predetermined form size.
//
if (!$customSelect.is('.small, .medium, .large, .expand')) {
// ------------------------------------------------------------------------------------
// This is a work-around for when elements are contained within hidden parents.
// For example, when custom-form elements are inside of a hidden reveal modal.
//
// We need to display the current custom list element as well as hidden parent elements
// in order to properly calculate the list item element's width property.
// -------------------------------------------------------------------------------------
$customSelect.addClass('open');
//
// Quickly, display all parent elements.
// This should help us calcualate the width of the list item's within the drop down.
//
var self = Foundation.libs.forms;
self.hidden_fix.adjust($customList);
maxWidth = (self.outerWidth($listItems) > maxWidth) ? self.outerWidth($listItems) : maxWidth;
Foundation.libs.forms.hidden_fix.reset();
$customSelect.removeClass('open');
} // endif
},
assign_id: function ($select, $customSelect) {
var id = [+new Date(), Foundation.random_str(5)].join('-');
$select.attr('data-id', id);
$customSelect.attr('data-id', id);
},
refresh_custom_select: function ($select, force_refresh) {
var self = this;
var maxWidth = 0,
$customSelect = $select.next(),
$options = $select.find('option'),
$listItems = $customSelect.find('li');
if ($listItems.length != this.cache[$customSelect.data('id')] || force_refresh) {
$customSelect.find('ul').html('');
$options.each(function () {
var $li = $('<li>' + $(this).html() + '</li>');
$customSelect.find('ul').append($li);
});
// re-populate
$options.each(function (index) {
if (this.selected) {
$customSelect.find('li').eq(index).addClass('selected');
$customSelect.find('.current').html($(this).html());
}
if ($(this).is(':disabled')) {
$customSelect.find('li').eq(index).addClass('disabled');
}
});
// fix width
$customSelect.removeAttr('style')
.find('ul').removeAttr('style');
$customSelect.find('li').each(function () {
$customSelect.addClass('open');
if (self.outerWidth($(this)) > maxWidth) {
maxWidth = self.outerWidth($(this));
}
$customSelect.removeClass('open');
});
$listItems = $customSelect.find('li');
// cache list length
this.cache[$customSelect.data('id')] = $listItems.length;
}
},
toggle_checkbox: function ($element) {
var $input = $element.prev(),
input = $input[0];
if (false === $input.is(':disabled')) {
input.checked = ((input.checked) ? false : true);
$element.toggleClass('checked');
$input.trigger('change');
}
},
toggle_radio: function ($element) {
var $input = $element.prev(),
$form = $input.closest('form.custom'),
input = $input[0];
if (false === $input.is(':disabled')) {
$form.find('input[type="radio"][name="' + this.escape($input.attr('name')) + '"]')
.next().not($element).removeClass('checked');
if (!$element.hasClass('checked')) {
$element.toggleClass('checked');
}
input.checked = $element.hasClass('checked');
$input.trigger('change');
}
},
escape: function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
},
hidden_fix: {
/**
* Sets all hidden parent elements and self to visibile.
*
* @method adjust
* @param {jQuery Object} $child
*/
// We'll use this to temporarily store style properties.
tmp: [],
// We'll use this to set hidden parent elements.
hidden: null,
adjust: function ($child) {
// Internal reference.
var _self = this;
// Set all hidden parent elements, including this element.
_self.hidden = $child.parents().addBack().filter(":hidden");
// Loop through all hidden elements.
_self.hidden.each(function () {
// Cache the element.
var $elem = $(this);
// Store the style attribute.
// Undefined if element doesn't have a style attribute.
_self.tmp.push($elem.attr('style'));
// Set the element's display property to block,
// but ensure it's visibility is hidden.
$elem.css({
'visibility': 'hidden',
'display': 'block'
});
});
}, // end adjust
/**
* Resets the elements previous state.
*
* @method reset
*/
reset: function () {
// Internal reference.
var _self = this;
// Loop through our hidden element collection.
_self.hidden.each(function (i) {
// Cache this element.
var $elem = $(this),
_tmp = _self.tmp[i]; // Get the stored 'style' value for this element.
// If the stored value is undefined.
if (_tmp === undefined)
// Remove the style attribute.
$elem.removeAttr('style');
else
// Otherwise, reset the element style attribute.
$elem.attr('style', _tmp);
});
// Reset the tmp array.
_self.tmp = [];
// Reset the hidden elements variable.
_self.hidden = null;
} // end reset
},
off: function () {
$(this.scope).off('.fndtn.forms');
}
};
var getFirstPrevSibling = function($el, selector) {
var $el = $el.prev();
while ($el.length) {
if ($el.is(selector)) return $el;
$el = $el.prev();
}
return $();
};
}(Foundation.zj, this, this.document));
|
/**
*
* @note 字符 转换成 UTF-8 编码
* @param charStr
* @return {Array}
*
*/
const encode = (charStr) => {
const encodeStr = encodeURIComponent(charStr);
return encodeStr.split("%").map(item=>parseInt(item,16))
}
/**
* @note 转译 UTF-8
* @param charList
* @return {string}
*/
const decode = (charList) => {
return charList.map(item=>"%" + item.toString(16)).join()
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* 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.
*/
import {assumeMap} from '../detect/assume-map.js';
import {isMap} from '../../src/core/util/is-map.js';
describe('isMap', () => {
it('should return true with a map', () => {
assumeMap();
expect(isMap(new Map())).toBe(true);
});
it('should return false without a map', () => {
expect(isMap(null)).toBe(false);
expect(isMap(undefined)).toBe(false);
expect(isMap([])).toBe(false);
expect(isMap({})).toBe(false);
});
});
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides class sap.ui.core.support.Plugin
sap.ui.define(['jquery.sap.global', 'sap/ui/base/Object', 'jquery.sap.dom', 'jquery.sap.script'],
function(jQuery, BaseObject/* , jQuerySap1, jQuerySap */) {
"use strict";
/**
* Creates an instance of sap.ui.core.support.Plugin.
* @class This class represents a plugin for the support tool functionality of UI5. This class is internal and all its functions must not be used by an application.
*
* @abstract
* @extends sap.ui.base.Object
* @version 1.26.8
* @constructor
* @private
* @alias sap.ui.core.support.Plugin
*/
var Plugin = BaseObject.extend("sap.ui.core.support.Plugin", {
constructor : function(sId, sTitle, oStub) {
BaseObject.apply(this);
this._id = sId ? sId : jQuery.sap.uid();
this._title = sTitle ? sTitle : "";
this._bActive = false;
this._aEventIds = [];
this._bIsToolPlugin = oStub.getType() === sap.ui.core.support.Support.StubType.TOOL;
}
});
/**
* Inititalization function called each time the support mode is started
* (support popup is opened).
*
* @param {sap.ui.core.support.Support} oSupportStub the support stub
* @private
*/
Plugin.prototype.init = function(oSupportStub){
for (var i = 0; i < this._aEventIds.length; i++) {
var fHandler = this["on" + this._aEventIds[i]];
if (fHandler && jQuery.isFunction(fHandler)) {
oSupportStub.attachEvent(this._aEventIds[i], fHandler, this);
}
}
this._bActive = true;
};
/**
* Finalization function called each time the support mode is ended
* (support popup is closed).
*
* @param {sap.ui.core.support.Support} oSupportStub the support stub
* @private
*/
Plugin.prototype.exit = function(oSupportStub){
for (var i = 0; i < this._aEventIds.length; i++) {
var fHandler = this["on" + this._aEventIds[i]];
if (fHandler && jQuery.isFunction(fHandler)) {
oSupportStub.detachEvent(this._aEventIds[i], fHandler, this);
}
}
this._bActive = false;
};
/**
* Returns the id of this plugin instance.
*
* @return {string} the id
* @private
*/
Plugin.prototype.getId = function(){
return this._id;
};
/**
* Returns the title of this plugin instance.
*
* @return {string} the title
* @private
*/
Plugin.prototype.getTitle = function(){
return this._title;
};
/**
* Returns <code>true</code> when this plugin instance runs in the support tool, <code>false</code> otherwise.
*
* @see sap.ui.core.support.Support.StubType.TOOL
* @return {boolean} whether this plugin instance runs in the support tool
* @private
*/
Plugin.prototype.isToolPlugin = function(){
return this._bIsToolPlugin;
};
/**
* Returns the DOM node that represents this plugin wrapped as jQuery object.
*
* If an ID suffix is given, the ID of this Element is concatenated with the suffix
* (separated by a single dash) and the DOM node with that compound ID will be wrapped by jQuery.
* This matches the naming convention for named inner DOM nodes of a plugin.
*
* If no suffix is given and if no DOM exists, a DIV with the ID of this plugin will be created
* and appended to the support popup content section (identified by class .sapUiSupportCntnt).
*
* @param {string} [sSuffix] ID suffix to get a jQuery object for
* @return {jQuery} The jQuery wrapped plugin's DOM reference
* @private
*/
Plugin.prototype.$ = function(sSuffix){
var jRef = jQuery.sap.byId(sSuffix ? this.getId() + "-" + sSuffix : this.getId());
if (jRef.length == 0 && !sSuffix) {
jRef = jQuery("<DIV/>", {id:this.getId()});
jRef.appendTo(jQuery(".sapUiSupportCntnt"));
}
return jRef;
};
/**
* Returns whether the plugin is currently active or not.
*
* @return {boolean} whether the plugin is currently active or not
* @private
*/
Plugin.prototype.isActive = function(){
return this._bActive;
};
return Plugin;
}, /* bExport= */ true);
|
/**
* Created by joannarosedelmar on 1/5/15.
* angular-ui/angular-google-maps
* branch: master angular-google-maps/example/assets/scripts/controllers/search-box-autocomplete.js
*/
myApp.controller('mapController',
function ($scope, $log, $timeout ){
console.log("HERE IN MAP CONTROLLER center=" + JSON.stringify( $scope.center));
//center pointed at IT park
//$scope.center = {lat : 10.329356405981207, lng : 123.90657164680783 }
/**var center = $scope.center;
$scope.map = { center: { latitude: center.lat, longitude: center.lng }, zoom: 12 };
$scope.options = {scrollwheel: false};
$scope.coordsUpdates = 0;
$scope.dynamicMoveCtr = 0;
$scope.marker = {
id: 0,
coords: {
latitude: center.lat,
longitude: center.lng
},
options: { draggable: true },
events: {
dragend: function (marker, eventName, args) {
$log.log('marker dragend');
var lat = marker.getPosition().lat();
var lon = marker.getPosition().lng();
$log.log(lat);
$log.log(lon);
$scope.marker.options = {
draggable: true,
//labelContent: "lat: " + $scope.marker.coords.latitude + ' ' + 'lon: ' + $scope.marker.coords.longitude,
labelAnchor: "100 0",
labelClass: "marker-labels"
};
}
}
};
**/
var center = GOOGLE_MAP_DEFAULT_CENTER;
createMap(center);
$scope.changeCoordinates = function(){
var center = { lat : 10.519119107920403, lng : 123.81902434456174}
createMap(center);
}
/*
Latitude: 10.329356405981207
Longitude: 123.90657164680783
*/
function createMap(center){
//delete first?
$scope.map = null;
$scope.marker = null;
console.log("HERE IN CREATE MAP FUNCTION");
//var center = $scope.center;
$scope.center = center;
$scope.map = { center: { latitude: center.lat, longitude: center.lng }, zoom: 12 };
$scope.options = {scrollwheel: false};
//$scope.coordsUpdates = 0;
//$scope.dynamicMoveCtr = 0;
$scope.marker = {
id: 0,
coords: {
latitude: center.lat,
longitude: center.lng
},
options: { draggable: true },
events: {
dragend: function (marker, eventName, args) {
$log.log('marker dragend');
var lat = marker.getPosition().lat();
var lon = marker.getPosition().lng();
$log.log(lat);
$log.log(lon);
$scope.marker.options = {
draggable: true,
//labelContent: "lat: " + $scope.marker.coords.latitude + ' ' + 'lon: ' + $scope.marker.coords.longitude,
labelAnchor: "100 0",
labelClass: "marker-labels"
};
}
}
};
console.log("show markers=>" + JSON.stringify($scope.marker));
}
/**$scope.$watchCollection("marker.coords", function (newVal, oldVal) {
if (_.isEqual(newVal, oldVal))
return;
//$scope.coordsUpdates++;
});
/** $timeout(function () {
$scope.marker.coords = {
latitude: center.lat,
longitude: center.lng
};
$scope.dynamicMoveCtr++;
$timeout(function () {
$scope.marker.coords = {
latitude: center.lat,
longitude: center.lng
};
$scope.dynamicMoveCtr++;
}, 2000);
}, 1000)**/
/* $timeout(function () {
console.log("here in timeout");
if($scope.marker!=null && $scope.center!=null){
var center = $scope.center;
$scope.marker.coords = {
latitude: center.lat,
longitude: center.lng
};
} else console.log("no marker defined");
}, 1000)
,*/
$scope.getCoordinates = function (){
console.log("get coordinates function");
console.log( "lat=" + $scope.marker.coords.latitude);
console.log( "long=" + $scope.marker.coords.longitude );
};
});//end of controller
|
'use strict';
(function (module) {
module.exports.getFilterCallback = getFilterCallback;
/**
* Function to provide a dynamic filter for Arrays of Objects.
*
* Example `filterObject`:
* {name: /Bill/} // Regexp match of Bill
* {name: 'Bill'} // Requires equality to 'Bill'
* {name: 'Bill', gender: 'Male'} // Combined filter
*
* Usage: Array.filter(getFilterCallback({name: /Bill/}))
*
* The usage example returns an Array of Objects where the property `name` contains 'Bill'
*
* @param filterObject
* @returns {Function}
*/
function getFilterCallback(filterObject) {
/**
* This inner function is a dynamic callback function for the built in Array.prototype.filter method.
* It returns true if the value object contains a matching property concerning the filter, otherwise false.
*
* For more information about the callback:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
*
* @param object
* @param index
* @returns {boolean}
*/
var filterCallback = function filterCallback(object, index) {
for (var prop in filterObject) {
var value = object[prop],
expression = filterObject[prop];
// Validate the expression. It needs to be type of RegExp or String.
if ("string" !== typeof expression && !expression instanceof RegExp) {
throw "Invalid filter expression. Required to be of type String or RegExp: %s", expression
}
// Continue if the requested filter is undefined
if (undefined === value) {
continue;
}
// Check if value has a "match" method and check against the filter.
if (expression instanceof RegExp && expression.exec(value)) {
return true;
}
var isStringOrNumber = ("string" === typeof expression || "number" === typeof expression)
// If the expression is a String, just use the comparison operator.
if (isStringOrNumber && expression === value) {
return true;
}
}
return false;
};
return filterCallback;
}
})(module); |
module.exports = function(EventEmitter) {
return EventEmitter('notification');
};
|
const en = [
{id: 1, value: 'Topics', description: 'for topics count in %ForumName% on forumItem component'},
{id: 2, value: 'Posts', description: 'for posts count in %ForumName% on forumItem component'},
{id: 3, value: 'Last message', description: 'for last message in %TopicName% on forumItem component'},
{id: 4, value: 'ago', description: 'suffix Ago for TransformDateTime'},
{id: 5, value: 'less than a minute', description: 'for TransformDateTime'},
{id: 6, value: 'about a minute', description: 'single minute for TransformDateTime'},
{id: 7, value: 'minutes', description: 'several minutes several minutes for TransformDateTime'},
{id: 8, value: 'minutes', description: 'several minutes several minutes for TransformDateTime'},
{id: 9, value: 'minutes', description: 'several minutes several minutes for TransformDateTime'},
{id: 10, value: 'about an hour', description: 'single hour for TransformDateTime'},
{id: 11, value: 'hours', description: 'several hours for TransformDateTime'},
{id: 12, value: 'hours', description: 'several hours for TransformDateTime'},
{id: 13, value: 'about a day', description: 'single day for TransformDateTime'},
{id: 14, value: 'days', description: 'several days for TransformDateTime'},
{id: 15, value: 'days', description: 'several days for TransformDateTime'},
{id: 16, value: 'about a month', description: 'single month for TransformDateTime'},
{id: 17, value: 'months', description: 'several months for TransformDateTime'},
{id: 18, value: 'months', description: 'several months for TransformDateTime'},
{id: 19, value: 'about a year', description: 'single year for TransformDateTime'},
{id: 20, value: 'years', description: 'several years for TransformDateTime'},
{id: 21, value: 'years', description: 'several years for TransformDateTime'},
{id: 22, value: 'Views', description: 'for topics label on topicArray component'},
{id: 23, value: 'Topics', description: 'for topics label on topicArray component'},
{id: 24, value: '>>', description: 'for topics body on topicArray component'},
{id: 25, value: 'Forum:', description: 'for topics body on topicArray component'},
{id: 26, value: 'Last messages', description: 'title for lastActiveTopicArray component'},
{id: 27, value: 'DeusExMachina', description: 'web site name for title'},
{id: 28, value: 'View forum', description: 'action name for title'},
{id: 29, value: 'View topic', description: 'action name for title'},
{id: 30, value: 'Posts', description: 'action name for title'},
{id: 31, value: 'Offtopic:', description: 'header for Offtopic bbCode'},
{id: 32, value: 'wrote:', description: 'header for Quote bbCode'},
{id: 33, value: 'Quote:', description: 'header for Quote bbCode'},
{id: 34, value: 'Code:', description: 'header for Code bbCode'},
{id: 35, value: 'Ctrl+A, Ctrl+C', description: 'header for Code bbCode'},
{id: 36, value: 'Last modified:', description: 'Post edit text label'},
];
export default en;
|
import React from 'react'
import PropTypes from 'prop-types'
import Props from 'rsg-components/Props'
import Methods from 'rsg-components/Methods'
import Events from 'rsg-components/Events'
import SlotsTable from 'rsg-components/SlotsTable'
export default function Usage({ props: { props, methods, events, slots } }) {
let slotsNode
if (slots && Object.keys(slots).length > 0) {
slotsNode = slots && <SlotsTable props={slots} />
}
const propsNode = props && <Props props={props} />
let eventsNode
if (events && Object.keys(events).length > 0) {
eventsNode = events && <Events props={events} />
}
const methodsNode = methods && methods.length > 0 && <Methods methods={methods} />
if (!propsNode && !methodsNode && !slotsNode && !eventsNode) {
return null
}
return (
<div>
{propsNode}
{methodsNode}
{eventsNode}
{slotsNode}
</div>
)
}
Usage.propTypes = {
props: PropTypes.shape({
props: PropTypes.array,
methods: PropTypes.array,
events: PropTypes.object,
slots: PropTypes.object
}).isRequired
}
|
var Lru = require("lru-cache");
var memory_store = function (args) {
args = args || {};
var self = {};
self.name = 'memory';
var ttl = args.ttl;
var lru_opts = {
max: args.max || 500,
maxAge: ttl ? ttl * 1000 : null
};
var lru_cache = new Lru(lru_opts);
self.set = function (key, value, cb) {
lru_cache.set(key, value);
if (cb) {
process.nextTick(cb);
}
};
self.get = function (key, cb) {
process.nextTick(function () {
cb(null, lru_cache.get(key));
});
};
self.del = function (key, cb) {
lru_cache.del(key);
if (cb) {
process.nextTick(cb);
}
};
return self;
};
var methods = {
create: function (args) {
return memory_store(args);
}
};
module.exports = methods;
|
(function() {
module.exports = function(args, c) {
var locals, n, output, _i, _len, _ref;
if (args.length < 2) {
throw new Error("'fun' needs at least two arguments");
}
if (!c.isIdArray(args[0])) {
throw new Error("'fun' expects first parameter to be an array of identifiers");
}
output = [];
c.pushScope();
_ref = args[0];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
n = _ref[_i];
c.define(n.name, true);
}
output.push("(function(" + (((function() {
var _j, _len1, _ref1, _results;
_ref1 = args[0];
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
n = _ref1[_j];
_results.push(n.name);
}
return _results;
})()).join(', ')) + ") { ");
output.push('');
output.push("return " + (c.compileNode(args[1])) + "; })");
locals = c.getLocals();
if (locals.length > 0) {
output[1] = "var " + (((function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = locals.length; _j < _len1; _j++) {
n = locals[_j];
_results.push(n);
}
return _results;
})()).join(', ')) + "; ";
}
c.popScope();
return output.join('');
};
}).call(this);
|
var formModule = angular.module('mlcl_forms.form');
var field = function field($compile, $templateCache, $rootScope) {
return function (fieldScope) {
var self = this;
this.render = function () {
var inputHtml = $templateCache.get('plugins/field_string_select_typeahead/field_string_select_typeahead.tpl.html');
self.htmlObject = $compile(inputHtml)(fieldScope);
return this;
};
};
};
formModule.factory('string:select:typeahead', [
'$compile',
'$templateCache',
'$rootScope',
field
]); |
var path = require('path'),
logger = require('../logger')(),
isString = require('../isString');
function transcribe(libs, clients) {
function transcribeSingle(lib) {
if (lib.unify.getValue('type') === 'app')
return;
var name = lib.unify.getValue('name') || lib.name;
logger.info('Updated records for ' + name);
var dist = lib.unify.getValue('dist') || undefined;
if (!dist) {
dist = lib.bower.file.getValue('main') || undefined;
if (!isString(dist))
dist = undefined;
}
if (dist && isDefaultLibPath(name, dist))
dist = undefined;
var exports = lib.unify.getValue('library/exports') || undefined;
var themes = lib.unify.getValue('themes') || undefined;
if (themes) {
themes = JSON.parse(JSON.stringify(themes));
}
var deps = (lib.bowerDeps || [])
.filter(isDependencyIncluded)
.map(function (dep) {
return dep.unify.getValue('name') || dep.name;
});
if (deps.length <= 0)
deps = undefined;
clients
.setValue('libs/' + name + '/exports', exports)
.setPathValue('libs/' + name + '/base', '', lib.name)
.setPathValue('libs/' + name + '/path', dist, lib.name)
.setValue('libs/' + name + '/deps', deps, function (value, file, test) {
if (!value || !Array.isArray(value) || value.length <= 0)
return value;
var val = value.filter(function (item) {
return !inClientExc(test, item);
});
if (val.length > 0)
return val;
return undefined;
})
.setValue('themes/' + name, themes)
.fallback('libs/' + name, {})
.fallback('themes/' + name, 'none');
}
(libs || []).forEach(transcribeSingle);
clients
.exclude('libs', function (key, file, test) {
return inClientExc(test, key);
})
.exclude('themes', function (key, file, test) {
return inClientExc(test, key);
});
}
function isDefaultLibPath(name, dist) {
var dist = normalize(dist);
var expected = normalize(path.join('dist', name));
logger.debug('isDefault: ' + dist + ' === ' + expected);
return (dist === expected)
|| (dist === expected + '.js');
}
function normalize(relpath) {
return path.normalize(relpath).replace(/\\/g, '/');
}
function isDependencyIncluded(dep) {
if (dep.unify.exists)
dep.unify.loadSync();
var exclusions = dep.unify.getValue('client/exclude');
return !exclusions || exclusions.indexOf('self') < 0;
}
function inClientExc(test, name) {
var exc = test.exclude;
if (!Array.isArray(exc) || exc.length <= 0)
return false;
return exc.indexOf(name) > -1;
}
module.exports = transcribe; |
'use strict';
module.exports = {
app: {
title: 'Expert-Alians',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
}; |
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
<%= crudNameCap %> = mongoose.model('<%= crudNameCap %>');
/**
* Globals
*/
var user, <%= crudName %>;
/**
* Unit tests
*/
describe('<%= crudNameCap %> Model Unit Tests:', function () {
beforeEach(function (done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'M3@n.jsI$Aw3$0m3'
});
user.save(function () {
<%= crudName %> = new <%= crudNameCap %>({
title: '<%= crudNameCap %> Title',
content: '<%= crudNameCap %> Content',
user: user
});
done();
});
});
describe('Method Save', function () {
it('should be able to save without problems', function (done) {
this.timeout(10000);
return <%= crudName %>.save(function (err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without title', function (done) {
<%= crudName %>.title = '';
return <%= crudName %>.save(function (err) {
should.exist(err);
done();
});
});
});
afterEach(function (done) {
<%= crudNameCap %>.remove().exec(function () {
User.remove().exec(done);
});
});
});
|
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var del = require('del');
var jshint = require('gulp-jshint');
var bump = require('gulp-bump');
var shell = require('gulp-shell');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var dest = {
dist: './dist'
}
gulp.task('clean', function() {
del([dest.dist], function(err) {
console.log('dist directory deleted');
});
});
gulp.task('script', function() {
return gulp.src('public/iceberg-client/index.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(rename("iceberg-client.js"))
.pipe(browserify({
standalone: 'IcebergClient',
ignore: 'superagent'
}))
.pipe(gulp.dest('public/iceberg-client'))
.pipe(rename({
suffix: '.min'
}))
.pipe(uglify())
.pipe(gulp.dest('public/js/iceberg-client'));
});
gulp.task('copy', function(){
var c1 = gulp.src('public/iceberg-client/*.js').pipe(gulp.dest(dest.dist));
var c2 = gulp.src('public/iceberg-client/index.js').pipe(gulp.dest(''));
return merge(c1, c2);
});
gulp.task('bump', function() {
var package = gulp.src('./package.json')
.pipe(bump())
.pipe(gulp.dest('./'))
var bower = gulp.src('./bower.json')
.pipe(bump())
.pipe(gulp.dest('./'));
return merge(package, bower);
});
gulp.task('tag', function() {
var pkg = require('./package.json');
var v = pkg.version;
var message = v;
return gulp.src('./')
.pipe(shell([
'git add -A :/',
'git commit -m "' + v + '"',
'git push',
'git tag -a ' + v + ' -m "' + message + '"',
"git push origin master --tags"
]));
});
gulp.task('zip', function() {
var zip = require('gulp-zip');
var pkg = require('./package.json');
return gulp.src(dest.dist + '/**')
.pipe(zip('iceberg-' + pkg.version + '.zip'))
.pipe(gulp.dest(dest.dist));
});
gulp.task('default', function(callback) {
runSequence('clean', 'script', 'copy', 'bump', 'zip', 'tag', callback);
});
|
function Ago(a,b){a instanceof Array||(b=a,a=void 0),a=a||document.querySelectorAll("time"),b=b||{};var c={interval:1e4,units:[["minute",60],["hour",3600],["day",86400],["week",604800],["month",2592e3],["year",31536e3]],date:function(a){return new Date(a.getAttribute("datetime"))},format:function(a,b){if(!b)return"just now";var c=0>a?" ahead":" ago";return Math.abs(a)+" "+b+c},plural:{minute:"minutes",hour:"hours",day:"days",week:"weeks",month:"months",year:"years"}};for(var d in c)b[d]=b[d]||c[d];var e=function(a){var c=b.date(a),d=((new Date).getTime()-c.getTime())/1e3,e=Math.floor(Math.abs(d)),f=null,g=null;for(var h in b.units){var i=b.units[h][1];if(!(e>=i))break;f=b.units[h][0],g=i}null!==g&&(e=Math.floor(e/g),1!=e&&(f=b.plural[f])),a.textContent=b.format(0>d?-e:e,f)},f=function(){for(var b=0;b<a.length;b++)e(a[b])};f(),setInterval(function(){f()},b.interval)} |
const { api, _, Action } = require("../../")
const util = require('icebreaker-network/lib/util')
module.exports = () => {
const groupId = "cjtvt7ch50000e8uj3gsn0fjv"
api.groups.put({ id: groupId, name: "friends", allow: "*" }, (err) => {
if (err) {
api.log.error(err)
process.exit(1)
}
})
api.friends = {}
api.actions.friends = {}
api.friends.put = api.actions.friends.put = Action({
type: "async",
input: "string",
desc: "Put a friend",
run: (key, cb) => {
try {
util.decode(key, api.config.encoding)
} catch (err) {
return cb(err)
}
api.identities.get(key, (err, identity) => {
if (err) return api.identities.put({ id: key, groups: groupId }, cb);
if (identity && identity.groups && !Array.isArray(identity.groups)) identity.groups = []
if (identity.groups.indexOf(groupId) === -1) {
identity.groups.put(groupId)
return api.identities.put(identity, cb);
}
return cb(null, identity)
})
}
})
api.friends.remove = api.actions.friends.remove = Action({
type: "async",
input: "string",
desc: "Remove a friend by id",
run: (key, cb) => {
api.identities.remove(key, cb)
}
})
api.friends.isFriend = function (id, cb) {
api.identities.get(id, (err, identity) => {
if (err) return cb(err, false)
if (!identity.groups || !Array.isArray(identity.groups)) return cb(null, false)
if (identity.groups.indexOf(groupId) !== -1) return cb(err, true)
return cb(err, false)
})
}
api.friends.ls = api.actions.friends.ls = Action({
type: "source",
input: { live: "boolean|string", old: "boolean|string" },
desc: "Returns all friends",
usage: {
live: "Receive all friends until cancelled",
old: "Recive all old friends"
},
defaults: {
live: false,
old: true
},
run: (opts) => {
return _(api.identities.ls(opts), _.filterNot((item) => item && Array.isArray(item.groups) && item.groups.indexOf(groupId) === -1
))
}
})
api.config.authenticate = function (id, cb) {
if(!id)return cb("access denied for " + id);
if (this.protocol && this.protocol.indexOf("+unix") !== -1){
return api.friends.isFriend(id,(err,found)=>{
if(!found)return api.friends.put(id, (err) => cb(null, true))
return cb(null,true)
})
}
return api.identities.get(id, (err, identity) => {
if (err) return cb(err, false);
if(identity.groups && Array.isArray(identity.groups) && identity.groups.length > 0) return cb(null,true)
return cb("access denied for " + id,false);
})
}
api.config.perms = function (id, cb) {
if(!id) return cb("access denied for " + id,false);
api.identities.get(id, (err, identity) => {
if (err) return cb(err);
if (!(identity.groups && Array.isArray(identity.groups))) return cb("access denied for " + id,{allow:[]});
if (identity.groups.indexOf(groupId) !== -1)
return this.protocol && this.protocol.indexOf("+unix") !== -1?cb(null):cb(null,{deny:["stop","lb.stop"]})
_(identity.groups, _.asyncMap((group, cb) => api.groups.get(group, (err, data) => cb(err, data.allow || []))
), _.flatten(), _.unique(), _.collect((err, data) => {
if (err) return cb(err)
if (data && data.length > 0) return data.indexOf("*") !== -1 ? cb(null) : cb(null, {allow:data||[],deny:["stop","lb.stop"]})
return cb("access denied for " + id,false);
}))
})
}
} |
"use strict";
let EventEmitter = require('events');
module.exports = function(config) {
const me = this;
this.start = start;
this.stop = stop;
function start() {
console.log("Starting Fake Tamper generator for zone '" + config.zone + "'");
if (!me.emitter) {
me.emitter = new EventEmitter();
fake();
}
return {
zone: config.zone,
emitter: me.emitter,
};
}
function stop() {
console.log("Stopping Fake Tamper generator for zone '" + config.zone + "'");
if (me.emitter) {
me.emitter = null;
}
}
function fake() {
setTimeout(function() {
if (me.emitter) {
me.emitter.emit('tamper', { event: 'tamper-start', zone: config.zone });
}
fake();
}, 5000);
}
}; |
class EnrolleeAddFormController{
constructor($uibModalInstance,API){
'ngInject';
var vm=this;
vm.data={
lastname:'Иванов',
firstname:'Иван',
middlename:'Иванович',
dateofbirth:new Date(),
gender:0,
profession:null,
basis:null,
needhostel:false,
medical:false
}
vm.dateOptions = {
altInputFormats: ['yyyy-MM-dd', 'dd.MM.yyyy'],
formatDay: 'dd',
formatMonth: 'MM',
formatYear: 'yyyy',
minDate: new Date(),
startingDay: 1
};
vm.dateEnd = {
altInputFormats: ['yyyy-MM-dd', 'dd.MM.yyyy'],
formatDay: 'dd',
formatMonth: 'MM',
formatYear: 'yyyy',
minDate: new Date(moment().set('month',5).set('date',30)),
startingDay: 1
};
vm.profession=API.all('programforoption').getList().$object;
vm.basis=API.all('basis').getList().$object;
vm.dateofbirth = function () {
opened = false
}
vm.openDateofbirth = function () {
vm.dateofbirth.opened = true;
};
}
$onInit(){
}
}
export const EnrolleeAddFormComponent = {
templateUrl: './views/app/components/enrollee-add-form/enrollee-add-form.component.html',
controller: EnrolleeAddFormController,
controllerAs: 'vm',
bindings: {}
}
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Home from './Home';
import Layout from '../../components/Layout';
import {fetchNews} from '../../actions/home';
export default {
path: '/',
async action({ store }) {
store.dispatch(fetchNews());
return {
title: 'React Starter Kit',
component: <Layout><Home /></Layout>,
};
},
};
|
(function() {
'use strict';
angular.module('app', [
/*
* Order is not important. Angular makes a
* pass to register all of the modules listed
* and then when app.dashboard tries to use app.data,
* it's components are available.
*/
/*
* Everybody has access to these.
* We could place these under every feature area,
* but this is easier to maintain.
*/
'ngRoute',
'ngResource',
'app.core',
/*
* Feature areas
*/
'app.dailyOffer',
'app.kitchenManagement',
'app.kitchenStaff',
'app.routes'
]);
})(); |
//Play.js
var GAME_INIT_STATE = 0;
var GAME_PLAY_STATE = 1;
var GAME_OVER_STATE = 2;
var GAME_PAUSE_STATE = 3;
var GAME_OVER_TRANSITION_STATE = 10;
var gamePlayState = GAME_INIT_STATE;
var playState = function(game) {
var score;
this.create = function() {
console.log('playState-create');
// this.game.physics.startSystem(Phaser.Physics.P2JS);
score = 0;
level.create();
player.create();
enemies.create();
};
this.update = function() {
switch(gamePlayState) {
case GAME_INIT_STATE:
this.updateInitState();
break;
case GAME_PLAY_STATE:
player.updatePlayStation();
score += enemies.updatePlayState();
level.updatePlayStation(score);
// this.updatePlayStation();
break;
case GAME_OVER_TRANSITION_STATE:
gamePlayState = GAME_OVER_STATE;
level.stopLevel();
enemies.stopEnemies();
level.showGameOver(score);
break;
case GAME_OVER_STATE:
player.updateGameOverState();
this.updateGameOverState();
break;
case GAME_PAUSE_STATE:
// this.updatePauseState();
break;
}
};
this.updateGameOverState = function() {
if (game.input.keyboard.isDown(Phaser.Keyboard.R)) {
gamePlayState = GAME_INIT_STATE;
game.state.start(STATE_PLAY);
}
};
// this.updatePlayStation = function() {
//
// this.hud.text = 'score: '+score;
// };
this.updateInitState = function () {
if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
gamePlayState = GAME_PLAY_STATE;
player.initGravity();
enemies.initEnemies();
level.initLevel();
}
};
};
|
/**
* file: index.js
* auth: qk@detu.com
* update: 2016-01-27
*/
/**
* 打包阶段插件接口
* @param {Object} ret 一个包含处理后源码的结构
* @param {Object} conf 一般不需要关心,自动打包配置文件
* @param {Object} settings 插件配置属性
* @param {Object} opt 命令行参数
* @return {undefined}
*/
module.exports = function (ret, conf, settings, opt) {
fis.util.map(ret.src, function (subpath, file) {
file['requires'] = file.requires || [];
if(file.isHtmlLike && file.useCompile){
var content = file.getContent();
content.replace(/[\t\r\n\s]*?require\s*?\(['"]{1}(.*)?['"]{1}\)/g, function (words, $1) {
ret.src[subpath]['requires'].indexOf($1) < 0 ? ret.src[subpath]['requires'].push($1) : null;
return words;
});
}
//jsx添加同名less、css依赖
// if(/\.jsx$/g.test(file.subpath) && file.useSameNameRequire){
// var less = file.subpath.replace('.jsx', '.less');
// var css = file.subpath.replace('.jsx', '.css');
// if(ret.src[less]){
// var lessId = ret.src[less].getId();
// if(file.requires.indexOf(lessId) < 0){
// file.requires.push(lessId);
// }
// }
// if(ret.src[css]){
// var cssId = ret.src[css].getId();
// if(file.requires.indexOf(cssId) < 0){
// file.requires.push(cssId);
// }
// }
// }
});
}; |
/**
* Created by guangqiang on 2017/8/26.
*/
/** 网络请求工具类的拓展类,便于后期网络层修改维护 **/
import HttpUtils from './HttpUtils'
import {API_URL, MIAMI_URL, TIME_MOVIE_URL, TIME_TICKET_URL} from '../../../constants/urlConfig'
import {ApiSource} from '../../../constants/commonType'
import {dataCache} from '../cache'
/**
* GET \ POST
* 从缓存中读取数据
* @param isCache 是否缓存
* @param requestType 网络请求类型
* @param url 请求url
* @param params 请求参数
* @param source API资源
* @param callback 是否有回调函数
* @returns {value \ promise}
* 返回的值如果从缓存中取到数据就直接换行数据,或则返回promise对象
*/
const fetchData = (isCache, requestType) => (url, params, source, callback) => {
switch (source) {
case ApiSource.MIAMIMUSIC:
url = `${MIAMI_URL}${url}`
break
case ApiSource.TIMEMOVIE:
url = `${TIME_MOVIE_URL}${url}`
break
case ApiSource.TIMETICKET:
url = `${TIME_TICKET_URL}${url}`
break
default:
url = `${API_URL}${url}`
break
}
const fetchFunc = () => {
let promise = requestType === 'GET' ? HttpUtils.getRequest(url, params) : HttpUtils.postRequrst(url, params)
if (callback && typeof callback === 'function') {
promise.then(response => {
return callback(response)
})
}
return promise
}
return dataCache(url, fetchFunc, isCache)
}
/**
* GET 请求
* @param url
* @param params
* @param source
* @param callback
* @returns {{promise: Promise}}
*/
const getFetch = fetchData(false, 'GET')
/**
* POST 请求
* @param url
* @param params
* @param callback
* @returns {{promise: Promise}}
*/
const postFetch = fetchData(false, 'POST')
/**
* GET 请求,带缓存策略
* @param url
* @param params
* @param callback
* @returns {{promise: Promise}}
*/
const getFetchFromCache = fetchData(true, 'GET')
const postFetchForValidator = (url, params) => {
let promise
promise = () => {
return fetchData(false, 'GET')(url, {})
}
return {
data: params,
params,
nextPayload: {
promise: promise
}
}
}
export {getFetch, postFetch, getFetchFromCache, postFetchForValidator} |
/**
* Created by zhangruofan on 2015/12/23.
*/
var cookie=require('../lib/cookie.js');
$(document).ready(function () {
var wait = 60;
function getUrlParam(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null) return r[2]; return null;
}
$('form').submit(function () {
var mobile = $('#mobile').val();
var code = $('#code').val();
if (!isMobile(mobile)) {
$('#mobileErr').text('非法手机号码!').fadeOut(5000);
return false;
}
if (code.length != 6) {
$('#codeErr').text('验证码错误!').fadeOut(5000);
}
$.ajax({
url:url + 'User/Put/Login/',
data: {
mobile: mobile,
verifycode: code
},
type:'post'
}).done(function (data) {
if (data.code !== 0) {
$('#loginErr').text(data.msg === "" ? "登录失败,请重新尝试!" : data.msg)
.fadeOut(5000);
return false;
}
if (data.token !== '' && data.key !== '') {
var now = new Date();
now.setDate(now.getDate()+parseInt(expire));
cookie.setCookie('key', data.key, now);
cookie.setCookie('token', data.token, now);
var redirect=decodeURIComponent(getUrlParam('redirect'));
if(redirect=='null' || redirect=='')
{
redirect='/';
}
window.location.href = redirect;
}
}).fail(function () {
$('#loginErr').text("请求超时!").fadeOut(5000);
});
return false;
});
$('#codeGet').on('click', function () {
var mobile=$('#mobile').val();
if (!isMobile(mobile)) {
$('#mobileErr').text('非法手机号码!').fadeOut(5000);
return false;
}
setTime($(this));
getCode(mobile);
});
function isMobile(mobile){
return !!(mobile.length === 11 && /^(((13)|(15)|(17)|(18))+\d{9})$/.test(mobile));
}
function getCode(mobile) {
$.ajax({
url: url + '/Captcha/Add',
data: {
mobile: mobile
},
type: 'POST'
}).done(function(data){
if (data.code !== 0) {
$('#codeErr').text(data.msg === "" ? "获取验证码失败,请重新尝试!" : data.msg)
.fadeOut(5000);
return false;
}
alert(data.msg===''?'验证码已发送,请注意查收!':data.msg);
}).fail(function () {
$('#codeErr').text("请求超时!").fadeOut(5000);
});
}
function setTime(object) {
if (wait === 0) {
object.removeAttr('disabled');
object.text("点击获取验证码");
wait = 60;
} else {
object.attr('disabled', true);
object.text("重新发送(" + wait + ")");
wait--;
setTimeout(function () {
setTime(object);
}, 1000);
}
}
}); |
/* [MS-XLS] 2.4.326 TODO: payload is a zip file */
function parse_Theme(blob, length, opts) {
var end = blob.l + length;
var dwThemeVersion = blob.read_shift(4);
if(dwThemeVersion === 124226) return;
if(!opts.cellStyles || !jszip) { blob.l = end; return; }
var data = blob.slice(blob.l);
blob.l = end;
var zip; try { zip = new jszip(data); } catch(e) { return; }
var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
if(!themeXML) return;
return parse_theme_xml(themeXML, opts);
}
/* 2.5.49 */
function parse_ColorTheme(blob/*::, length*/) { return blob.read_shift(4); }
/* 2.5.155 */
function parse_FullColorExt(blob/*::, length*/) {
var o = {};
o.xclrType = blob.read_shift(2);
o.nTintShade = blob.read_shift(2);
switch(o.xclrType) {
case 0: blob.l += 4; break;
case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
case 4: blob.l += 4; break;
}
blob.l += 8;
return o;
}
/* 2.5.164 TODO: read 7 bits*/
function parse_IcvXF(blob, length) {
return parsenoop(blob, length);
}
/* 2.5.280 */
function parse_XFExtGradient(blob, length) {
return parsenoop(blob, length);
}
/* [MS-XLS] 2.5.108 */
function parse_ExtProp(blob/*::, length*/)/*:Array<any>*/ {
var extType = blob.read_shift(2);
var cb = blob.read_shift(2) - 4;
var o = [extType];
switch(extType) {
case 0x04: case 0x05: case 0x07: case 0x08:
case 0x09: case 0x0A: case 0x0B: case 0x0D:
o[1] = parse_FullColorExt(blob, cb); break;
case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
}
return o;
}
/* 2.4.355 */
function parse_XFExt(blob, length) {
var end = blob.l + length;
blob.l += 2;
var ixfe = blob.read_shift(2);
blob.l += 2;
var cexts = blob.read_shift(2);
var ext/*:AOA*/ = [];
while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
return {ixfe:ixfe, ext:ext};
}
/* xf is an XF, see parse_XFExt for xfext */
function update_xfext(xf, xfext) {
xfext.forEach(function(xfe) {
switch(xfe[0]) { /* 2.5.108 extPropData */
case 0x04: break; /* foreground color */
case 0x05: break; /* background color */
case 0x06: break; /* gradient fill */
case 0x07: break; /* top cell border color */
case 0x08: break; /* bottom cell border color */
case 0x09: break; /* left cell border color */
case 0x0a: break; /* right cell border color */
case 0x0b: break; /* diagonal cell border color */
case 0x0d: /* text color */
break;
case 0x0e: break; /* font scheme */
case 0x0f: break; /* indentation level */
}
});
}
|
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/article/:number',
name: 'article',
component: () =>
import(/* webpackChunkName: "article" */ './views/Article.vue'),
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ './views/About.vue'),
},
{
path: '*',
redirect: '/',
},
],
})
|
'use strict';
const app = require('./app');
const bootstrap = require('./bootstrap');
const port = app.get('port');
const server = app.listen(port);
server.on('listening', function() {
var p = bootstrap.init();
p.then(function() {
return app.logger.info(`Feathers application started on ${app.get('host')}:${port}`);
});
});
|
console.log('TD_COAP_CORE_13 Handle request containing several URI-Query options');
var common = require('./common.js');
erbium = require('node-erbium');
udpApp = common.udpBearer();
coapServerApp = common.server();
coapClientApp = common.client();
exports.TEST_ENDPOINT = '/query';
function check1(raw) {
common.checkStep(2);
var pkt = new erbium.Erbium(raw);
if (pkt.getHeaderType() != 0)
throw new Error('Wrong type');
if (pkt.getHeaderStatusCode() != 1)
throw new Error('Wrong code');
if (pkt.getHeaderUriQuery().toString() != 'first=1&second=2&third=3')
throw new Error('Wrong query');
}
function check2(raw) {
common.checkStep(3);
var pkt = new erbium.Erbium(raw);
if (pkt.getHeaderStatusCode() != 69)
throw new Error('Wrong code');
if (pkt.getHeaderContentType() != erbium.TEXT_PLAIN)
throw new Error('Wrong type');
if (pkt.getHeaderMID() != 0x1234)
throw new Error('Wrong MID '+pkt.getHeaderMID());
}
coapServerApp.get(common.TEST_ENDPOINT, function(req, res) {
console.log(req.query);
res.setContentType('text/plain');
res.send(erbium.CONTENT_2_05, 'Hello world');
});
function stimulus1() {
common.checkStep(1);
coapClientApp.get(erbium.COAP_TYPE_CON, common.TEST_URL_BASE + common.TEST_ENDPOINT + '?first=1&second=2&third=3', {
mid: 0x1234,
beforeSend: check1,
beforeReceive: check2,
success: function(inpkt, payload) {
common.checkStep(4);
console.log(payload.toString());
process.exit(0);
}
});
}
udpApp.start(5683, coapClientApp, coapServerApp, function(err) {
if (err) {
console.log(err);
process.exit(1);
}
coapServerApp.start();
stimulus1();
});
|
app.factory('MessageFactory', ['$http', 'AuthFactory', function($http, AuthFactory){
// console.log('MessageFactory running');
var currentMessage = {};
var unreadMessages = {};
//--------------------------------------------------------------------------//
function setMessage(item){
currentMessage.thing = item;
}
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
// Get request to retrieve the user's unread messages
function getUnreadMessages(){
AuthFactory.auth.$onAuthStateChanged(function(currentUser) {
if(currentUser){
return currentUser.getToken().then(function(idToken) {
return $http({
method: 'GET',
url: '/message/unread-messages',
headers: {
id_token: idToken
}
})
.then(function(response) {
unreadMessages.unread = response.data.length;
}),
function(error) {
console.log('Error with messages POST request: ', error);
};
});
}
});
}
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
var publicApi = {
currentMessage: currentMessage,
unreadMessages: unreadMessages,
setMessage: function(item){
return setMessage(item);
},
getUnreadMessages: function(){
return getUnreadMessages();
}
};
return publicApi;
//--------------------------------------------------------------------------//
}]);
|
'use strict'
const db = require('APP/db')
const Warehouse = db.model('warehouse')
const Router = require('express').Router()
Router.get('/', (req, res, next) => {
Warehouse.findAll()
.then(warehouses => {
res.json(warehouses)
})
.catch(next)
})
Router.get('/:id', (req, res, next) => {
Warehouse.findById(req.params.id)
.then(warehouse => {
res.json(warehouse)
})
.catch(next)
})
Router.post('/', (req, res, next) => {
Warehouse.create(req.body)
.then(warehouse => {
res.status(201).json(warehouse)
})
.catch(next)
})
Router.put('/:id', (req, res, next) => {
Warehouse.findById(req.params.id)
.then(warehouse => {
warehouse.update(req.body)
})
.then(selected => {
res.json(selected)
})
.catch(next)
})
Router.delete('/:id', (req, res, next) => {
Warehouse.findById(req.params.id)
.then(warehouse => {
warehouse.destroy()
})
.then(count => {
res.json(count)
})
.catch(next)
})
module.exports = Router;
|
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/maps/google_maps_api_v3.js
// ==/ClosureCompiler==
/**
* @name MarkerClusterer for Google Maps v3
* @version version 1.0
* @author Luke Mahe
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of
* markers.
* <br/>
* This is a v3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >v2 MarkerClusterer</a>.
*/
/**
* @license
* Copyright 2010 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A Marker Clusterer that clusters markers.
*
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to
* the cluster.
* @param {Object=} opt_options support the following options:
* 'gridSize': (number) The grid size of a cluster in pixels.
* 'maxZoom': (number) The maximum zoom level that a marker can be part of a
* cluster.
* 'zoomOnClick': (boolean) Whether the default behaviour of clicking on a
* cluster is to zoom into it.
* 'averageCenter': (boolean) Whether the center of each cluster should be
* the average of all markers in the cluster.
* 'minimumClusterSize': (number) The minimum number of markers to be in a
* cluster before the markers are hidden and a count
* is shown.
* 'styles': (object) An object that has style properties:
* 'url': (string) The image url.
* 'height': (number) The image height.
* 'width': (number) The image width.
* 'anchor': (Array) The anchor position of the label text.
* 'textColor': (string) The text color.
* 'textSize': (number) The text size.
* 'backgroundPosition': (string) The position of the backgound x, y.
* 'iconAnchor': (Array) The anchor position of the icon x, y.
* @constructor
* @extends google.maps.OverlayView
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
this.map_ = map;
/**
* @type {Array.<google.maps.Marker>}
* @private
*/
this.markers_ = [];
/**
* @type {Array.<Cluster>}
*/
this.clusters_ = [];
this.sizes = [53, 56, 66, 78, 90];
/**
* @private
*/
this.styles_ = [];
/**
* @type {boolean}
* @private
*/
this.ready_ = false;
var options = opt_options || {};
/**
* @type {number}
* @private
*/
this.gridSize_ = options['gridSize'] || 60;
/**
* @private
*/
this.minClusterSize_ = options['minimumClusterSize'] || 2;
/**
* @type {?number}
* @private
*/
this.maxZoom_ = options['maxZoom'] || null;
this.styles_ = options['styles'] || [];
/**
* @type {string}
* @private
*/
this.imagePath_ = options['imagePath'] ||
this.MARKER_CLUSTER_IMAGE_PATH_;
/**
* @type {string}
* @private
*/
this.imageExtension_ = options['imageExtension'] ||
this.MARKER_CLUSTER_IMAGE_EXTENSION_;
/**
* @type {boolean}
* @private
*/
this.zoomOnClick_ = true;
if (options['zoomOnClick'] != undefined) {
this.zoomOnClick_ = options['zoomOnClick'];
}
/**
* @type {boolean}
* @private
*/
this.averageCenter_ = false;
if (options['averageCenter'] != undefined) {
this.averageCenter_ = options['averageCenter'];
}
this.setupStyles_();
this.setMap(map);
/**
* @type {number}
* @private
*/
this.prevZoom_ = this.map_.getZoom();
// Add the map event listeners
var that = this;
google.maps.event.addListener(this.map_, 'zoom_changed', function() {
var zoom = that.map_.getZoom();
if (that.prevZoom_ != zoom) {
that.prevZoom_ = zoom;
that.resetViewport();
}
});
google.maps.event.addListener(this.map_, 'idle', function() {
that.redraw();
});
// Finally, add the markers
if (opt_markers && opt_markers.length) {
this.addMarkers(opt_markers, false);
}
}
/**
* The marker cluster image path.
*
* @type {string}
* @private
*/
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ = '../images/m';
/**
* The marker cluster image path.
*
* @type {string}
* @private
*/
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_ = 'png';
/**
* Extends a objects prototype by anothers.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function(obj1, obj2) {
return (function(object) {
for (var property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* Implementaion of the interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function() {
this.setReady_(true);
};
/**
* Implementaion of the interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function() {};
/**
* Sets up the styles object.
*
* @private
*/
MarkerClusterer.prototype.setupStyles_ = function() {
if (this.styles_.length) {
return;
}
for (var i = 0, size; size = this.sizes[i]; i++) {
this.styles_.push({
url: this.imagePath_ + (i + 1) + '.' + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fit the map to the bounds of the markers in the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function() {
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
this.map_.fitBounds(bounds);
};
/**
* Sets the styles.
*
* @param {Object} styles The style to set.
*/
MarkerClusterer.prototype.setStyles = function(styles) {
this.styles_ = styles;
};
/**
* Gets the styles.
*
* @return {Object} The styles object.
*/
MarkerClusterer.prototype.getStyles = function() {
return this.styles_;
};
/**
* Whether zoom on click is set.
*
* @return {boolean} True if zoomOnClick_ is set.
*/
MarkerClusterer.prototype.isZoomOnClick = function() {
return this.zoomOnClick_;
};
/**
* Whether average center is set.
*
* @return {boolean} True if averageCenter_ is set.
*/
MarkerClusterer.prototype.isAverageCenter = function() {
return this.averageCenter_;
};
/**
* Returns the array of markers in the clusterer.
*
* @return {Array.<google.maps.Marker>} The markers.
*/
MarkerClusterer.prototype.getMarkers = function() {
return this.markers_;
};
/**
* Returns the number of markers in the clusterer
*
* @return {Number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function() {
return this.markers_.length;
};
/**
* Sets the max zoom for the clusterer.
*
* @param {number} maxZoom The max zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Gets the max zoom for the clusterer.
*
* @return {number} The max zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function() {
return this.maxZoom_;
};
/**
* The function for calculating the cluster icon image.
*
* @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
* @param {number} numStyles The number of styles available.
* @return {Object} A object properties: 'text' (string) and 'index' (number).
* @private
*/
MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
var index = 0;
var count = markers.length;
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index
};
};
/**
* Set the calculator function.
*
* @param {function(Array, number)} calculator The function to set as the
* calculator. The function should return a object properties:
* 'text' (string) and 'index' (number).
*
*/
MarkerClusterer.prototype.setCalculator = function(calculator) {
this.calculator_ = calculator;
};
/**
* Get the calculator function.
*
* @return {function(Array, number)} the calculator function.
*/
MarkerClusterer.prototype.getCalculator = function() {
return this.calculator_;
};
/**
* Add an array of markers to the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean=} opt_nodraw Whether to redraw the clusters.
*/
MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) {
for (var i = 0, marker; marker = markers[i]; i++) {
this.pushMarkerTo_(marker);
}
if (!opt_nodraw) {
this.redraw();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
* @private
*/
MarkerClusterer.prototype.pushMarkerTo_ = function(marker) {
marker.isAdded = false;
if (marker['draggable']) {
// If the marker is draggable add a listener so we update the clusters on
// the drag end.
var that = this;
google.maps.event.addListener(marker, 'dragend', function() {
marker.isAdded = false;
that.repaint();
});
}
this.markers_.push(marker);
};
/**
* Adds a marker to the clusterer and redraws if needed.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean=} opt_nodraw Whether to redraw the clusters.
*/
MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw();
}
};
/**
* Removes a marker and returns true if removed, false if not
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
* @private
*/
MarkerClusterer.prototype.removeMarker_ = function(marker) {
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (var i = 0, m; m = this.markers_[i]; i++) {
if (m == marker) {
index = i;
break;
}
}
}
if (index == -1) {
// Marker is not in our list of markers.
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1);
return true;
};
/**
* Remove a marker from the cluster.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean=} opt_nodraw Optional boolean to force no redraw.
* @return {boolean} True if the marker was removed.
*/
MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.resetViewport();
this.redraw();
return true;
} else {
return false;
}
};
/**
* Removes an array of markers from the cluster.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean=} opt_nodraw Optional boolean to force no redraw.
*/
MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw) {
var removed = false;
for (var i = 0, marker; marker = markers[i]; i++) {
var r = this.removeMarker_(marker);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.resetViewport();
this.redraw();
return true;
}
};
/**
* Sets the clusterer's ready state.
*
* @param {boolean} ready The state.
* @private
*/
MarkerClusterer.prototype.setReady_ = function(ready) {
if (!this.ready_) {
this.ready_ = ready;
this.createClusters_();
}
};
/**
* Returns the number of clusters in the clusterer.
*
* @return {number} The number of clusters.
*/
MarkerClusterer.prototype.getTotalClusters = function() {
return this.clusters_.length;
};
/**
* Returns the google map that the clusterer is associated with.
*
* @return {google.maps.Map} The map.
*/
MarkerClusterer.prototype.getMap = function() {
return this.map_;
};
/**
* Sets the google map that the clusterer is associated with.
*
* @param {google.maps.Map} map The map.
*/
MarkerClusterer.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* Returns the size of the grid.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function() {
return this.gridSize_;
};
/**
* Sets the size of the grid.
*
* @param {number} size The grid size.
*/
MarkerClusterer.prototype.setGridSize = function(size) {
this.gridSize_ = size;
};
/**
* Returns the min cluster size.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getMinClusterSize = function() {
return this.minClusterSize_;
};
/**
* Sets the min cluster size.
*
* @param {number} size The grid size.
*/
MarkerClusterer.prototype.setMinClusterSize = function(size) {
this.minClusterSize_ = size;
};
/**
* Extends a bounds object by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
*/
MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Determins if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
* @private
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Clears all clusters and markers from the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function() {
this.resetViewport(true);
// Set the markers a empty array.
this.markers_ = [];
};
/**
* Clears all existing clusters and recreates them.
* @param {boolean} opt_hide To also hide the marker.
*/
MarkerClusterer.prototype.resetViewport = function(opt_hide) {
// Remove all the clusters
for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
cluster.remove();
}
// Reset the markers to not be added and to be invisible.
for (var i = 0, marker; marker = this.markers_[i]; i++) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
this.clusters_ = [];
};
/**
*
*/
MarkerClusterer.prototype.repaint = function() {
var oldClusters = this.clusters_.slice();
this.clusters_.length = 0;
this.resetViewport();
this.redraw();
// Remove the old clusters.
// Do it in a timeout so the other clusters have been drawn first.
window.setTimeout(function() {
for (var i = 0, cluster; cluster = oldClusters[i]; i++) {
cluster.remove();
}
}, 0);
};
/**
* Redraws the clusters.
*/
MarkerClusterer.prototype.redraw = function() {
this.createClusters_();
};
/**
* Calculates the distance between two latlng locations in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @private
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) {
if (!p1 || !p2) {
return 0;
}
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Add a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
* @private
*/
MarkerClusterer.prototype.addToClosestCluster_ = function(marker) {
var distance = 40000; // Some large number
var clusterToAddTo = null;
var pos = marker.getPosition();
for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
var center = cluster.getCenter();
if (center) {
var d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
var cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters.
*
* @private
*/
MarkerClusterer.prototype.createClusters_ = function() {
if (!this.ready_) {
return;
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),
this.map_.getBounds().getNorthEast());
var bounds = this.getExtendedBounds(mapBounds);
for (var i = 0, marker; marker = this.markers_[i]; i++) {
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
this.addToClosestCluster_(marker);
}
}
};
/**
* A cluster that contains markers.
*
* @param {MarkerClusterer} markerClusterer The markerclusterer that this
* cluster is associated with.
* @constructor
* @ignore
*/
function Cluster(markerClusterer) {
this.markerClusterer_ = markerClusterer;
this.map_ = markerClusterer.getMap();
this.gridSize_ = markerClusterer.getGridSize();
this.minClusterSize_ = markerClusterer.getMinClusterSize();
this.averageCenter_ = markerClusterer.isAverageCenter();
this.center_ = null;
this.markers_ = [];
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(),
markerClusterer.getGridSize());
}
/**
* Determins if a marker is already added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker is already added.
*/
Cluster.prototype.isMarkerAlreadyAdded = function(marker) {
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) != -1;
} else {
for (var i = 0, m; m = this.markers_[i]; i++) {
if (m == marker) {
return true;
}
}
}
return false;
};
/**
* Add a marker the cluster.
*
* @param {google.maps.Marker} marker The marker to add.
* @return {boolean} True if the marker was added.
*/
Cluster.prototype.addMarker = function(marker) {
if (this.isMarkerAlreadyAdded(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l-1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l-1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
var len = this.markers_.length;
if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
// Min cluster size not reached so show the marker.
marker.setMap(this.map_);
}
if (len == this.minClusterSize_) {
// Hide the markers that were showing.
for (var i = 0; i < len; i++) {
this.markers_[i].setMap(null);
}
}
if (len >= this.minClusterSize_) {
marker.setMap(null);
}
this.updateIcon();
return true;
};
/**
* Returns the marker clusterer that the cluster is associated with.
*
* @return {MarkerClusterer} The associated marker clusterer.
*/
Cluster.prototype.getMarkerClusterer = function() {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
*/
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
return bounds;
};
/**
* Removes the cluster
*/
Cluster.prototype.remove = function() {
this.clusterIcon_.remove();
this.markers_.length = 0;
delete this.markers_;
};
/**
* Returns the center of the cluster.
*
* @return {number} The cluster center.
*/
Cluster.prototype.getSize = function() {
return this.markers_.length;
};
/**
* Returns the center of the cluster.
*
* @return {Array.<google.maps.Marker>} The cluster center.
*/
Cluster.prototype.getMarkers = function() {
return this.markers_;
};
/**
* Returns the center of the cluster.
*
* @return {google.maps.LatLng} The cluster center.
*/
Cluster.prototype.getCenter = function() {
return this.center_;
};
/**
* Calculated the extended bounds of the cluster with the grid.
*
* @private
*/
Cluster.prototype.calculateBounds_ = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Determines if a marker lies in the clusters bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
*/
Cluster.prototype.isMarkerInClusterBounds = function(marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Returns the map that the cluster is associated with.
*
* @return {google.maps.Map} The map.
*/
Cluster.prototype.getMap = function() {
return this.map_;
};
/**
* Updates the cluster icon
*/
Cluster.prototype.updateIcon = function() {
var zoom = this.map_.getZoom();
var mz = this.markerClusterer_.getMaxZoom();
if (mz && zoom > mz) {
// The zoom is greater than our max zoom so show all the markers in cluster.
for (var i = 0, marker; marker = this.markers_[i]; i++) {
marker.setMap(this.map_);
}
return;
}
if (this.markers_.length < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.setSums(sums);
this.clusterIcon_.show();
};
/**
* A cluster icon
*
* @param {Cluster} cluster The cluster to be associated with.
* @param {Object} styles An object that has style properties:
* 'url': (string) The image url.
* 'height': (number) The image height.
* 'width': (number) The image width.
* 'anchor': (Array) The anchor position of the label text.
* 'textColor': (string) The text color.
* 'textSize': (number) The text size.
* 'backgroundPosition: (string) The background postition x, y.
* @param {number=} opt_padding Optional padding to apply to the cluster icon.
* @constructor
* @extends google.maps.OverlayView
* @ignore
*/
function ClusterIcon(cluster, styles, opt_padding) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.styles_ = styles;
this.padding_ = opt_padding || 0;
this.cluster_ = cluster;
this.center_ = null;
this.map_ = cluster.getMap();
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(this.map_);
}
/**
* Triggers the clusterclick event and zoom's if the option is set.
*
* @param {google.maps.MouseEvent} event The event to propagate
*/
ClusterIcon.prototype.triggerClusterClick = function(event) {
var markerClusterer = this.cluster_.getMarkerClusterer();
// Trigger the clusterclick event.
google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_, event);
if (markerClusterer.isZoomOnClick()) {
// Zoom into the cluster.
this.map_.fitBounds(this.cluster_.getBounds());
}
};
/**
* Adding the cluster icon to the dom.
* @ignore
*/
ClusterIcon.prototype.onAdd = function() {
this.div_ = document.createElement('DIV');
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
this.div_.innerHTML = this.sums_.text;
}
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this.div_);
var that = this;
var isDragging = false;
google.maps.event.addDomListener(this.div_, 'click', function(event) {
// Only perform click when not preceded by a drag
if (!isDragging) {
that.triggerClusterClick(event);
}
});
google.maps.event.addDomListener(this.div_, 'mousedown', function() {
isDragging = false;
});
google.maps.event.addDomListener(this.div_, 'mousemove', function() {
isDragging = true;
});
};
/**
* Returns the position to place the div dending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
* @private
*/
ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
if (typeof this.iconAnchor_ === 'object' && this.iconAnchor_.length === 2) {
pos.x -= this.iconAnchor_[0];
pos.y -= this.iconAnchor_[1];
} else {
pos.x -= parseInt(this.width_ / 2, 10);
pos.y -= parseInt(this.height_ / 2, 10);
}
return pos;
};
/**
* Draw the icon.
* @ignore
*/
ClusterIcon.prototype.draw = function() {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + 'px';
this.div_.style.left = pos.x + 'px';
}
};
/**
* Hide the icon.
*/
ClusterIcon.prototype.hide = function() {
if (this.div_) {
this.div_.style.display = 'none';
}
this.visible_ = false;
};
/**
* Position and show the icon.
*/
ClusterIcon.prototype.show = function() {
if (this.div_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
this.div_.style.display = '';
}
this.visible_ = true;
};
/**
* Remove the icon from the map
*/
ClusterIcon.prototype.remove = function() {
this.setMap(null);
};
/**
* Implementation of the onRemove interface.
* @ignore
*/
ClusterIcon.prototype.onRemove = function() {
if (this.div_ && this.div_.parentNode) {
this.hide();
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Set the sums of the icon.
*
* @param {Object} sums The sums containing:
* 'text': (string) The text to display in the icon.
* 'index': (number) The style index of the icon.
*/
ClusterIcon.prototype.setSums = function(sums) {
this.sums_ = sums;
this.text_ = sums.text;
this.index_ = sums.index;
if (this.div_) {
this.div_.innerHTML = sums.text;
}
this.useStyle();
};
/**
* Sets the icon to the the styles.
*/
ClusterIcon.prototype.useStyle = function() {
var index = Math.max(0, this.sums_.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style['url'];
this.height_ = style['height'];
this.width_ = style['width'];
this.textColor_ = style['textColor'];
this.anchor_ = style['anchor'];
this.textSize_ = style['textSize'];
this.backgroundPosition_ = style['backgroundPosition'];
this.iconAnchor_ = style['iconAnchor'];
};
/**
* Sets the center of the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function(center) {
this.center_ = center;
};
/**
* Create the css text based on the position of the icon.
*
* @param {google.maps.Point} pos The position.
* @return {string} The css style text.
*/
ClusterIcon.prototype.createCss = function(pos) {
var style = [];
style.push('background-image:url(' + this.url_ + ');');
var backgroundPosition = this.backgroundPosition_ ? this.backgroundPosition_ : '0 0';
style.push('background-position:' + backgroundPosition + ';');
if (typeof this.anchor_ === 'object') {
if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 &&
this.anchor_[0] < this.height_) {
style.push('height:' + (this.height_ - this.anchor_[0]) +
'px; padding-top:' + this.anchor_[0] + 'px;');
} else if (typeof this.anchor_[0] === 'number' && this.anchor_[0] < 0 &&
-this.anchor_[0] < this.height_) {
style.push('height:' + this.height_ + 'px; line-height:' + (this.height_ + this.anchor_[0]) +
'px;');
} else {
style.push('height:' + this.height_ + 'px; line-height:' + this.height_ +
'px;');
}
if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 &&
this.anchor_[1] < this.width_) {
style.push('width:' + (this.width_ - this.anchor_[1]) +
'px; padding-left:' + this.anchor_[1] + 'px;');
} else {
style.push('width:' + this.width_ + 'px; text-align:center;');
}
} else {
style.push('height:' + this.height_ + 'px; line-height:' +
this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;');
}
var txtColor = this.textColor_ ? this.textColor_ : 'black';
var txtSize = this.textSize_ ? this.textSize_ : 11;
style.push('cursor:pointer; top:' + pos.y + 'px; left:' +
pos.x + 'px; color:' + txtColor + '; position:absolute; font-size:' +
txtSize + 'px; font-family:Arial,sans-serif; font-weight:bold');
return style.join('');
};
// Export Symbols for Closure
// If you are not going to compile with closure then you can remove the
// code below.
window['MarkerClusterer'] = MarkerClusterer;
MarkerClusterer.prototype['addMarker'] = MarkerClusterer.prototype.addMarker;
MarkerClusterer.prototype['addMarkers'] = MarkerClusterer.prototype.addMarkers;
MarkerClusterer.prototype['clearMarkers'] =
MarkerClusterer.prototype.clearMarkers;
MarkerClusterer.prototype['fitMapToMarkers'] =
MarkerClusterer.prototype.fitMapToMarkers;
MarkerClusterer.prototype['getCalculator'] =
MarkerClusterer.prototype.getCalculator;
MarkerClusterer.prototype['getGridSize'] =
MarkerClusterer.prototype.getGridSize;
MarkerClusterer.prototype['getExtendedBounds'] =
MarkerClusterer.prototype.getExtendedBounds;
MarkerClusterer.prototype['getMap'] = MarkerClusterer.prototype.getMap;
MarkerClusterer.prototype['getMarkers'] = MarkerClusterer.prototype.getMarkers;
MarkerClusterer.prototype['getMaxZoom'] = MarkerClusterer.prototype.getMaxZoom;
MarkerClusterer.prototype['getStyles'] = MarkerClusterer.prototype.getStyles;
MarkerClusterer.prototype['getTotalClusters'] =
MarkerClusterer.prototype.getTotalClusters;
MarkerClusterer.prototype['getTotalMarkers'] =
MarkerClusterer.prototype.getTotalMarkers;
MarkerClusterer.prototype['redraw'] = MarkerClusterer.prototype.redraw;
MarkerClusterer.prototype['removeMarker'] =
MarkerClusterer.prototype.removeMarker;
MarkerClusterer.prototype['removeMarkers'] =
MarkerClusterer.prototype.removeMarkers;
MarkerClusterer.prototype['resetViewport'] =
MarkerClusterer.prototype.resetViewport;
MarkerClusterer.prototype['repaint'] =
MarkerClusterer.prototype.repaint;
MarkerClusterer.prototype['setCalculator'] =
MarkerClusterer.prototype.setCalculator;
MarkerClusterer.prototype['setGridSize'] =
MarkerClusterer.prototype.setGridSize;
MarkerClusterer.prototype['setMaxZoom'] =
MarkerClusterer.prototype.setMaxZoom;
MarkerClusterer.prototype['onAdd'] = MarkerClusterer.prototype.onAdd;
MarkerClusterer.prototype['draw'] = MarkerClusterer.prototype.draw;
Cluster.prototype['getCenter'] = Cluster.prototype.getCenter;
Cluster.prototype['getSize'] = Cluster.prototype.getSize;
Cluster.prototype['getMarkers'] = Cluster.prototype.getMarkers;
ClusterIcon.prototype['onAdd'] = ClusterIcon.prototype.onAdd;
ClusterIcon.prototype['draw'] = ClusterIcon.prototype.draw;
ClusterIcon.prototype['onRemove'] = ClusterIcon.prototype.onRemove;
|
import { browserHistory } from 'react-router';
import { NotificationManager } from 'react-notifications';
import * as t from './actionTypes';
import { app } from '../lib/WebApi';
/*
* Set the "sending request" flag in state.
* Can be used to show a spinner or something
*/
export function setSendingRequest(isSending) {
return {
type: t.SENDING_REQUEST,
isSending
}
}
/*
* Set the current login state of the user
*/
export function setLoginState(loginState) {
return {
type: t.SET_LOGIN_STATE,
loginState
}
}
/*
* Forward the user to a certain target location
*/
export function forwardTo(target) {
browserHistory.push(target);
}
/*
* User Login and forward to /articles
*/
export function login(email, password) {
return (dispatch) => {
dispatch(setSendingRequest(true));
if (anyElementsEmpty({ email, password })) {
dispatch(setSendingRequest(false));
NotificationManager.error('Please provide username and password', 'Sign in');
}
app.authenticate({
type: 'local',
email,
password
}).then((result) => {
dispatch(setSendingRequest(false));
const user = result.data;
if (!user) {
app.logout();
NotificationManager.error('Something went wrong, please try again', 'Sign in');
return;
}
if (!user.isVerified) {
app.logout();
forwardTo('/login/pendingVerification/' + email);
return;
}
dispatch(setLoginState(true));
NotificationManager.success('You have been successfully signed in.', 'Sign in');
forwardTo('/articles');
}).catch((error) => {
dispatch(setSendingRequest(false));
NotificationManager.error(error.message, 'Sign in unsuccessful');
});
}
}
/*
* User Logout and forward to index page
*/
export function logout() {
return (dispatch) => {
dispatch(setSendingRequest(true));
app.logout().then(() => {
dispatch(setSendingRequest(false));
dispatch(setLoginState(false));
NotificationManager.success('You have been successfully logged out.', 'Logout successful');
forwardTo('/');
}).catch((error) => {
dispatch(setSendingRequest(false));
NotificationManager.error(error.message, 'Logout failed');
})
}
}
/*
* Sign up a new user and forward to /login
*/
export function register(email, password, confirmPassword) {
return (dispatch) => {
dispatch(setSendingRequest(true));
if (anyElementsEmpty({ email, password, confirmPassword })) {
dispatch(setSendingRequest(false));
NotificationManager.error('Please provide all mandatory information.', 'Sign up');
return;
}
if (password !== confirmPassword) {
dispatch(setSendingRequest(false));
NotificationManager.error('Password and confirmation do not match.', 'Sign up');
return;
}
const userService = app.service('users');
userService.create({
email,
password
})
.then((response) => {
dispatch(setSendingRequest(false));
NotificationManager.info('Thanks for the registration. We sent a mail to verify your email address', 'Success!', 5000);
forwardTo('/');
})
.catch((error) => {
dispatch(setSendingRequest(false));
NotificationManager.error(error.message, 'Sign up unsuccessful');
});
}
}
export function verifyEmail(slug) {
return (dispatch) => {
dispatch(setSendingRequest(true));
if (!slug) {
dispatch(setSendingRequest(false));
NotificationManager.error('Please provide all mandatory information.', 'Verification');
return;
}
const authManagement = app.service('authManagement');
authManagement.create({
action: 'verifySignupLong',
value: slug
})
.then((response) => {
dispatch(setSendingRequest(false));
console.log('the response: ' + JSON.stringify(response));
NotificationManager.info('Your email was successfully verified.');
})
.catch((error) => {
dispatch(setSendingRequest(false));
NotificationManager.error(error.message, 'Verification unsuccessful');
});
}
}
export function resendVerificationMail(email) {
return (dispatch) => {
dispatch(setSendingRequest(true));
if (!email) {
dispatch(setSendingRequest(false));
NotificationManager.error('Please provide all mandatory information.', 'Verification');
return;
}
const authManagement = app.service('authManagement');
console.log(JSON.stringify({ email }));
authManagement.create({
action: 'resendVerifySignup',
value: { email },
notifierOptions: {}
}).then((response) => {
dispatch(setSendingRequest(false));
NotificationManager.info('A new verification mail was sent.');
forwardTo('/');
}).catch((error) => {
dispatch(setSendingRequest(false));
NotificationManager.error(error.message, 'Something went wrong, please try again.');
})
}
}
function anyElementsEmpty(elements) {
for (let element in elements) {
if (!elements[element]) {
return true;
}
}
return false;
} |
import deepEqual from 'deep-equal';
import uniqueId from 'lodash.uniqueid';
import { createSheet } from './utils';
import { composes, config } from './composes';
import { attachRule, addRule } from './attach';
import { formatRule } from './format';
let cache = [];
let vuduSheet = createSheet('vSheet');
/**
* buildRuleset:
* 1) Generates unique vudu classes
* 2) Adds formatted rules to the sheet
* 3) Returns an object of vudu classes
*
* @param {Object} group
* @param {Object} sheet
* @param {Object} [options={}]
* @returns {Object}
*/
const buildRuleset = (group, sheet, options={}) => {
const suffix = typeof options.suffix === 'function' ? options.suffix() : options.suffix;
const rules = Object.keys(group).map(classname => {
return {
classname,
vuduClass: `${classname}-${suffix || uniqueId()}`,
styles: group[classname],
};
});
rules.forEach(r => addRule(formatRule(r.styles), r.vuduClass, sheet, true));
return rules.reduce((a, b) => ({
...a,
[b.classname]: b.vuduClass,
}), {});
};
/**
* V kicks off adding a new rule.
*
* @param {Object} el
* @param {Object} [customSheet]
* @param {Object} [options={}]
* @returns {Object}
*/
const v = (el, customSheet, options={}) => {
const cachedItem = cache.find(item => deepEqual(item.element, el));
if (cachedItem) {
return cachedItem.classes;
}
const sheet = customSheet || vuduSheet;
const classes = buildRuleset(el, sheet, options);
const cacheItem = {};
cacheItem.element = el;
cacheItem.classes = classes;
cache.push(cacheItem);
return classes;
};
/**
* PUBLIC METHODS
*/
const addFontFace = (font, customSheet) => {
const sheet = customSheet || vuduSheet;
const dec = formatRule(font)
.map(r => `${r.key}: ${r.value}`)
.join(';');
attachRule(`@font-face { ${dec}; }`, sheet);
return font.fontFamily.toString();
};
const logOutput = () => {
const rules = vuduSheet.cssRules;
console.log(
Object.keys(rules)
.map(r => rules[r].cssText)
.join('\n\n')
);
};
/**
* Curries v to make configuring v easier
*
* @param {Object} options
* @returns {Function}
*/
const options = (options) => (el, customSheet) => v(el, customSheet, options)
v.addFontFace = addFontFace;
v.logOutput = logOutput;
v.composes = composes;
v.config = config;
v.options = options;
v.v = v;
export default v;
|
(function() {
'use strict';
angular.module('workspaceApp')
.controller('OpenimagesCtrl', ['$scope', '$http', function($scope, $http) {
$scope.results = [];
$scope.search = function() {
$http({
method: 'GET',
url: 'https://api.flickr.com/services/rest',
params: {
method: 'flickr.photos.getRecent',
api_key: '8f6c9ad706307b69902de0fc15452bfb',
text: $scope.searchTerm,
format: 'json',
nojsoncallback: 1
}
}).success(function(data) {
console.log(data);
$scope.results = data;
}).error(function(error) {
console.log(error);
});
}
}]);
})(); |
'use strict';
// Module dependencies.
var express = require('express'),
fs = require('fs'),
path = require('path'),
mongoose = require('mongoose'),
passport = require('passport'),
logger = require('mean-logger');
var app = express();
// Load configurations
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./config/config');
// DB Connection
mongoose.connect(config.db);
// Models
var modelsPath = path.join(__dirname, 'app/models');
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if(stat.isFile()) {
if (/(.*)\.(js$)/.test(file)) {
require(newPath);
}
} else if(stat.isDirectory()) {
walk(newPath);
}
});
};
walk(modelsPath);
// Express settings
require('./config/passport')(passport);
require('./config/express')(app, passport);
// Routes
var routesPath = path.join(__dirname, 'app/routes');
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if(stat.isFile()) {
if (/(.*)\.(js$)/.test(file)) {
require(newPath)(app, passport);
}
// Middlewares is not a route itself
} else if(stat.isDirectory() && file !== 'middlewares') {
walk(newPath);
}
});
};
walk(routesPath);
// Start the server and app.
app.listen(app.get('port'), function() {
console.log('Express App listening at port ' + app.get('port'));
});
logger.init(app, passport, mongoose);
exports = module.exports = app; |
import DS from 'ember-data';
export default DS.Model.extend({
currently: DS.attr(),
daily: DS.attr(),
flags: DS.attr(),
hourly: DS.attr(),
minutely: DS.attr()
});
|
var apistatus = require('../lib/apistatus.js')
var statusCodes = require('../lib/codes.js')
var assert = require('assert')
var nock = require('nock');
// Mock http responses
var nockServer = nock('http://localhost:9876');
nockServer.get('/ok').reply(200, undefined).persist();
nockServer.get('/fail').reply(501, undefined).persist();
nockServer.get('/redirect').reply(301, undefined).persist();
nockServer.get('/123').reply(123, undefined).persist();
nockServer.get('/500').reply(500, undefined).persist();
nockServer.get('/501').reply(501, undefined).persist();
nockServer.get('/777').reply(777, undefined).persist();
nockServer.get('/404').reply(404, undefined, {
Location: 'http://localhost:9876/ok'
}).persist();
nockServer.get('/301').reply(301, undefined, {
Location: 'http://localhost:9876/ok'
}).get('/302').reply(302, undefined, {
Location: 'http://localhost:9876/ok'
})
describe('Package', function () {
it('should still work with missing callback', function(){
assert.doesNotThrow(function() {
apistatus('http://localhost:9876/ok')
}, Error)
})
it('should throw error for missing URL', function(done){
assert.throws(function() {
apistatus(function(){})
}, Error)
done()
})
it('should throw error for invalid URL', function(){
assert.throws(function() {
apistatus(53, function(){})
}, Error)
})
})
describe('Online', function () {
it('should return online true', function(done){
apistatus('http://localhost:9876/ok', function(status){
assert.equal(status.online, true)
done()
})
})
it('should return message "OK"', function(done){
apistatus('http://localhost:9876/ok', function(status){
assert.equal(status.message, "OK")
done()
})
})
it('should return statusCode 200', function(done){
apistatus('http://localhost:9876/ok', function(status){
assert.equal(status.statusCode, 200)
done()
})
})
})
describe('Offline', function () {
it('should return online false', function(done){
apistatus('http://nodomain:9876/', function(status){
assert.equal(status.online, false)
done()
})
})
it('should return undefined statusDescription', function(done){
apistatus('http://nodomain:9876/', function(status){
assert.equal(status.statusDescription, undefined)
done()
})
})
it('should return undefined status', function(done){
apistatus('http://nodomain:9876/', function(status){
assert.equal(status.code, undefined)
done()
})
})
})
describe('Redirects', function () {
it('should not follow 301 redirects', function(done){
apistatus('http://localhost:9876/301', function(status){
assert.equal(status.statusCode, 301)
done()
})
})
it('should not follow 302 redirects', function(done){
apistatus('http://localhost:9876/302', function(status){
assert.equal(status.statusCode, 302)
done()
})
})
it('should not follow 404 redirect', function(done){
apistatus('http://localhost:9876/404', function(status){
assert.equal(status.statusCode, 404)
done()
})
})
})
describe('Errors', function () {
it('should return client errors', function(done){
apistatus('http://localhost:9876/404', function(status){
assert.equal(status.category, "Client Error")
done()
})
})
it('should return server errors', function(done){
apistatus('http://localhost:9876/501', function(status){
assert.equal(status.category, "Server Error")
done()
})
})
it('should return message "Not Found"', function(done){
apistatus('http://localhost:9876/404', function(status){
assert.equal(status.message, "Not Found")
done()
})
})
it('should return status "404"', function(done){
apistatus('http://localhost:9876/404', function(status){
assert.equal(status.statusCode, "404")
done()
})
})
it('should not follow 404 redirect', function(done){
apistatus('http://localhost:9876/404', function(status){
assert.equal(status.statusCode, 404)
done()
})
})
})
describe('Status Codes', function () {
it('should be an object', function(){
assert.equal(typeof statusCodes, "object")
})
it('should return status "123"', function(done){
apistatus('http://localhost:9876/123', function(status){
assert.equal(status.statusCode, 123)
done()
})
})
it('should return non-standard status cpde', function(done){
apistatus('http://localhost:9876/777', function(status){
assert.equal(status.category, "Non-standard Category")
done()
})
})
it('should return non-standard status description', function(done){
apistatus('http://localhost:9876/123', function(status){
assert.equal(status.message, "Non-standard Status")
done()
})
})
it('should return standard status descriptions', function(done){
apistatus('http://localhost:9876/500', function(status){
assert.equal(status.message, "Internal Server Error")
done()
})
})
})
describe('HAR Requests', function () {
var har = require('./har.json')
it('should be an array ', function(done){
apistatus(har, function(data){
assert.equal(data instanceof Array, true)
done()
})
})
it('should have three results', function(done){
apistatus(har, function(data){
assert.equal(data.length, 3)
done()
})
})
it('should throw an error on invalid har', function(done){
assert.throws(function() {
apistatus({"not": "a har file"}, function(){})
}, Error)
done()
})
it('should have have the correct status codes', function(done){
apistatus(har, function(data){
var codes = [200, 301, 501], c = 0
data.map(function(d){
assert.equal(d.statusCode, codes[c++])
})
done()
})
})
})
describe('Latency', function () {
it('should be a number', function(){
apistatus('http://mockbin.com', function(status){
assert.equal(typeof status.latency, "number")
done()
})
})
})
|
//
// APNDevice.js — APNRS
// today is 11/13/12, it is now 04:42 PM
// created by TotenDev
// see LICENSE for details.
//
//Modules
var assert = require('assert'),
deviceStoreWrapper = require('./APNDeviceQueryWrapper.js'),
definitions = require('./definitions.js')();
/**
* Initialize APNDevice function
**/
module.exports = function (databaseOptions) { return new APNDevice(databaseOptions); }
function APNDevice(databaseOptions) {
this.deviceWrapper = deviceStoreWrapper(databaseOptions);
}
//helper fuction
function twoCharString(str) { return ("0" + str).slice(-2); }
/**
* Register APNDevice function
* @param Obj bodyData - body data recieved on request
* @param Function callback - function callback - REQUIRED
* @param Boolean callback.okay - if filled okay (true) or with errored (false).
* @param String callback.resp - response string|obj when convinient.
**/
APNDevice.prototype.APNDeviceRegister = function APNDeviceRegister(bodyData,callback) {
//Check for required value
if (bodyData && bodyData['token'] && bodyData['token'].length > 0) {
var token = bodyData['token'].replace("-","").toLowerCase(), startDate = null, endDate = null, timeZone = null, tags = null;
//optional values
if (bodyData['silentTime'] && bodyData['silentTime']['startDate'] && bodyData['silentTime']['startDate'].length == 5) { startDate = bodyData['silentTime']['startDate']; }
else { startDate = '09:00'; /*Defaults*/ }
if (bodyData['silentTime'] && bodyData['silentTime']['endDate'] && bodyData['silentTime']['endDate'].length == 5) { endDate = bodyData['silentTime']['endDate']; }
else { endDate = '23:00'; /*Defaults*/ }
if (bodyData['silentTime'] && bodyData['silentTime']['timezone'] && bodyData['silentTime']['timezone'].length == 5) { timeZone = bodyData['silentTime']['timezone']; }
else { timeZone = '-0000'; /*Defaults*/ }
if (bodyData['tags'] && bodyData['tags'].length > 0) { tags = bodyData['tags']; }
else { tags = []; /*Defaults*/ }
//format date
var now = new Date(Date.now());
startDate = twoCharString(now.getMonth()+1) + '/' + twoCharString(now.getDate()) + '/' + now.getFullYear() + ' ' + startDate + ' ' + timeZone;
var startDateGMT = new Date(startDate);
var startDateGMTString = twoCharString(startDateGMT.getUTCHours()) + ":" + twoCharString(startDateGMT.getUTCMinutes()) + ":00";
endDate = twoCharString(now.getMonth()+1) + '/' + twoCharString(now.getDate()) + '/' + now.getFullYear() + ' ' + endDate + ' ' + timeZone;
var endDateGMT = new Date(endDate);
var endDateGMTString = twoCharString(endDateGMT.getUTCHours())+":"+twoCharString(endDateGMT.getUTCMinutes())+":00";
//try to insert into device
this.deviceWrapper.APNDeviceRegisterOnDB(token,tags,startDateGMTString,endDateGMTString,0,callback);/*Create/Update device into DB*/
}else { callback(definitions.retValAccept,"token key is missing :("); }
}
/**
* Unregister APNDevice function
* @param Obj bodyData - body data recieved on request
* @param Function callback - function callback - REQUIRED
* @param Boolean callback.okay - if filled okay (true) or with errored (false).
* @param String callback.resp - response string|obj when convinient.
**/
APNDevice.prototype.APNDeviceUnregister = function APNDeviceUnregister(token,callback) {
//Check for required values
if (!token || token.length == 0) { assert.ok(false,"** APNDevice ** token is **REQUIRED** ,but is not specified."); }
//try to insert into device
this.deviceWrapper.APNDeviceUnregisterOnDB(token,callback);
}
/**
* List Devices function
* @param Obj bodyData - body data recieved on request
* @param Function callback - function callback - REQUIRED
* @param Boolean callback.okay - if filled okay (true) or with errored (false).
* @param String callback.resp - response string|obj when convinient.
**/
APNDevice.prototype.APNDeviceList = function APNDeviceList(bodyData,callback) {
//list registered devices
var order ;
if (bodyData && bodyData['order']) {
if (bodyData['order'].length == 3) { order = bodyData['order']; }
else {
callback(definitions.retValAccept,"order value contains wrong length :(");
return;
}
} else { order = 'ASC'; }
//continue
if (order == 'DSC' || order == 'ASC') { this.deviceWrapper.APNDeviceListOnDB(order,callback);/*List device in DB*/ }
else { callback(definitions.retValAccept,"order value is invalid :("); }
}
/**
* List Tags function
* @param Obj bodyData - body data recieved on request
* @param Function callback - function callback - REQUIRED
* @param Boolean callback.okay - if filled okay (true) or with errored (false).
* @param String callback.resp - response string|obj when convinient.
**/
APNDevice.prototype.APNDeviceListTags = function APNDeviceListTags(bodyData,callback) {
//list tags
var order ;
if (bodyData && bodyData['order']) {
if (bodyData['order'].length == 3) { order = bodyData['order']; }
else {
callback(definitions.retValAccept,"order value contains wrong length :(");
return;
}
} else { order = 'ASC'; }
//continue
if (order == 'DSC' || order == 'ASC') { this.deviceWrapper.APNDeviceListTagsOnDB(order,callback);/*List tags in DB*/ }
else { callback(definitions.retValAccept,"order value is invalid :("); }
}
/**
* List Device Register Call function
* @param Obj bodyData - body data recieved on request
* @param Function callback - function callback - REQUIRED
* @param Boolean callback.okay - if filled okay (true) or with errored (false).
* @param String callback.resp - response string|obj when convinient.
**/
APNDevice.prototype.APNDeviceListDeviceRegisterDataPoints = function APNDeviceListDeviceRegisterDataPoints(bodyData,callback) {
//device create
if (bodyData && bodyData['startDate'] && bodyData['startDate'].length > 7 &&
bodyData['endDate'] && bodyData['endDate'].length > 7) {
var startDate = bodyData['startDate'],
endDate = bodyData['endDate'];
//make sure date is in correct format and it's on GMT
var startDateGMT = new Date(startDate);
var endDateGMT = new Date(endDate);
if (startDateGMT == 'Invalid Date' || endDateGMT == 'Invalid Date') { callback(definitions.retValAccept,'start or end date is invalid'); }
else {
var startDateGMTString = startDateGMT.getUTCFullYear() + '-' + twoCharString(startDateGMT.getUTCMonth()+1) + '-' + twoCharString(startDateGMT.getUTCDate()) + ' ' + twoCharString(startDateGMT.getUTCHours())+":" + twoCharString(startDateGMT.getUTCMinutes()) + ":" + twoCharString(startDateGMT.getUTCSeconds());
var endDateGMTString = endDateGMT.getUTCFullYear() + '-' + twoCharString(endDateGMT.getUTCMonth()+1) + '-' + twoCharString(endDateGMT.getUTCDate()) + ' ' + twoCharString(endDateGMT.getUTCHours()) + ":" + twoCharString(endDateGMT.getUTCMinutes()) + ":" + twoCharString(endDateGMT.getUTCSeconds());
//
this.deviceWrapper.APNDeviceListDeviceRegisterDataPointsOnDB(startDateGMTString,endDateGMTString,callback);
}
}else { callback(definitions.retValAccept,"token key is missing :("); }
} |
/*!
* ansi-green <https://github.com/jonschlinkert/ansi-green>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var wrap = require('ansi-wrap');
module.exports = function green(message) {
return wrap(32, 39, message);
};
//# sourceMappingURL=index-compiled.js.map |
/**
* @module ember-paper
*/
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import Component from '@ember/component';
import { isPresent } from '@ember/utils';
import { htmlSafe } from '@ember/string';
import layout from '../templates/components/paper-progress-linear';
import ColorMixin from 'ember-paper/mixins/color-mixin';
function makeTransform(value) {
let scale = value / 100;
let translateX = (value - 100) / 2;
return `translateX(${translateX.toString()}%) scale(${scale.toString()}, 1)`;
}
const MODE_DETERMINATE = 'determinate';
const MODE_INDETERMINATE = 'indeterminate';
const MODE_BUFFER = 'buffer';
const MODE_QUERY = 'query';
/**
* @class PaperProgressLinear
* @extends Ember.Component
* @uses ColorMixin
*/
export default Component.extend(ColorMixin, {
layout,
tagName: 'md-progress-linear',
attributeBindings: ['mode:md-mode', 'bufferValue:md-buffer-value'],
classNames: ['md-default-theme'],
constants: service(),
mode: computed('value', {
get() {
if (this._mode !== undefined) {
return this._mode;
}
let value = this.value;
let bufferValue = this.bufferValue;
if (isPresent(value)) {
if (isPresent(bufferValue)) {
return MODE_BUFFER;
} else {
return MODE_DETERMINATE;
}
} else {
return MODE_INDETERMINATE;
}
},
set(key, value) {
return this._mode = value;
}
}),
queryModeClass: computed('mode', function() {
let mode = this.mode;
if ([MODE_QUERY, MODE_BUFFER, MODE_DETERMINATE, MODE_INDETERMINATE].includes(mode)) {
return `md-mode-${mode}`;
} else {
return '';
}
}),
bar1Style: computed('clampedBufferValue', function() {
return htmlSafe(`${this.get('constants.CSS.TRANSFORM')}: ${makeTransform(this.clampedBufferValue)}`);
}),
bar2Style: computed('clampedValue', 'mode', function() {
if (this.mode === MODE_QUERY) {
return htmlSafe('');
}
return htmlSafe(`${this.get('constants.CSS.TRANSFORM')}: ${makeTransform(this.clampedValue)}`);
}),
clampedValue: computed('value', function() {
let value = this.value;
return Math.max(0, Math.min(value || 0, 100));
}),
clampedBufferValue: computed('bufferValue', function() {
let value = this.bufferValue;
return Math.max(0, Math.min(value || 0, 100));
})
});
|
/**
* @jsx React.DOM
*/
/* not used but thats how you can use touch events
* */
//React.initializeTouchEvents(true);
/* not used but thats how you can use animation and other transition goodies
* */
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
/**
* we will use yes for true
* we will use no for false
*
* React has some built ins that rely on state being true/false like classSet()
* and these will not work with yes/no but can easily be modified / reproduced
*
* this single app uses the yes/no var so if you want you can switch back to true/false
*
* */
var yes = 'yes', no = 'no';
//var yes = true, no = false;
/* bootstrap components
* */
var Flash = ReactBootstrap.Alert;
var Btn = ReactBootstrap.Button;
var Modal = ReactBootstrap.Modal;
/* create the container object
* */
var snowUI = {};
/* create flash message
* */
snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash',
getInitialState: function() {
return {
isVisible: true
};
},
getDefaultProps: function() {
return ({showclass:'info'});
},
render: function() {
console.log(this.props);
if(!this.state.isVisible)
return null;
var message = this.props.message ? this.props.message : this.props.children;
return (
Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash},
React.DOM.p(null, message)
)
);
},
dismissFlash: function() {
this.setState({isVisible: false});
}
});
/* my little man component
* simple example
* */
snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan',
getDefaultProps: function() {
return ({divstyle:{float:'right',}});
},
render: function() {
return this.transferPropsTo(
React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}})
);
}
});
//loading div
snowUI.loading = React.createClass({displayName: 'loading',
render: function() {
console.log('loading')
return this.transferPropsTo(
React.DOM.div({key: "load", className: "loader"},
"Loading ", React.DOM.br(null),
React.DOM.div({id: "loadgif"})
)
);
}
});
//wallet component
snowUI.wallet = React.createClass({displayName: 'wallet',
componentDidUpdate: function() {
console.log('wallet')
this.props.methods.updateState({loading:false});
},
render: function() {
return this.transferPropsTo(
React.DOM.div(null)
);
}
});
//receive component
snowUI.receive = React.createClass({displayName: 'receive',
componentDidUpdate: function() {
this.props.methods.updateState({loading:false});
},
render: function() {
console.log('receive component')
return (
React.DOM.div(null)
)
}
});
//settings component
snowUI.settings = React.createClass({displayName: 'settings',
componentDidUpdate: function() {
this.props.methods.updateState({loading:false});
},
render: function() {
console.log('settings')
return (
React.DOM.div(null)
);
}
});
//inq component
snowUI.inq = React.createClass({displayName: 'inq',
componentDidUpdate: function() {
this.props.methods.updateState({loading:false});
},
render: function() {
console.log('inqueue')
return (
React.DOM.div(null)
);
}
});
//wallet select
snowUI.walletSelect = React.createClass({displayName: 'walletSelect',
componentDidMount: function() {
this.updateSelect();
},
componentDidUpdate: function() {
this.updateSelect();
},
componentWillUpdate: function() {
$("#walletselect").selectbox("detach");
},
updateSelect: function() {
var _this = this
$("#walletselect").selectbox({
onChange: function (val, inst) {
_this.props.route(val)
},
effect: "fade"
});
//console.log('wallet select updated')
},
render: function() {
var wallets;
if(this.props.wally instanceof Array) {
var wallets = this.props.wally.map(function (w) {
return (
React.DOM.option({key: w.key, value: snowPath.wallet + '/' + w.key}, w.name)
);
});
}
if(this.props.section === snowPath.wallet) {
var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet;
} else {
var _df = this.props.section;
}
//console.log(_df)
return this.transferPropsTo(
React.DOM.div({className: "list"},
React.DOM.div({className: "walletmsg", style: {display:'none'}}),
React.DOM.select({onChange: this.props.route, id: "walletselect", value: _df},
wallets,
React.DOM.optgroup(null),
React.DOM.option({value: snowPath.wallet + '/new'}, snowtext.menu.plus.name),
React.DOM.option({value: snowPath.wallet}, snowtext.menu.list.name),
React.DOM.option({value: snowPath.receive}, snowtext.menu.receive.name),
React.DOM.option({value: snowPath.settings}, snowtext.menu.settings.name),
React.DOM.option({value: snowPath.inq}, snowtext.menu.inqueue.name)
)
)
);
}
});
var UI = React.createClass({displayName: 'UI',
getInitialState: function() {
/**
* initialize the app
* the plan is to keep only active references in root state.
* we should use props for the fill outs
* */
return {
section: this.props.section || 'wallet',
moon: this.props.moon || false,
wallet: this.props.wallet || false,
loading: true,
mywallets: [],
};
},
componentDidMount: function() {
//stop the loader
this.setState({loading: false});
//grab our initial data
$.get("/api/snowcoins/local/contacts/?setnonce=true")
.done(function( resp,status,xhr ) {
_csrf = xhr.getResponseHeader("x-snow-token");
console.log('wally',resp.wally)
this.setState({mywallets:resp.wally});
}.bind(this));
},
componentWillReceiveProps: function(nextProps) {
if(nextProps.section)this.setState({section:nextProps.section});
if(nextProps.moon)this.setState({moon:nextProps.moon});
if(nextProps.wallet)this.setState({wallet:nextProps.wallet});
//wallet list
if(nextProps.mywallets)this.setState({mywallets:nextProps.mywallets});
if(nextProps.loading) {
this.setState({loading:nextProps.loading})
} else {
this.setState({loading:true})
}
return false;
},
updateState: function(prop,value) {
this.setState({prop:value});
return false
},
loader: function() {
this.setState({loading:!this.state.loading});
return false
},
changeTheme: function() {
var mbody = $('body');
if(mbody.hasClass('themeable-snowcoinslight')==true) {
mbody.removeClass('themeable-snowcoinslight');
} else {
mbody.addClass('themeable-snowcoinslight');
}
return false
},
valueRoute: function(route) {
bone.router.navigate(snowPath.root + route, {trigger:true});
return false
},
hrefRoute: function(route) {
route.preventDefault();
bone.router.navigate(snowPath.root + $(route.target)[0].pathname, {trigger:true});
return false;
},
render: function() {
var loader = this.state.loading ? React.DOM.div({key: "loadme"}, snowUI.loading(null)) :'';
var methods = {
hrefRoute: this.hrefRoute,
valueRoute: this.valueRoute,
updateState: this.updateState,
loader: this.loader,
}
var comp = {}
comp[snowPath.wallet]=snowUI.wallet;
comp[snowPath.receive]=snowUI.receive;
comp[snowPath.settings]=snowUI.settings;
comp[snowPath.inq]=snowUI.inq;
var mycomp = comp[this.state.section]
return this.transferPropsTo(
React.DOM.div(null,
React.DOM.div({id: "snowpi-body"},
React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}),
React.DOM.div({id: "walletbar", className: "affix"},
React.DOM.div({className: "wallet"},
React.DOM.div({className: "button-group"},
Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name),
React.DOM.ul({className: "dropdown-menu", role: "menu"},
React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet + '/new'}, snowtext.menu.plus.name)),
React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet}, snowtext.menu.list.name)),
React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.receive}, snowtext.menu.receive.name)),
React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.settings}, snowtext.menu.settings.name)),
React.DOM.li({className: "divider"}),
React.DOM.li({className: "nav-item-snowcat"}),
React.DOM.li({className: "divider"}),
React.DOM.li(null,
React.DOM.div(null,
React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})),
React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.inq, className: "nav-item-inq"})),
React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))),
React.DOM.div({className: "clearfix"})
)
)
)
)
),
snowUI.walletSelect({route: this.valueRoute, section: this.state.section, wallet: this.state.wallet, wally: this.state.mywallets}),
React.DOM.div({className: "logo"}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"}))
),
React.DOM.div({className: "container-fluid"},
React.DOM.div({id: "menuspy", className: "dogemenu col-xs-1 col-md-2", 'data-spy': "affix", 'data-offset-top': "0"}
),
React.DOM.div({id: "menuspyhelper", className: "dogemenu col-xs-1 col-md-2"}),
React.DOM.div({className: "dogeboard col-xs-11 col-md-10"},
snowUI.AppInfo(null),
React.DOM.div({className: "dogeboard-left col-xs-12 col-md-12"},
ReactCSSTransitionGroup({transitionName: "loading", component: React.DOM.div},
loader
),
mycomp({methods: methods})
)
)
)
/* end snowpi-body */
)
)
);
}
});
//app info
snowUI.AppInfo = React.createClass({displayName: 'AppInfo',
render: function() {
return (
React.DOM.div({id: "easter-egg", style: {display:'none'}},
React.DOM.div(null,
React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"},
React.DOM.h4(null, "Get Snowcoins"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")),
React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz"))
),
React.DOM.h4(null, "Built With"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose"))
),
React.DOM.h4(null, "Donate"),
React.DOM.div({className: "row"},
React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")),
React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")),
React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")),
React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")),
React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin"))
)
),
React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"},
React.DOM.h4(null, "Digital Coin Wallets"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin "))
),
React.DOM.h4(null, "Links"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/snowcoins", target: "_blank"}, "/r/snowcoins")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/dogecoin", target: "_blank"}, "/r/dogecoin"))
)
),
React.DOM.div({className: "clearfix"})
)
)
);
}
});
|
"use strict";
import Id from "./Id";
if ( __CLIENT__ ) {
var THREE = require( "three" );
}
/**
* Entity
*/
export default class Entity extends Id {
static ID = 0;
/**
* Config
* @type {{}}
* @protected
*/
_config = {};
/**
* Create an entity
* @param {String} name
* @param {Object} [config]
*/
constructor( name, config = {} ) {
super( name );
// Config
this._config = config;
// Physics
this._body = null;
// Object 3D
this._object3D = null;
// Components
this._components = [];
}
/**
* Config
* @returns {{}}
*/
get config() {
return this._config;
}
/**
* Scene
* @returns {Scene}
*/
get scene() {
return this._scene;
}
/**
* Scene
* @params {Scene} scene
*/
set scene( scene ) {
this._scene = scene;
}
/**
* Physics body
* @returns {CANNON.body}
*/
get body() {
return this._body;
}
/**
* Object 3D
* @returns {THREE.Object3D}
*/
get object3D() {
return this._object3D;
}
/**
* Components
* @returns {Array<Component>}
*/
get components() {
return this._components;
}
/*get position() {
return this._body ? this._body.position : this._object3D.position;
}
get rotation() {
return this._body ? this._body.position : this._object3D.rotation;
}
get quaternion() {
return this._body ? this._body.position : this._object3D.quaternion;
}*/
/**
* Add an component to the entity
* @param {Component} component
*/
addComponent( component ) {
if ( !component ) {
throw new Error( "You can't add a null component" );
}
component.entity = this;
this._components.push( component );
if ( this._scene && this._scene.initialized ) {
component.init();
}
}
/**
* Remove an component from the entity
* @param {Component} component
*/
removeComponent( component ) {
if ( !component ) {
throw new Error( "You can't remove a null component" );
}
if ( component.entity != this ) {
throw new Error( `You can't remove component ${component.name} from ${this.name} as this scene does not own the component` );
}
component.entity = null;
this._components.splice( this._components.indexOf( component ), 1 );
}
/**
* Add THREE.Object3D object to the stage (THREE.Scene)
* @param {THREE.Object3D} object3D
*/
addObject( object3D ) {
this._object3D.add( object3D );
}
/**
* Remove THREE.Object3D object from the stage (THREE.Scene)
* @param {THREE.Object3D} object3D
*/
removeObject( object3D ) {
this._object3D.remove( object3D );
}
init() {
if ( this._body ) {
this._body.__id = this._name;
this._scene.physics.addBody(this._body);
}
if ( __CLIENT__ ) {
this._object3D = new THREE.Object3D();
this._scene.stage.add( this._object3D );
}
this._components.forEach( component => component.init() );
}
/**
* Update the entity
* @param {number} dt - Time delta since last update
*/
update( dt ) {
// Entities update
this._components.forEach( component => component.update( dt ) );
if ( __CLIENT__ ) {
if ( this._body ) {
this._object3D.position.copy( this._body.position );
this._object3D.quaternion.copy( this._body.quaternion );
}
}
}
/**
* Destroy an entity
*/
dispose() {
if ( this._body ) {
this._scene.physics.removeBody(this.body);
}
this._components.forEach( components => components.dispose() );
if (__CLIENT__) {
this._scene.stage.remove( this._object3D );
this._object3D = null;
}
this._scene = null;
}
} |
(function(/*! Stitch !*/) {
if (!this.require) {
var modules = {}, cache = {};
var require = function(name, root) {
var path = expand(root, name), indexPath = expand(path, './index'), module, fn;
module = cache[path] || cache[indexPath];
if (module) {
return module;
} else if (fn = modules[path] || modules[path = indexPath]) {
module = {id: path, exports: {}};
cache[path] = module.exports;
fn(module.exports, function(name) {
return require(name, dirname(path));
}, module);
return cache[path] = module.exports;
} else {
throw 'module ' + name + ' not found';
}
};
var expand = function(root, name) {
var results = [], parts, part;
// If path is relative
if (/^\.\.?(\/|$)/.test(name)) {
parts = [root, name].join('/').split('/');
} else {
parts = name.split('/');
}
for (var i = 0, length = parts.length; i < length; i++) {
part = parts[i];
if (part == '..') {
results.pop();
} else if (part != '.' && part != '') {
results.push(part);
}
}
return results.join('/');
};
var dirname = function(path) {
return path.split('/').slice(0, -1).join('/');
};
this.require = function(name) {
return require(name, '');
};
this.require.define = function(bundle) {
for (var key in bundle) {
modules[key] = bundle[key];
}
};
this.require.modules = modules;
this.require.cache = cache;
}
return this.require.define;
}).call(this)({
"models/orm": function(exports, require, module) {
module.exports = {orm: true};
window.ormCount = window.ormCount || 0;
window.ormCount += 1;
}, "models/user": function(exports, require, module) {
var ORM = require('models/orm');
var User = function(name){
this.name = name;
};
User.ORM = ORM;
module.exports = User;
}, "models/person": function(exports, require, module) {
var ORM = require('models/orm');
}, "index": function(exports, require, module) {
require('models/user');
require('models/person');
// Do some stuff
}
}); |
import { Map } from 'immutable';
import { INITIALIZE_GAMES,
NEW_GAME,
MAKE_MOVE,
MOVE_CURSOR,
SET_GAME_EVALUATOR,
SET_INITIAL_BOOK_MOVES,
SET_BOOK_MOVES,
SET_SCORE_DATA,
SET_HIGHLIGHT_SAN,
} from '../constants';
import {
gameFromImmutable,
GameState,
} from '../store/model/gameState';
export default function gameplay(state = Map(), action) {
let gameID = null;
let clientID = null;
let gameData = null;
let gameState = null;
if (action.payload) {
clientID = action.payload.clientID;
gameID = action.payload.gameID;
if (gameID && clientID) {
gameData = state.getIn([clientID, 'games', gameID]);
if (gameData) {
gameState = gameFromImmutable(gameData);
}
}
}
switch (action.type) {
case INITIALIZE_GAMES:
return state.setIn([clientID, 'games'], Map());
case NEW_GAME: // eslint-disable-line no-case-declarations
if (!state.get(clientID)) {
state = state.set(clientID, Map()); // eslint-disable-line no-param-reassign
}
if (!state.get(clientID).get('games')) {
state = state.setIn([clientID, 'games'], Map()); // eslint-disable-line no-param-reassign
}
const newGameObject = new GameState();
if (action.payload.level) {
newGameObject.setLevel(action.payload.level);
}
if (action.payload.white) {
newGameObject.setWhite(action.payload.white);
}
if (action.payload.black) {
newGameObject.setBlack(action.payload.black);
}
if (newGameObject.black === 'YOU' && newGameObject.white === 'COMPUTER') {
newGameObject.setEvaluator('book');
}
return state.setIn([clientID, 'games', gameID], newGameObject.toImmutable());
case MAKE_MOVE:
if (gameState) {
gameState.makeMove(action.payload.move, action.payload.evaluator);
// eslint-disable-next-line no-param-reassign
state = state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
case MOVE_CURSOR:
if (gameState) {
gameState.moveCursor(action.payload.cursor);
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
case SET_GAME_EVALUATOR:
if (gameState) {
gameState.setEvaluator(action.payload.evaluator);
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
case SET_INITIAL_BOOK_MOVES:
if (gameState) {
gameState.setInitialBookMoves(action.payload.initialBookMoves);
}
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
case SET_BOOK_MOVES: {
if (gameState) {
gameState.setBookMoves(action.payload.books);
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
}
case SET_SCORE_DATA:
if (gameState) {
gameState.setScoreData(action.payload.cursor,
action.payload.score,
action.payload.mate,
action.payload.pv,
action.payload.bestMove);
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
case SET_HIGHLIGHT_SAN: {
if (gameState) {
gameState.setHighlightSAN(action.payload.san);
return state.setIn([clientID, 'games', gameID], gameState.toImmutable());
}
return state;
}
default:
return state;
}
}
|
import DS from 'ember-data';
import Ember from 'ember';
export default DS.ActiveModelAdapter.extend({
namespace: 'api',
channelService: Ember.inject.service("channel"),
channel: null,
setupChannel: function(){
this.set('channel', this.get('channelService').connect('todos','list', {}));
this.channel.on("todo", todo => {
console.log("Received updated TODO!");
console.log(todo);
this.get('store').push('todo', todo.todo);
});
this.channel.on("deleted_todo", todo => {
console.log("Received deleted TODO!");
console.log(todo);
let record = this.get('store').getById('todo', todo.todo.id);
if(record) {
this.get('store').unloadRecord(record);
}
});
}.on('init')
});
|
import {curry} from 'ramda'
export const createEnvelope = curry((ctx: Object, patch: Object) => {
const envelope = ctx.createGain()
envelope.gain.value = 0.0;
return {
triggerAttack() {
var now = ctx.currentTime;
var envAttackEnd = now + (patch.attack/20.0);
envelope.gain.setValueAtTime( 0.0, now );
envelope.gain.linearRampToValueAtTime( 1.0, envAttackEnd );
envelope.gain.setTargetAtTime( (patch.sustain/100.0), envAttackEnd, (patch.decay/100.0)+0.001 );
},
triggerRelease() {
var now = ctx.currentTime;
var release = now + (patch.release/10.0);
envelope.gain.cancelScheduledValues(now);
envelope.gain.setValueAtTime( envelope.gain.value, now );
envelope.gain.setTargetAtTime(0.0, now, (patch.release/100));
return release
},
input: envelope,
connect(node) { envelope.connect(node) }
}
})
|
import 'angular';
import config from './blocks.config.js';
import logger from './blocks.logger.js';
import exception from './blocks.exception.js';
export default angular.module('app.blocks', [
//Module
config.name,
//Blocks
logger.name, exception.name
]); |
var questionData= require('../questions.json')
exports.view = function(req, res) {
res.render('teacherQueue',questionData);
} |
/*
weighted.test.js - WeightedSnapshot test
The MIT License (MIT)
Copyright (c) 2014-2019 Tristan Slominski
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.
*/
"use strict";
const WeightedSnapshot = require('./weighted.js');
expect.extend(
{
toBeBetween(received, floor, ceiling)
{
const pass = received < ceiling && received > floor;
if (pass)
{
return (
{
message: () => `expected ${received} not to be between ${floor} and ${ceiling}`,
pass: true
}
);
}
return (
{
message: () => `expected ${received} to be between ${floor} and ${ceiling}`,
pass: false
}
);
}
}
);
describe("WeightedSnapshot", () =>
{
let snapshot, WEIGHTED_ARRAY;
beforeEach(() =>
{
WEIGHTED_ARRAY =
[
{
value: 5,
weight: 1
},
{
value: 1,
weight: 2
},
{
value: 2,
weight: 3
},
{
value: 3,
weight: 2
},
{
value: 4,
weight: 2
}
];
snapshot = new WeightedSnapshot(WEIGHTED_ARRAY);
}
);
it("small quantiles are first values", () =>
{
expect(snapshot.quantile(0.0)).toBeBetween(0.9, 1.1);
}
);
it("big quantiles are the last value", () =>
{
expect(snapshot.quantile(1.0)).toBeBetween(4.9, 5.1);
}
);
it("has median", () =>
{
expect(snapshot.median()).toBeBetween(2.9, 3.1);
}
);
it("has percentile75", () =>
{
expect(snapshot.percentile75()).toBeBetween(3.9, 4.1);
}
);
it("has percentile95", () =>
{
expect(snapshot.percentile95()).toBeBetween(4.9, 5.1);
}
);
it("has percentile98", () =>
{
expect(snapshot.percentile98()).toBeBetween(4.9, 5.1);
}
);
it("has percentile99", () =>
{
expect(snapshot.percentile99()).toBeBetween(4.9, 5.1);
}
);
it("has percentile999", () =>
{
expect(snapshot.percentile999()).toBeBetween(4.9, 5.1);
}
);
it("has values", () =>
{
expect(snapshot.values).toEqual([1, 2, 3, 4, 5]);
}
);
it("has size", () =>
{
expect(snapshot.size()).toBe(5);
}
);
it("calculates the minimum value", () =>
{
expect(snapshot.min()).toBe(1);
}
);
it("calculates the maximum value", () =>
{
expect(snapshot.max()).toBe(5);
}
);
it("calculates the mean value", () =>
{
expect(snapshot.mean()).toBe(2.7);
}
);
it("calculates the standard deviation", () =>
{
expect(snapshot.standardDeviation()).toBeBetween(1.2687, 1.2689);
}
);
describe("empty snapshot", () =>
{
beforeEach(() =>
{
snapshot = new WeightedSnapshot([]);
}
);
it("calculates a minimum of 0", () =>
{
expect(snapshot.min()).toBe(0);
}
);
it("calculates a maximum of 0", () =>
{
expect(snapshot.max()).toBe(0);
}
);
it("calculates a mean of 0", () =>
{
expect(snapshot.mean()).toBe(0);
}
);
it("calculates a standard deviation of 0", () =>
{
expect(snapshot.standardDeviation()).toBe(0);
}
);
});
describe("singleton snapshot", () =>
{
beforeEach(() =>
{
snapshot = new WeightedSnapshot(
[
{
value: 1,
weight: 1
}
]
);
}
);
it("calculates a standard deviation of 0", () =>
{
expect(snapshot.standardDeviation()).toBe(0);
}
);
});
describe("low weights", () =>
{
beforeEach(() =>
{
snapshot = new WeightedSnapshot(
[
{
value: 1,
weight: Number.MIN_VALUE
},
{
value: 2,
weight: Number.MIN_VALUE
},
{
value: 3,
weight: Number.MIN_VALUE
}
]
);
}
);
it("no overflow", () =>
{
expect(snapshot.mean()).toBe(2);
}
);
});
});
|
// Javascript file used to change slide //
$(function() {
/**
* Declaration of the carousel
* @return {void}
*/
var slideShow = $('.carousel');
slideShow.carousel('pause');
/**
* Event to previous and next slide
* @return {void}
*/
$('#prevSlide').on('click', prevSlide);
$('#nextSlide').on("click", nextSlide);
});
/**
* Previous slide
* @return {void}
*/
remotePrev = function() {
$('.carousel').carousel('prev');
}
/**
* Emit to the server
* @return {void}
*/
prevSlide = function() {
socket.emit('prevSlide');
}
/**
* Next slide
* @return {void}
*/
remoteNext = function() {
$('.carousel').carousel('next');
}
/**
* Emit to the server
* @return {void}
*/
nextSlide = function() {
socket.emit('nextSlide');
} |
import React from 'react';
import Portal from './Portal';
import Position from './Position';
import RootCloseWrapper from './RootCloseWrapper';
import elementType from 'react-prop-types/lib/elementType';
/**
* Built on top of `<Position/>` and `<Portal/>`, the overlay component is great for custom tooltip overlays.
*/
class Overlay extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {exited: !props.show};
this.onHiddenListener = this.handleHidden.bind(this);
this.updatePosition = this.updatePosition.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.show) {
this.setState({exited: false});
} else if (!nextProps.transition) {
// Otherwise let handleHidden take care of marking exited.
this.setState({exited: true});
}
}
updatePosition() {
if (this.refs && this.refs.position) {
this.refs.position.updatePosition(this.refs.position.getTarget());
}
}
render() {
let {
container
, containerPadding
, target
, offset
, placement
, shouldUpdatePosition
, rootClose
, children
, transition: Transition
, portalClassName
, ...props } = this.props;
// Don't un-render the overlay while it's transitioning out.
const mountOverlay = props.show || (Transition && !this.state.exited);
if (!mountOverlay) {
// Don't bother showing anything if we don't have to.
return null;
}
let child = children;
// Position is be inner-most because it adds inline styles into the child,
// which the other wrappers don't forward correctly.
child = (
<Position ref="position" {...{container, containerPadding, target, offset, placement, shouldUpdatePosition}}>
{child}
</Position>
);
if (Transition) {
let { onExit, onExiting, onEnter, onEntering, onEntered } = props;
// This animates the child node by injecting props, so it must precede
// anything that adds a wrapping div.
child = (
<Transition
in={props.show}
transitionAppear
onExit={onExit}
onExiting={onExiting}
onExited={this.onHiddenListener}
onEnter={onEnter}
onEntering={onEntering}
onEntered={onEntered}
>
{child}
</Transition>
);
}
// This goes after everything else because it adds a wrapping div.
if (rootClose) {
child = (
<RootCloseWrapper onRootClose={props.onHide}>
{child}
</RootCloseWrapper>
);
}
return (
<Portal className={portalClassName} container={container}>
{child}
</Portal>
);
}
handleHidden(...args) {
this.setState({exited: true});
if (this.props.onExited) {
this.props.onExited(...args);
}
}
}
Overlay.propTypes = {
...Portal.propTypes,
...Position.propTypes,
/**
* Set the visibility of the Overlay
*/
show: React.PropTypes.bool,
/**
* Specify whether the overlay should trigger `onHide` when the user clicks outside the overlay
*/
rootClose: React.PropTypes.bool,
/**
* A Callback fired by the Overlay when it wishes to be hidden.
*
* __required__ when `rootClose` is `true`.
*
* @type func
*/
onHide(props, ...args) {
let propType = React.PropTypes.func;
if (props.rootClose) {
propType = propType.isRequired;
}
return propType(props, ...args)
},
/**
* A `<Transition/>` component used to animate the overlay changes visibility.
*/
transition: elementType,
/**
* Callback fired before the Overlay transitions in
*/
onEnter: React.PropTypes.func,
/**
* Callback fired as the Overlay begins to transition in
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the Overlay finishes transitioning in
*/
onEntered: React.PropTypes.func,
/**
* Callback fired right before the Overlay transitions out
*/
onExit: React.PropTypes.func,
/**
* Callback fired as the Overlay begins to transition out
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the Overlay finishes transitioning out
*/
onExited: React.PropTypes.func,
/**
* ClassName to use on the Portal element
*/
portalClassName: React.PropTypes.string
};
export default Overlay;
|
"use strict";
var escapeHTML = require("hexo-util").escapeHTML;
hexo.extend.helper.register("escapeHTML", (str) => escapeHTML(str));
|
/* jshint node:true */
var runCommand = require('ember-addon-genie/lib/utils/run-command');
module.exports = {
init: function() {
this._previousVersion = require('../package.json').version;
},
afterPublish: function(project, versions) {
runCommand('ember github-pages:commit --message "Released ' + versions.next + '"', true);
runCommand('git push origin gh-pages:gh-pages', true);
},
publish: true
};
|
import { select } from 'd3';
export default function layout(element) {
const containers = {
main: select(element)
.append('div')
.classed('query-overview', true)
};
containers.topRow = containers.main.append('div').classed('qo-row qo-row--top', true);
containers.controls = containers.topRow
.append('div')
.classed('qo-component qo-component--controls', true);
containers.chart = containers.controls
.append('div')
.classed('qo-component qo-component--chart', true);
containers.bottomRow = containers.main.append('div').classed('qo-row qo-row--bottom', true);
containers.listing = containers.bottomRow
.append('div')
.classed('qo-component qo-component--listing', true);
return containers;
}
|
import React from 'react';
import { connect } from 'react-redux';
import { navigate } from '../../../actions/route';
import _ from 'lodash';
import $ from 'jquery';
import D3ForceLayout from './D3ForceLayout';
import ComponentNode from './ComponentNode';
import ComponentLink from './ComponentLink';
class ComponentsGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
forceLayout: new D3ForceLayout({
renderCallback: () => {
this.forceUpdate();
},
}),
};
}
componentDidMount() {
const { components, depends } = this.props;
const { forceLayout } = this.state;
forceLayout.containerDOM = this.svgRef;
forceLayout.addNodes(
components.map(c => this._componentToNode(c))
);
forceLayout.addLinks(
depends.map(l => this._dependToLink(l))
);
this.resizeHandler = () => {
if (this.svgRef) {
const svgWidth = $(this.svgRef).width();
const svgHeight = $(this.svgRef).height();
this.state.forceLayout.forceSimulationSize = {
width: svgWidth,
height: svgHeight,
};
}
};
window.addEventListener('resize', this.resizeHandler);
this.resizeHandler();
}
componentWillReceiveProps(nextProps) {
const n = nextProps;
const o = this.props;
// If Component Created Or Deleted, we can't really handle it now
// (and it's pretty rare occation i would say)
if (n.components.length !== o.components.length) {
location.reload();
}
// Same with links
if (n.depends.length !== o.depends.length) {
location.reload();
}
this.state.forceLayout.updateNodes(
_.filter(n.components, (component) => component.statusChanged)
.map((component) => this._componentToNode(component))
);
this.forceUpdate();
}
componentWillUnmount() {
window.removeEventListener('resize', this.resizeHandler);
}
_ComponentDependencyOnClick(component) {
if (this.cd.firstComponent) {
this._ComponentDependencyCreate(this.cd.firstComponent, component);
delete this.isCreatingComponentDependency;
delete this.cd;
} else {
this.cd.firstComponent = component;
window.alert('click dependency end component'); // eslint-disable-line
}
}
_ComponentDependencyStart() {
this.isCreatingComponentDependency = true;
this.cd = {};
window.alert('click dependency start component'); // eslint-disable-line
}
_ComponentDependencyCreate(firstComponent, secondComponent) {
$.post('/api/cypher/relate', {
firstId: firstComponent.id,
type: 'DEPEND',
secondId: secondComponent.id,
}).done(() => {
window.alert('Change Saved!'); // eslint-disable-line
window.location.reload();
})
.fail((e) => {
console.error(e); // eslint-disable-line
});
}
_componentToNode(c) {
return {
id: c.id,
size: 40,
type: 'Component',
data: c,
};
}
_dependToLink(l) {
return {
source: Number(l.startNode),
target: Number(l.endNode),
type: 'depend',
id: l.id,
data: l,
};
}
drawLinks() {
return this.state.forceLayout.links.map((link) => (
<ComponentLink
key={link.id}
link={link}
/>
));
}
drawNodes() {
return this.state.forceLayout.nodes.map((node) => (
<ComponentNode
key={node.id}
node={node}
onClick={() => {
if (!this.isCreatingComponentDependency) {
this.props.navigate(`/components/${node.id}`);
} else {
this._ComponentDependencyOnClick(node.data);
}
}}
/>
));
}
render() {
return (
<div
style={{
padding: '20px',
boxSizing: 'border-box',
width: '100%',
height: '100%',
}}
>
<button
className="btn btn-sm btn-primary"
style={{
position: 'absolute',
margin: '10px',
}}
onClick={() => this._ComponentDependencyStart()}
>
Connnect
</button>
<svg
ref={(c) => { this.svgRef = c; }}
width="100%"
height="1000px"
style={{
border: '1px solid black',
boxSizing: 'border-box',
}}
>
<defs>
<marker
id="arrowMarker"
viewBox="0 0 10 10"
refX="5"
refY="5"
markerWidth="4"
markerHeight="4"
orient="auto"
strokeWidth="5"
>
<path d="M 0 0 L 10 5 L 0 10 z" />
</marker>
</defs>
{this.drawLinks()}
{this.drawNodes()}
</svg>
</div>
);
}
}
ComponentsGraph.propTypes = {
components: React.PropTypes.array,
groups: React.PropTypes.array,
contains: React.PropTypes.array,
depends: React.PropTypes.array,
// Actions
navigate: React.PropTypes.func,
};
export default connect(null, { navigate })(ComponentsGraph);
|
/*!
* datastructures-js
* directedGraph
* Copyright(c) 2015 Eyas Ranjous <eyas@eyasranjous.info>
* MIT Licensed
*/
function directedGraph() {
'use strict';
var self = {},
vertices = [], // graph nodes
directions = [], // graph directions [][]
verticesCount = 0,
removeElementFromArray = function(arr, v) {
if (isNaN(parseInt(v))) {
delete arr[v];
}
else {
arr.splice(v, 1);
}
};
self.addVertex = function(v) {
if (vertices[v] === undefined) {
vertices[v] = true;
verticesCount++;
}
};
self.removeVertex = function(v) {
// remove the vertex from vertices
if (vertices[v]) {
removeElementFromArray(vertices, v);
verticesCount--;
}
// remove the directions from vertex
if (directions[v] !== undefined) {
removeElementFromArray(directions, v);
}
// remove the directions to vertex
for (var vertex in directions) {
if (directions[vertex][v] && Object.keys(directions[vertex]).length === 1) {
removeElementFromArray(directions, vertex);
}
else {
removeElementFromArray(directions[vertex], v);
}
}
};
self.hasVertex = function(v) {
return vertices[v] !== undefined ? true : false;
};
self.countVertices = function() {
return verticesCount;
};
self.visit = function(func) {
var visit = function(dirs, visited, func) {
for (var vertex in dirs) {
if (dirs.hasOwnProperty(vertex) && !visited[vertex]) {
func.call(func, vertex);
visited[vertex] = true;
if (directions[vertex]) {
visit(directions[vertex], visited, func); // depth-first approach
}
}
}
};
visit(directions, [], func);
};
self.getSeparatedVertices = function() {
var separated = [],
directionsVertices = [];
this.visit(function(vertex){
directionsVertices[vertex] = true;
});
for (var v in vertices) {
if (vertices.hasOwnProperty(v) && !directionsVertices[v]) {
separated.push(v);
}
}
return separated;
};
self.addDirection = function(v1, v2, weight) {
if (vertices[v1] && vertices[v2]) {
if (directions[v1] === undefined) {
directions[v1] = [];
}
if (isNaN(parseInt(weight))) {
throw {
message: 'weight is not a valid number'
};
}
directions[v1][v2] = weight;
}
};
self.hasDirection = function(v1, v2) {
if (this.hasVertex(v1) && this.hasVertex(v2) &&
directions[v1] && directions[v1][v2] !== undefined) {
return true;
}
return false;
};
// return the weight of a direction if it exists
self.getDirectionWeight = function(v1, v2) {
return this.hasDirection(v1, v2) ? directions[v1][v2] : null;
};
self.removeDirection = function(v1, v2) {
if (this.hasDirection(v1, v2)) {
if (Object.keys(directions[v1]).length === 1) {
removeElementFromArray(directions, v1);
}
else {
removeElementFromArray(directions[v1], v2);
}
}
};
self.calculatePathWeight = function(path) {
var sum = 0;
for (var i = 0; i <= path.length - 2; i++) {
sum += directions[path[i]][path[i + 1]];
}
return sum;
};
self.findShortestPath = function(v1, v2) {
var that = this,
shortestPaths = [],
reccentPathWeight,
existingPathWeight,
findShortestPath = function(v1, v2, path, visited) {
if (visited.indexOf(v1) === -1) {
visited.push(v1); // visit the starting vertex
path.push(v1); // push the starting vertex in the path
if (v1 === v2) { // if we arrived to the destination
if (shortestPaths.length > 0) { // if there's already a shortest path
reccentPathWeight = that.calculatePathWeight(path); // calculate path weight
// calculate the existing shortest path weight
existingPathWeight = that.calculatePathWeight(shortestPaths[0]);
// reset the shortestPaths if recent path is better
if (reccentPathWeight < existingPathWeight) {
shortestPaths = [];
}
// if the recent path is better or similar then push it to shortestPaths
if (reccentPathWeight <= existingPathWeight) {
shortestPaths.push(path);
}
}
else {
shortestPaths.push(path); // no shortest path yet, then push the path
}
}
// we haven't arrived to the destination and we still have directions
else if (directions[v1] && (v1 !== v2)) {
for (var vertex in directions[v1]) {
if (directions[v1].hasOwnProperty(vertex)) {
findShortestPath(vertex, v2, path, visited); // depth-first appraoch
// slice path and visited arrays to allow to push the other directions of v1
path = path.slice(0, path.indexOf(v1) + 1);
visited = visited.slice(0, path.indexOf(v1) + 1);
}
}
}
}
};
findShortestPath(v1, v2, [], []);
return shortestPaths;
};
// export the directedGraph api
self.export = function() {
var that = this;
return {
addVertex: that.addVertex.bind(that),
hasVertex: that.hasVertex.bind(that),
removeVertex: that.removeVertex.bind(that),
countVertices: that.countVertices.bind(that),
getSeparatedVertices: that.getSeparatedVertices.bind(that),
addDirection: that.addDirection.bind(that),
hasDirection: that.hasDirection.bind(that),
getDirectionWeight: that.getDirectionWeight.bind(that),
removeDirection: that.removeDirection.bind(that),
visit: that.visit.bind(that),
findShortestPath: that.findShortestPath.bind(that),
};
};
return self;
}
module.exports = directedGraph; |
import {route} from 'part:@lyra/base/router'
import LyraVision from './LyraVision'
import VisionIcon from './components/VisionIcon'
export default {
router: route('/*'),
name: 'vision',
title: 'Vision',
icon: VisionIcon,
component: LyraVision
}
|
/* eslint-env mocha */
import expect from 'expect';
import React from 'react';
import { render } from '../../__tests__/render';
import { CardMedia } from '../';
describe('Card', () => {
describe('CardMedia', () => {
it('should render a div with the card media css class', () => {
const output = render(<CardMedia />);
expect(output.type).toBe('div');
expect(output.props.className).toInclude('mdl-card__media');
});
it('should allow custom css classes', () => {
const output = render(<CardMedia className="my-media" />);
expect(output.props.className)
.toInclude('mdl-card__media')
.toInclude('my-media');
});
it('should render with the children', () => {
const element = (
<CardMedia>
<img src="test.png" />
</CardMedia>
);
const output = render(element);
expect(output.props.children)
.toEqual(<img src="test.png" />);
});
});
});
|
import $ from 'jquery';
import BaseRoute from '../base-route';
/**
* Route to be created for handling modules
* @class API.Modules
* @constructor
* @extends Ember.Route
*/
export default BaseRoute.extend({
/**
* Fetches modules's JSON at: `${this.get('fountainhead.apiNamespace')}/modules/${params.file_id}.json`
* @method model
* @param {Object} params
* @param {string} params.module_id Name of this class, use to fetch data
* @return {Promise} jQuery ajax promise
*/
model(params) {
return $.ajax(`${this.get('fountainhead.apiNamespace')}/modules/${params.module_id}.json`);
}
});
|
// Copyright 2014, Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.
var WebDriverManager = require('../../../');
var AbstractClientDecorator = require('preceptor').AbstractClientDecorator;
var Promise = require('promise');
var utils = require('preceptor-core').utils;
var istanbul = require('istanbul');
var minimatch = require('minimatch');
var _ = require('underscore');
/**
* @class WebDriverClientDecorator
* @extends AbstractClientDecorator
*
* @constructor
*
* @property {Driver} _instance
* @property {WebDriverManager} _webDriverManager
* @property {WebDriverContainer} _webDriverContainer
*/
var WebDriverClientDecorator = AbstractClientDecorator.extend(
{
/**
* Initializes the instance
*
* @method initialize
*/
initialize: function () {
this.getOptions().configuration = utils.deepExtend({}, [
{
"isolation": false,
"client": {},
"server": {}
},
this.getConfiguration()
]);
this.__super();
this._webDriverManager = new WebDriverManager();
},
/**
* Setup of web-driver
*
* @method _setup
* @return {Promise}
* @private
*/
_setup: function () {
var webDriverContainer,
server,
client;
webDriverContainer = this.getWebDriverManager().generate(this.getConfiguration());
server = webDriverContainer.getServer();
client = webDriverContainer.getClient();
this._webDriverContainer = webDriverContainer;
return server.setup(client.getCapabilities()).then(function () {
return client.start();
}).then(function () {
var capabilities = client.getCapabilities(),
id = [];
if (capabilities.browserName) {
id.push(capabilities.browserName);
}
if (capabilities.version) {
id.push(capabilities.version);
}
global.PRECEPTOR_WEBDRIVER = {
"driver": client.getInstance(),
"browserName": capabilities.browserName,
"browserVersion": capabilities.version,
"browser": id.join('_'),
"clientName": client.getType(),
"serverName": server.getType(),
"collectCoverage": this.collectCoverage.bind(this)
};
}.bind(this));
},
/**
* Tear-down of web-driver
*
* @method _tearDown
* @return {Promise}
* @private
*/
_tearDown: function () {
var webDriverContainer = this._webDriverContainer;
return this.collectCoverage().then(function () {
return webDriverContainer.getClient().stop().then(function () {
return webDriverContainer.getServer().tearDown();
});
}).then(function () {
delete global.PRECEPTOR_WEBDRIVER;
});
},
/**
* Collects the coverage-report when requested
*
* @returns {Promise}
*/
collectCoverage: function () {
var coverageVar,
coverageObj;
// Should remote coverage be retrieved?
coverageObj = this._webDriverContainer.getCoverage();
if (coverageObj.isActive()) {
// Load remote coverage
coverageVar = coverageObj.getCoverageVar();
return this._webDriverContainer.getClient().loadCoverage(coverageVar).then(function (coverage) {
var collector, excludes;
// Filter coverage
excludes = coverageObj.getExcludes();
if (excludes && (excludes.length !== 0)) {
coverage = this._filterCoverage(coverage, excludes);
}
// Mapping
if (coverageObj.hasMapping()) {
coverage = this._mapCoverage(coverage, coverageObj.getMapping());
}
// Combine local and remote coverage
collector = new istanbul.Collector();
collector.add(global.__preceptorCoverage__ || {});
collector.add(coverage);
// Set new Preceptor coverage
global.__preceptorCoverage__ = collector.getFinalCoverage() || {};
}.bind(this));
} else {
return Promise.resolve();
}
},
/**
* Filters the coverage report according to excludes
*
* @param {object} coverage
* @param {string[]} excludes
* @returns {object}
* @private
*/
_filterCoverage: function (coverage, excludes) {
var keys = _.keys(coverage),
result = {};
_.each(keys, function (key) {
var allowed = true;
_.each(excludes, function (exclude) {
allowed = allowed && !minimatch(key, exclude);
});
if (allowed) {
result[key] = coverage[key];
}
});
return result;
},
/**
* Maps coverage paths to a new path
*
* @param {object} coverage
* @param {object[]} mappingList
* @returns {object}
* @private
*/
_mapCoverage: function (coverage, mappingList) {
var keys = _.keys(coverage),
result = {};
_.each(keys, function (key) {
var path = key;
// Update paths
_.each(mappingList, function (mapping) {
path = path.replace(new RegExp(mapping.from), mapping.to);
});
// Copy coverage
result[path] = coverage[key];
// Replace path in child
if (result[path].path) {
result[path].path = path;
}
});
return result;
},
/**
* Gets the web-driver manager
*
* @method getWebDriverManager
* @return {WebDriverManager}
*/
getWebDriverManager: function () {
return this._webDriverManager;
},
/**
* Should tests be run in isolation?
*
* @method inIsolation
* @return {boolean}
*/
inIsolation: function () {
return this.getConfiguration().isolation;
},
/**
* Processes the begin of the testing environment
*
* @method processBefore
* @return {Promise}
*/
processBefore: function () {
if (!this.inIsolation()) {
return this._setup();
} else {
return Promise.resolve();
}
},
/**
* Processes the end of the testing environment
*
* @method processAfter
* @return {Promise}
*/
processAfter: function () {
if (!this.inIsolation()) {
return this._tearDown();
} else {
return Promise.resolve();
}
},
/**
* Processes the beginning of a test
*
* @method processBeforeTest
* @return {Promise}
*/
processBeforeTest: function () {
if (this.inIsolation()) {
return this._setup();
} else {
return Promise.resolve();
}
},
/**
* Processes the ending of a test
*
* @method processAfterTest
* @return {Promise}
*/
processAfterTest: function () {
if (this.inIsolation()) {
return this._tearDown();
} else {
return Promise.resolve();
}
}
});
module.exports = WebDriverClientDecorator;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.