code stringlengths 2 1.05M |
|---|
'use strict';
import expectThrow from '../installed_contracts/zeppelin-solidity/test//helpers/expectThrow';
var Mintable23Token = artifacts.require('../contracts/Tokens/Mintable23Token.sol');
contract('Mintable23Token', function(accounts) {
let token;
let MAIN_ACCOUNT = accounts[0];
const INITAL_SUPPLY = 100;
beforeEach(async function() {
token = await Mintable23Token.new();
});
it('Mintable23Token #1 should start with a totalSupply of 0', async function() {
console.log("Mintable23Token #1 BEGIN==========================================================");
let totalSupply = await token.totalSupply();
assert.equal(totalSupply, 0);
});
it('Mintable23Token #2 should return mintingFinished false after construction', async function() {
console.log("Mintable23Token #2 BEGIN==========================================================");
let mintingFinished = await token.mintingFinished();
assert.equal(mintingFinished, false);
});
it('Mintable23Token #3 should mint a given amount of tokens to a given address', async function() {
console.log("Mintable23Token #3 BEGIN==========================================================");
let mainAccountBalanceBeforeMint = await token.balanceOf(MAIN_ACCOUNT);
console.log("mainAccountBalanceBeforeMint = " +mainAccountBalanceBeforeMint +" should equal to 0 ");
assert.equal(mainAccountBalanceBeforeMint, 0);
const result = await token.mint(MAIN_ACCOUNT, INITAL_SUPPLY);
let mainAccountBalanceAfterMint = await token.balanceOf(MAIN_ACCOUNT);
console.log("mainAccountBalanceAfterMint = " +mainAccountBalanceAfterMint +" should equal to INITAL_SUPPLY =" +INITAL_SUPPLY);
assert.equal(mainAccountBalanceAfterMint, INITAL_SUPPLY);
let totalSupplyAfterMint = await token.totalSupply();
console.log("totalSupplyAfterMint = " +totalSupplyAfterMint +" should equal to INITAL_SUPPLY =" +INITAL_SUPPLY);
assert(totalSupplyAfterMint, INITAL_SUPPLY);
});
it('Mintable23Token #4 should fail to mint after call to finishMinting', async function () {
console.log("Mintable23Token #4 BEGIN==========================================================");
let mainAccountBalanceBeforeMint = await token.balanceOf(MAIN_ACCOUNT);
console.log("mainAccountBalanceBeforeMint = " +mainAccountBalanceBeforeMint +" should equal to 0");
assert.equal(mainAccountBalanceBeforeMint, 0);
await token.finishMinting();
assert.equal(await token.mintingFinished(), true);
await expectThrow(token.mint(MAIN_ACCOUNT, INITAL_SUPPLY));
let mainAccountBalanceAfterMint = await token.balanceOf(MAIN_ACCOUNT);
console.log("mainAccountBalanceAfterMint = " +mainAccountBalanceAfterMint +" should equal to 0");
assert.equal(mainAccountBalanceAfterMint, 0);
});
});
|
!function(){"use strict";function e(){var e,a=navigator.userAgent,r=a.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(r[1]))return e=/\brv[ :]+(\d+)/g.exec(a)||[],{name:"ie",version:e[1]||""};if("Chrome"===r[1]){e=a.match(/\b(Edge)\/(\d+)/);var t=a.split("/").pop();if(t=t.split("."),null!=e)return{name:"edge",version:t[0]}}if("Chrome"===r[1]&&(e=a.match(/\bOPR\/(\d+)/),null!=e))return{name:"opera",version:e[1]};r=r[2]?[r[1],r[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(e=a.match(/version\/(\d+)/i))&&M.splice(1,1,e[1]),"IE"!=r[0]&&"MSIE"!=r[0]||(r[0]="ie");var n={name:r[0].toLowerCase(),version:r[1]};return n}var a=e(),r=document.getElementsByTagName("html")[0];r.setAttribute("data-browser",a.name),r.setAttribute("data-version",a.version);var t=r.className;t.length>0?r.className=r.className+" "+a.name+" "+a.name+a.version:r.className=a.name+a.version+" "+a.name}(); |
"use babel";
import { CompositeDisposable } from "atom";
import { dirname } from "path";
const linterName = "linter-joker";
let jokerExecutablePath;
let lintsOnChange;
export default {
activate() {
require("atom-package-deps").install("linter-joker");
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(
atom.config.observe(`${linterName}.jokerExecutablePath`, value => {
jokerExecutablePath = value;
})
);
this.subscriptions.add(
atom.config.observe(`${linterName}.lintsOnChange`, value => {
lintsOnChange = value;
})
);
},
deactivate() {
this.subscriptions.dispose();
},
provideLinter() {
const helpers = require("atom-linter");
return {
name: "joker",
scope: "file", // or 'project'
lintsOnChange: lintsOnChange,
grammarScopes: ["source.clojure"],
lint(textEditor) {
const editorPath = textEditor.getPath();
const editorText = textEditor.getText();
const [extension] = editorPath.match(/\.\w+$/gi) || [];
// console.log("linter-joker: file extension", extension);
const command =
extension === ".clj"
? "--lintclj"
: extension === ".cljs"
? "--lintcljs"
: extension === ".edn" || extension === ".joker"
? "--lintedn"
: extension === ".joke" ? "--lintjoker" : "--lintclj";
return helpers
.exec(jokerExecutablePath, [command, "-"], {
cwd: dirname(editorPath),
uniqueKey: linterName,
stdin: editorText,
stream: "both"
})
.then(function(data) {
if (!data) {
// console.log("linter-joker: process killed", data);
return null;
}
const { exitCode, stdout, stderr } = data;
// console.log("linter-joker: data", data);
if (exitCode === 1 && stderr) {
const regex = /[^:]+:(\d+):(\d+): ([\s\S]+)/;
const messages = stderr
.split(/[\r\n]+/)
.map(function(joke) {
const exec = regex.exec(joke);
if (!exec) {
// console.log("linter-joker: failed exec", joke);
return null;
}
const line = Number(exec[1]);
const excerpt = exec[3];
return {
severity: excerpt.startsWith("Parse warning:")
? "warning"
: "error",
location: {
file: editorPath,
position: helpers.generateRange(textEditor, line - 1)
},
excerpt: `${excerpt}`
};
})
.filter(m => m); // filter out null messages
// console.log("linter-joker: messages", messages);
return messages;
}
return [];
});
}
};
}
};
|
/* eslint react/jsx-filename-extension: [1, { "extensions": [".js", ".jsx"] }] */
import isDev from 'isdev';
import React from 'react';
import Helmet from 'react-helmet';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { renderToString } from 'react-dom/server';
import { RouterContext } from 'react-router';
import { Provider } from 'mobx-react';
import { setMatchMediaConfig } from 'mobx-react-matchmedia';
import { fetchData, dehydrate } from 'rfx-core';
import stores from '@/shared/stores';
import bootstrap from './bootstrap';
export default (req, res, props) => {
const cookieName = 'ssrToken';
const store = stores.inject({
app: { ssrLocation: req.url },
auth: { jwt: req.cookies[cookieName], cookieName },
ui: { mui: { userAgent: req.headers['user-agent'] } },
});
Promise.all(bootstrap(store))
.then(() => fetchData(store, props)
.then(() => setMatchMediaConfig(req))
.then(() => renderToString(
<MuiThemeProvider muiTheme={store.ui.getMui()}>
<Provider store={store}>
<RouterContext {...props} />
</Provider>
</MuiThemeProvider>,
))
.then(html => res
.status(200)
.render('index', {
build: isDev ? null : '/build',
head: Helmet.rewind(),
state: dehydrate(),
root: html,
})));
};
|
function HackerNews()
{
/**
* The service URLs. From api.ihackernews.com
*/
this.apiFrontPageURL = "http://api.ihackernews.com/page/";
this.apiAskHNUrl = "http://api.ihackernews.com/ask/";
this.newlySubmittedHNUrl = "http://api.ihackernews.com/new/";
this.apiUserUrl = "http://api.ihackernews.com/profile/";
// Headings
this.frontPage = "Hacker News (Front Page)";
this.askHackerNews = "Ask Hacker News";
this.newlySubmittedPosts = "Newest Posts";
// the current API being used. Assigned from above variables
this.apiURL = "";
this.nextId = "";
// API URL for each story call. Used in the details scene. concat id before json request.
this.storyApiURL = "http://api.ihackernews.com/post/";
// URL for each story on Hacker News site. concat id before json request.
this.storyURL = "http://news.ycombinator.com/item?id=";
// for check to verify first run
this.firstRun = true;
// only pull data in the welcome scene when set to true.
this.timeForWelcomeDataPull = true;
// only pull data in the details scene when set to true.
this.timeForDetailsDataPull = true;
// only pull data in the user scene when set to true.
this.timeForUserDataPull = true;
// Flag set to true when a search is being performed.
//this.searchInProgress = false;
/**
* Reference to the currently selected business.
*/
this.currentNewsItem = null;
// currently selected username
this.currentUserID = null;
//
// Search Parameters
this.searchParams = { };
//
// Checks for Internet connectivity and calls the appropriate callback.
//
// @param inAssistant The scene assistant from which this is called.
// @param inSuccessCallback Function to call if connectivity is available.
// @param inFailureCallback Function to call if connectivity is NOT available.
//
this.checkConnectivity = function(inAssistant, inSuccessCallback, inFailureCallback) {
inAssistant.controller.serviceRequest("palm://com.palm.connectionmanager", {
method : "getstatus",
parameters : { subscribe : false },
onSuccess : function(inResponse) {
// Note: isInternetConnectionAvailable seems to always return true
// in the emulator... even pulling the network cable out didn't help,
// nor did turning on airplane mode. It may be possible to configure
// VirtualBox's proxy settings, but I didn't try that (disabling the
// network adapter in VirtualBox didn't work either!)
inSuccessCallback();
/*
if (inResponse.isInternetConnectionAvailable) {
inSuccessCallback();
}
else {
// Note that the failure callback is called AFTER the dialog is
// dismissed. Also note that Mojo.Dialog.errorDialog doesn't work
// here either, although I'm not sure why. Ditto for the
// onFailure handler below.
inAssistant.controller.showAlertDialog({
onChoose : function() { inFailureCallback() },
title : "Error",
message : "Internet connection not avalailable1",
choices : [ { label : "Ok", value : "ok" } ]
});
} */
}, //end onSuccess
onFailure : function() {
// Service call failed.
inAssistant.controller.showAlertDialog({
onChoose : function() { inFailureCallback() },
title : "Error",
message : "Internet connection not avalailable",
choices : [ { label : "Ok", value : "ok" } ]
});
} // end onFailure
});
}; // End checkConnectivity()
} // End HackerNews class
// Declare the only instance of the object that will be used
var hackerNews = new HackerNews(); |
import Vue from 'vue'
const noopData = () => ({})
// window.onNuxtReady(() => console.log('Ready')) hook
// Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading)
if (process.browser) {
window._nuxtReadyCbs = []
window.onNuxtReady = function (cb) {
window._nuxtReadyCbs.push(cb)
}
}
export function applyAsyncData (Component, asyncData) {
const ComponentData = Component.options.data || noopData
// Prevent calling this method for each request on SSR context
if (!asyncData && Component.options.hasAsyncData) {
return
}
Component.options.hasAsyncData = true
Component.options.data = function () {
const data = ComponentData.call(this)
if (this.$ssrContext) {
asyncData = this.$ssrContext.asyncData[Component.cid]
}
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}
export function sanitizeComponent (Component) {
if (!Component.options) {
Component = Vue.extend(Component) // fix issue #6
Component._Ctor = Component
} else {
Component._Ctor = Component
Component.extendOptions = Component.options
}
// For debugging purpose
if (!Component.options.name && Component.options.__file) {
Component.options.name = Component.options.__file
}
return Component
}
export function getMatchedComponents (route) {
return [].concat.apply([], route.matched.map(function (m) {
return Object.keys(m.components).map(function (key) {
return m.components[key]
})
}))
}
export function getMatchedComponentsInstances (route) {
return [].concat.apply([], route.matched.map(function (m) {
return Object.keys(m.instances).map(function (key) {
return m.instances[key]
})
}))
}
export function flatMapComponents (route, fn) {
return Array.prototype.concat.apply([], route.matched.map(function (m, index) {
return Object.keys(m.components).map(function (key) {
return fn(m.components[key], m.instances[key], m, key, index)
})
}))
}
export function getContext (context, app) {
let ctx = {
isServer: !!context.isServer,
isClient: !!context.isClient,
isStatic: process.static,
isDev: true,
isHMR: context.isHMR || false,
app: app,
route: (context.to ? context.to : context.route),
payload: context.payload,
error: context.error,
base: '/',
env: {}
}
const next = context.next
ctx.params = ctx.route.params || {}
ctx.query = ctx.route.query || {}
ctx.redirect = function (status, path, query) {
if (!status) return
ctx._redirected = true // Used in middleware
// if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
if (typeof status === 'string' && (typeof path === 'undefined' || typeof path === 'object')) {
query = path || {}
path = status
status = 302
}
next({
path: path,
query: query,
status: status
})
}
if (context.req) ctx.req = context.req
if (context.res) ctx.res = context.res
if (context.from) ctx.from = context.from
if (ctx.isServer && context.beforeRenderFns) {
ctx.beforeNuxtRender = (fn) => context.beforeRenderFns.push(fn)
}
if (ctx.isClient && window.__NUXT__) {
ctx.nuxtState = window.__NUXT__
}
return ctx
}
export function middlewareSeries (promises, context) {
if (!promises.length || context._redirected) {
return Promise.resolve()
}
return promisify(promises[0], context)
.then(() => {
return middlewareSeries(promises.slice(1), context)
})
}
export function promisify (fn, context) {
let promise
if (fn.length === 2) {
// fn(context, callback)
promise = new Promise((resolve) => {
fn(context, function (err, data) {
if (err) {
context.error(err)
}
data = data || {}
resolve(data)
})
})
} else {
promise = fn(context)
}
if (!promise || (!(promise instanceof Promise) && (typeof promise.then !== 'function'))) {
promise = Promise.resolve(promise)
}
return promise
}
// Imported from vue-router
export function getLocation (base, mode) {
var path = window.location.pathname
if (mode === 'hash') {
return window.location.hash.replace(/^#\//, '')
}
if (base && path.indexOf(base) === 0) {
path = path.slice(base.length)
}
return (path || '/') + window.location.search + window.location.hash
}
export function urlJoin () {
return [].slice.call(arguments).join('/').replace(/\/+/g, '/')
}
// Imported from path-to-regexp
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
export function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
const PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g')
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = []
var key = 0
var index = 0
var path = ''
var defaultDelimiter = options && options.delimiter || '/'
var res
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0]
var escaped = res[1]
var offset = res.index
path += str.slice(index, offset)
index = offset + m.length
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1]
continue
}
var next = str[index]
var prefix = res[2]
var name = res[3]
var capture = res[4]
var group = res[5]
var modifier = res[6]
var asterisk = res[7]
// Push the current path onto the tokens.
if (path) {
tokens.push(path)
path = ''
}
var partial = prefix != null && next != null && next !== prefix
var repeat = modifier === '+' || modifier === '*'
var optional = modifier === '?' || modifier === '*'
var delimiter = res[2] || defaultDelimiter
var pattern = capture || group
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
})
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index)
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path)
}
return tokens
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty (str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk (str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length)
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
}
}
return function (obj, opts) {
var path = ''
var data = obj || {}
var options = opts || {}
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
path += token
continue
}
var value = data[token.name]
var segment
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (Array.isArray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j])
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value)
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
|
MEMO.services.dataStorageSvc = (function () {
"use strict";
(function () {
// immediate ivoke functions come here.
})();
var _add = function (key, obj) {
var value = JSON.stringify(obj);
localStorage.setItem(key, value);
};
var _get = function (key) {
return JSON.parse(localStorage.getItem(key));
};
var _remove = function (key) {
localStorage.removeItem(key);
};
var _changeOption = function(options) {
return extend(_options, options);
};
var extend = function (a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
};
}
};
return {
save: _add,
add: _add,
addUpdate: _add,
get: _get,
remove: _remove,
changeOpt: _changeOption
};
})(); |
/**
* Comment Provider
* Provides functionality to send or receive danmaku
* @license MIT
* @author Jim Chen
**/
var CommentProvider = (function () {
function CommentProvider () {
this._started = false;
this._destroyed = false;
this._staticSources = {};
this._dynamicSources = {};
this._parsers = {}
this._targets = [];
}
CommentProvider.SOURCE_JSON = 'JSON';
CommentProvider.SOURCE_XML = 'XML';
CommentProvider.SOURCE_TEXT = 'TEXT';
/**
* Provider for HTTP content. This returns a promise that resolves to TEXT.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {string} responseType - type of response expected.
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.BaseHttpProvider = function (method, url, responseType, args, body) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var uri = url;
if (args && (method === 'POST' || method === 'PUT')) {
uri += '?';
var argsArray = [];
for (var key in args) {
if (args.hasOwnProperty(key)) {
argsArray.push(encodeURIComponent(key) +
'=' + encodeURIComponent(args[key]));
}
}
uri += argsArray.join('&');
}
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(this.response);
} else {
reject(new Error(this.status + " " + this.statusText));
}
};
xhr.onerror = function () {
reject(new Error(this.status + " " + this.statusText));
};
xhr.open(method, uri);
// Limit the response type based on input
xhr.responseType = typeof responseType === "string" ?
responseType : "";
if (typeof body !== 'undefined') {
xhr.send(body);
} else {
xhr.send();
}
});
};
/**
* Provider for JSON content. This returns a promise that resolves to JSON.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.JSONProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "json", args, body).then(function (response) {
return response;
});
};
/**
* Provider for XML content. This returns a promise that resolves to Document.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.XMLProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "document", args, body).then(function (response) {
return response;
});
};
/**
* Provider for text content. This returns a promise that resolves to Text.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.TextProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "text", args, body).then(function (response) {
return response;
});
};
/**
* Attaches a static source to the corresponding type.
* NOTE: Multiple static sources will race to determine the initial comment
* list so it is imperative that they all parse to the SAME content.
*
* @param {Provider} source - Promise that resolves to one of the supported types
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addStaticSource = function (source, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more sources.');
}
if (!(type in this._staticSources)) {
this._staticSources[type] = [];
}
this._staticSources[type].push(source);
return this;
};
/**
* Attaches a dynamic source to the corresponding type
* NOTE: Multiple dynamic sources will collectively provide comment data.
*
* @param {DynamicProvider} source - Listenable that resolves to one of the supported types
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addDynamicSource = function (source, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more sources.');
}
if (!(type in this._dynamicSources)) {
this._dynamicSources[type] = [];
}
this._dynamicSources[type].push(source);
return this;
};
/**
* Attaches a target comment manager so that we can stream comments to it
*
* @param {CommentManager} commentManager - Comment Manager instance to attach to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addTarget = function (commentManager) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, '
+'cannot attach more targets.');
}
if (!(commentManager instanceof CommentManager)) {
throw new Error(
'Expected the target to be an instance of CommentManager.');
}
this._targets.push(commentManager);
return this;
};
/**
* Adds a parser for an incoming data type. If multiple parsers are added,
* parsers added later take precedence.
*
* @param {CommentParser} parser - Parser spec compliant parser
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addParser = function (parser, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more parsers.');
}
if (!(type in this._parsers)) {
this._parsers[type] = [];
}
this._parsers[type].unshift(parser);
return this;
};
CommentProvider.prototype.applyParsersOne = function (data, type) {
return new Promise(function (resolve, reject) {
if (!(type in this._parsers)) {
reject(new Error('No parsers defined for "' + type + '"'));
return;
}
for (var i = 0; i < this._parsers[type].length; i++) {
var output = null;
try {
output = this._parsers[type][i].parseOne(data);
} catch (e) {
// TODO: log this failure
console.error(e);
}
if (output !== null) {
resolve(output);
return;
}
}
reject(new Error("Ran out of parsers for they target type"));
}.bind(this));
};
CommentProvider.prototype.applyParsersList = function (data, type) {
return new Promise(function (resolve, reject) {
if (!(type in this._parsers)) {
reject(new Error('No parsers defined for "' + type + '"'));
return;
}
for (var i = 0; i < this._parsers[type].length; i++) {
var output = null;
try {
output = this._parsers[type][i].parseMany(data);
} catch (e) {
// TODO: log this failure
console.error(e);
}
if (output !== null) {
resolve(output);
return;
}
}
reject(new Error("Ran out of parsers for the target type"));
}.bind(this));
};
/**
* (Re)loads static comments
*
* @return {Promise} that is resolved when the static sources have been
* loaded
*/
CommentProvider.prototype.load = function () {
if (this._destroyed) {
throw new Error('Cannot load sources on a destroyed provider.');
}
var promises = [];
// TODO: This race logic needs to be rethought to provide redundancy
for (var type in this._staticSources) {
promises.push(Promises.any(this._staticSources[type])
.then(function (data) {
return this.applyParsersList(data, type);
}.bind(this)));
}
if (promises.length === 0) {
// No static loaders
return Promise.resolve([]);
}
return Promises.any(promises).then(function (commentList) {
for (var i = 0; i < this._targets.length; i++) {
this._targets[i].load(commentList);
}
return Promise.resolve(commentList);
}.bind(this));
};
/**
* Commit the changes and boot up the provider
*
* @return {Promise} that is resolved when all the static sources are loaded
* and all the dynamic sources are hooked up
**/
CommentProvider.prototype.start = function () {
if (this._destroyed) {
throw new Error('Cannot start a provider that has been destroyed.');
}
this._started = true;
return this.load().then(function (commentList) {
// Bind the dynamic sources
for (var type in this._dynamicSources) {
this._dynamicSources[type].forEach(function (source) {
source.addEventListener('receive', function (data) {
for (var i = 0; i < this._targets.length; i++) {
this._targets[i].send(
this.applyParserOne(data, type));
}
}.bind(this));
}.bind(this));
}
return Promise.resolve(commentList);
}.bind(this));
};
/**
* Send out comments to both dynamic sources and POST targets.
*
* @param commentData - commentData to be sent to the server. Object.
* @param requireAll - Do we require that all servers to accept the comment
* for the promise to resolve. Defaults to true. If
* false, the returned promise will resolve as long as a
* single target accepts.
* @return Promise that is resolved when the server accepts or rejects the
* comment. Dynamic sources will decide based on their promise while
* POST targets are considered accepted if they return a successful
* HTTP response code.
**/
CommentProvider.prototype.send = function (commentData, requireAll) {
throw new Error('Not implemented');
};
/**
* Stop providing dynamic comments to the targets
*
* @return Promise that is resolved when all bindings between dynamic
* sources have been successfully unloaded.
**/
CommentProvider.prototype.destroy = function () {
if (this._destroyed) {
return Promise.resolve();
}
// TODO: implement debinding for sources
this._destroyed = true;
return Promise.resolve();
};
return CommentProvider;
})();
|
module.exports = api => {
// register styleguide command
api.extendPackage({
scripts: {
styleguide: 'vue-cli-service styleguidist',
'styleguide:build': 'vue-cli-service styleguidist:build'
}
})
// add all the files from template
api.render('./template')
}
|
/**
* Created by Yang on 16/11/16.
*/
import React from 'react';
const BSContainer = (props) => <div className={`container ${props.className}`}>
{props.children}
</div>;
BSContainer.propTypes = {
className: React.PropTypes.any,
children: React.PropTypes.any,
};
export default BSContainer;
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var Class = require('../utils/Class');
var PluginCache = require('../plugins/PluginCache');
var SceneEvents = require('../scene/events');
/**
* @classdesc
* The Update List plugin.
*
* Update Lists belong to a Scene and maintain the list Game Objects to be updated every frame.
*
* Some or all of these Game Objects may also be part of the Scene's [Display List]{@link Phaser.GameObjects.DisplayList}, for Rendering.
*
* @class UpdateList
* @memberof Phaser.GameObjects
* @constructor
* @since 3.0.0
*
* @param {Phaser.Scene} scene - The Scene that the Update List belongs to.
*/
var UpdateList = new Class({
initialize:
function UpdateList (scene)
{
/**
* The Scene that the Update List belongs to.
*
* @name Phaser.GameObjects.UpdateList#scene
* @type {Phaser.Scene}
* @since 3.0.0
*/
this.scene = scene;
/**
* The Scene's Systems.
*
* @name Phaser.GameObjects.UpdateList#systems
* @type {Phaser.Scenes.Systems}
* @since 3.0.0
*/
this.systems = scene.sys;
/**
* The list of Game Objects.
*
* @name Phaser.GameObjects.UpdateList#_list
* @type {array}
* @private
* @default []
* @since 3.0.0
*/
this._list = [];
/**
* Game Objects that are pending insertion into the list.
*
* @name Phaser.GameObjects.UpdateList#_pendingInsertion
* @type {array}
* @private
* @default []
* @since 3.0.0
*/
this._pendingInsertion = [];
/**
* Game Objects that are pending removal from the list.
*
* @name Phaser.GameObjects.UpdateList#_pendingRemoval
* @type {array}
* @private
* @default []
* @since 3.0.0
*/
this._pendingRemoval = [];
scene.sys.events.once(SceneEvents.BOOT, this.boot, this);
scene.sys.events.on(SceneEvents.START, this.start, this);
},
/**
* This method is called automatically, only once, when the Scene is first created.
* Do not invoke it directly.
*
* @method Phaser.GameObjects.UpdateList#boot
* @private
* @since 3.5.1
*/
boot: function ()
{
this.systems.events.once(SceneEvents.DESTROY, this.destroy, this);
},
/**
* This method is called automatically by the Scene when it is starting up.
* It is responsible for creating local systems, properties and listening for Scene events.
* Do not invoke it directly.
*
* @method Phaser.GameObjects.UpdateList#start
* @private
* @since 3.5.0
*/
start: function ()
{
var eventEmitter = this.systems.events;
eventEmitter.on(SceneEvents.PRE_UPDATE, this.preUpdate, this);
eventEmitter.on(SceneEvents.UPDATE, this.update, this);
eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this);
},
/**
* Add a Game Object to the Update List.
*
* @method Phaser.GameObjects.UpdateList#add
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} child - The Game Object to add.
*
* @return {Phaser.GameObjects.GameObject} The added Game Object.
*/
add: function (child)
{
// Is child already in this list?
if (this._list.indexOf(child) === -1 && this._pendingInsertion.indexOf(child) === -1)
{
this._pendingInsertion.push(child);
}
return child;
},
/**
* The pre-update step.
*
* Handles Game Objects that are pending insertion to and removal from the list.
*
* @method Phaser.GameObjects.UpdateList#preUpdate
* @since 3.0.0
*/
preUpdate: function ()
{
var toRemove = this._pendingRemoval.length;
var toInsert = this._pendingInsertion.length;
if (toRemove === 0 && toInsert === 0)
{
// Quick bail
return;
}
var i;
var gameObject;
// Delete old gameObjects
for (i = 0; i < toRemove; i++)
{
gameObject = this._pendingRemoval[i];
var index = this._list.indexOf(gameObject);
if (index > -1)
{
this._list.splice(index, 1);
}
}
// Move pending to active
this._list = this._list.concat(this._pendingInsertion.splice(0));
// Clear the lists
this._pendingRemoval.length = 0;
this._pendingInsertion.length = 0;
},
/**
* The update step.
*
* Pre-updates every active Game Object in the list.
*
* @method Phaser.GameObjects.UpdateList#update
* @since 3.0.0
*
* @param {number} time - The current timestamp.
* @param {number} delta - The delta time elapsed since the last frame.
*/
update: function (time, delta)
{
for (var i = 0; i < this._list.length; i++)
{
var gameObject = this._list[i];
if (gameObject.active)
{
gameObject.preUpdate.call(gameObject, time, delta);
}
}
},
/**
* Remove a Game Object from the list.
*
* @method Phaser.GameObjects.UpdateList#remove
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} child - The Game Object to remove from the list.
*
* @return {Phaser.GameObjects.GameObject} The removed Game Object.
*/
remove: function (child)
{
var index = this._list.indexOf(child);
if (index !== -1)
{
this._list.splice(index, 1);
}
return child;
},
/**
* Remove all Game Objects from the list.
*
* @method Phaser.GameObjects.UpdateList#removeAll
* @since 3.0.0
*
* @return {Phaser.GameObjects.UpdateList} This UpdateList.
*/
removeAll: function ()
{
var i = this._list.length;
while (i--)
{
this.remove(this._list[i]);
}
return this;
},
/**
* The Scene that owns this plugin is shutting down.
* We need to kill and reset all internal properties as well as stop listening to Scene events.
*
* @method Phaser.GameObjects.UpdateList#shutdown
* @since 3.0.0
*/
shutdown: function ()
{
var i = this._list.length;
while (i--)
{
this._list[i].destroy(true);
}
i = this._pendingRemoval.length;
while (i--)
{
this._pendingRemoval[i].destroy(true);
}
i = this._pendingInsertion.length;
while (i--)
{
this._pendingInsertion[i].destroy(true);
}
this._list.length = 0;
this._pendingRemoval.length = 0;
this._pendingInsertion.length = 0;
var eventEmitter = this.systems.events;
eventEmitter.off(SceneEvents.PRE_UPDATE, this.preUpdate, this);
eventEmitter.off(SceneEvents.UPDATE, this.update, this);
eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this);
},
/**
* The Scene that owns this plugin is being destroyed.
* We need to shutdown and then kill off all external references.
*
* @method Phaser.GameObjects.UpdateList#destroy
* @since 3.0.0
*/
destroy: function ()
{
this.shutdown();
this.scene.sys.events.off(SceneEvents.START, this.start, this);
this.scene = null;
this.systems = null;
},
/**
* The length of the list.
*
* @name Phaser.GameObjects.UpdateList#length
* @type {integer}
* @readonly
* @since 3.10.0
*/
length: {
get: function ()
{
return this._list.length;
}
}
});
PluginCache.register('UpdateList', UpdateList, 'updateList');
module.exports = UpdateList;
|
/**
* Created by Kevin on 12/14/2016.
*/
(function () {
'use strict';
/* @ngInject */
angular.module('app.fhir')
.config(['$fhirProvider', fhirProvider]);
fhirProvider.$inject = ['$fhirProvider'];
function fhirProvider($fhirProvider) {
// $fhirProvider.baseUrl = 'https://fhir-open-api-dstu2.smarthealthit.org';
$fhirProvider.baseUrl = 'https://sb-fhir-dstu2.smarthealthit.org/api/smartdstu2/open';
// $fhirProvider.baseUrl = 'http://try-fhirplace.hospital-systems.com';
// $fhirProvider.baseUrl = 'https://open-ic.epic.com/Argonaut/api/FHIR/Argonaut/metadata';
$fhirProvider.auth = {
user: 'user',
pass: 'secret'
};
$fhirProvider.credentials = 'same-origin'
}
})(); |
angular.module('templateStore.templates',['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/templates', {
templateUrl: 'templates/templates.html',
controller: 'TemplatesCtrl'
}).
when('/templates/:templateId', {
templateUrl: 'templates/template-details.html',
controller: 'TemplateDetailsCtrl'
})
}])
.controller('TemplatesCtrl', ['$scope', '$http', function($scope, $http){
$http.get('json/templates.json').success(function(data){
$scope.templates = data;
});
}])
.controller('TemplateDetailsCtrl', ['$scope', '$routeParams', '$http', '$filter', function($scope, $routeParams, $http, $filter){
var templateId = $routeParams.templateId;
$http.get('json/templates.json').success(function(data){
$scope.template = $filter('filter')(data, function(d){
return d.id == templateId;
})[0];
$scope.mainImage = $scope.template.images[0].name;
});
$scope.setImage = function(image){
$scope.mainImage = image.name;
}
}]); |
/* jshint node:true */
'use strict';
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: ['browserify', 'jasmine-ajax', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/phantomjs-polyfill/bind-polyfill.js',
'node_modules/es6-promise/dist/es6-promise.js',
'test.js'
],
// list of files to exclude
exclude: [],
preprocessors: {
'*': ['browserify']
},
browserify: {
debug: true
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters: ['spec'],
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_{DISABLE,ERROR,WARN,INFO,DEBUG}
logLevel: config.LOG_INFO,
// watch files and execute tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
|
/**
* @author: @AngularClass
*/
var path = require('path');
const EVENT = process.env.npm_lifecycle_event || '';
// Helper functions
var ROOT = path.resolve(__dirname, '..');
function hasProcessFlag(flag) {
return process.argv.join('').indexOf(flag) > -1;
}
function hasNpmFlag(flag) {
return EVENT.includes(flag);
}
function isWebpackDevServer() {
return process.argv[1] && !! (/webpack-dev-server/.exec(process.argv[1]));
}
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [ROOT].concat(args));
}
exports.hasProcessFlag = hasProcessFlag;
exports.hasNpmFlag = hasNpmFlag;
exports.isWebpackDevServer = isWebpackDevServer;
exports.root = root; |
function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.getBytes();
var strData = forge.util.encode64(encrypted);
};
return strData;
};
function date2Str(x){
var d = new Date(x * 1000);
return d.toISOString().replace('Z', '');
}
function encryptData(data, encrypt=null) {
var encryptedData = [];
for (var i0=0; i0<data.length; i0++) {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
};
return encryptedData;
};
// AJAX for posting
function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#id_your_name').val(''); // remove the value from the input
console.log('Python result: ' + json['result']);
console.log(json);
console.log('success'); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}; |
const openTutorial = () => {
return { type: 'OPEN_TUTORIAL' };
};
const closeTutorial = () => {
return { type: 'CLOSE_TUTORIAL' };
};
const viewNext = () => {
return { type: 'VIEW_NEXT' };
};
const viewPrevious = () => {
return { type: 'VIEW_PREVIOUS' };
};
const toggleHelpHighlight = () => {
return { type: 'TOGGLE_HELP_HIGHLIGHT' };
};
export default {
openTutorial,
closeTutorial,
viewNext,
viewPrevious,
toggleHelpHighlight
}; |
var class_kluster_kite_1_1_web_1_1_nginx_configurator_1_1_nginx_configurator_actor =
[
[ "NginxConfiguratorActor", "class_kluster_kite_1_1_web_1_1_nginx_configurator_1_1_nginx_configurator_actor.html#af357a9a4abe3f5249b81991976190368", null ],
[ "Configuration", "class_kluster_kite_1_1_web_1_1_nginx_configurator_1_1_nginx_configurator_actor.html#a4d5f91c2fcfea5dcb56f229a298991f6", null ],
[ "KnownActiveNodes", "class_kluster_kite_1_1_web_1_1_nginx_configurator_1_1_nginx_configurator_actor.html#ada26feafdc67178b78939b3ac6c92c51", null ],
[ "NodePublishUrls", "class_kluster_kite_1_1_web_1_1_nginx_configurator_1_1_nginx_configurator_actor.html#a6ee6bd7d1a1a76359fc6862a7c20fc4d", null ]
]; |
/// <reference path="../../../../typings/tsd.d.ts" />
//NOTE: The angular app is initialised in ~/scripts/app/app.js
angular.module('app')
.factory('AdminService', function($http, HttpHelper) {
var fac = {};
fac.passwordRules = function() { return HttpHelper.get(['api/UsersAdmin/PasswordRules'].join('')); };
fac.allUsers = function() { return HttpHelper.get(['api/UsersAdmin/Users'].join('')); };
fac.saveUser = function(user) { return HttpHelper.post(['api/UsersAdmin/SaveUser'].join(''), user); };
//TODO: Figure out why the ResetPassword post with data gets 404 with WebApi
fac.resetPassword = function(userId, password) {
return HttpHelper.post(['api/UsersAdmin/ResetPassword'].join(''), { UserId: userId, Password: password });
};
fac.deleteUser = function(id, isDeleted) { return HttpHelper.post(['api/UsersAdmin/DeleteUser'].join(''), { id: id, isDeleted: isDeleted }) };
fac.lockoutUser = function(id, isLocked) { return HttpHelper.post(['api/UsersAdmin/LockUser'].join(''), { id: id, isLocked: isLocked }) };
return fac;
})
.controller('AdminController', function($scope, $http, $document, $timeout, $window, $browser, $uibModal, AdminService, UserDetails, toastr) {
var vm = this;
vm.state = {};
vm.debug = false;
vm.passwordUser = false;
$window.vm = vm;
// TODO: Get the ag-grid functionality working for the button clicks
// Configure ag-grid
var columnDefs = [
{ headerName: 'Id', field: 'Id', width: 40, hide: false }, // NOTE: We can set this equal to vm.debug
{ headerName: 'Login', field: 'UserName', width: 150 },
{ headerName: 'Description', field: 'Description', width: 90 },
{ headerName: 'Role', field: 'Role', width: 120 },
{ headerName: 'Status', width: 90, cellRenderer: ageCellRendererFunc }
];
function ageClicked(age) {
window.alert('Age clicked: ' + age);
}
function ageCellRendererFunc(params) {
params.$scope.ageClicked = ageClicked;
return '<button class="btn btn-xs btn-info" ng-click="vm.assignSim(data)" >Simulators</button>';
}
vm.gridOptions = {
columnDefs: columnDefs,
enableSorting: true,
enableFilter: true,
enableColResize: true,
angularCompileRows: true
};
var getUsers = function() {
// Get users
// Promise to show a spinner if this takes a while
var promise = $timeout(function () { vm.state.showSpinner = true; }, 50);
AdminService.allUsers().then(function(response) {
// TODO: Use ag-grid to render the users
//vm.gridOptions.api.setRowData(response.data);
//vm.gridOptions.api.sizeColumnsToFit();
vm.users = response.data;
// Cancel promise to show spinner
$timeout.cancel(promise);
vm.state.showSpinner = false;
});
};
vm.selectRow = function(user) {
vm.state.selectedTester = user;
};
// Assign Sim modal
vm.assignSim = function(user) {
vm.selectedTester = user;
var modalInstance = $uibModal.open({
animation: true,
templateUrl: $browser.baseHref() + 'scripts/app/partials/usersAdmin/assignSim.tpl.html',
controller: 'AssignSimController',
size: 'lg',
resolve: {
user: function() {
return user;
}
}
});
modalInstance.result.then(function() {
getUsers();
// TODO: Select selectedTester
var msg = ['Simulators have been assigned to ', $scope.vm.selectedTester.UserName].join('');
toastr.info(msg);
}, function() {
//toastr.info('Rest password cancelled');
});
};
// Add/Edit User section
//TODO: Replace $scope with vm
vm.addUser = function() {
// Create a default user
$scope.vm.passwordUser = null;
$scope.vm.user = { Id: 0, LockoutEnabled: false, IsDeleted: false, PasswordChanged: false, Role: 'Tester' };
};
// Edit user
vm.editUser = function(user) {
$scope.vm.passwordUser = null;
$scope.vm.user = user;
};
// On button click
$scope.okUser = function(user) {
AdminService.saveUser(user).then(function(response) {
var succeeded = response.data.Succeeded;
if (succeeded) {
$scope.vm.user = null;
var action = user.Id === 0 ? ' created' : ' updated';
var msg = ['User ', user.UserName, action].join('');
toastr.info(msg);
getUsers();
} else {
var reason = response.data.Errors[0] || 'An error occurred.';
toastr.error(reason, 'User Error');
}
});
};
$scope.cancelUser = function() {
$scope.vm.user = null;
};
// END Add/Edit User section
// Reset Password Section
$scope.resetPassword = function(user) {
$scope.vm.user = null;
var passwordUser = { Id: user.Id, UserName: user.UserName, Password: '' };
$scope.vm.passwordUser = passwordUser;
$timeout(function() {
document.getElementById('passwordInput').focus();
}, 300);
};
$scope.okResetPassword = function(user) {
AdminService.resetPassword(user.Id, user.Password).then(function(response) {
var succeeded = response.data.Succeeded;
if (succeeded) {
getUsers();
$scope.cancelResetPassword();
toastr.info(['Password reset for ', user.UserName].join(''), 'Reset Password');
} else {
var reason = response.data.Errors[0] || 'An error occurred.';
toastr.error(reason, 'Password Error');
}
});
};
$scope.cancelResetPassword = function() {
$scope.vm.passwordUser = null;
};
// END Reset Password Section
var getPasswordRules = function() {
AdminService.passwordRules().then(function(response) {
$scope.vm.passwordRules = response.data.PasswordRules;
$scope.vm.autoLogoutSettings = response.data.AutoLogoutSettings;
$scope.vm.userLockoutSettings = response.data.UserLockoutSettings;
});
};
UserDetails.get().then(function(data) {
$scope.vm.userDetails = data;
if (data.IsAdmin) {
$window.document.title = 'Manage Users';
}
if (data.IsSupport) {
$window.document.title = 'Manage Testers';
}
});
// Initialise
getUsers();
getPasswordRules();
}
); |
/**
* Success Criterion 1.2.9: Audio-only (Live)
*
* @see http://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-live-audio-only.html
*/
quail.guidelines.wcag.successCriteria['1.2.9'] = (function (quail) {
/**
* Determines if this Success Criteria applies to the document.
*/
function preEvaluator () {
return true;
}
// Create a new SuccessCriteria and pass it the evaluation callbacks.
var sc = quail.lib.SuccessCriteria({
name: 'wcag:1.2.9',
preEvaluator: preEvaluator
});
// Techniques
sc.techniques = {};
// Failures
sc.failures = {};
return sc;
}(quail));
|
(function(){
var util = require("util");
function match(keys, conditions, environment, options) {
if(!conditions) return true;
if(!keys) return false;
if(util.isArray(keys) == false) keys = [ keys.toString() ];
if(util.isArray(conditions) == false) conditions = [ conditions.toString() ];
return conditions.some(function(condition){
return keys.some(function(key){
if(key == condition) return true;
return key.match(condition);
})
})
}
var handler = function(){
}
handler.create = function(keyProvider){
return function(conditions, environment, options){
var keys = keyProvider(environment, options);
return match(keys, conditions, environment, options);
}
}
module.exports = handler;
})(); |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';
import { setNavigationVisibility } from '../Navigation/reducer';
import './ViewInfo.scss';
// CRA does not support importing text files
// this is offered as a solution here
// (https://github.com/facebook/create-react-app/issues/3722)
const markdown = raw('./content_fi.md');
class InfoView extends Component {
static propTypes = {
setNavigationVisibility: PropTypes.func
};
static BODY_CLASS = 'helerm-info-view';
componentDidMount() {
if (document.body) {
document.body.className = document.body.className + InfoView.BODY_CLASS;
}
this.props.setNavigationVisibility(true);
}
componentWillUnmount() {
if (document.body) {
document.body.className = document.body.className.replace(
InfoView.BODY_CLASS,
''
);
}
}
render() {
const classname =
this.props.match.path === '/info' ? 'info-view-center' : 'info-view';
return (
<div className={classname}>
<ReactMarkdown plugins={[gfm]} children={markdown} />
</div>
);
}
}
InfoView.propTypes = {};
const mapStateToProps = null;
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
setNavigationVisibility
},
dispatch
);
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(InfoView)
);
|
class PasteGesture extends Gesture {
constructor() {
super();
this.relocatedCells_ = [];
this.hoveredCell_ = null;
}
startHover(cell) {
if (!state.clipboard) return;
if (cell.role != state.clipboard.anchor.role) return;
this.hoveredCell_ = cell;
this.relocateCells_(cell);
this.forEachRelocatedAndGroupCell_((targetCell, layer, content) => {
targetCell.showHighlight(layer, content);
}, (objectCell, layer) => {
objectCell.showHighlight(layer, null);
});
}
stopHover() {
this.forEachRelocatedAndGroupCell_((targetCell, layer, content) => {
targetCell.hideHighlight(layer);
}, (objectCell, layer) => {
objectCell.hideHighlight(layer);
});
this.relocatedCells_ = [];
this.hoveredCell_ = null;
}
startGesture() {
super.startGesture();
this.forEachRelocatedAndGroupCell_((targetCell, layer, content) => {
targetCell.setLayerContent(layer, content, true);
}, (objectCell, layer) => {
objectCell.setLayerContent(layer, null, true);
});
// Completing a paste resets the gesture selection.
state.menu.setToInitialSelection();
state.opCenter.recordOperationComplete();
}
continueGesture(/* cell */) {}
stopGesture() {
super.stopGesture();
state.opCenter.recordOperationComplete();
}
/*
rotateLeft() {
this.updateLocation_(location => ({
row: -location.column,
column: location.row,
}));
}
rotateRight() {
this.updateLocation_(location => ({
row: location.column,
column: -location.row,
}));
}
flipVertically() {
this.updateLocation_(location => ({
row: location.row,
column: -location.column,
}));
}
flipHorizontally() {
this.updateLocation_(location => ({
row: -location.row,
column: location.column,
}));
}
*/
updateLocation_(callback) {
this.stopHover();
this.relocatedCells_.forEach(relocatedCell => {
relocatedCell.location = callback(relocatedCell.location);
});
if (this.hoveredCell_) {
this.startHover(this.hoveredCell_);
}
}
forEachRelocatedAndGroupCell_(cellCallback, groupCallback) {
// First, apply to existing colliding objects.
this.forEachRelocatedCellLayerContent_((targetCell, layer, content) => {
this.forEachObjectCell_(targetCell, layer, objectCell => {
groupCallback(objectCell, layer);
});
});
// Then apply to relocated cells.
this.forEachRelocatedCellLayerContent_((targetCell, layer, content) => {
cellCallback(targetCell, layer, content);
});
}
forEachRelocatedCellLayerContent_(callback) {
this.relocatedCells_.forEach(({key, location, layerContents}) => {
const targetCell = state.theMap.cells.get(key);
if (!targetCell) return;
ct.children.forEach(layer => {
callback(targetCell, layer, layerContents.get(layer));
});
});
}
forEachObjectCell_(cell, layer, callback) {
const content = cell.getLayerContent(layer);
if (!content) return;
const endCellKey = content[ck.endCell];
const startCellKey = content[ck.startCell];
if (!endCellKey && !startCellKey) return;
const startCell =
startCellKey ? state.theMap.cells.get(startCellKey) : cell;
const endCell =
state.theMap.cells.get(startCell.getLayerContent(layer)[ck.endCell]);
startCell.getPrimaryCellsInSquareTo(endCell).forEach(groupCell => {
callback(groupCell);
});
}
relocateCells_(newAnchor) {
state.clipboard.cells.forEach(({location, key, role, layerContents}) => {
const updatedLayerContents = new Map();
layerContents.forEach((content, layer) => {
updatedLayerContents.set(
layer, this.updateContent_(layer, key, location, content));
});
this.relocatedCells_.push({
key: this.calcKey_(newAnchor, role, location),
location,
layerContents: updatedLayerContents,
});
});
}
updateContent_(layer, key, location, content) {
if (!content) return content;
const newContent = Object.assign({}, content);
// We only copy multi-cell layer content if *all* the relevant cells are
// being copied.
const startCellKey = content[ck.startCell];
if (startCellKey) {
const endCellKey = state.theMap.cells.get(startCellKey)
.getLayerContent(layer, [ck.endCell]);
if (!this.areAllCellsBeingCopied_(layer, startCellKey, endCellKey)) {
return null;
}
const relocatedStartCellKey =
this.relocateCellKey_(location, startCellKey);
if (!state.theMap.cells.get(relocatedStartCellKey)) {
// Pasted group ends beyond the bounds.
return null;
}
newContent[ck.startCell] = relocatedStartCellKey;
}
const endCellKey = content[ck.endCell];
if (endCellKey) {
if (!this.areAllCellsBeingCopied_(layer, key, endCellKey)) {
return null;
}
const relocatedEndCellKey = this.relocateCellKey_(location, endCellKey);
if (!state.theMap.cells.get(relocatedEndCellKey)) {
// Pasted group ends beyond the bounds.
return null;
}
newContent[ck.endCell] = relocatedEndCellKey;
}
return newContent;
}
areAllCellsBeingCopied_(layer, startCellKey, endCellKey) {
if (!state.clipboard.cells.some(({key}) => key == startCellKey)) {
// The start cell is not being copied.
return false;
}
for (const cell of state.theMap.cells.values()) {
const cellLayerContent = cell.getLayerContent(layer);
if (!cellLayerContent) continue;
const cellStartCellKey = cellLayerContent[ck.startCell];
if (cellStartCellKey && startCellKey == cellStartCellKey) {
// This cell belongs to the same object!
if (!state.clipboard.cells.some(({key}) => key == cell.key)) {
// This cell doesn't appear in the clipboard.
return false;
}
}
}
return true;
}
relocateCellKey_(location, key) {
const rowDiff =
this.hoveredCell_.row - state.clipboard.anchor.location.row;
const columnDiff =
this.hoveredCell_.column - state.clipboard.anchor.location.column;
return key.split(':').map(part => {
const coords = part.split(',');
return Math.floor(Number(coords[0]) + rowDiff) + ',' +
Math.floor(Number(coords[1]) + columnDiff);
}).join(':');
}
calcKey_(anchor, cellRole, location) {
const row = anchor.row + location.row;
const column = anchor.column + location.column;
switch (cellRole) {
case 'primary':
return CellMap.primaryCellKey(row, column);
case 'vertical':
case 'horizontal':
case 'corner':
return CellMap.dividerCellKey(
Math.floor(row), Math.floor(column),
Math.ceil(row), Math.ceil(column));
}
}
}
|
import routes from './routes';
import middleware from './middleware';
class AppConfiguration {
static run(app) {
middleware(app);
routes(app);
}
}
export default AppConfiguration;
|
(function(){
'use strict';
angular.module('rcw',[]).config(function($locationProvider){
$locationProvider.html5Mode(true);
});
}());
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.requirejs_license = {
setUp: function(done) {
// setup here if necessary
done();
},
default_options: function(test) {
test.expect(1);
/*var actual = grunt.file.read('tmp/default_options');
var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should describe what the default behavior is.');
*/
test.ok(true);
test.done();
},
custom_options: function(test) {
test.expect(1);
/*
var actual = grunt.file.read('tmp/custom_options');
var expected = grunt.file.read('test/expected/custom_options');
test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');
*/
test.ok(true);
test.done();
},
};
|
/*
* PekeUpload 2.0 - jQuery plugin
* written by Pedro Molina
* http://www.pekebyte.com/
*
* Copyright (c) 2015 Pedro Molina (http://pekebyte.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
*
*/
(function($) {
$.fn.pekeUpload = function(options) {
// default configuration properties
var defaults = {
dragMode: false,
dragText: "Drag and Drop your files here",
bootstrap: false,
btnText: "Browse files...",
allowedExtensions: "",
invalidExtError: "Invalid File Type",
maxSize: 0,
sizeError: "Size of the file is greather than allowed",
showPreview: true,
showFilename: true,
showPercent: true,
showErrorAlerts: true,
errorOnResponse: "There has been an error uploading your file",
onSubmit: false,
url: "upload.php",
data: null,
limit: 0,
limitError: "You have reached the limit of files that you can upload",
delfiletext: "Remove from queue",
onFileError: function(file, error) {},
onFileSuccess: function(file, data) {}
};
var options = $.extend(defaults, options);
var pekeUpload = {
obj: $(this),
files: [],
uparea: null,
container: null,
uploadedfiles: 0,
hasErrors: false,
init: function() {
this.replacehtml();
this.uparea.on("click", function() {
pekeUpload.selectfiles();
});
///Handle events when drag
if (options.dragMode) {
this.handledragevents();
}
this.handlebuttonevents();
//Dismiss all warnings
$(document).on("click", ".pkwrncl", function() {
$(this).parent("div").remove();
});
//Bind event if is on Submit
if (options.onSubmit) {
this.handleFormSubmission();
}
},
replacehtml: function() {
var html = null;
switch (options.dragMode) {
case true:
switch (options.bootstrap) {
case true:
html = '<div class="well well-lg pkuparea pkdragarea" style="cursor:pointer"><h4>' + options.dragText + "</h4></div>";
break;
case false:
html = '<div class="pekeupload-drag-area pkuparea pkdragarea" style="cursor:pointer"><h4>' + options.dragText + "</h4></div>";
break;
}
break;
case false:
switch (options.bootstrap) {
case true:
html = '<a href="javascript:void(0)" class="btn btn-primary btn-upload pkuparea"> <i class="glyphicon glyphicon-upload"></i> ' + options.btnText + "</a>";
break;
case false:
html = '<a href="javascript:void(0)" class="pekeupload-btn-file pkuparea">' + options.btnText + "</a>";
break;
}
break;
}
this.obj.hide();
this.uparea = $(html).insertAfter(this.obj);
this.container = $('<div class="pekecontainer"><ul></ul></div>').insertAfter(this.uparea);
},
selectfiles: function() {
this.obj.click();
},
handlebuttonevents: function() {
$(document).on("change", this.obj.selector, function() {
pekeUpload.checkFile(pekeUpload.obj[0].files[0]);
});
$(document).on('click','.pkdel',function(){
var parent = $(this).parent('div').parent('div');
pekeUpload.delAndRearrange(parent);
});
},
handledragevents: function() {
$(document).on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
$(document).on("dragover", function(e) {
e.stopPropagation();
e.preventDefault();
});
$(document).on("drop", function(e) {
e.stopPropagation();
e.preventDefault();
});
this.uparea.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
$(this).css("border", "2px solid #0B85A1");
});
this.uparea.on("dragover", function(e) {
e.stopPropagation();
e.preventDefault();
});
this.uparea.on("drop", function(e) {
$(this).css("border", "2px dotted #0B85A1");
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
pekeUpload.checkFile(files[i]);
}
});
},
checkFile: function(file) {
error = this.validateFile(file);
if (error) {
if (options.showErrorAlerts) {
this.addWarning(error);
}
this.hasErrors = true;
options.onFileError(file, error);
} else {
this.files.push(file);
if (this.files.length > options.limit && options.limit > 0) {
this.files.splice(this.files.length - 1, 1);
if (options.showErrorAlerts) {
this.addWarning(options.limitError, this.obj);
}
this.hasErrors = true;
options.onFileError(file, error);
} else {
this.addRow(file);
if (options.onSubmit == false) {
this.upload(file, this.files.length - 1);
}
}
}
},
addWarning: function(error, c) {
var html = null;
switch (options.bootstrap) {
case true:
html = '<div class="alert alert-danger"><button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "</div>";
break;
case false:
html = '<div class="alert-pekeupload"><button type="button" class="close pkwrncl" data-dismiss="alert">×</button> ' + error + "</div>";
break;
}
if (!c) {
this.container.append(html);
} else {
$(html).insertBefore(c);
}
},
validateFile: function(file) {
if (!this.checkExtension(file)) {
return options.invalidExtError;
}
if (!this.checkSize(file)) {
return options.sizeError;
}
return null;
},
checkExtension: function(file) {
if (options.allowedExtensions == "") {
return true;
}
var ext = file.name.split(".").pop().toLowerCase();
var allowed = options.allowedExtensions.split("|");
if ($.inArray(ext, allowed) == -1) {
return false;
} else {
return true;
}
},
checkSize: function(file) {
if (options.maxSize == 0) {
return true;
}
if (file.size > options.maxSize) {
return false;
} else {
return true;
}
},
addRow: function(file) {
var i = this.files.length - 1;
switch (options.bootstrap) {
case true:
var newRow = $('<div class="row pkrw" rel="' + i + '"></div>').appendTo(this.container);
if (options.showPreview) {
var prev = $('<div class="col-lg-2 col-md-2 col-xs-4"></div>').appendTo(newRow);
this.previewFile(prev, file);
}
var finfo = $('<div class="col-lg-8 col-md-8 col-xs-8"></div>').appendTo(newRow);
if (options.showFilename) {
finfo.append('<div class="filename">' + file.name + "</div>");
}
if (options.notAjax == false){
var progress = $('<div class="progress"><div class="pkuppbr progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em;"></div></div>').appendTo(finfo);
if (options.showPercent) {
progress.find("div.progress-bar").text("0%");
}
}
var dismiss = $('<div class="col-lg-2 col-md-2 col-xs-2"></div>').appendTo(newRow);
$('<a href="javascript:void(0);" class="btn btn-danger pkdel">'+options.delfiletext+'</a>').appendTo(dismiss);
break;
case false:
var newRow = $('<div class="pekerow pkrw" rel="' + i + '"></div>').appendTo(this.container);
if (options.showPreview) {
var prev = $('<div class="pekeitem_preview"></div>').appendTo(newRow);
this.previewFile(prev, file);
}
var finfo = $('<div class="file"></div>').appendTo(newRow);
if (options.showFilename) {
finfo.append('<div class="filename">' + file.name + "</div>");
}
if (options.notAjax == false){
var progress = $('<div class="progress-pekeupload"><div class="pkuppbr bar-pekeupload pekeup-progress-bar" style="min-width: 2em;width:0%"><span></span></div></div>').appendTo(finfo);
if (options.showPercent) {
progress.find("div.bar-pekeupload").text("0%");
}
}
var dismiss = $('<div class="pkdelfile"></div>').appendTo(newRow);
$('<a href="javascript:void(0);" class="delbutton pkdel">'+options.delfiletext+'</a>').appendTo(dismiss);
break;
}
},
previewFile: function(container, file) {
var type = file.type.split("/")[0];
switch (type) {
case "image":
var fileUrl = window.URL.createObjectURL(file);
var prev = $('<img class="thumbnail" src="' + fileUrl + '" height="64" />').appendTo(container);
break;
case "video":
var fileUrl = window.URL.createObjectURL(file);
var prev = $('<video src="' + fileUrl + '" width="100%" controls></video>').appendTo(container);
break;
case "audio":
var fileUrl = window.URL.createObjectURL(file);
var prev = $('<audio src="' + fileUrl + '" width="100%" controls></audio>').appendTo(container);
break;
default:
if (options.bootstrap) {
var prev = $('<i class="glyphicon glyphicon-file"></i>').appendTo(container);
} else {
var prev = $('<div class="pekeupload-item-file"></div>').appendTo(container);
}
break;
}
},
upload: function(file, pos) {
var formData = new FormData();
formData.append(this.obj.attr("name"), file);
for (var key in options.data) {
formData.append(key, options.data[key]);
}
$.ajax({
url: options.url,
type: "POST",
data: formData,
dataType: "json",
success: function(data) {
if (data == 1 || data.success == 1) {
pekeUpload.files[pos] = null;
$('div.row[rel="' + pos + '"]').find(".pkuppbr").css("width", "100%");
options.onFileSuccess(file, data);
} else {
pekeUpload.files.splice(pos, 1);
var err = null;
if (error in data) {
err = null;
} else {
err = options.errorOnResponse;
}
if (options.showErrorAlerts) {
pekeUpload.addWarning(err, $('div.row[rel="' + pos + '"]'));
}
$('div.row[rel="' + pos + '"]').remove();
pekeUpload.hasErrors = true;
options.onFileError(file, err);
}
},
error: function(xhr, ajaxOptions, thrownError) {
pekeUpload.files.splice(pos, 1);
if (options.showErrorAlerts) {
pekeUpload.addWarning(thrownError, $('div.pkrw[rel="' + pos + '"]'));
}
pekeUpload.hasErrors = true;
options.onFileError(file, thrownError);
$('div.pkrw[rel="' + pos + '"]').remove();
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener("progress", function(e) {
pekeUpload.handleProgress(e, pos);
}, false);
}
return myXhr;
},
complete: function() {
if (options.onSubmit) {
pekeUpload.uploadedfiles++;
if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
pekeUpload.obj.remove();
pekeUpload.obj.parent("form").submit();
}
}
},
cache: false,
contentType: false,
processData: false
});
},
handleProgress: function(e, pos) {
if (e.lengthComputable) {
var total = e.total;
var loaded = e.loaded;
var percent = Number((e.loaded * 100 / e.total).toFixed(2));
var progressbar = $('div.pkrw[rel="' + pos + '"]').find(".pkuppbr");
progressbar.css("width", percent + "%");
if (options.showPercent) {
progressbar.text(percent + "%");
}
}
},
handleFormSubmission: function() {
var form = this.obj.parent("form");
form.submit(function() {
pekeUpload.hasErrors = false;
pekeUpload.uploadedfiles = 0;
for (var i = 0; i < pekeUpload.files.length; i++) {
if (pekeUpload.files[i]) {
pekeUpload.upload(pekeUpload.files[i], i);
} else {
pekeUpload.uploadedfiles++;
if (pekeUpload.uploadedfiles == pekeUpload.files.length && pekeUpload.hasErrors == false) {
pekeUpload.obj.remove();
return true;
}
}
}
return false;
});
},
delAndRearrange: function(parent){
var id = parent.attr('rel');
pekeUpload.files.splice(parseInt(id), 1);
parent.remove();
pekeUpload.container.find('div.pkrw').each(function(index){
$(this).attr('rel',index);
});
}
};
pekeUpload.init();
};
})(jQuery); |
/**
* marked-tex-renderer
* A plug-in style renderer to produce TeX output for marked
* https://github.com/sampathsris/marked-tex-renderer
*/
/*jshint node: true */
'use strict';
var NEWLINE = '\r\n';
function Renderer() {
}
Renderer.prototype.failOnUnsupported = function() {
if (!this.options.hasOwnProperty('failOnUnsupported')) {
return true;
}
return this.options.failOnUnsupported;
};
Renderer.prototype.code = function (code, lang, escaped) {
return [
'\\begin{verbatim}',
code,
'\\end{verbatim}'
].join(NEWLINE) + NEWLINE;
};
Renderer.prototype.blockquote = function (quote) {
return [
'\\begin{quote}',
quote,
'\\end{quote}'
].join(NEWLINE) + NEWLINE;
};
Renderer.prototype.html = function (html) {
return html;
};
Renderer.prototype.heading = function (text, level, raw) {
var command = '';
switch (level) {
case 1:
command = '\\chapter';
break;
case 2:
command = '\\section';
break;
case 3:
command = '\\subsection';
break;
case 4:
command = '\\subsubsection';
break;
case 5:
command = '\\paragraph';
break;
case 6:
command = '\\subparagraph';
break;
}
if (command !== '' && text.indexOf('\\{-\\}') !== -1) {
command += '*';
text = text.replace(' \\{-\\}', '').replace('\\{-\\}', '');
}
return NEWLINE + command + '{' + text + '}' + NEWLINE;
};
Renderer.prototype.hr = function () {
return '\\hrulefill' + NEWLINE;
};
Renderer.prototype.list = function (body, ordered) {
if (ordered) {
return [
NEWLINE,
'\\begin{enumerate}',
body,
'\\end{enumerate}',
NEWLINE
].join(NEWLINE);
} else {
return [
NEWLINE,
'\\begin{itemize}',
body,
'\\end{itemize}',
NEWLINE
].join(NEWLINE);
}
};
Renderer.prototype.listitem = function (text) {
return '\\item ' + text + NEWLINE;
};
Renderer.prototype.paragraph = function (text) {
return '\\par ' + text;
};
Renderer.prototype.tablecell = function (content, flags) {
// treat the cell as an element of a JSON array, and add a comma
// to separate it from the subsequent cells
return JSON.stringify({ content: content, flags: flags}) + ',';
};
Renderer.prototype.tablerow = function (content) {
// remove trailing comma from the list of cells
var row = content.substr(0, content.length - 1);
// and return it as a JSON array. add a comma to separate the
// row from the subsequent rows
return '[' + row + '],';
};
Renderer.prototype.table = function (header, body) {
var headerArr = [],
bodyArr = [],
hasHeader = false,
firstRow,
tex,
tableSpec;
// remove the trailing comma from header row
if (header) {
header = header.substr(0, header.length - 1);
headerArr = JSON.parse(header);
if (headerArr.length !== 0) {
hasHeader = true;
}
}
// remove the trailing comma from body row(s)
if (body) {
body = body.substr(0, body.length - 1);
bodyArr = JSON.parse('[' + body + ']');
}
if (headerArr.length !== 0) {
firstRow = headerArr;
} else {
firstRow = bodyArr[0];
}
tex = '\\begin{tabular}';
// create table spec
tableSpec = '{|';
for (var i = 0; i < firstRow.length; i++) {
var alignFlag = firstRow[i].flags.align || 'none';
var align = 'l|';
switch (alignFlag) {
case 'right':
align = 'r|';
break;
case 'center':
align = 'c|';
break;
}
tableSpec += align;
}
tableSpec += '}';
tex += tableSpec + NEWLINE;
// create table body
tex += '\\hline' + NEWLINE;
if (hasHeader) {
tex += createTableRow(headerArr);
tex += '\\hline' + NEWLINE;
}
for (var j = 0; j < bodyArr.length; j++) {
tex += createTableRow(bodyArr[j]);
}
tex += '\\hline' + NEWLINE;
tex += '\\end{tabular}' + NEWLINE;
return tex;
};
Renderer.prototype.strong = function (text) {
return '\\textbf{' + text + '}';
};
Renderer.prototype.em = function (text) {
return '\\emph{' + text + '}';
};
Renderer.prototype.codespan = function (text) {
return '\\texttt{' + this.text(text) + '}';
};
Renderer.prototype.br = function () {
return '\\\\';
};
Renderer.prototype.del = function (text) {
if (this.options.delRenderer) {
return this.options.delRenderer(text);
} else if (this.failOnUnsupported()) {
throw new Error(
'Client should provide a function to render deleted texts. ' +
'Use options.delRenderer = function (text)');
} else {
// deleted text is meant to be deleted. return ''.
return '';
}
};
Renderer.prototype.link = function (href, title, text) {
if (this.options.linkRenderer) {
return this.options.linkRenderer(href, title, text);
} else if (this.failOnUnsupported()) {
throw new Error(
'Client should provide a function to render hyperlinks. ' +
'Use options.linkRenderer = function (href, title, text)');
} else {
// omit hyperlink and just return the text.
return text;
}
};
Renderer.prototype.image = function (href, title, text) {
if (this.options.imageRenderer) {
return this.options.imageRenderer(href, title, text);
} else if (this.failOnUnsupported()) {
throw new Error(
'Client should provide a function to render images. ' +
'Use options.imageRenderer = function (href, title, text)');
} else {
// some text without an image would be weird. return ''.
return '';
}
};
Renderer.prototype.text = function (text) {
return texEscape(htmlUnescape(text));
};
/*
* Implementation for unsupported features of plain TeX
*/
Renderer.delImpl = function (text) {
// requires \usepackage{ulem}
// use \normalem to retain normal emphasis
return '\\sout{' + text + '}';
};
Renderer.linkImpl = function (href, title, text) {
// requires \usepackage{hyperref}
return '\\href{' + href + '}{' + text + '}';
};
Renderer.imageImpl = function (herf, title, text) {
// requires \usepackage{graphicx}
return [
NEWLINE,
'\\begin{figure}[h!]',
'\\caption{' + text + '}',
'\\centering',
'\\includegraphics{' + herf + '}',
'\\end{figure}'
].join(NEWLINE) + NEWLINE;
};
/*
* Helpers
*/
function createTableRow(rowArr) {
var tex = '';
for (var c = 0; c < rowArr.length; c++) {
tex += rowArr[c].content;
if (c < rowArr.length - 1) {
tex += ' & ';
} else {
tex += ' \\\\' + NEWLINE;
}
}
return tex;
}
function htmlUnescape(html) {
return html.replace(/&([#\w]+);/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n === 'amp') return '&';
if (n.charAt(0) === '#') {
var charCode = 0;
if (n.charAt(1) === 'x') {
charCode = parseInt(n.substring(2), 16);
} else {
charCode = +n.substring(1);
}
return String.fromCharCode(charCode);
}
return '';
});
}
function texEscape(text) {
// some characters have special meaning in TeX
// \ & % $ # _ { } ~ ^
return text
.replace(/\\/g, '\\textbackslash')
.replace(/\&/g, '\\&')
.replace(/%/g, '\\%')
.replace(/\$/g, '\\$')
.replace(/#/g, '\\#')
.replace(/\_/g, '\\_')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/~/g, '\\textasciitilde')
.replace(/\^/g, '\\textasciicircum');
}
module.exports = Renderer;
|
version https://git-lfs.github.com/spec/v1
oid sha256:03db059771bee943dbbcb286f9db14347a815154b7a9a65e938fd14082e47095
size 3115
|
/**
* 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.
*/
/* eslint-disable max-len */
export const port = process.env.PORT || 3000;
export const host = process.env.WEBSITE_HOSTNAME || `localhost:${port}`;
export const databaseUrl = process.env.DATABASE_URL || 'postgres://andrew:andrew@localhost/andrew';
export const analytics = {
// https://analytics.google.com/
google: {
trackingId: process.env.GOOGLE_TRACKING_ID, // UA-XXXXX-X
},
};
export const auth = {
jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' },
// https://developers.facebook.com/
facebook: {
id: process.env.FACEBOOK_APP_ID || '186244551745631',
secret: process.env.FACEBOOK_APP_SECRET || 'a970ae3240ab4b9b8aae0f9f0661c6fc',
},
// https://cloud.google.com/console/project
google: {
id: process.env.GOOGLE_CLIENT_ID || '251410730550-ahcg0ou5mgfhl8hlui1urru7jn5s12km.apps.googleusercontent.com',
secret: process.env.GOOGLE_CLIENT_SECRET || 'Y8yR9yZAhm9jQ8FKAL8QIEcd',
},
// https://apps.twitter.com/
twitter: {
key: process.env.TWITTER_CONSUMER_KEY || 'Ie20AZvLJI2lQD5Dsgxgjauns',
secret: process.env.TWITTER_CONSUMER_SECRET || 'KTZ6cxoKnEakQCeSpZlaUCJWGAlTEBJj0y2EMkUBujA7zWSvaQ',
},
};
|
'use strict';
const psplit = require('../psplit');
/**
* Routes the mock API calls (from Lambda functions) into the AWS
* actions.
*
* @param {RouteMap} actionMap - the route entry from the api/route.js
* file, for a specific service name.
* @return {Object[]} list of { actionName, handler }.
*/
module.exports = function(p) {
var serviceName = p.serviceName;
var url = p.url;
var actionMap = p.actionMap;
var ret = [];
for (var i = 0; i < actionMap.routes.length; i++) {
var route = actionMap.routes[i];
ret.push({
actionName: route.Action,
handler: createHandler({
serviceName: serviceName,
url: url,
route: route,
}),
});
}
return ret;
};
function createHandler(p) {
var serviceName = p.serviceName;
var url = p.url;
var route = p.route;
return function(awsConfig, params, callback) {
console.log(`[local route ${serviceName}] calling ${route.Action} with params ${JSON.stringify(params)}`);
try {
var aws = createAws({
awsConfig: awsConfig,
serviceName: serviceName,
url: url,
route: route,
params: params,
});
route.LongPoll(aws)
.then(function(res) {
console.log(`[local route ${serviceName}] received response ${JSON.stringify(res)}`);
if (res[0] >= 400) {
// Error result
callback(new Error(res[3]));
} else {
callback(null, res[1]);
}
})
.catch(function(err) {
callback(err, null);
});
} catch (err) {
console.log(`[local route ${serviceName}] invoking ${route.Action} with params ${JSON.stringify(params)} generated: ${err.message}\n${err.stack}`);
callback(err, null);
}
};
}
/**
* Creates the mock AWS object.
*/
function createAws(p) {
var awsConfig = p.awsConfig;
var serviceName = p.serviceName;
var url = p.url;
var route = p.route;
var params = p.params;
// FIXME
return {
baseUrl: 'http://localhost/' + url, // TODO fix
requestUrl: url, // TODO fix
serviceName: serviceName,
params: params,
restParams: params,
data: psplit.split(params),
reqParams: params,
version: awsConfig.VERSION, // AWS.config.versions, really.
action: route.Action,
accessKey: '1123', // TODO should come from AWS.config
expires: '123412341234', // TODO fix
signature: '12341234', // TODO fix
signatureMethod: '', // TODO fix
signatureVersion: '', // TODO fix
timestamp: 10, // TODO fix
region: (!!awsConfig.region ? awsConfig.region : 'ZN-MOCK-1'),
isRest: (!route.Action),
};
}
|
var mcLevel=0;
var mcScore=0;
function initStorage() {
if(localStorage.mcLevel!=null){
mcLevel=localStorage.mcLevel
} else {
mcLevel=0
}
if(localStorage.mcScore!=null){
mcScore=localStorage.mcScore
} else {
mcScore=0
}
}
function showMcStorage() { alert("Level="+mcLevel+"\n"+"Score="+mcScore); }
function updateMcStorage(level,score) {
localStorage.mcLevel=level;
localStorage.mcScore=score;
}
initStorage();
showMcStorage();
updateMcStorage(mcLevel=2,mcScore=3);
showMcStorage(); |
class Test {
/**
* @returns {Number}
* @typecheck
*/
myMethod() {
if (true) {
return 1;
} else {
return 2;
}
}
}
|
/**
* 定义marketplace类的数据模型
*
* Created by zephyre on 11/3/15.
*/
CoreModel.Marketplace = {};
const Marketplace = CoreModel.Marketplace;
const Misc = CoreModel.Misc;
Marketplace.Seller = new SimpleSchema({
// 商家的主键
sellerId: {
type: Number,
min: 1
},
// 商家对应的UserInfo
userInfo: {
type: CoreModel.Account.UserInfo,
blackbox: true
},
// 商家店铺的名称
name: {
type: String,
min: 1,
max: 128
},
// 商家介绍
desc: {
type: Misc.RichText,
optional: true
},
// 商家图集
images: {
type: [Misc.Image],
optional: true
},
// 商家评分
rating: {
type: Number,
decimal: true,
optional: true,
min: 0,
max: 1
},
// 商家支持那些语言
lang: {
type: [String],
allowedValues: ["en", "zh", "local"],
maxCount: 3,
optional: true
},
// 商家资质
qualifications: {
type: [String],
allowedValues: [],
optional: true
},
// 商家支持那些服务区域
serviceZones: {
type: [CoreModel.Geo.GeoEntity],
maxCount: 1024,
optional: true
},
// 服务标签
// 包括: 语言帮助/行程规划/当地咨询
services: {
type: [String],
allowedValues: ["language", "plan", "consult"],
maxCount: 3,
optional: true
},
// 银行账户
bankAccounts: {
type: [CoreModel.Finance.BankAccount],
maxCount: 64,
optional: true
},
// 商家的实名信息
identity: {
type: CoreModel.Account.RealNameInfo,
blackbox: true,
optional: true
},
// 电子邮件
email: {
type: [String],
maxCount: 4,
regEx: SimpleSchema.RegEx.Email,
optional: true
},
// 联系电话
phone: {
type: [Misc.PhoneNumber],
maxCount: 4,
optional: true
},
// 地址
address: {
type: String,
max: 1024,
optional: true
},
// 商家被多少人关注
favorCnt: {
type: Number,
min: 0,
optional: true
},
// 开店时间
createTime: {
type: Date
}
});
// 定价
Marketplace.Pricing = new SimpleSchema({
// 价格
price: {
type: Number,
min: 0
},
// 价格在哪个时间区间内有效([start, end], 左开右闭区间)
// [start, null)表示从start到今后, price都有效
// [null, end)表示在end之前, price都有效
// 如果timeRange为null, 则在所有时间段, price都有效
timeRange: {
type: [Date],
minCount: 2,
maxCount: 2,
optional: true
}
});
// 库存信息
Marketplace.StockInfo = new SimpleSchema({
// 库存状态。可选值:empty, nonempty, plenty。如果为nonempty,后面的quantity字段将生效
status: {
type: String,
regEx: /^(empty|nonempty|plenty)$/
},
// 库存数量
quantity: {
type: Number,
min: 0,
optional: true
},
// 该库存状态说明所对应的时间区间。格式:[start, end]
timeRange: {
type: [Date],
minCount: 2,
maxCount: 2,
optional: true
}
});
// 套餐信息
Marketplace.CommodityPlan = new SimpleSchema({
// 套餐的标识
planId: {
type: String,
min: 1,
max: 64
},
// 套餐标题
title: {
type: String,
min: 1,
max: 64
},
// 套餐描述
desc: {
type: String,
min: 1,
max: 65535,
optional: true
},
// 价格信息
pricing: {
type: [Marketplace.Pricing],
minCount: 1
},
// 市场价格
marketPrice: {
type: Number,
optional: true,
min: 0
},
// 商品售价
price: {
type: Number,
min: 0
},
// 库存信息
stockInfo: {
type: [Marketplace.StockInfo],
minCount: 1,
optional: true
},
// 购买该商品是否需要确定时间
timeRequired: {
type: Boolean
}
});
// 商品
Marketplace.Commodity = new SimpleSchema({
// 商品编号
commodityId: {
type: Number,
min: 1
},
// 商家
seller: {
type: Marketplace.Seller,
blackbox: true
},
// 商品标题
title: {
type: String,
min: 1,
max: 1024
},
// 商品描述
desc: {
type: Misc.RichText,
optional: true
},
// 市场价格
marketPrice: {
type: Number,
optional: true,
min: 0
},
// 商品售价
price: {
type: Number,
min: 0
},
// 套餐信息
plans: {
type: [Marketplace.CommodityPlan],
minCount: 1
},
// 商品销量
salesVolume: {
type: Number,
min: 0,
optional: true
},
// 商品类别
category: {
type: [String],
minCount: 1,
maxCount: 1
},
// 商品的详细消费地址
address: {
max: 1024,
type: String,
optional: true
},
// 服务时长
timeCost: {
type: String,
max: 1024,
optional: true
},
// 购买须知
notice: {
type: [Misc.RichText],
optional: true
},
// 退改规定
refundPolicy: {
type: [Misc.RichText],
optional: true
},
// 交通信息
trafficInfo: {
type: [Misc.RichText],
optional: true
},
// 商品封面图
cover: {
type: Misc.Image,
optional: true
},
// 商品图集
images: {
type: [Misc.Image],
optional: true
},
// 商品评分
rating: {
type: Number,
decimal: true,
optional: true,
min: 0,
max: 1
},
// 商品状态
status: {
type: String,
// 审核中 / 已发布 / 已下架
allowedValues: ["review", "pub", "disabled"]
},
// 商品的国家信息
country: {
type: CoreModel.Geo.Country,
optional: true,
blackbox: true
},
// 商品的目的地属性
locality: {
type: CoreModel.Geo.Locality,
optional: true,
blackbox: true
},
// 商品的创建时间
createTime: {
type: Date
},
// 商品修改时间
updateTime: {
type: Date,
optional: true
},
// 商品的版本号
version: {
type: Number,
// 暂时先不做检测
optional: true
}
});
// 支付信息
Marketplace.Prepay = new SimpleSchema({
// 支付渠道
provider: {
type: String,
allowedValues: ["alipay", "wechat"]
},
// 预支付ID
prepayId: {
type: String
},
// 支付金额
amount: {
type: Number,
min: 0
}
});
// 订单的操作日志,比如: 创建订单, 支付, 申请退款等
Marketplace.OrderActivity = new SimpleSchema({
// 操作发生的时间
timestamp: {
type: Date
},
// 操作前的状态
prevStatus: {
type: String,
allowedValues: ["pending", "paid", "committed", "finished", "canceled", "refundApplied", "refunded"]
},
// 分别对应于: 创建订单/取消订单/支付订单/商户发货/订单过期/订单完成/申请退款/退款/拒绝退款
action: {
type: String,
allowedValues: ["create", "cancel", "pay", "commit", "expire", "finish", 'refundApply', 'refundApprove', 'refundDeny']
},
// 附加数据
data: {
type: Object, // allowedKeys: ['userId'|'memo'|'amount'|'reason']
blackbox: true,
optional: true
}
});
// 订单
Marketplace.Order = new SimpleSchema({
// 订单编号
orderId: {
type: Number,
min: 1
},
// 消费者的用户名
consumerId: {
type: Number,
min: 1
},
// 对应的商品
commodity: {
type: Marketplace.Commodity,
blackbox: true
},
// 选择的套餐Id(暂时保留)
planId: {
type: String,
optional: true
},
// 选择的套餐
plan: {
type: Marketplace.CommodityPlan,
optional: true,
blackbox: true
},
// 旅客信息
travellers: {
type: [Misc.RealNameInfo],
optional: true
},
// 订单联系人
contact: {
type: Misc.RealNameInfo,
// 应该是必须的
optional: true
},
// 预约时间
rendezvousTime: {
type: Date,
optional: true
},
// 订单过期时间
expireDate: {
type: Date
},
// 订单总价
totalPrice: {
type: Number,
min: 0
},
// 订单折扣
discount: {
type: Number,
min: 0,
optional: true
},
// 商品数量
quantity: {
type: Number,
min: 1
},
// 支付信息 Map[String, Prepay]
paymentInfo: {
type: Object,
optional: true
},
// 订单状态
// 分别为: 待付款, 已付款, 商户已确认, 订单完成, 已取消, 退款申请中, 退款完成
status: {
type: String,
allowedValues: ["pending", "paid", "committed", "finished", "canceled", "refundApplied", "refunded"]
},
// 订单的操作日志
activities: {
type: [Marketplace.OrderActivity]
},
// 附言
comment: {
type: String,
max: 65535,
optional: true
},
// 创建时间
createTime: {
type: Date
},
// 更新时间
updateTime: {
type: Date,
optional: true
}
});
|
import SVGPath from './SVGPath';
export default SVGPath;
|
Object.prototype.repeat = function (count) {
var s = this;
s._repeat = count;
return s;
};
module.exports = {
/** データ定義 **/
entries: [
{
_id: "15${padZero(rownum, 22)}",
name: "${flower}"
}.repeat(10)
]
}; |
const ServerRepository = require('../Repository/ServerRepository'),
IgnoredRepository = require('../Repository/IgnoredRepository');
module.exports = {
"repository.server": {module: ServerRepository, args: ['%storage%', '@brain.memory']},
"repository.ignored": {module: IgnoredRepository, args: ['%storage%']}
};
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser Global (gms is your global library identifier)
window.gms = factory();
}
}(this, function() {
/**
* @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice,
jsSuffixRegExp = /\.js$/;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap, lastIndex,
foundI, foundStarMap, starI, i, j, part,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseParts = baseParts.slice(0, baseParts.length - 1);
name = name.split('/');
lastIndex = name.length - 1;
// Node .js allowance:
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
name = baseParts.concat(name);
//start trimDots
for (i = 0; i < name.length; i += 1) {
part = name[i];
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i,
args = [],
callbackType = typeof callback,
usingExports;
//Use name if no relName
relName = relName || name;
//Call the callback to define the module, if necessary.
if (callbackType === 'undefined' || callbackType === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback ? callback.apply(defined[name], args) : undefined;
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (config.deps) {
req(config.deps, config.callback);
}
if (!callback) {
return;
}
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
return req(cfg);
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("almond", function(){});
// vim:ts=4:sts=4:sw=4:
/*!
*
* Copyright 2009-2012 Kris Kowal under the terms of the MIT
* license found at http://github.com/kriskowal/q/raw/master/LICENSE
*
* With parts by Tyler Close
* Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
* at http://www.opensource.org/licenses/mit-license.html
* Forked at ref_send.js version: 2009-05-11
*
* With parts by Mark Miller
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function (definition) {
// Turn off strict mode for this function so we can assign to global.Q
/* jshint strict: false */
// This file will function properly as a <script> tag, or a module
// using CommonJS and NodeJS or RequireJS module formats. In
// Common/Node/RequireJS, the module exports the Q API and when
// executed as a simple <script>, it creates a Q global instead.
// Montage Require
if (typeof bootstrap === "function") {
bootstrap("promise", definition);
// CommonJS
} else if (typeof exports === "object") {
module.exports = definition();
// RequireJS
} else if (typeof define === "function" && define.amd) {
define('q',definition);
// SES (Secure EcmaScript)
} else if (typeof ses !== "undefined") {
if (!ses.ok()) {
return;
} else {
ses.makeQ = definition;
}
// <script>
} else {
Q = definition();
}
})(function () {
"use strict";
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported
// by Q.
var qStartingLine = captureLine();
var qFileName;
// shims
// used for fallback in "allResolved"
var noop = function () {};
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
var nextTick =(function () {
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestTick = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
nextTick = function (task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestTick();
}
};
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestTick = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestTick = setImmediate.bind(window, flush);
} else {
requestTick = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
// At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
// working message ports the first time a page loads.
channel.port1.onmessage = function () {
requestTick = requestPortTick;
channel.port1.onmessage = flush;
flush();
};
var requestPortTick = function () {
// Opera requires us to provide a message payload, regardless of
// whether we use it.
channel.port2.postMessage(0);
};
requestTick = function () {
setTimeout(flush, 0);
requestPortTick();
};
} else {
// old browsers
requestTick = function () {
setTimeout(flush, 0);
};
}
return nextTick;
})();
// Attempt to make generics safe in the face of downstream
// modifications.
// There is no situation where this is necessary.
// If you need a security guarantee, these primordials need to be
// deeply frozen anyway, and if you don’t need a security guarantee,
// this is just plain paranoid.
// However, this **might** have the nice side-effect of reducing the size of
// the minified code by reducing x.call() to merely x()
// See Mark Miller’s explanation of what this does.
// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
var call = Function.call;
function uncurryThis(f) {
return function () {
return call.apply(f, arguments);
};
}
// This is equivalent, but slower:
// uncurryThis = Function_bind.bind(Function_bind.call);
// http://jsperf.com/uncurrythis
var array_slice = uncurryThis(Array.prototype.slice);
var array_reduce = uncurryThis(
Array.prototype.reduce || function (callback, basis) {
var index = 0,
length = this.length;
// concerning the initial value, if one is not provided
if (arguments.length === 1) {
// seek to the first value in the array, accounting
// for the possibility that is is a sparse array
do {
if (index in this) {
basis = this[index++];
break;
}
if (++index >= length) {
throw new TypeError();
}
} while (1);
}
// reduce
for (; index < length; index++) {
// account for the possibility that the array is sparse
if (index in this) {
basis = callback(basis, this[index], index);
}
}
return basis;
}
);
var array_indexOf = uncurryThis(
Array.prototype.indexOf || function (value) {
// not a very good shim, but good enough for our one use of it
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return i;
}
}
return -1;
}
);
var array_map = uncurryThis(
Array.prototype.map || function (callback, thisp) {
var self = this;
var collect = [];
array_reduce(self, function (undefined, value, index) {
collect.push(callback.call(thisp, value, index, self));
}, void 0);
return collect;
}
);
var object_create = Object.create || function (prototype) {
function Type() { }
Type.prototype = prototype;
return new Type();
};
var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
var object_keys = Object.keys || function (object) {
var keys = [];
for (var key in object) {
if (object_hasOwnProperty(object, key)) {
keys.push(key);
}
}
return keys;
};
var object_toString = uncurryThis(Object.prototype.toString);
function isObject(value) {
return value === Object(value);
}
// generator related shims
// FIXME: Remove this function once ES6 generators are in SpiderMonkey.
function isStopIteration(exception) {
return (
object_toString(exception) === "[object StopIteration]" ||
exception instanceof QReturnValue
);
}
// FIXME: Remove this helper and Q.return once ES6 generators are in
// SpiderMonkey.
var QReturnValue;
if (typeof ReturnValue !== "undefined") {
QReturnValue = ReturnValue;
} else {
QReturnValue = function (value) {
this.value = value;
};
}
// long stack traces
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, promise) {
// If possible, transform the error stack trace by removing Node and Q
// cruft, then concatenating with the stack trace of `promise`. See #57.
if (hasStacks &&
promise.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var p = promise; !!p; p = p.source) {
if (p.stack) {
stacks.unshift(p.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n");
var desiredLines = [];
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
// In IE10 function name can have spaces ("Anonymous function") O_o
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) {
return [attempt1[1], Number(attempt1[2])];
}
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) {
return [attempt2[1], Number(attempt2[2])];
}
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) {
return [attempt3[1], Number(attempt3[2])];
}
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0];
var lineNumber = fileNameAndLineNumber[1];
return fileName === qFileName &&
lineNumber >= qStartingLine &&
lineNumber <= qEndingLine;
}
// discover own file name and line number range for filtering stack
// traces
function captureLine() {
if (!hasStacks) {
return;
}
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) {
return;
}
qFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function deprecate(callback, name, alternative) {
return function () {
if (typeof console !== "undefined" &&
typeof console.warn === "function") {
console.warn(name + " is deprecated, use " + alternative +
" instead.", new Error("").stack);
}
return callback.apply(callback, arguments);
};
}
// end of shims
// beginning of real work
/**
* Constructs a promise for an immediate reference, passes promises through, or
* coerces promises from different systems.
* @param value immediate reference or promise
*/
function Q(value) {
// If the object is already a Promise, return it directly. This enables
// the resolve function to both be used to created references from objects,
// but to tolerably coerce non-promises to promises.
if (isPromise(value)) {
return value;
}
// assimilate thenables
if (isPromiseAlike(value)) {
return coerce(value);
} else {
return fulfill(value);
}
}
Q.resolve = Q;
/**
* Performs a task in a future turn of the event loop.
* @param {Function} task
*/
Q.nextTick = nextTick;
/**
* Controls whether or not long stack traces will be on
*/
Q.longStackSupport = false;
/**
* Constructs a {promise, resolve, reject} object.
*
* `resolve` is a callback to invoke with a more resolved value for the
* promise. To fulfill the promise, invoke `resolve` with any value that is
* not a thenable. To reject the promise, invoke `resolve` with a rejected
* thenable, or invoke `reject` with the reason directly. To resolve the
* promise to another thenable, thus putting it in the same state, invoke
* `resolve` with that other thenable.
*/
Q.defer = defer;
function defer() {
// if "messages" is an "Array", that indicates that the promise has not yet
// been resolved. If it is "undefined", it has been resolved. Each
// element of the messages array is itself an array of complete arguments to
// forward to the resolved promise. We coerce the resolution value to a
// promise using the `resolve` function because it handles both fully
// non-thenable values and other thenables gracefully.
var messages = [], progressListeners = [], resolvedPromise;
var deferred = object_create(defer.prototype);
var promise = object_create(Promise.prototype);
promise.promiseDispatch = function (resolve, op, operands) {
var args = array_slice(arguments);
if (messages) {
messages.push(args);
if (op === "when" && operands[1]) { // progress operand
progressListeners.push(operands[1]);
}
} else {
nextTick(function () {
resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
});
}
};
// XXX deprecated
promise.valueOf = function () {
if (messages) {
return promise;
}
var nearerValue = nearer(resolvedPromise);
if (isPromise(nearerValue)) {
resolvedPromise = nearerValue; // shorten chain
}
return nearerValue;
};
promise.inspect = function () {
if (!resolvedPromise) {
return { state: "pending" };
}
return resolvedPromise.inspect();
};
if (Q.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
// NOTE: don't try to use `Error.captureStackTrace` or transfer the
// accessor around; that causes memory leaks as per GH-111. Just
// reify the stack trace as a string ASAP.
//
// At the same time, cut off the first line; it's always just
// "[object Promise]\n", as per the `toString`.
promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
}
// NOTE: we do the checks for `resolvedPromise` in each method, instead of
// consolidating them into `become`, since otherwise we'd create new
// promises with the lines `become(whatever(value))`. See e.g. GH-252.
function become(newPromise) {
resolvedPromise = newPromise;
promise.source = newPromise;
array_reduce(messages, function (undefined, message) {
nextTick(function () {
newPromise.promiseDispatch.apply(newPromise, message);
});
}, void 0);
messages = void 0;
progressListeners = void 0;
}
deferred.promise = promise;
deferred.resolve = function (value) {
if (resolvedPromise) {
return;
}
become(Q(value));
};
deferred.fulfill = function (value) {
if (resolvedPromise) {
return;
}
become(fulfill(value));
};
deferred.reject = function (reason) {
if (resolvedPromise) {
return;
}
become(reject(reason));
};
deferred.notify = function (progress) {
if (resolvedPromise) {
return;
}
array_reduce(progressListeners, function (undefined, progressListener) {
nextTick(function () {
progressListener(progress);
});
}, void 0);
};
return deferred;
}
/**
* Creates a Node-style callback that will resolve or reject the deferred
* promise.
* @returns a nodeback
*/
defer.prototype.makeNodeResolver = function () {
var self = this;
return function (error, value) {
if (error) {
self.reject(error);
} else if (arguments.length > 2) {
self.resolve(array_slice(arguments, 1));
} else {
self.resolve(value);
}
};
};
/**
* @param resolver {Function} a function that returns nothing and accepts
* the resolve, reject, and notify functions for a deferred.
* @returns a promise that may be resolved with the given resolve and reject
* functions, or rejected by a thrown exception in resolver
*/
Q.Promise = promise; // ES6
Q.promise = promise;
function promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("resolver must be a function.");
}
var deferred = defer();
try {
resolver(deferred.resolve, deferred.reject, deferred.notify);
} catch (reason) {
deferred.reject(reason);
}
return deferred.promise;
}
promise.race = race; // ES6
promise.all = all; // ES6
promise.reject = reject; // ES6
promise.resolve = Q; // ES6
// XXX experimental. This method is a way to denote that a local value is
// serializable and should be immediately dispatched to a remote upon request,
// instead of passing a reference.
Q.passByCopy = function (object) {
//freeze(object);
//passByCopies.set(object, true);
return object;
};
Promise.prototype.passByCopy = function () {
//freeze(object);
//passByCopies.set(object, true);
return this;
};
/**
* If two promises eventually fulfill to the same value, promises that value,
* but otherwise rejects.
* @param x {Any*}
* @param y {Any*}
* @returns {Any*} a promise for x and y if they are the same, but a rejection
* otherwise.
*
*/
Q.join = function (x, y) {
return Q(x).join(y);
};
Promise.prototype.join = function (that) {
return Q([this, that]).spread(function (x, y) {
if (x === y) {
// TODO: "===" should be Object.is or equiv
return x;
} else {
throw new Error("Can't join: not the same: " + x + " " + y);
}
});
};
/**
* Returns a promise for the first of an array of promises to become fulfilled.
* @param answers {Array[Any*]} promises to race
* @returns {Any*} the first promise to be fulfilled
*/
Q.race = race;
function race(answerPs) {
return promise(function(resolve, reject) {
// Switch to this once we can assume at least ES5
// answerPs.forEach(function(answerP) {
// Q(answerP).then(resolve, reject);
// });
// Use this in the meantime
for (var i = 0, len = answerPs.length; i < len; i++) {
Q(answerPs[i]).then(resolve, reject);
}
});
}
Promise.prototype.race = function () {
return this.then(Q.race);
};
/**
* Constructs a Promise with a promise descriptor object and optional fallback
* function. The descriptor contains methods like when(rejected), get(name),
* set(name, value), post(name, args), and delete(name), which all
* return either a value, a promise for a value, or a rejection. The fallback
* accepts the operation name, a resolver, and any further arguments that would
* have been forwarded to the appropriate method above had a method been
* provided with the proper name. The API makes no guarantees about the nature
* of the returned object, apart from that it is usable whereever promises are
* bought and sold.
*/
Q.makePromise = Promise;
function Promise(descriptor, fallback, inspect) {
if (fallback === void 0) {
fallback = function (op) {
return reject(new Error(
"Promise does not support operation: " + op
));
};
}
if (inspect === void 0) {
inspect = function () {
return {state: "unknown"};
};
}
var promise = object_create(Promise.prototype);
promise.promiseDispatch = function (resolve, op, args) {
var result;
try {
if (descriptor[op]) {
result = descriptor[op].apply(promise, args);
} else {
result = fallback.call(promise, op, args);
}
} catch (exception) {
result = reject(exception);
}
if (resolve) {
resolve(result);
}
};
promise.inspect = inspect;
// XXX deprecated `valueOf` and `exception` support
if (inspect) {
var inspected = inspect();
if (inspected.state === "rejected") {
promise.exception = inspected.reason;
}
promise.valueOf = function () {
var inspected = inspect();
if (inspected.state === "pending" ||
inspected.state === "rejected") {
return promise;
}
return inspected.value;
};
}
return promise;
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.then = function (fulfilled, rejected, progressed) {
var self = this;
var deferred = defer();
var done = false; // ensure the untrusted promise makes at most a
// single call to one of the callbacks
function _fulfilled(value) {
try {
return typeof fulfilled === "function" ? fulfilled(value) : value;
} catch (exception) {
return reject(exception);
}
}
function _rejected(exception) {
if (typeof rejected === "function") {
makeStackTraceLong(exception, self);
try {
return rejected(exception);
} catch (newException) {
return reject(newException);
}
}
return reject(exception);
}
function _progressed(value) {
return typeof progressed === "function" ? progressed(value) : value;
}
nextTick(function () {
self.promiseDispatch(function (value) {
if (done) {
return;
}
done = true;
deferred.resolve(_fulfilled(value));
}, "when", [function (exception) {
if (done) {
return;
}
done = true;
deferred.resolve(_rejected(exception));
}]);
});
// Progress propagator need to be attached in the current tick.
self.promiseDispatch(void 0, "when", [void 0, function (value) {
var newValue;
var threw = false;
try {
newValue = _progressed(value);
} catch (e) {
threw = true;
if (Q.onerror) {
Q.onerror(e);
} else {
throw e;
}
}
if (!threw) {
deferred.notify(newValue);
}
}]);
return deferred.promise;
};
/**
* Registers an observer on a promise.
*
* Guarantees:
*
* 1. that fulfilled and rejected will be called only once.
* 2. that either the fulfilled callback or the rejected callback will be
* called, but not both.
* 3. that fulfilled and rejected will not be called in this turn.
*
* @param value promise or immediate reference to observe
* @param fulfilled function to be called with the fulfilled value
* @param rejected function to be called with the rejection exception
* @param progressed function to be called on any progress notifications
* @return promise for the return value from the invoked callback
*/
Q.when = when;
function when(value, fulfilled, rejected, progressed) {
return Q(value).then(fulfilled, rejected, progressed);
}
Promise.prototype.thenResolve = function (value) {
return this.then(function () { return value; });
};
Q.thenResolve = function (promise, value) {
return Q(promise).thenResolve(value);
};
Promise.prototype.thenReject = function (reason) {
return this.then(function () { throw reason; });
};
Q.thenReject = function (promise, reason) {
return Q(promise).thenReject(reason);
};
/**
* If an object is not a promise, it is as "near" as possible.
* If a promise is rejected, it is as "near" as possible too.
* If it’s a fulfilled promise, the fulfillment value is nearer.
* If it’s a deferred promise and the deferred has been resolved, the
* resolution is "nearer".
* @param object
* @returns most resolved (nearest) form of the object
*/
// XXX should we re-do this?
Q.nearer = nearer;
function nearer(value) {
if (isPromise(value)) {
var inspected = value.inspect();
if (inspected.state === "fulfilled") {
return inspected.value;
}
}
return value;
}
/**
* @returns whether the given object is a promise.
* Otherwise it is a fulfilled value.
*/
Q.isPromise = isPromise;
function isPromise(object) {
return isObject(object) &&
typeof object.promiseDispatch === "function" &&
typeof object.inspect === "function";
}
Q.isPromiseAlike = isPromiseAlike;
function isPromiseAlike(object) {
return isObject(object) && typeof object.then === "function";
}
/**
* @returns whether the given object is a pending promise, meaning not
* fulfilled or rejected.
*/
Q.isPending = isPending;
function isPending(object) {
return isPromise(object) && object.inspect().state === "pending";
}
Promise.prototype.isPending = function () {
return this.inspect().state === "pending";
};
/**
* @returns whether the given object is a value or fulfilled
* promise.
*/
Q.isFulfilled = isFulfilled;
function isFulfilled(object) {
return !isPromise(object) || object.inspect().state === "fulfilled";
}
Promise.prototype.isFulfilled = function () {
return this.inspect().state === "fulfilled";
};
/**
* @returns whether the given object is a rejected promise.
*/
Q.isRejected = isRejected;
function isRejected(object) {
return isPromise(object) && object.inspect().state === "rejected";
}
Promise.prototype.isRejected = function () {
return this.inspect().state === "rejected";
};
//// BEGIN UNHANDLED REJECTION TRACKING
// This promise library consumes exceptions thrown in handlers so they can be
// handled by a subsequent promise. The exceptions get added to this array when
// they are created, and removed when they are handled. Note that in ES6 or
// shimmed environments, this would naturally be a `Set`.
var unhandledReasons = [];
var unhandledRejections = [];
var trackUnhandledRejections = true;
function resetUnhandledRejections() {
unhandledReasons.length = 0;
unhandledRejections.length = 0;
if (!trackUnhandledRejections) {
trackUnhandledRejections = true;
}
}
function trackRejection(promise, reason) {
if (!trackUnhandledRejections) {
return;
}
unhandledRejections.push(promise);
if (reason && typeof reason.stack !== "undefined") {
unhandledReasons.push(reason.stack);
} else {
unhandledReasons.push("(no stack) " + reason);
}
}
function untrackRejection(promise) {
if (!trackUnhandledRejections) {
return;
}
var at = array_indexOf(unhandledRejections, promise);
if (at !== -1) {
unhandledRejections.splice(at, 1);
unhandledReasons.splice(at, 1);
}
}
Q.resetUnhandledRejections = resetUnhandledRejections;
Q.getUnhandledReasons = function () {
// Make a copy so that consumers can't interfere with our internal state.
return unhandledReasons.slice();
};
Q.stopUnhandledRejectionTracking = function () {
resetUnhandledRejections();
trackUnhandledRejections = false;
};
resetUnhandledRejections();
//// END UNHANDLED REJECTION TRACKING
/**
* Constructs a rejected promise.
* @param reason value describing the failure
*/
Q.reject = reject;
function reject(reason) {
var rejection = Promise({
"when": function (rejected) {
// note that the error has been handled
if (rejected) {
untrackRejection(this);
}
return rejected ? rejected(reason) : this;
}
}, function fallback() {
return this;
}, function inspect() {
return { state: "rejected", reason: reason };
});
// Note that the reason has not been handled.
trackRejection(rejection, reason);
return rejection;
}
/**
* Constructs a fulfilled promise for an immediate reference.
* @param value immediate reference
*/
Q.fulfill = fulfill;
function fulfill(value) {
return Promise({
"when": function () {
return value;
},
"get": function (name) {
return value[name];
},
"set": function (name, rhs) {
value[name] = rhs;
},
"delete": function (name) {
delete value[name];
},
"post": function (name, args) {
// Mark Miller proposes that post with no name should apply a
// promised function.
if (name === null || name === void 0) {
return value.apply(void 0, args);
} else {
return value[name].apply(value, args);
}
},
"apply": function (thisp, args) {
return value.apply(thisp, args);
},
"keys": function () {
return object_keys(value);
}
}, void 0, function inspect() {
return { state: "fulfilled", value: value };
});
}
/**
* Converts thenables to Q promises.
* @param promise thenable promise
* @returns a Q promise
*/
function coerce(promise) {
var deferred = defer();
nextTick(function () {
try {
promise.then(deferred.resolve, deferred.reject, deferred.notify);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
}
/**
* Annotates an object such that it will never be
* transferred away from this process over any promise
* communication channel.
* @param object
* @returns promise a wrapping of that object that
* additionally responds to the "isDef" message
* without a rejection.
*/
Q.master = master;
function master(object) {
return Promise({
"isDef": function () {}
}, function fallback(op, args) {
return dispatch(object, op, args);
}, function () {
return Q(object).inspect();
});
}
/**
* Spreads the values of a promised array of arguments into the
* fulfillment callback.
* @param fulfilled callback that receives variadic arguments from the
* promised array
* @param rejected callback that receives the exception if the promise
* is rejected.
* @returns a promise for the return value or thrown exception of
* either callback.
*/
Q.spread = spread;
function spread(value, fulfilled, rejected) {
return Q(value).spread(fulfilled, rejected);
}
Promise.prototype.spread = function (fulfilled, rejected) {
return this.all().then(function (array) {
return fulfilled.apply(void 0, array);
}, rejected);
};
/**
* The async function is a decorator for generator functions, turning
* them into asynchronous generators. Although generators are only part
* of the newest ECMAScript 6 drafts, this code does not cause syntax
* errors in older engines. This code should continue to work and will
* in fact improve over time as the language improves.
*
* ES6 generators are currently part of V8 version 3.19 with the
* --harmony-generators runtime flag enabled. SpiderMonkey has had them
* for longer, but under an older Python-inspired form. This function
* works on both kinds of generators.
*
* Decorates a generator function such that:
* - it may yield promises
* - execution will continue when that promise is fulfilled
* - the value of the yield expression will be the fulfilled value
* - it returns a promise for the return value (when the generator
* stops iterating)
* - the decorated function returns a promise for the return value
* of the generator or the first rejected promise among those
* yielded.
* - if an error is thrown in the generator, it propagates through
* every following yield until it is caught, or until it escapes
* the generator function altogether, and is translated into a
* rejection for the promise returned by the decorated generator.
*/
Q.async = async;
function async(makeGenerator) {
return function () {
// when verb is "send", arg is a value
// when verb is "throw", arg is an exception
function continuer(verb, arg) {
var result;
// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
// engine that has a deployed base of browsers that support generators.
// However, SM's generators use the Python-inspired semantics of
// outdated ES6 drafts. We would like to support ES6, but we'd also
// like to make it possible to use generators in deployed browsers, so
// we also support Python-style generators. At some point we can remove
// this block.
if (typeof StopIteration === "undefined") {
// ES6 Generators
try {
result = generator[verb](arg);
} catch (exception) {
return reject(exception);
}
if (result.done) {
return result.value;
} else {
return when(result.value, callback, errback);
}
} else {
// SpiderMonkey Generators
// FIXME: Remove this case when SM does ES6 generators.
try {
result = generator[verb](arg);
} catch (exception) {
if (isStopIteration(exception)) {
return exception.value;
} else {
return reject(exception);
}
}
return when(result, callback, errback);
}
}
var generator = makeGenerator.apply(this, arguments);
var callback = continuer.bind(continuer, "next");
var errback = continuer.bind(continuer, "throw");
return callback();
};
}
/**
* The spawn function is a small wrapper around async that immediately
* calls the generator and also ends the promise chain, so that any
* unhandled errors are thrown instead of forwarded to the error
* handler. This is useful because it's extremely common to run
* generators at the top-level to work with libraries.
*/
Q.spawn = spawn;
function spawn(makeGenerator) {
Q.done(Q.async(makeGenerator)());
}
// FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
/**
* Throws a ReturnValue exception to stop an asynchronous generator.
*
* This interface is a stop-gap measure to support generator return
* values in older Firefox/SpiderMonkey. In browsers that support ES6
* generators like Chromium 29, just use "return" in your generator
* functions.
*
* @param value the return value for the surrounding generator
* @throws ReturnValue exception with the value.
* @example
* // ES6 style
* Q.async(function* () {
* var foo = yield getFooPromise();
* var bar = yield getBarPromise();
* return foo + bar;
* })
* // Older SpiderMonkey style
* Q.async(function () {
* var foo = yield getFooPromise();
* var bar = yield getBarPromise();
* Q.return(foo + bar);
* })
*/
Q["return"] = _return;
function _return(value) {
throw new QReturnValue(value);
}
/**
* The promised function decorator ensures that any promise arguments
* are settled and passed as values (`this` is also settled and passed
* as a value). It will also ensure that the result of a function is
* always a promise.
*
* @example
* var add = Q.promised(function (a, b) {
* return a + b;
* });
* add(Q(a), Q(B));
*
* @param {function} callback The function to decorate
* @returns {function} a function that has been decorated.
*/
Q.promised = promised;
function promised(callback) {
return function () {
return spread([this, all(arguments)], function (self, args) {
return callback.apply(self, args);
});
};
}
/**
* sends a message to a value in a future turn
* @param object* the recipient
* @param op the name of the message operation, e.g., "when",
* @param args further arguments to be forwarded to the operation
* @returns result {Promise} a promise for the result of the operation
*/
Q.dispatch = dispatch;
function dispatch(object, op, args) {
return Q(object).dispatch(op, args);
}
Promise.prototype.dispatch = function (op, args) {
var self = this;
var deferred = defer();
nextTick(function () {
self.promiseDispatch(deferred.resolve, op, args);
});
return deferred.promise;
};
/**
* Gets the value of a property in a future turn.
* @param object promise or immediate reference for target object
* @param name name of property to get
* @return promise for the property value
*/
Q.get = function (object, key) {
return Q(object).dispatch("get", [key]);
};
Promise.prototype.get = function (key) {
return this.dispatch("get", [key]);
};
/**
* Sets the value of a property in a future turn.
* @param object promise or immediate reference for object object
* @param name name of property to set
* @param value new value of property
* @return promise for the return value
*/
Q.set = function (object, key, value) {
return Q(object).dispatch("set", [key, value]);
};
Promise.prototype.set = function (key, value) {
return this.dispatch("set", [key, value]);
};
/**
* Deletes a property in a future turn.
* @param object promise or immediate reference for target object
* @param name name of property to delete
* @return promise for the return value
*/
Q.del = // XXX legacy
Q["delete"] = function (object, key) {
return Q(object).dispatch("delete", [key]);
};
Promise.prototype.del = // XXX legacy
Promise.prototype["delete"] = function (key) {
return this.dispatch("delete", [key]);
};
/**
* Invokes a method in a future turn.
* @param object promise or immediate reference for target object
* @param name name of method to invoke
* @param value a value to post, typically an array of
* invocation arguments for promises that
* are ultimately backed with `resolve` values,
* as opposed to those backed with URLs
* wherein the posted value can be any
* JSON serializable object.
* @return promise for the return value
*/
// bound locally because it is used by other methods
Q.mapply = // XXX As proposed by "Redsandro"
Q.post = function (object, name, args) {
return Q(object).dispatch("post", [name, args]);
};
Promise.prototype.mapply = // XXX As proposed by "Redsandro"
Promise.prototype.post = function (name, args) {
return this.dispatch("post", [name, args]);
};
/**
* Invokes a method in a future turn.
* @param object promise or immediate reference for target object
* @param name name of method to invoke
* @param ...args array of invocation arguments
* @return promise for the return value
*/
Q.send = // XXX Mark Miller's proposed parlance
Q.mcall = // XXX As proposed by "Redsandro"
Q.invoke = function (object, name /*...args*/) {
return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
};
Promise.prototype.send = // XXX Mark Miller's proposed parlance
Promise.prototype.mcall = // XXX As proposed by "Redsandro"
Promise.prototype.invoke = function (name /*...args*/) {
return this.dispatch("post", [name, array_slice(arguments, 1)]);
};
/**
* Applies the promised function in a future turn.
* @param object promise or immediate reference for target function
* @param args array of application arguments
*/
Q.fapply = function (object, args) {
return Q(object).dispatch("apply", [void 0, args]);
};
Promise.prototype.fapply = function (args) {
return this.dispatch("apply", [void 0, args]);
};
/**
* Calls the promised function in a future turn.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q["try"] =
Q.fcall = function (object /* ...args*/) {
return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
};
Promise.prototype.fcall = function (/*...args*/) {
return this.dispatch("apply", [void 0, array_slice(arguments)]);
};
/**
* Binds the promised function, transforming return values into a fulfilled
* promise and thrown errors into a rejected one.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q.fbind = function (object /*...args*/) {
var promise = Q(object);
var args = array_slice(arguments, 1);
return function fbound() {
return promise.dispatch("apply", [
this,
args.concat(array_slice(arguments))
]);
};
};
Promise.prototype.fbind = function (/*...args*/) {
var promise = this;
var args = array_slice(arguments);
return function fbound() {
return promise.dispatch("apply", [
this,
args.concat(array_slice(arguments))
]);
};
};
/**
* Requests the names of the owned properties of a promised
* object in a future turn.
* @param object promise or immediate reference for target object
* @return promise for the keys of the eventually settled object
*/
Q.keys = function (object) {
return Q(object).dispatch("keys", []);
};
Promise.prototype.keys = function () {
return this.dispatch("keys", []);
};
/**
* Turns an array of promises into a promise for an array. If any of
* the promises gets rejected, the whole array is rejected immediately.
* @param {Array*} an array (or promise for an array) of values (or
* promises for values)
* @returns a promise for an array of the corresponding values
*/
// By Mark Miller
// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
Q.all = all;
function all(promises) {
return when(promises, function (promises) {
var countDown = 0;
var deferred = defer();
array_reduce(promises, function (undefined, promise, index) {
var snapshot;
if (
isPromise(promise) &&
(snapshot = promise.inspect()).state === "fulfilled"
) {
promises[index] = snapshot.value;
} else {
++countDown;
when(
promise,
function (value) {
promises[index] = value;
if (--countDown === 0) {
deferred.resolve(promises);
}
},
deferred.reject,
function (progress) {
deferred.notify({ index: index, value: progress });
}
);
}
}, void 0);
if (countDown === 0) {
deferred.resolve(promises);
}
return deferred.promise;
});
}
Promise.prototype.all = function () {
return all(this);
};
/**
* Waits for all promises to be settled, either fulfilled or
* rejected. This is distinct from `all` since that would stop
* waiting at the first rejection. The promise returned by
* `allResolved` will never be rejected.
* @param promises a promise for an array (or an array) of promises
* (or values)
* @return a promise for an array of promises
*/
Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");
function allResolved(promises) {
return when(promises, function (promises) {
promises = array_map(promises, Q);
return when(all(array_map(promises, function (promise) {
return when(promise, noop, noop);
})), function () {
return promises;
});
});
}
Promise.prototype.allResolved = function () {
return allResolved(this);
};
/**
* @see Promise#allSettled
*/
Q.allSettled = allSettled;
function allSettled(promises) {
return Q(promises).allSettled();
}
/**
* Turns an array of promises into a promise for an array of their states (as
* returned by `inspect`) when they have all settled.
* @param {Array[Any*]} values an array (or promise for an array) of values (or
* promises for values)
* @returns {Array[State]} an array of states for the respective values.
*/
Promise.prototype.allSettled = function () {
return this.then(function (promises) {
return all(array_map(promises, function (promise) {
promise = Q(promise);
function regardless() {
return promise.inspect();
}
return promise.then(regardless, regardless);
}));
});
};
/**
* Captures the failure of a promise, giving an oportunity to recover
* with a callback. If the given promise is fulfilled, the returned
* promise is fulfilled.
* @param {Any*} promise for something
* @param {Function} callback to fulfill the returned promise if the
* given promise is rejected
* @returns a promise for the return value of the callback
*/
Q.fail = // XXX legacy
Q["catch"] = function (object, rejected) {
return Q(object).then(void 0, rejected);
};
Promise.prototype.fail = // XXX legacy
Promise.prototype["catch"] = function (rejected) {
return this.then(void 0, rejected);
};
/**
* Attaches a listener that can respond to progress notifications from a
* promise's originating deferred. This listener receives the exact arguments
* passed to ``deferred.notify``.
* @param {Any*} promise for something
* @param {Function} callback to receive any progress notifications
* @returns the given promise, unchanged
*/
Q.progress = progress;
function progress(object, progressed) {
return Q(object).then(void 0, void 0, progressed);
}
Promise.prototype.progress = function (progressed) {
return this.then(void 0, void 0, progressed);
};
/**
* Provides an opportunity to observe the settling of a promise,
* regardless of whether the promise is fulfilled or rejected. Forwards
* the resolution to the returned promise when the callback is done.
* The callback can return a promise to defer completion.
* @param {Any*} promise
* @param {Function} callback to observe the resolution of the given
* promise, takes no arguments.
* @returns a promise for the resolution of the given promise when
* ``fin`` is done.
*/
Q.fin = // XXX legacy
Q["finally"] = function (object, callback) {
return Q(object)["finally"](callback);
};
Promise.prototype.fin = // XXX legacy
Promise.prototype["finally"] = function (callback) {
callback = Q(callback);
return this.then(function (value) {
return callback.fcall().then(function () {
return value;
});
}, function (reason) {
// TODO attempt to recycle the rejection with "this".
return callback.fcall().then(function () {
throw reason;
});
});
};
/**
* Terminates a chain of promises, forcing rejections to be
* thrown as exceptions.
* @param {Any*} promise at the end of a chain of promises
* @returns nothing
*/
Q.done = function (object, fulfilled, rejected, progress) {
return Q(object).done(fulfilled, rejected, progress);
};
Promise.prototype.done = function (fulfilled, rejected, progress) {
var onUnhandledError = function (error) {
// forward to a future turn so that ``when``
// does not catch it and turn it into a rejection.
nextTick(function () {
makeStackTraceLong(error, promise);
if (Q.onerror) {
Q.onerror(error);
} else {
throw error;
}
});
};
// Avoid unnecessary `nextTick`ing via an unnecessary `when`.
var promise = fulfilled || rejected || progress ?
this.then(fulfilled, rejected, progress) :
this;
if (typeof process === "object" && process && process.domain) {
onUnhandledError = process.domain.bind(onUnhandledError);
}
promise.then(void 0, onUnhandledError);
};
/**
* Causes a promise to be rejected if it does not get fulfilled before
* some milliseconds time out.
* @param {Any*} promise
* @param {Number} milliseconds timeout
* @param {String} custom error message (optional)
* @returns a promise for the resolution of the given promise if it is
* fulfilled before the timeout, otherwise rejected.
*/
Q.timeout = function (object, ms, message) {
return Q(object).timeout(ms, message);
};
Promise.prototype.timeout = function (ms, message) {
var deferred = defer();
var timeoutId = setTimeout(function () {
deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
}, ms);
this.then(function (value) {
clearTimeout(timeoutId);
deferred.resolve(value);
}, function (exception) {
clearTimeout(timeoutId);
deferred.reject(exception);
}, deferred.notify);
return deferred.promise;
};
/**
* Returns a promise for the given value (or promised value), some
* milliseconds after it resolved. Passes rejections immediately.
* @param {Any*} promise
* @param {Number} milliseconds
* @returns a promise for the resolution of the given promise after milliseconds
* time has elapsed since the resolution of the given promise.
* If the given promise rejects, that is passed immediately.
*/
Q.delay = function (object, timeout) {
if (timeout === void 0) {
timeout = object;
object = void 0;
}
return Q(object).delay(timeout);
};
Promise.prototype.delay = function (timeout) {
return this.then(function (value) {
var deferred = defer();
setTimeout(function () {
deferred.resolve(value);
}, timeout);
return deferred.promise;
});
};
/**
* Passes a continuation to a Node function, which is called with the given
* arguments provided as an array, and returns a promise.
*
* Q.nfapply(FS.readFile, [__filename])
* .then(function (content) {
* })
*
*/
Q.nfapply = function (callback, args) {
return Q(callback).nfapply(args);
};
Promise.prototype.nfapply = function (args) {
var deferred = defer();
var nodeArgs = array_slice(args);
nodeArgs.push(deferred.makeNodeResolver());
this.fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
/**
* Passes a continuation to a Node function, which is called with the given
* arguments provided individually, and returns a promise.
* @example
* Q.nfcall(FS.readFile, __filename)
* .then(function (content) {
* })
*
*/
Q.nfcall = function (callback /*...args*/) {
var args = array_slice(arguments, 1);
return Q(callback).nfapply(args);
};
Promise.prototype.nfcall = function (/*...args*/) {
var nodeArgs = array_slice(arguments);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
/**
* Wraps a NodeJS continuation passing function and returns an equivalent
* version that returns a promise.
* @example
* Q.nfbind(FS.readFile, __filename)("utf-8")
* .then(console.log)
* .done()
*/
Q.nfbind =
Q.denodeify = function (callback /*...args*/) {
var baseArgs = array_slice(arguments, 1);
return function () {
var nodeArgs = baseArgs.concat(array_slice(arguments));
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
Q(callback).fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
};
Promise.prototype.nfbind =
Promise.prototype.denodeify = function (/*...args*/) {
var args = array_slice(arguments);
args.unshift(this);
return Q.denodeify.apply(void 0, args);
};
Q.nbind = function (callback, thisp /*...args*/) {
var baseArgs = array_slice(arguments, 2);
return function () {
var nodeArgs = baseArgs.concat(array_slice(arguments));
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
function bound() {
return callback.apply(thisp, arguments);
}
Q(bound).fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
};
Promise.prototype.nbind = function (/*thisp, ...args*/) {
var args = array_slice(arguments, 0);
args.unshift(this);
return Q.nbind.apply(void 0, args);
};
/**
* Calls a method of a Node-style object that accepts a Node-style
* callback with a given array of arguments, plus a provided callback.
* @param object an object that has the named method
* @param {String} name name of the method of object
* @param {Array} args arguments to pass to the method; the callback
* will be provided by Q and appended to these arguments.
* @returns a promise for the value or error
*/
Q.nmapply = // XXX As proposed by "Redsandro"
Q.npost = function (object, name, args) {
return Q(object).npost(name, args);
};
Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
Promise.prototype.npost = function (name, args) {
var nodeArgs = array_slice(args || []);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
/**
* Calls a method of a Node-style object that accepts a Node-style
* callback, forwarding the given variadic arguments, plus a provided
* callback argument.
* @param object an object that has the named method
* @param {String} name name of the method of object
* @param ...args arguments to pass to the method; the callback will
* be provided by Q and appended to these arguments.
* @returns a promise for the value or error
*/
Q.nsend = // XXX Based on Mark Miller's proposed "send"
Q.nmcall = // XXX Based on "Redsandro's" proposal
Q.ninvoke = function (object, name /*...args*/) {
var nodeArgs = array_slice(arguments, 2);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
Promise.prototype.ninvoke = function (name /*...args*/) {
var nodeArgs = array_slice(arguments, 1);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
/**
* If a function would like to support both Node continuation-passing-style and
* promise-returning-style, it can end its internal promise chain with
* `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user
* elects to use a nodeback, the result will be sent there. If they do not
* pass a nodeback, they will receive the result promise.
* @param object a result (or a promise for a result)
* @param {Function} nodeback a Node.js-style callback
* @returns either the promise or nothing
*/
Q.nodeify = nodeify;
function nodeify(object, nodeback) {
return Q(object).nodeify(nodeback);
}
Promise.prototype.nodeify = function (nodeback) {
if (nodeback) {
this.then(function (value) {
nextTick(function () {
nodeback(null, value);
});
}, function (error) {
nextTick(function () {
nodeback(error);
});
});
} else {
return this;
}
};
// All code before this point will be filtered from stack traces.
var qEndingLine = captureLine();
return Q;
});
// Library Container
define('gms', ['q'], function (Q) {
var API_URL;
var API_DATA;
var VERSION = '1.0.0';
var init = function (_API_URL) {
API_URL = _API_URL;
};
var CDN_URLS = [];
var MMAs = [];
var VALID_MMAs = []; //MMA objects that succesfully returned some data.
function resetState() {
//blow away state variables. Should only be used for unit test purposes!;
CDN_URLS.splice(0,CDN_URLS.length);
MMAs.splice(0, MMAs.length);
VALID_MMAs.splice(0, VALID_MMAs.length);
}
function processAPIData (data) {
resetState();
//Currently we only ever expect there to be ONE CDN,
//and we only care about the 'hmhCentral' (as opposed to 'legacy') CDN.
for (var i=0; i<data.cdnServers.length; i++) {
var cdn = data.cdnServers[i];
if (cdn.serverType === 'hmhCentral') {
CDN_URLS.push(cdn.url);
break; //we found what we came for
}
}
if(CDN_URLS.length === 0) {
//No HMHCentral CDN URL was provided/found! Throw some kind of error.
throw({
message: "No HMHCentral CDN URL was provided/found was provided by the API!",
name: "CDNNotFoundException"
});
}
for (var j=0; j<data.mediaServers.length; j++) {
var mma = data.mediaServers[j];
if(mma.serverType === 'hmhCentral') {
//we only care about !legacy MMAs!
MMAs.push(mma);
}
}
}
function pingMMA(mma) {
//tries to download the DUMMY file from each MMA, saves the ones that are successful.
var dummyFileUrl = mma.url + '/dummy/file/location.gif';
var deferred = Q.defer();
getDataFromURL(dummyFileUrl).then(function (data) {
//succesfully got the file.
console.log('found valid MMA');
VALID_MMAs.push(mma);
deferred.resolve(mma);
}, function (err) {
console.log('COULD NOT REACH MMA WITH URL:', dummyFileUrl);
deferred.reject();
});
return deferred.promise;
}
function pingMMASync(mma) {
}
function pingAllMMAs() {
//attempts to reach all MMAs provided by API.
//If no
var mma;
var deferred = Q.defer();
var MMAPingPromises = [];
//deal with the no-mmas-provided case.
if (MMAs.length === 0) {
console.log('No valid MMAs provided by API. Using CDN URL instead.');
deferred.reject();
}
//ping 'em all.
for (var i=0; i<MMAs.length; i++) {
mma = MMAs[i];
MMAPingPromises.push(pingMMA(mma));
}
Q.allSettled(MMAPingPromises).then(function (results) {
if (VALID_MMAs.length > 0) {
//find the highest priority one.
console.log('HERE ARE THE RESULTS FOR PING ALL MMAS:', results);
console.log('THIS SHOULD BE THE BEST RESULT', results[0]);
deferred.resolve(results[0]);
} else {
console.log('No reachable MMAs found. Using CDN URL instead.');
deferred.reject();
}
}, function (err) {
console.log('No reachable MMAs found. Using CDN URL instead.');
deferred.reject();
});
return deferred.promise;
}
function hasHTTPError(request) {
if (request.status >= 200 && request.status < 300) {
return false;
} else {
return true;
}
}
//Three stages:
// 1) Init - set correct API url
// 2) Get data from API, populate state variables
// 3) if (MMAs)
// find_working, enumerate from start of list (=priority)
// else
// return CDN url
function getDataFromURLSync(URL) {
//Always return the actual data if request succeeds.
//If request fails, return request object for further inspection.
//
// THIS CALL BLOCKS UNTIL THE HTTP GET CALL RETURNS!
//
var request = new XMLHttpRequest();
var HTTP_METHOD = 'GET';
function generateReturnValue() {
//Sync logic
if (hasHTTPError(request)) {
return request;
} else {
return request.response;
}
}
request.open(HTTP_METHOD, URL, false); //third arg = false for sync call.
request.send(null);
return generateReturnValue();
}
function getDataFromURL(URL) {
// Returns a promise that resolves when data is returned. The resolved
// value will be the response data itself.
//
// The promise will reject if there is ANY error (including status code !== 200).
// Rejection value will be the XMLHttpRequest to allow further inspection by the caller.
//
var request = new XMLHttpRequest();
var deferred = Q.defer();
var HTTP_METHOD = 'GET';
function requestListener() {
if (hasHTTPError(request)) {
deferred.reject(request);
} else {
deferred.resolve(request.response);
}
}
function requestErrorListener() {
deferred.reject(request);
}
request.onload = requestListener;
request.onerror = requestErrorListener;
request.open(HTTP_METHOD, URL, true); //third arg indicates whether async or not.
request.send(null);
return deferred.promise;
}
var getMediaServerURLSync = function () {
return API_URL;
};
var getMediaServerURL = function () {
var deferred = Q.defer();
deferred.resolve(API_URL);
return deferred.promise;
};
return {
VERSION: VERSION,
init: init,
getMediaServerURL: getMediaServerURL,
getMediaServerURLSync: getMediaServerURLSync,
__getDataFromURL: getDataFromURL,
__getDataFromURLSync: getDataFromURLSync,
__processAPIData: processAPIData,
__pingAllMMAs: pingAllMMAs,
CDN_URLS: CDN_URLS,
MMAs: MMAs,
VALID_MMAs: VALID_MMAs,
resetState: resetState
};
});
// Ask almond to synchronously require the
// module value for 'gms' here and return it as the
// value to use for the public API for the built file.
return require('gms');
}));
//# sourceMappingURL=gms.js.map |
var app = angular.module('myApp', ['ngRoute',
'ui.bootstrap',
'ngAnimate',
'ngTable',
'cloudinary',
'photoAlbumAnimations',
'photoAlbumControllers',
'photoAlbumServices'
]);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
title: 'List questions',
templateUrl: 'html/questions/question.html',
controller: 'questionCtrl',
})
.when('/question/add', {
title: 'Add questions',
templateUrl: 'html/questions/questionNew.html',
controller: 'addQuestionCtrl',
})
.when('/question/edit/:id', {
title: ' Edit questions',
templateUrl: 'html/questions/questionEdit.html',
controller: 'editQuestionCtrl',
})
.when('/categories', {
title: "List Category",
templateUrl: 'html/categories/category.html',
controller: 'categoryCtrl',
})
.when('/examies',{
title: "Exam",
templateUrl: 'html/examies/exam.html',
controller: 'examCtrl',
})
.when('/examies/:id/sections',{
title: "Exam",
templateUrl: 'html/sections/section.html',
controller: 'sectionCtrl',
})
.when('/examies/:id/show',{
title: "Exam",
templateUrl: 'html/examies/detail.html',
controller: 'detailExamCtrl',
})
.when('/section_questions', {
title: "Question in Section",
controller: 'section_questionCtrl',
}).
when('/categories/:id/questions', {
title: "Question in Category",
controller: 'section_questionCtrl',
})
.otherwise({
redirectTo: '/home'
});
}]);
|
const versions = {
0: ({ mechanism }) => {
const request = require('./v0/request')
const response = require('./v0/response')
return { request: request({ mechanism }), response }
},
1: ({ mechanism }) => {
const request = require('./v1/request')
const response = require('./v1/response')
return { request: request({ mechanism }), response }
},
}
module.exports = {
versions: Object.keys(versions),
protocol: ({ version }) => versions[version],
}
|
/**
* Created by ane on 5/20/15.
*/
var app = angular.module('myApp', []);
app.directive('ensureUnique',['$http',function($http){
return {
require: 'ngModel',
link: function(scope,ele,attrs,c){
scope.$watch(attrs.ngModel,function(n){
if(!n) return;
$http({
method: 'POST',
url: '/api/check/' + attrs.ensureUnique,
data: {
field: attrs.ensureUnique,
value: scope.ngModel
}
}).success(function(data){
c.$setValidity('unique',data.isUnique);
}).error(function(data){
c.$setValidity('unique',false);
});
});
}
};
}]);
//app.controller('signupController',function($scope){
// $scope.submitted = false;
// $scope.signupForm = function(){
// if($scope.signup_form.$valid){
//
// }else{
// $scope.signup_form.submitted = true;
// }
// };
//}); |
var authrocket = new AuthRocket({
jsUrl: 'https://tessellate.e1.loginrocket.com/v1/',
accountId: 'org_0vFdP9Zc11Y7yucwRTSCg8',
apiKey: 'key_AAAe02TUpGzBNgkrLkXYi6j57tmaiU0ll27NEvDRjBq',
realmId: 'rl_0vFhopfukY34r8EPGmKVpb'
});
console.log('authrocket:', authrocket);
//Set logged in status when dom is loaded
document.addEventListener("DOMContentLoaded", function(event) {
setStatus();
});
//Set status styles
function setStatus() {
var statusEl = document.getElementById("status");
var logoutButton = document.getElementById("logout-btn");
if(authrocket.isLoggedIn){
statusEl.innerHTML = "True";
statusEl.style.color = 'green';
// statusEl.className = statusEl.className ? ' status-loggedIn' : 'status-loggedIn';
logoutButton.style.display='inline';
} else {
statusEl.innerHTML = "False";
statusEl.style.color = 'red';
logoutButton.style.display='none';
}
}
function login(loginData){
if(!loginData){
var loginData = {};
loginData.username = document.getElementById('login-username').value;
loginData.password = document.getElementById('login-password').value;
}
authrocket.login(loginData).then(function(loginInfo){
console.log('successful login:', loginInfo);
setStatus();
}, function(err){
console.error('login() : Error logging in:', err);
});
}
function logout(){
authrocket.logout().then(function(){
console.log('successful logout');
setStatus();
}, function(err){
console.error('logout() : Error logging out:', err);
});
}
function signup(signupData){
if(!signupData){
var signupData = {};
signupData.name = document.getElementById('signup-name').value;
signupData.username = document.getElementById('signup-username').value;
signupData.email = document.getElementById('signup-email').value;
signupData.password = document.getElementById('signup-password').value;
}
authrocket.signup(signupData).then(function(signupRes){
console.log('successful signup', signupRes);
setStatus();
}, function(err){
console.error('logout() : Error signing up:', err);
});
}
function getUsers(){
authrocket.Users.get().then(function(usersList){
console.log('users loaded', usersList);
}, function(err){
console.error('error getting users', err);
});
}
|
(function($){//Модули: getfile, setfile, .xml(), customScrollIFrame
var defaultOptions = {
$mapNavigatorContainer: undefined,
nameIFrame: "PP_iframe",
pixelsScrollableInSeconds: 2000,
minWOuterScroll: 23,
minHOuterScroll: 23,
permanentVisible: true,
minWDraggable: 15,
minHDraggable: 15,
minWIFrame: 320,
minHIFrame: 480,
$dimensions: undefined,
responsiveToMovementOfTheCursorInAConfinedSpace: true,
movementOfTheCursorInAConfinedSpaceSpred: 10,
factorDraggableGrid: 0.5,
gorizontalFixation: "center",
verticalFixation: "top",
minHeightCalculateAuto: 480,
heightCalculateRatio: 16/9,
calculatedHeightAsMaxHeight: true,
stopAllAnimationsAtResize: true
};
var pageManagerVisualizator = function($container, sessionModel, options) {
this._options = options;
var ____ = this;
____.$container = $container;
var customScrollIFrame = new modules.customScrollIFrame($container, this._options);
var mapNavigatorIFrame = new modules.mapNavigatorIFrame($container, this._options);
____.mapNavigatorIFrame = mapNavigatorIFrame;
var resizeIFrame = new modules.resizeIFrame($container, this._options);
var fixationContentAtResize = new modules.fixationContentAtResize($container, this._options);
//Синхронизируем с кастомным скроллом
customScrollIFrame._initPasteHTML();
$container.on("pmv.load.iframe", function(){
customScrollIFrame.reload();
});
//Синхронизируем с мап навигатором
$container.on({
"pmv.load.iframe": mapNavigatorIFrame.reload,
"rif.center-iframe": function() {
mapNavigatorIFrame.updateDraggable();
mapNavigatorIFrame.temporarilyVisibleNavigator();
}
});
//Синхронизируем с ресайзером
$container.on("pmv.load.iframe", resizeIFrame.reload);
$container.one("pmv.load.iframe", resizeIFrame._reloadShowDimensions);
//Синхронизируем с фиксатором контента при ресайзе
$container.on({
"pmv.load.iframe": fixationContentAtResize.reload,
"rifStartResize": fixationContentAtResize.startFixation,
"rifStopResize": fixationContentAtResize.stopFixation
});
this.setSizeIFrame = function( w, source_h, fast ) {
if(w !== null) {
var $fittingWrap;
if($("#"+(____._options.nameIFrame)).length) {
$fittingWrap = $("#"+(____._options.nameIFrame)).closest(".pmv-fitting-wrap");
} else {
$fittingWrap = $container.find(" .pmv-fitting-wrap");
}
var h;
w = parseInt(w);
if(source_h == "auto") {
h = Math.round(w / ____._options.heightCalculateRatio);
if(h < ____._options.minHeightCalculateAuto) {
h = ____._options.minHeightCalculateAuto;
}
} else {
h = source_h;
}
if(fast) {
fixationContentAtResize.startFixation();
if(source_h == "auto" && ____._options.calculatedHeightAsMaxHeight) {
$fittingWrap.stop().css({width: w+'px', height: '100%', maxHeight: h+'px'});
} else {
$fittingWrap.stop().css({width: w+'px', height: h+'px', maxHeight: ''});
}
fixationContentAtResize.stopFixation();
} else {
fixationContentAtResize.startFixation();
if(source_h == "auto" && ____._options.calculatedHeightAsMaxHeight) {
var $outerWrap = $("#"+(____._options.nameIFrame)).closest(".pmv-outer-wrap");
$fittingWrap.css({height: ($fittingWrap.height())+'px', maxHeight: ''});
$fittingWrap.stop().animate({width: w+'px', height: ((h < $outerWrap.height())?h:$outerWrap.height())+'px'}, 1000, "swing", function() {
$fittingWrap.stop().css({width: w+'px', height: '100%', maxHeight: h+'px'});
fixationContentAtResize.stopFixation();
});
} else {
$fittingWrap.css({maxHeight: ''});
$fittingWrap.stop().animate({width: w+'px', height: h+'px'}, 1000, "swing", function() {
fixationContentAtResize.stopFixation();
});
}
}
}
}
this.setPositionIFrame = function(l_factor, t_factor) {
var $iframe = $("#" + (____._options.nameIFrame));
var $fittingWrap;
var $outerWrap;
if($iframe.length) {
$fittingWrap = $iframe.closest(".pmv-fitting-wrap");
$outerWrap = $iframe.closest(".pmv-outer-wrap");
} else {
$fittingWrap = $container.find(" .pmv-fitting-wrap");
$outerWrap = $container.find(" .pmv-outer-wrap");
}
var w, h, w_c, h_c, l, t;
w = $fittingWrap.width();
h = $fittingWrap.height();
w_c = $outerWrap.width();
h_c = $outerWrap.height();
l = Math.round( (w_c - w) * l_factor );
t = Math.round( (h_c - h) * t_factor );
$fittingWrap.css({
top: t,
left: l
});
resizeIFrame._centerIFrameAndNoEmptySpace();//И так сработает после всех методов - потому что события выполняються позже (КРОМЕ FIREFOX)
}
this.setScrollIFrame = function(l_factor, t_factor) {
var iframe = document.getElementById(____._options.nameIFrame);
var win = iframe.contentWindow || iframe;
var doc = iframe.contentDocument || iframe.contentWindow.document;
var wWindow, wDocument, leftScroll, hWindow, hDocument, topScroll;
wWindow = $(win).width();
wDocument = $(doc).width();
hWindow = $(win).height();
hDocument = $(doc).height();
leftScroll = Math.round( (wDocument - wWindow) * l_factor );
topScroll = Math.round( (hDocument - hWindow) * t_factor );
$(win).scrollLeft((leftScroll < 0)?0:leftScroll);
$(win).scrollTop((topScroll < 0)?0:topScroll);
}
this._create = function() {
this._init();
//Чтобы скролл работал не только в iFrame Но и во всём блоке
$container.on('wheel', customScrollIFrame._handlerMouseWheel);
}
this._destroy = function() {
//Чтобы скролл работал не только в iFrame Но и во всём блоке
$container.off('wheel', customScrollIFrame._handlerMouseWheel);
$container.find( ".pmv-outer-wrap" ).remove();
}
this._init = function() {
$container.append('<div class="pmv-outer-wrap"><div class="pmv-fitting-wrap">' +
'<div class="pmv-fitting-wrap-bl"></div><div class="pmv-fitting-wrap-bb"></div><div class="pmv-fitting-wrap-br"></div>' +
'</div></div>');
$container.append('<div class="pmv-container-bl"></div><div class="pmv-container-bb"></div><div class="pmv-container-br"></div>');
//Получем список страниц
}
this.selectPage = function(href) {
____.currentPage = href;
____._destroyIFrame();
if(href !== null) {
____._createIFrame(href);
}
}
this._createIFrame = function(href) {
$container.trigger("pmv.prepaste.iframe");
____.lastLoadPage = href;
____.currentPage = href;
$container.find( ".pmv-fitting-wrap" ).append('<iframe id="'+(____._options.nameIFrame)+'" name="'+(____._options.nameIFrame)+'" src="'+href+'" width="100%" height="100%"></iframe>');
$('#'+(____._options.nameIFrame)).load(function(){
$container.trigger( "pmv.load.iframe");
$('#'+(____._options.nameIFrame)).contents().find('body').on('click', function(e){
e.type = "click.body.iframe";
$("body").trigger( e );
});
$('#'+(____._options.nameIFrame)).contents().find('body').on('mousedown', function(e){
e.type = "mousedown.body.iframe";
$("body").trigger( e );
});
$('#'+(____._options.nameIFrame)).contents().find('body').on('mouseup', function(e){
e.type = "mouseup.body.iframe";
$("body").trigger( e );
});
$('#'+(____._options.nameIFrame)).contents().find('body').on('mousemove', function(e){
e.type = "mousemove.body.iframe";
$("body").trigger( e );
});
});
}
this._destroyIFrame = function() {
$( '#'+(____._options.nameIFrame) ).remove();
}
this.updateModules = function() {
customScrollIFrame.updateOuterScroll();
resizeIFrame._handlerResize();
}
}
modules.pageManagerVisualizator = pageManagerVisualizator;
})(jQuery); |
'use strict';
const async = require('async');
const _ = require('underscore');
const config = require('../config.json').MessageGenerator;
let mixedConfig = _.defaults(config, {
sendInterval: 500,
deliveryTimeoutTime: 2000,
sendNextMessageOnDelivery: false
});
module.exports = class MessageGenerator {
constructor(scope, nodeManager, messageEmitter) {
_.extend(this, mixedConfig);
this.scope = scope;
this.currentNode = 0;
this.nodeManager = nodeManager;
this.messageEmitter = messageEmitter;
this.lastDeliveryFailed = true;
this.lastMessage = null;
this.logger = scope.logger;
}
getMessage() {
this.cnt = this.cnt || 0;
return this.cnt++;
}
sendMessage(next) {
let nextNode = this.getNextNode(),
messageEmitter = this.messageEmitter,
nodeName = this.scope.nodeName,
publisher = this.scope.publisher;
let goNext = () => {}
if(next) {
goNext = () => {
setTimeout(next, this.sendInterval);
};
}
next = next || () => {};
if(!nextNode) {
return goNext();
}
if(!this.lastDeliveryFailed || !this.lastMessage) {
this.lastMessage = this.getMessage();
}
this.lastDeliveryFailed = false;
let onDeliveryCallback = () => {
clearTimeout(deliveryTimeout);
goNext();
};
let deliveryTimeout = setTimeout(() => {
this.logger.trace('node dead on delivery', nextNode);
messageEmitter.removeListener(`${nodeName}:recieved`,onDeliveryCallback);
this.lastDeliveryFailed = true;
this.nodeManager.deleteNodeAndSyncAllNodes(nextNode, next);
}, this.deliveryTimeoutTime);
this.logger.info(`send message ${this.lastMessage}:`, nextNode);
messageEmitter.once(`${nodeName}:recieved`, onDeliveryCallback);
publisher.publish(`${nextNode}:message`, JSON.stringify({node: nodeName, message: this.lastMessage}));
}
getNextNode() {
let scope = this.scope,
nodeList = scope.nodeList,
nodeName = scope.nodeName;
if(nodeList.length < 2) {
return null;
}
this.currentNode++;
if(this.currentNode >= nodeList.length) {
this.currentNode = 0;
}
if(nodeList[this.currentNode] === scope.nodeName) {
return this.getNextNode();
}
return nodeList[this.currentNode];
}
startSendMessages(callback) {
this.scope.publisher.get('currentCounter', (error, counter) => {
if(error) {
this.cnt = 0
}
if(!counter) {
this.cnt = 0;
}
this.messageEmitter.subscribe([`${this.scope.nodeName}:recieved`], () => {
if(this.sendNextMessageOnDelivery) {
async.forever(this.sendMessage.bind(this));
} else {
setInterval(this.sendMessage.bind(this), this.sendInterval)
}
});
callback(null);
});
}
}
|
export const u1F4F2 = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M1218 1420l-594 436v-272H69v-325h555V985zm1262-940v1844q0 155-182.5 192.5T1906 2554t-391.5-37.5T1332 2324V480q0-75 51.5-131t219-77.5T1906 250t303.5 21.5 219 77.5 51.5 131zm-224-65.5q11 10.5 27 10.5t27-10.5 11-26.5-11-27-27-11-27 11-11 27 11 26.5zM1801 353q-8 0-14 6t-6 14 6 13.5 14 5.5h210q8 0 14-5.5t6-13.5-6-14-14-6h-210zm-175 1960q25 0 39.5-7.5t14.5-30.5q0-21-14.5-29t-39.5-8h-16v-13l-29 21 29 21v-14h16q21 0 30 5t9 17q0 13-9 18t-30 5h-37v15h37zm335-60l-54-23-55 23v55h109v-55zm-54-6l38 17v28h-77v-28zm313 4h-91v57h91v-57zm-16 41h-59v-26h59v26zm42-66h-84v16h68v33h16v-49zm130-1606h-939v1555h939V620z"},"children":[]}]}; |
describe("DurationJS", function() {
it("can parse durations as strings", function(){
var d = new Duration();
expect(d.parse('1 hours 33 mins 2 seconds').seconds()).toBe(5582);
expect(d.parse('2 w 3day 1 h 33 m 2 sec').seconds()).toBe(1474382);
expect(d.parse('5 weeks').weeks()).toBe(5);
expect(d.parse('6w').weeks()).toBe(6);
expect(d.parse('12 week').weeks()).toBe(12);
expect(d.parse('9d').days()).toBe(9);
expect(d.parse('2 days ').days()).toBe(2);
expect(d.parse(' 19518 day qsdlmfkj ---').days()).toBe(19518);
expect(d.parse(' 78 h mlkj').hours()).toBe(78);
expect(d.parse('22 hours ').hours()).toBe(22);
expect(d.parse('3 hour').hours()).toBe(3);
expect(d.parse('4min').minutes()).toBe(4);
expect(d.parse('7 mins').minutes()).toBe(7);
expect(d.parse('3 m').minutes()).toBe(3);
expect(d.parse('8minutes').minutes()).toBe(8);
expect(d.parse('90 minute').minutes()).toBe(90);
expect(d.parse('4sec').seconds()).toBe(4);
expect(d.parse('7 secs').seconds()).toBe(7);
expect(d.parse('3 s').seconds()).toBe(3);
expect(d.parse('8seconds').seconds()).toBe(8);
expect(d.parse('90 second').seconds()).toBe(90);
});
it("can parse decimal numbers too", function(){
var d = new Duration();
expect(d.parse('0.5 hours').seconds()).toBe(1800);
expect(d.parse('.2 hours').seconds()).toBe(720);
expect(d.parse('.5 seconds').seconds()).toBe(0.5);
});
it("can create a duration from an existing one", function(){
var d = new Duration("1000s");
var d2 = new Duration(d);
expect(d2.seconds()).toBe(1000);
});
it("can format a time to a given format", function(){
var a = new Duration('5 week 2d 7h 17 minutes 6 s');
expect(a.format('ww weeks dd days hh hours mm minutes ss seconds')).toBe("5 weeks 2 days 7 hours 17 minutes 6 seconds");
expect(a.format('ww weeks hh hours')).toBe("5 weeks 55 hours");
});
});
/**
* Starts the testing environment
*/
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 250;
/**
Create the `HTMLReporter`, which Jasmine calls to provide results of each spec and each suite. The Reporter is responsible for presenting results to the user.
*/
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
/**
Delegate filtering of specs to the reporter. Allows for clicking on single suites or specs in the results to only run a subset of the suite.
*/
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
/**
Run all of the tests when the page finishes loading - and make sure to run any previous `onload` handler
### Test Results
Scroll down to see the results of all of these specs.
*/
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})(); |
var Cons = (function() {
var counter = 0
// The outer function is not the constructor itself, but is instead to wrap
// around private members.
var ActualConstructor = function(prop) {
this.text = prop
this.id = (counter += 1)
}
ActualConstructor.prototype.getLastId = function() {
return counter
}
ActualConstructor.prototype.getText = function() {
return this.text
}
ActualConstructor.prototype.getId = function() {
return this.id
}
return ActualConstructor
}()) // Using an IIFE
var x = new Cons('Test')
console.log(x.getLastId())
console.log(x.getText())
var y = new Cons('Test2')
console.log(y.getLastId())
console.log(y.getText())
console.log(x.getLastId())
console.log(x.getId())
|
var express = require('express')
, passport = require('passport')
, util = require('util')
, WeiboStrategy = require('../../').Strategy;
var WEIBO_CLIENT_ID = "--CLIENT_ID--";
var WEIBO_CLIENT_SECRET = "--CLIENT_SECRET--";
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete Weibo profile is serialized
// and deserialized.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
// Use the WeiboStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, an accessToken, refreshToken, and Weibo
// profile), and invoke a callback with a user object.
passport.use(new WeiboStrategy({
clientID: WEIBO_CLIENT_ID,
clientSecret: WEIBO_CLIENT_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/weibo/callback"
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// To keep the example simple, the user's Weibo profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the Weibo account with a user record in your database,
// and return that user instead.
return done(null, profile);
});
}
));
var app = express.createServer();
// configure Express
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.get('/', function(req, res){
res.render('index', { user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { user: req.user });
});
// GET /auth/weibo
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Weibo authentication will involve redirecting
// the user to weibo.com. After authorization, Weibo will redirect the user
// back to this application at /auth/weibo/callback
app.get('/auth/weibo',
passport.authenticate('weibo'),
function(req, res){
// The request will be redirected to Weibo for authentication, so this
// function will not be called.
});
// GET /auth/weibo/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/weibo/callback',
passport.authenticate('weibo', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.listen(3000);
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
|
// console.log(' - ljswitchboard-require.js test-file, test-file.js');
var localRequire = require('../lib/ljswitchboard-require');
exports.testVar = 'test-file.js';
exports.tFunc = function() {
var isFound = false;
try {
require('nodeunit');
isFound = true;
} catch (err) {
}
return isFound;
};
exports.req = localRequire; |
const node = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
module.exports = {
plugins: [
node({
mainFields: ['browser', 'es2015', 'module', 'jsnext:main', 'main'],
}),
commonjs(),
],
}; |
//Version 1.0
/**
* highlightRow and highlight are used to show a visual feedback. If the row has been successfully modified, it will be highlighted in green. Otherwise, in red
*/
function highlightRow(rowId, bgColor, after)
{
var rowSelector = $("#" + rowId);
rowSelector.css("background-color", bgColor);
rowSelector.fadeTo("normal", 0.5, function() {
rowSelector.fadeTo("fast", 1, function() {
rowSelector.css("background-color", '');
});
});
}
function highlight(div_id, style) {
highlightRow(div_id, style == "error" ? "#e5afaf" : style == "warning" ? "#ffcc00" : "#999999");
}
/**
updateCellValue calls the PHP script that will update the database.
*/
function updateCellValue(EditableGrid, rowIndex, columnIndex, oldValue, newValue, row, onResponse)
{
$.ajax({
url: 'update.php',
type: 'POST',
dataType: "html",
data: {
tablename : EditableGrid.name,
id: EditableGrid.getRowId(rowIndex),
newvalue: EditableGrid.getColumnType(columnIndex) == "boolean" ? (newValue ? 1 : 0) : newValue,
colname: EditableGrid.getColumnName(columnIndex),
coltype: EditableGrid.getColumnType(columnIndex)
},
success: function (response)
{
// reset old value if failed then highlight row
var success = onResponse ? onResponse(response) : (response == "ok" || !isNaN(parseInt(response))); // by default, a sucessfull reponse can be "ok" or a database id
if (!success) EditableGrid.setValueAt(rowIndex, columnIndex, oldValue);
highlight(row.id, success ? "ok" : "error");
},
error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
async: true
});
}
function DatabaseGrid()
{
this.EditableGrid = new EditableGrid("html_space", {
enableSort: true,
// define the number of row visible by page
pageSize: 50,
// Once the table is displayed, we update the paginator state
tableRendered: function() { updatePaginator(this); },
tableLoaded: function() { datagrid.initializeGrid(this); },
modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
}
});
this.fetchGrid();
}
DatabaseGrid.prototype.fetchGrid = function() {
// call a PHP script to get the data
this.EditableGrid.loadJSON("loaddata_spaces.php?db_tablename=html_space");
};
DatabaseGrid.prototype.initializeGrid = function(grid) {
var self = this;
// render for the action column
grid.setCellRenderer("action", new CellRenderer({
render: function(cell, id) {
cell.innerHTML+= "<i onclick=\"datagrid.deleteRow("+id+");\" class='fa fa-trash-o red' ></i>";
}
}));
grid.renderGrid("tablecontent", "iRulez");
};
DatabaseGrid.prototype.deleteRow = function(id)
{
var self = this;
if ( confirm(spaces_delete.replace('$', id)) ) {
$.ajax({
url: 'delete.php',
type: 'POST',
dataType: "html",
data: {
tablename : self.EditableGrid.name,
id: id
},
success: function (response)
{
if (response == "ok" )
self.EditableGrid.removeRow(id);
},
error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
async: true
});
}
};
DatabaseGrid.prototype.addRow = function(id)
{
var self = this;
$.ajax({
url: 'add_spaces.php',
type: 'POST',
dataType: "html",
data: {
tablename : self.EditableGrid.name,
naam: $("#naam").val(),
verdiep: $("#verdiep").val(),
},
success: function (response)
{
if (response.trim() == "ok" ) {
// hide form
showAddForm();
$("#naam").val('');
$("#verdiep").val('');
alert(spaces_add);
self.fetchGrid();
}
else
alert(response);
},
error: function(XMLHttpRequest, textStatus, exception) { alert("Ajax failure\n" + errortext); },
async: true
});
};
function updatePaginator(grid, divId)
{
divId = divId || "paginator";
var paginator = $("#" + divId).empty();
var nbPages = grid.getPageCount();
// get interval
var interval = grid.getSlidingPageInterval(20);
if (interval == null) return;
// get pages in interval (with links except for the current page)
var pages = grid.getPagesInInterval(interval, function(pageIndex, isCurrent) {
if (isCurrent) return "<span id='currentpageindex'>" + (pageIndex + 1) +"</span>";
return $("<a>").css("cursor", "pointer").html(pageIndex + 1).click(function(event) { grid.setPageIndex(parseInt($(this).html()) - 1); });
});
// "first" link
var link = $("<a class='nobg'>").html("<i class='fa fa-fast-backward'></i>");
if (!grid.canGoBack()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
else link.css("cursor", "pointer").click(function(event) { grid.firstPage(); });
paginator.append(link);
// "prev" link
link = $("<a class='nobg'>").html("<i class='fa fa-backward'></i>");
if (!grid.canGoBack()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
else link.css("cursor", "pointer").click(function(event) { grid.prevPage(); });
paginator.append(link);
// pages
for (p = 0; p < pages.length; p++) paginator.append(pages[p]).append(" ");
// "next" link
link = $("<a class='nobg'>").html("<i class='fa fa-forward'>");
if (!grid.canGoForward()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
else link.css("cursor", "pointer").click(function(event) { grid.nextPage(); });
paginator.append(link);
// "last" link
link = $("<a class='nobg'>").html("<i class='fa fa-fast-forward'>");
if (!grid.canGoForward()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
else link.css("cursor", "pointer").click(function(event) { grid.lastPage(); });
paginator.append(link);
};
function showAddForm() {
if ( $("#addform").is(':visible') )
$("#addform").hide();
else
$("#addform").show();
}
$('select').change(function() {
if ($(this).children('option:first-child').is(':selected')) {
$(this).addClass('placeholder');
} else {
$(this).removeClass('placeholder');
}
});
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'da', {
toolbar: 'Ny side'
} );
|
'use strict';
var process = require('process');
var path = require('path');
var expect = require('../../helper').expect;
var maybeRead = require('../../../lib/command/utils/maybe-read-descriptor-file');
describe('Reading descriptor', function () {
let originalWd;
beforeEach(function () {
originalWd = process.cwd();
process.chdir(path.resolve(__dirname, '../../fake-working-dir'));
});
afterEach(function () {
process.chdir(originalWd);
});
it('extends options with an absolute path of the default "widget.json" file', function () {
let options = {};
return maybeRead(options).then(function () {
expect(options.descriptor).to.eq(path.resolve(process.cwd(), 'widget.json'));
});
});
it('resolves an absolute path of the provided descriptor file', function () {
let options = {descriptor: 'other-widget/my-widget.json'};
return maybeRead(options).then(function () {
expect(options.descriptor).to.eq(path.resolve(process.cwd(), 'other-widget/my-widget.json'));
});
});
it('reads the default "widget.json" file', function () {
return maybeRead({}).then(function (descriptor) {
expect(descriptor.id).to.eq('lol');
expect(descriptor.name).to.eq('lol');
expect(descriptor.fieldTypes[0]).to.eq('Symbol');
expect(descriptor.fieldTypes.length).to.eq(1);
});
});
it('reads the provided descriptor file', function () {
return maybeRead({descriptor: 'other-widget/my-widget.json'})
.then(function (descriptor) {
expect(descriptor.id).to.eq('my-widget');
expect(descriptor.name).to.eq('My widget');
expect(descriptor.fieldTypes[0]).to.eq('Symbol');
expect(descriptor.fieldTypes.length).to.eq(1);
});
});
it('resolves "srcdoc" property relatively to the descriptor file', function () {
let options = {descriptor: 'other-widget/my-widget.json'};
return maybeRead(options).then(function (descriptor) {
let resolved = path.resolve(path.dirname(options.descriptor), 'my-widget.html');
expect(descriptor.srcdoc).to.eq(resolved);
});
});
it('fails on invalid JSON', function () {
return maybeRead({descriptor: 'invalid.json'}).catch(function (err) {
expect(err.message).to.have.string('In file invalid.json: Unexpected token');
});
});
it('fails on lack of widget ID', function () {
return maybeRead({descriptor: 'incomplete1.json'}).catch(function (err) {
expect(err.message).to.have.string('Missing widget ID');
});
});
it('fails when both src and srcdoc properties are not provided', function () {
return maybeRead({descriptor: 'incomplete2.json'}).catch(function (err) {
expect(err.message).to.have.string('Missing "src" or "srcdoc" property');
});
});
});
|
var searchData=
[
['recurringcommand_107',['RecurringCommand',['../class_command_lib_1_1_recurring_command.html',1,'CommandLib']]],
['retryablecommand_108',['RetryableCommand',['../class_command_lib_1_1_retryable_command.html',1,'CommandLib']]],
['retrycallback_109',['RetryCallback',['../class_command_lib_1_1_retryable_command_1_1_retry_callback.html',1,'CommandLib::RetryableCommand']]]
];
|
"use strict";
var yeoman = require('yeoman-generator'),
glob = require('yeoman-generator/node_modules/glob'),
_ = require('yeoman-generator/node_modules/lodash'),
chalk = require('yeoman-generator/node_modules/chalk'),
mkdirp = require('yeoman-generator/node_modules/mkdirp'),
path = require('path'),
exec = require('child_process').exec,
fs = require('fs'),
del = require('del'),
log = console.log;
var win32 = process.platform === 'win32'
var homeDir = process.env[ win32? 'USERPROFILE' : 'HOME']
var cfgRoot = path.join(homeDir, '.generator-lego')
var libPath = path.join(cfgRoot, 'node_modules')
var configPath = path.join(cfgRoot, 'config.json')
var LegoGenerator = yeoman.generators.Base.extend({
// 1. 提问前的准备工作
init: function (){
this.conflicter.force = true
// 初始环境检测
// 若当前目录没有node_modules文件夹,则建立软连接;否则继续
// 若当前存在src文件夹,则退出;否则继续
var dirs = glob.sync('+(src|node_modules)')
if(!_.contains(dirs, 'node_modules')){
if(win32){
require('child_process').exec('mklink /d .\\node_modules '+ libPath )
}else{
this.spawnCommand('ln', ['-s', libPath, 'node_modules'])
}
log(chalk.bold.green('node_modules 软连接创建完毕!'))
}
if(_.contains(dirs, 'src')){
log(chalk.bold.green('资源已初始化,退出...'))
setTimeout(function(){
process.exit(1)
}, 200)
}
// 当前模板的全局配置数据,配置svn信息和命令执行的参数
this.gConfig = JSON.parse(fs.readFileSync(configPath, {encoding: 'utf8'}))
},
// 2. 提问
prompting: function(){
var done = this.async()
this.projectAuthor = process.env.USER
var timestamp = +new Date()
var questions = [
{
name: 'projectAssets',
type: 'list',
message: '初始的静态资源:',
choices: [
{
name: 'LegoUI for pc模板',
value: 'src4legopc',
checked: true
},{
name: 'LegoUI for mobile模板',
value: 'src4legomobi'
},{
name: '新游戏一线专区模板',
value: 'src4game1'
}
]
},{
name: 'projectFamily',
type: 'list',
message: 'CDN根目录(项目类型):',
choices: [
{
name: 'special',
value: 'special',
checked: true
},{
name: 'project',
value: 'project'
},{
name: 'game',
value: 'game'
}
]
},{
name: 'projectName',
message: 'CDN二级目录(项目名称)',
default: timestamp.toString(),
validate: function(val){
var done = this.async();
setTimeout(function() {
if (/[^a-zA-Z_-\d\/]+/.test(val)) {
done("非法字符,只能是数字、字符、下划线的组合");
return;
}
if (val.trim() === ''){
done("不能为空");
return;
}
done(true);
}, 100);
}
},{
name: 'projectVersion',
message: 'CDN三级目录(项目版本号)',
default: '1.0.0'
}
]
if(!this.gConfig.svnUsr){
questions.push({
name: 'svnUsr',
message: 'svn用户名',
default: this.gConfig.svnUsr||''
},{
name: 'svnPwd',
message: 'svn密码',
default: this.gConfig.svnPwd||''
})
}
this.prompt(questions, function(answers){
for(var item in answers){
answers.hasOwnProperty(item) && (this[item] = answers[item])
}
done()
}.bind(this))
},
// 3. 资源文件拷贝
writing: function(){
// 同步问答结果,更新当前模板的配置数据
this.gConfig.svnUsr = this.svnUsr?this.svnUsr:this.gConfig.svnUsr
this.gConfig.svnPwd = this.svnPwd?this.svnPwd:this.gConfig.svnPwd
fs.writeFileSync(configPath, JSON.stringify(this.gConfig, null, 4), {encoding: 'utf8'})
// 拷贝资源文件,资源文件可以通过`<%= %>`读取当前实例的数据
this.directory(this.projectAssets, 'src')
this.directory('tasks', 'tasks')
this.copy('gulpfile.js', 'gulpfile.js')
this.pkgGulpSassVersion = (win32?'1.3.3':'^2.0.0')
this.copy('package.json', 'package.json')
},
// 4. 拷贝后执行命令 如建立软链接等
end: function(){
// 文件转移后,删除不需要的文件
del(['src/**/.gitignore','src/**/.npmignore'])
// 安装包依赖,然后执行`gulp`
// https://github.com/yeoman/generator/blob/45258c0a48edfb917ecf915e842b091a26d17f3e/lib/actions/install.js#L67-69
this.installDependencies({
bower: false,
npm: true,
skipInstall: false,
callback: execAfterInstall.bind(this)
})
function execAfterInstall(){
if(!win32){
if(this.gConfig['open_app']){
this.spawnCommand('open', ['-a', this.gConfig['open_app'], '.'])
}
}
this.spawnCommand('gulp', ['-w'])
log('资源初始化完毕! 现在可以 coding...')
}
}
});
module.exports = LegoGenerator;
|
"use strict"
var o = require("../../ospec/ospec")
var callAsync = require("../../test-utils/callAsync")
var Stream = require("../stream")
o.spec("stream", function() {
o.spec("stream", function() {
o("works as getter/setter", function() {
var stream = Stream(1)
var initialValue = stream()
stream(2)
var newValue = stream()
o(initialValue).equals(1)
o(newValue).equals(2)
})
o("has undefined value by default", function() {
var stream = Stream()
o(stream()).equals(undefined)
})
o("can update to undefined", function() {
var stream = Stream(1)
stream(undefined)
o(stream()).equals(undefined)
})
o("can be stream of streams", function() {
var stream = Stream(Stream(1))
o(stream()()).equals(1)
})
})
o.spec("combine", function() {
o("transforms value", function() {
var stream = Stream()
var doubled = Stream.combine(function(s) {return s() * 2}, [stream])
stream(2)
o(doubled()).equals(4)
})
o("transforms default value", function() {
var stream = Stream(2)
var doubled = Stream.combine(function(s) {return s() * 2}, [stream])
o(doubled()).equals(4)
})
o("transforms multiple values", function() {
var s1 = Stream()
var s2 = Stream()
var added = Stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
s1(2)
s2(3)
o(added()).equals(5)
})
o("transforms multiple default values", function() {
var s1 = Stream(2)
var s2 = Stream(3)
var added = Stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
o(added()).equals(5)
})
o("transforms mixed default and late-bound values", function() {
var s1 = Stream(2)
var s2 = Stream()
var added = Stream.combine(function(s1, s2) {return s1() + s2()}, [s1, s2])
s2(3)
o(added()).equals(5)
})
o("combines atomically", function() {
var count = 0
var a = Stream()
var b = Stream.combine(function(a) {return a() * 2}, [a])
var c = Stream.combine(function(a) {return a() * a()}, [a])
var d = Stream.combine(function(b, c) {
count++
return b() + c()
}, [b, c])
a(3)
o(d()).equals(15)
o(count).equals(1)
})
o("combines default value atomically", function() {
var count = 0
var a = Stream(3)
var b = Stream.combine(function(a) {return a() * 2}, [a])
var c = Stream.combine(function(a) {return a() * a()}, [a])
var d = Stream.combine(function(b, c) {
count++
return b() + c()
}, [b, c])
o(d()).equals(15)
o(count).equals(1)
})
o("combine lists only changed upstreams in last arg", function() {
var streams = []
var a = Stream()
var b = Stream()
var c = Stream.combine(function(a, b, changed) {
streams = changed
}, [a, b])
a(3)
b(5)
o(streams.length).equals(1)
o(streams[0]).equals(b)
})
o("combine lists only changed upstreams in last arg with default value", function() {
var streams = []
var a = Stream(3)
var b = Stream(5)
var c = Stream.combine(function(a, b, changed) {
streams = changed
}, [a, b])
a(7)
o(streams.length).equals(1)
o(streams[0]).equals(a)
})
o("combine can return undefined", function() {
var a = Stream(1)
var b = Stream.combine(function(a) {
return undefined
}, [a])
o(b()).equals(undefined)
})
o("combine can return stream", function() {
var a = Stream(1)
var b = Stream.combine(function(a) {
return Stream(2)
}, [a])
o(b()()).equals(2)
})
o("combine can return pending stream", function() {
var a = Stream(1)
var b = Stream.combine(function(a) {
return Stream()
}, [a])
o(b()()).equals(undefined)
})
o("combine can halt", function() {
var count = 0
var a = Stream(1)
var b = Stream.combine(function(a) {
return Stream.HALT
}, [a])
["fantasy-land/map"](function() {
count++
return 1
})
o(b()).equals(undefined)
})
o("combine will throw with a helpful error if given non-stream values", function () {
var spy = o.spy()
var a = Stream(1)
var thrown = null;
try {
var b = Stream.combine(spy, [a, ''])
} catch (e) {
thrown = e
}
o(thrown).notEquals(null)
o(thrown.constructor === TypeError).equals(false)
o(spy.callCount).equals(0)
})
})
o.spec("merge", function() {
o("transforms an array of streams to an array of values", function() {
var all = Stream.merge([
Stream(10),
Stream("20"),
Stream({value: 30}),
])
o(all()).deepEquals([10, "20", {value: 30}])
})
o("remains pending until all streams are active", function() {
var straggler = Stream()
var all = Stream.merge([
Stream(10),
Stream("20"),
straggler,
])
o(all()).equals(undefined)
straggler(30)
o(all()).deepEquals([10, "20", 30])
})
o("calls run callback after all parents are active", function() {
var value = 0
var id = function(value) {return value}
var a = Stream()
var b = Stream()
var all = Stream.merge([a.map(id), b.map(id)]).map(function(data) {
value = data[0] + data[1]
})
a(1)
b(2)
o(value).equals(3)
a(3)
b(4)
o(value).equals(7)
})
})
o.spec("end", function() {
o("end stream works", function() {
var stream = Stream()
var doubled = Stream.combine(function(stream) {return stream() * 2}, [stream])
stream.end(true)
stream(3)
o(doubled()).equals(undefined)
})
o("end stream works with default value", function() {
var stream = Stream(2)
var doubled = Stream.combine(function(stream) {return stream() * 2}, [stream])
stream.end(true)
stream(3)
o(doubled()).equals(4)
})
o("cannot add downstream to ended stream", function() {
var stream = Stream(2)
stream.end(true)
var doubled = Stream.combine(function(stream) {return stream() * 2}, [stream])
stream(3)
o(doubled()).equals(undefined)
})
o("upstream does not affect ended stream", function() {
var stream = Stream(2)
var doubled = Stream.combine(function(stream) {return stream() * 2}, [stream])
doubled.end(true)
stream(4)
o(doubled()).equals(4)
})
})
o.spec("valueOf", function() {
o("works", function() {
o(Stream(1).valueOf()).equals(1)
o(Stream("a").valueOf()).equals("a")
o(Stream(true).valueOf()).equals(true)
o(Stream(null).valueOf()).equals(null)
o(Stream(undefined).valueOf()).equals(undefined)
o(Stream({a: 1}).valueOf()).deepEquals({a: 1})
o(Stream([1, 2, 3]).valueOf()).deepEquals([1, 2, 3])
o(Stream().valueOf()).equals(undefined)
})
o("allows implicit value access in mathematical operations", function() {
o(Stream(1) + Stream(1)).equals(2)
})
})
o.spec("toString", function() {
o("aliases valueOf", function() {
var stream = Stream(1)
o(stream.toString).equals(stream.valueOf)
})
o("allows implicit value access in string operations", function() {
o(Stream("a") + Stream("b")).equals("ab")
})
})
o.spec("toJSON", function() {
o("works", function() {
o(Stream(1).toJSON()).equals(1)
o(Stream("a").toJSON()).equals("a")
o(Stream(true).toJSON()).equals(true)
o(Stream(null).toJSON()).equals(null)
o(Stream(undefined).toJSON()).equals(undefined)
o(Stream({a: 1}).toJSON()).deepEquals({a: 1})
o(Stream([1, 2, 3]).toJSON()).deepEquals([1, 2, 3])
o(Stream().toJSON()).equals(undefined)
o(Stream(new Date(0)).toJSON()).equals(new Date(0).toJSON())
})
o("works w/ JSON.stringify", function() {
o(JSON.stringify(Stream(1))).equals(JSON.stringify(1))
o(JSON.stringify(Stream("a"))).equals(JSON.stringify("a"))
o(JSON.stringify(Stream(true))).equals(JSON.stringify(true))
o(JSON.stringify(Stream(null))).equals(JSON.stringify(null))
o(JSON.stringify(Stream(undefined))).equals(JSON.stringify(undefined))
o(JSON.stringify(Stream({a: 1}))).deepEquals(JSON.stringify({a: 1}))
o(JSON.stringify(Stream([1, 2, 3]))).deepEquals(JSON.stringify([1, 2, 3]))
o(JSON.stringify(Stream())).equals(JSON.stringify(undefined))
o(JSON.stringify(Stream(new Date(0)))).equals(JSON.stringify(new Date(0)))
})
})
o.spec("map", function() {
o("works", function() {
var stream = Stream()
var doubled = stream["fantasy-land/map"](function(value) {return value * 2})
stream(3)
o(doubled()).equals(6)
})
o("works with default value", function() {
var stream = Stream(3)
var doubled = stream["fantasy-land/map"](function(value) {return value * 2})
o(doubled()).equals(6)
})
o("works with undefined value", function() {
var stream = Stream()
var mapped = stream["fantasy-land/map"](function(value) {return String(value)})
stream(undefined)
o(mapped()).equals("undefined")
})
o("works with default undefined value", function() {
var stream = Stream(undefined)
var mapped = stream["fantasy-land/map"](function(value) {return String(value)})
o(mapped()).equals("undefined")
})
o("works with pending stream", function() {
var stream = Stream(undefined)
var mapped = stream["fantasy-land/map"](function(value) {return Stream()})
o(mapped()()).equals(undefined)
})
o("has alias", function() {
var stream = Stream(undefined)
o(stream["fantasy-land/map"]).equals(stream.map)
})
})
o.spec("ap", function() {
o("works", function() {
var apply = Stream(function(value) {return value * 2})
var stream = Stream(3)
var applied = stream["fantasy-land/ap"](apply)
o(applied()).equals(6)
apply(function(value) {return value / 3})
o(applied()).equals(1)
stream(9)
o(applied()).equals(3)
})
o("works with undefined value", function() {
var apply = Stream(function(value) {return String(value)})
var stream = Stream(undefined)
var applied = stream["fantasy-land/ap"](apply)
o(applied()).equals("undefined")
apply(function(value) {return String(value) + "a"})
o(applied()).equals("undefineda")
})
})
o.spec("fantasy-land", function() {
o.spec("functor", function() {
o("identity", function() {
var stream = Stream(3)
var mapped = stream["fantasy-land/map"](function(value) {return value})
o(stream()).equals(mapped())
})
o("composition", function() {
function f(x) {return x * 2}
function g(x) {return x * x}
var stream = Stream(3)
var mapped = stream["fantasy-land/map"](function(value) {return f(g(value))})
var composed = stream["fantasy-land/map"](g)["fantasy-land/map"](f)
o(mapped()).equals(18)
o(mapped()).equals(composed())
})
})
o.spec("apply", function() {
o("composition", function() {
var a = Stream(function(value) {return value * 2})
var u = Stream(function(value) {return value * 3})
var v = Stream(5)
var mapped = v["fantasy-land/ap"](u["fantasy-land/ap"](a["fantasy-land/map"](function(f) {
return function(g) {
return function(x) {
return f(g(x))
}
}
})))
var composed = v["fantasy-land/ap"](u)["fantasy-land/ap"](a)
o(mapped()).equals(30)
o(mapped()).equals(composed())
})
})
o.spec("applicative", function() {
o("identity", function() {
var a = Stream()["fantasy-land/of"](function(value) {return value})
var v = Stream(5)
o(v["fantasy-land/ap"](a)()).equals(5)
o(v["fantasy-land/ap"](a)()).equals(v())
})
o("homomorphism", function() {
var a = Stream(0)
var f = function(value) {return value * 2}
var x = 3
o(a["fantasy-land/of"](x)["fantasy-land/ap"](a["fantasy-land/of"](f))()).equals(6)
o(a["fantasy-land/of"](x)["fantasy-land/ap"](a["fantasy-land/of"](f))()).equals(a["fantasy-land/of"](f(x))())
})
o("interchange", function() {
var u = Stream(function(value) {return value * 2})
var a = Stream()
var y = 3
o(a["fantasy-land/of"](y)["fantasy-land/ap"](u)()).equals(6)
o(a["fantasy-land/of"](y)["fantasy-land/ap"](u)()).equals(u["fantasy-land/ap"](a["fantasy-land/of"](function(f) {return f(y)}))())
})
})
})
})
|
'use strict';
var gulp = require('gulp');
var execFile = require('child_process').execFile
var util = require('util');
gulp.task('link', function (done) {
var srcDir = process.env.PWD;
var cmd = util.format('ln -s -f %s/src %s/node_modules', srcDir, srcDir);
var nodeModules = srcDir + '/node_modules';
execFile('ln', ['-s', '-f', srcDir + '/src', nodeModules], function () {
console.log(cmd);
execFile('ln', ['-s', '-f', srcDir + '/recipe', nodeModules], function () {
cmd = util.format('ln -s -f %s/recipe %s/node_modules', srcDir, srcDir);
console.log(cmd);
done();
});
});
});
|
/**
* Return an array of valid extensions, eg. ['.js','.json','.node']
*
* @api public
*/
function require_extensions()
{
return Object.keys(require.extensions);
}
module.exports = require_extensions;
/**
* return a glob pattern for `require.extensions`
*
* @api public
*/
function glob()
{
return '.{'+
require_extensions()
.map(function(ext) {
return ext.substr(1)
})
.join(',')
+'}';
}
module.exports.glob = glob;
/**
* return a new `RegExp` object that matches `require.extensions`
*
* @api public
*/
function regexp(group)
{
return new RegExp(regexp_string(group)+'$');
}
module.exports.regexp = regexp;
/**
* return a new `String` regular expression that matches `require.extensions`
*
* @api public
*/
function regexp_string(group)
{
return '(' + (group ? '' : '?:') + (require_extensions()
.map(function(ext){ return '\\'+ext; })
.join('|')) +
')'
}
module.exports.regexp.string = regexp_string;
Object.defineProperty(require.extensions,'glob',{
enumerable: false,
get: module.exports.glob
});
Object.defineProperty(require.extensions,'regexp',{
enumerable: false,
get: module.exports.regexp
});
|
'use strict';
// Harnesses controller
angular.module('harnesses').controller('HarnessesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Harnesses',
function ($scope, $stateParams, $location, Authentication, Harnesses) {
$scope.authentication = Authentication;
// Create new Harness
$scope.create = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'harnessForm');
return false;
}
// Create new Harness object
var harness = new Harnesses({
vm_name: this.vm_name,
branchdc: this.branchdc,
branchdf: this.branchdf,
branchref: this.branchref,
branchdpn: this.branchdpn,
brancheval: this.brancheval,
branchwebui: this.branchwebui,
owner: this.owner,
harness_status: this.harness_status,
need_refresh: this.need_refresh,
tc_build_id: this.tc_build_id
});
// Redirect after save
harness.$save(function (response) {
$location.path('harnesses/' + response._id);
// Clear form fields
$scope.vm_name = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Harness
$scope.remove = function (harness) {
if (harness) {
harness.$remove();
for (var i in $scope.harnesses) {
if ($scope.harnesses[i] === harness) {
$scope.harnesses.splice(i, 1);
}
}
} else {
$scope.harness.$remove(function () {
$location.path('harnesses');
});
}
};
// Update existing Harness
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'harnessForm');
return false;
}
var harness = $scope.harness;
harness.$update(function () {
$location.path('harnesses/' + harness._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Harnesses
$scope.find = function () {
$scope.harnesses = Harnesses.query();
};
// Find existing Harness
$scope.findOne = function () {
$scope.harness = Harnesses.get({
harnessId: $stateParams.harnessId
});
};
}
])
.directive('capitalize', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var capitalize = function(inputValue) {
if(inputValue == undefined) inputValue = '';
var capitalized = inputValue.toUpperCase();
if(capitalized !== inputValue) {
modelCtrl.$setViewValue(capitalized);
modelCtrl.$render();
}
return capitalized;
}
modelCtrl.$parsers.push(capitalize);
capitalize(scope[attrs.ngModel]); // capitalize initial value
}
};
})
.filter('makeCaps',function(){
return function(input){
var capsInput = input.split(' '),
newInput = [];
angular.forEach(capsInput,function(val,index){
newInput.push(val.substr(0,1).toUpperCase()+val.substr(1));
});
return newInput.join(' ');
}
});
|
$(document).on('turbolinks:request-start', function () {
$('.loading-caption').removeAttr('hidden')
})
$(document).on('turbolinks:request-end', function () {
$('.loading-caption').attr('hidden', true)
})
$(document).on('turbolinks:load', function () {
var leftSidebar = new $.LeftSidebar.Constructor
leftSidebar.init()
$('[autofocus]').focus()
})
|
import Biome from "./biome";
class Snow extends Biome{
constructor(n){
super(18+n,0.9);
this.color = {H : 0,S : 0,B : 95};
}
}
export default Snow;
|
;(function(){
NuxComponentHeader.apply(this, arguments)
})('fetch', {
// global options
},function(){
// Your implementation goes here.
// Nux may not exist, therefore A light loader is implemented
// and your content is stored until the method can
// be successfully applied.
return {
fails: {},
expected: [],
listeners :{},
chain: [],
imported: [],
load: function() {
return Load.apply(this, arguments);
},
// [name], handler, path
use: function(name) {
/*
Externally accessible method o implement a Nux
extension. the Use method:
use(nameString [, handlerFunction][, importPathString])
returned is an extension chain containing:
then(name [, handlerFunction])
This method implements the fetch.get method
*/
var handler = arg(arguments, 1, Nux._F);
var path = arg(arguments, 2, Nux.__config().extensionPath);
// Add to handler chain
// This method may throw an error is the asset has been refused.
// Turn a string into an array if required.
var _handlerHooks = (Themis.of(name, Array))? name: [name];
// spaceify the names
var handlerHooks = [];
for (var i = 0; i < _handlerHooks.length; i++) {
var _name = Nux.space(_handlerHooks[i], path);
handlerHooks.push(_name);
};
console.time(handlerHooks)
// Add removeListener (on name import list) handler to listeners
Nux.listener.add(handlerHooks, function(ext){
handler(ext)
console.timeEnd(ext.name);
}, path);
for (var i = 0; i < handlerHooks.length; i++) {
var name = handlerHooks[i];
// begin import
Nux.fetch.get(name, path);
};
// Nux.fetch.get(Nux.space(name), path);
/*
// receive import
// handle import to all listeners
// slice import name from any handler in chain with importName in [name] array
// handler handlers with an empty array of names should be called:
Every call made removed a name from the list. If the
list is empty all names are imported and the handler
should be called.
// removed any called listener.
// return chain methods:
// Use:
perform another concurrent call.
use() is returned because you may want a different
handler hooked to a name import
// Then:
After the previous handlers have been executed, ( use() )
_then_ perform this method.
// On:
Inhert handler of which is only called when the name
is imported. No import is made when on() referenced
*/
return Nux
},
get: function(name){
/*
Perform an import utilizing the namespace.
A single fully qualified name should be passed.
listeners should already be prepared.
This method implements the internally used _import method.
*/
var path = arg(arguments, 1, Nux.__config().extensionPath);
return Nux.fetch._import(name, path);
},
_import: function(name, path){
/*
Performs an import to the referenced file.
This should be used internally in favour of the
fetch.use(name, handler) method.
Handlers and callbacks should have been setup prior
to calling this method.
return is undefined.
*/
var path = arg(arguments, 1, Nux.__config().extensionPath),
v = Include(name, path);
return v;
}
}
})
|
$('.js-add-photo-to-album').click(function () {
$(this).closest('.mde-photo-edit').find('.mde-photo-edit__input-photo-load').trigger('click');
return false;
});
$('.js-photo-load').change(function (e) {
var files = e.target.files;
var errFiles = [];
var completeFiles = 0;
var filesCount = Object.keys(files).length;
var toMuchFiles = [];
for (var i = 0, file; file = files[i]; i++) {
canvasResize(file, {
width: 800,
height: 0,
crop: false,
quality: 80,
//rotate: 90,
callback: function (data, width, height) {
if (width >= 220 && height >= 220) {
if (checkMaxAlbumElem()) {
toMuchFiles.push(this.name);
} else {
console.log(this.name + '_' + new Date().getTime());
$.ajax({
url: $('.mde-photo-edit').attr('action'),
dataType: 'json',
type: 'GET', //важно! заменить на POST!
data: {
//img: data
},
success: function (response) {
if (response.success) {
addPhotoToAlbum(data);
console.log('success!');
}
}
});
}
} else {
errFiles.push(this.name);
}
completeFiles++;
//console.log(completeFiles + ' ' + filesCount);
if (completeFiles >= filesCount && errFiles.length > 0) {
if (errFiles.length == 1 && 1 == filesCount) {
showPopUpMessage('Изображение: ' + errFiles + ' слишком маленькое.');
} else if (errFiles.length == 1 && 2 <= filesCount) {
showPopUpMessage('Изображение: ' + errFiles + ' слишком маленькое.<br>Остальные изображения были загружены.');
} else {
showPopUpMessage('Изображения: ' + errFiles + ' слишком маленькие.<br>Остальные изображения были загружены.');
}
}
if (completeFiles >= filesCount && toMuchFiles.length > 0) {
showPopUpMessage('Изображения: ' + toMuchFiles + ' не были загружены.<br>Закончилось место в альбоме.');
}
}.bind(file)
});
}
$(this).closest('.mde-photo-edit').trigger('reset');
});
function addPhotoToAlbum(data) {
if (checkMaxAlbumElem()) {
return false;
}
$('.mde-photo-edit').find('#elem-cont-template')
.clone(true)
.removeAttr('id')
.appendTo('.mde-photo-edit__wrapper')
.hide()
.fadeIn(500)
.find('.mde-photo-edit__img')
.attr('src', data)
.closest('.mde-photo-edit__img-cont').siblings('textarea').val('')
.closest('.mde-photo-edit__wrapper').append('<div class="mde-photo-edit__clear-div"></div>');
autosize($('.mde-photo-edit').find('textarea'));
if (checkMaxAlbumElem()) {
showPopUpMessage('Достигнуто максимальное количество фотографий в альбоме!');
$('.mde-photo-edit__add-btn').hide();
}
return true;
}
function checkMaxAlbumElem() {
var maxElem = $('.mde-photo-edit').data('maxElem');
var maxElemExisting = $('.mde-photo-edit').children('.mde-photo-edit__wrapper').find('.mde-photo-edit__elem-cont').length;
return (maxElem == maxElemExisting);
}
function writeAlbumEdit(responce) {
var albumCont = $('.mde-photo-edit__wrapper');
albumCont.html('');
for (var i = 0; i < responce.data.photos.length; i++) {
var src = responce.data.photos[i].preview;
addPhotoToAlbum(src);
}
} |
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
$(document).ready(function() {
$('.about_nav_content li:first-child a').click(function(){
$('#historic_event_1').addClass('current');
$('#historic_event_2').removeClass('current');
$('#historic_event_3').removeClass('current');
$('#historic_event_4').removeClass('current');
$('#historic_event_5').removeClass('current');
$('#historic_event_6').removeClass('current');
$('#historic_event_7').removeClass('current');
$('#history_clock').removeClass('animate1 animate2 animate3 animate4 animate5 animate6');
});
var hoverOrClick = function(){
$("#history_clock").removeClass('animate1 animate2 animate3 animate4 animate5 animate6');
$('#historic_event_1').addClass('current');
$('#historic_event_2, #historic_event_3, #historic_event_4, #historic_event_5, #historic_event_6, #historic_event_7').removeClass('current');
}
$('#historic_dot_1, #historic_event_1').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate1');
$("#history_clock").removeClass('animate2 animate3 animate4 animate5 animate6');
$('#historic_event_2').addClass('current');
$('#historic_event_1, #historic_event_3, #historic_event_4, #historic_event_5, #historic_event_6, #historic_event_7').removeClass('current');
}
$('#historic_dot_2, #historic_event_2').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate2');
$("#history_clock").removeClass('animate1 animate3 animate4 animate5 animate6');
$('#historic_event_3').addClass('current');
$('#historic_event_1, #historic_event_2, #historic_event_4, #historic_event_5, #historic_event_6, #historic_event_7').removeClass('current');
}
$('#historic_dot_3, #historic_event_3').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate3');
$("#history_clock").removeClass('animate1 animate2 animate4 animate5 animate6');
$('#historic_event_4').addClass('current');
$('#historic_event_1, #historic_event_2, #historic_event_3, #historic_event_5, #historic_event_6, #historic_event_7').removeClass('current');
}
$('#historic_dot_4, #historic_event_4').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate4');
$("#history_clock").removeClass('animate1 animate2 animate3 animate5 animate6');
$('#historic_event_5').addClass('current');
$('#historic_event_1, #historic_event_2, #historic_event_3, #historic_event_4, #historic_event_6, #historic_event_7').removeClass('current');
}
$('#historic_dot_5, #historic_event_5').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate5');
$("#history_clock").removeClass('animate1 animate2 animate3 animate4 animate6');
$('#historic_event_6').addClass('current');
$('#historic_event_1, #historic_event_2, #historic_event_3, #historic_event_4, #historic_event_5, #historic_event_7').removeClass('current');
}
$('#historic_dot_6, #historic_event_6').click(hoverOrClick).hover(hoverOrClick);
var hoverOrClick = function(){
$('#history_clock').addClass('animate6');
$("#history_clock").removeClass('animate1 animate2 animate3 animate4 animate5');
$('#historic_event_7').addClass('current');
$('#historic_event_1, #historic_event_2, #historic_event_3, #historic_event_4, #historic_event_5, #historic_event_6').removeClass('current');
}
$('#historic_dot_7, #historic_event_7').click(hoverOrClick).hover(hoverOrClick);
}); |
/* jshint ignore:start */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
/* jshint ignore:end */
|
//(function() {
'use strict';
appbanco.factory('serviciobanco', serviciobanco);
appbanco.$inject = ['$http', '$resource'];
function serviciobanco($http, $resource) {
return $resource('http://localhost:1029/api/Bancos/:id', { id: "@_id" }, {
'update': { method: 'PUT' }
});
};
/*appbanco.factory('serviciobanco', serviciobanco);
serviciobanco.$inject = ['$http', '$location', '$q', 'webapi']; //'exception', 'logger', ];
function serviciobanco($http, $location, $q, webapi) { //} exception, logger, ) {
var isPrimed = false;
var primePromise;
var service = {
obtenerBancos: obtenerBancos,
obtenerBanco: obtenerBanco,
editarBanco: editarBanco,
eliminarBanco: eliminarBanco,
registrarBanco: registrarBanco,
ready: ready
};
return service;
function editarBanco(banco) {
return $q(function(resolve, reject) {
var params = { dto: angular.toJson(banco), credentials: '' };
webapi.EditarBanco(params, function(data) {
resolve(data);
}, function(datoerror) {
alert('Ocurrio un error editando el banco');
console.log(datoerror);
reject(datoerror);
});
});
};
function eliminarBanco(id) {
return $q(function(resolve, reject) {
var params = { id: id, credentials: '' };
webapi.EliminarBanco(params, function(data) {
resolve(data);
}, function(datoerror) {
alert('Ocurrio un error eliminando el banco');
console.log(datoerror);
reject(datoerror);
});
});
};
function registrarBanco(banco) {
return $q(function(resolve, reject) {
var params = { dto: banco, credentials: '' };
//webapi.data = banco;
var webapp = new webapi();
webapp.data = banco;
webapi.RegistrarBanco(webapp, function(data) {
resolve(data);
}, function(datoerror) {
alert('Ocurrio un error registrando el banco');
console.log(datoerror);
reject(datoerror);
});
});
};
function obtenerBancos() {
return $q(function(resolve, reject) {
var params = { credentials: '' };
webapi.ObtenerBancos(params, function(data) {
resolve(data);
}, function(datoerror) {
alert('Ocurrio un error obteniendo los bancos');
console.log(datoerror);
reject(datoerror);
});
});
};
function obtenerBanco(id) {
return $q(function(resolve, reject) {
var params = { id: id, credentials: '' };
webapi.ObtenerBanco(params, function(data) {
resolve(data);
}, function(datoerror) {
alert('Ocurrio un error obteniendo el banco');
console.log(datoerror);
reject(datoerror);
});
});
};
function prime() {
// This function can only be called once.
if (primePromise) {
return primePromise;
}
primePromise = $q.when(true).then(success);
return primePromise;
function success() {
isPrimed = true;
//logger.info('Primed data');
}
};
function ready(nextPromises) {
var readyPromise = primePromise || prime();
return readyPromise
.then(function() { return $q.all(nextPromises); })
.catch(); //exception.catcher('"ready" function failed'));
};
}*/
//}) |
import BN from "../../../bn.js";
import * as utils from "../utils";
'use strict';
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;
function BaseCurve(type, conf) {
this.type = type;
this.p = new BN(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
// Useful for many curves
this.zero = new BN(0).toRed(this.red);
this.one = new BN(1).toRed(this.red);
this.two = new BN(2).toRed(this.red);
// Curve configuration, optional
this.n = conf.n && new BN(conf.n, 16);
this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
// Temporary arrays
this._wnafT1 = new Array(4);
this._wnafT2 = new Array(4);
this._wnafT3 = new Array(4);
this._wnafT4 = new Array(4);
this._bitLength = this.n ? this.n.bitLength() : 0;
// Generalized Greg Maxwell's trick
var adjustCount = this.n && this.p.div(this.n);
if (!adjustCount || adjustCount.cmpn(100) > 0) {
this.redN = null;
}
else {
this._maxwellTrick = true;
this.redN = this.n.toRed(this.red);
}
}
BaseCurve.prototype.point = function point() {
throw new Error('Not implemented');
};
BaseCurve.prototype.validate = function validate() {
throw new Error('Not implemented');
};
BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
assert(p.precomputed);
var doubles = p._getDoubles();
var naf = getNAF(k, 1, this._bitLength);
var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
I /= 3;
// Translate into more windowed form
var repr = [];
var j;
var nafW;
for (j = 0; j < naf.length; j += doubles.step) {
nafW = 0;
for (var l = j + doubles.step - 1; l >= j; l--)
nafW = (nafW << 1) + naf[l];
repr.push(nafW);
}
var a = this.jpoint(null, null, null);
var b = this.jpoint(null, null, null);
for (var i = I; i > 0; i--) {
for (j = 0; j < repr.length; j++) {
nafW = repr[j];
if (nafW === i)
b = b.mixedAdd(doubles.points[j]);
else if (nafW === -i)
b = b.mixedAdd(doubles.points[j].neg());
}
a = a.add(b);
}
return a.toP();
};
BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
var w = 4;
// Precompute window
var nafPoints = p._getNAFPoints(w);
w = nafPoints.wnd;
var wnd = nafPoints.points;
// Get NAF form
var naf = getNAF(k, w, this._bitLength);
// Add `this`*(N+1) for every w-NAF index
var acc = this.jpoint(null, null, null);
for (var i = naf.length - 1; i >= 0; i--) {
// Count zeroes
for (var l = 0; i >= 0 && naf[i] === 0; i--)
l++;
if (i >= 0)
l++;
acc = acc.dblp(l);
if (i < 0)
break;
var z = naf[i];
assert(z !== 0);
if (p.type === 'affine') {
// J +- P
if (z > 0)
acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
else
acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
}
else {
// J +- J
if (z > 0)
acc = acc.add(wnd[(z - 1) >> 1]);
else
acc = acc.add(wnd[(-z - 1) >> 1].neg());
}
}
return p.type === 'affine' ? acc.toP() : acc;
};
BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) {
var wndWidth = this._wnafT1;
var wnd = this._wnafT2;
var naf = this._wnafT3;
// Fill all arrays
var max = 0;
var i;
var j;
var p;
for (i = 0; i < len; i++) {
p = points[i];
var nafPoints = p._getNAFPoints(defW);
wndWidth[i] = nafPoints.wnd;
wnd[i] = nafPoints.points;
}
// Comb small window NAFs
for (i = len - 1; i >= 1; i -= 2) {
var a = i - 1;
var b = i;
if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
max = Math.max(naf[a].length, max);
max = Math.max(naf[b].length, max);
continue;
}
var comb = [
points[a],
null,
null,
points[b],
];
// Try to avoid Projective points, if possible
if (points[a].y.cmp(points[b].y) === 0) {
comb[1] = points[a].add(points[b]);
comb[2] = points[a].toJ().mixedAdd(points[b].neg());
}
else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
comb[1] = points[a].toJ().mixedAdd(points[b]);
comb[2] = points[a].add(points[b].neg());
}
else {
comb[1] = points[a].toJ().mixedAdd(points[b]);
comb[2] = points[a].toJ().mixedAdd(points[b].neg());
}
var index = [
-3,
-1,
-5,
-7,
0,
7,
5,
1,
3,
];
var jsf = getJSF(coeffs[a], coeffs[b]);
max = Math.max(jsf[0].length, max);
naf[a] = new Array(max);
naf[b] = new Array(max);
for (j = 0; j < max; j++) {
var ja = jsf[0][j] | 0;
var jb = jsf[1][j] | 0;
naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
naf[b][j] = 0;
wnd[a] = comb;
}
}
var acc = this.jpoint(null, null, null);
var tmp = this._wnafT4;
for (i = max; i >= 0; i--) {
var k = 0;
while (i >= 0) {
var zero = true;
for (j = 0; j < len; j++) {
tmp[j] = naf[j][i] | 0;
if (tmp[j] !== 0)
zero = false;
}
if (!zero)
break;
k++;
i--;
}
if (i >= 0)
k++;
acc = acc.dblp(k);
if (i < 0)
break;
for (j = 0; j < len; j++) {
var z = tmp[j];
p;
if (z === 0)
continue;
else if (z > 0)
p = wnd[j][(z - 1) >> 1];
else if (z < 0)
p = wnd[j][(-z - 1) >> 1].neg();
if (p.type === 'affine')
acc = acc.mixedAdd(p);
else
acc = acc.add(p);
}
}
// Zeroify references
for (i = 0; i < len; i++)
wnd[i] = null;
if (jacobianResult)
return acc;
else
return acc.toP();
};
function BasePoint(curve, type) {
this.curve = curve;
this.type = type;
this.precomputed = null;
}
BaseCurve.BasePoint = BasePoint;
BasePoint.prototype.eq = function eq( /*other*/) {
throw new Error('Not implemented');
};
BasePoint.prototype.validate = function validate() {
return this.curve.validate(this);
};
BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
bytes = utils.toArray(bytes, enc);
var len = this.p.byteLength();
// uncompressed, hybrid-odd, hybrid-even
if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
bytes.length - 1 === 2 * len) {
if (bytes[0] === 0x06)
assert(bytes[bytes.length - 1] % 2 === 0);
else if (bytes[0] === 0x07)
assert(bytes[bytes.length - 1] % 2 === 1);
var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len));
return res;
}
else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
bytes.length - 1 === len) {
return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
}
throw new Error('Unknown point format');
};
BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
return this.encode(enc, true);
};
BasePoint.prototype._encode = function _encode(compact) {
var len = this.curve.p.byteLength();
var x = this.getX().toArray('be', len);
if (compact)
return [this.getY().isEven() ? 0x02 : 0x03].concat(x);
return [0x04].concat(x, this.getY().toArray('be', len));
};
BasePoint.prototype.encode = function encode(enc, compact) {
return utils.encode(this._encode(compact), enc);
};
BasePoint.prototype.precompute = function precompute(power) {
if (this.precomputed)
return this;
var precomputed = {
doubles: null,
naf: null,
beta: null,
};
precomputed.naf = this._getNAFPoints(8);
precomputed.doubles = this._getDoubles(4, power);
precomputed.beta = this._getBeta();
this.precomputed = precomputed;
return this;
};
BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
if (!this.precomputed)
return false;
var doubles = this.precomputed.doubles;
if (!doubles)
return false;
return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
};
BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
if (this.precomputed && this.precomputed.doubles)
return this.precomputed.doubles;
var doubles = [this];
var acc = this;
for (var i = 0; i < power; i += step) {
for (var j = 0; j < step; j++)
acc = acc.dbl();
doubles.push(acc);
}
return {
step: step,
points: doubles,
};
};
BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
if (this.precomputed && this.precomputed.naf)
return this.precomputed.naf;
var res = [this];
var max = (1 << wnd) - 1;
var dbl = max === 1 ? null : this.dbl();
for (var i = 1; i < max; i++)
res[i] = res[i - 1].add(dbl);
return {
wnd: wnd,
points: res,
};
};
BasePoint.prototype._getBeta = function _getBeta() {
return null;
};
BasePoint.prototype.dblp = function dblp(k) {
var r = this;
for (var i = 0; i < k; i++)
r = r.dbl();
return r;
};
export default BaseCurve;
|
editAreaLoader.load_syntax["scm"] = {
'DISPLAY_NAME' : 'Scheme'
,'COMMENT_SINGLE' : {1 : ';', 2:';;'}
,'COMMENT_MULTI' : {'#|' : '|#'}
,'QUOTEMARKS' : ['"']
,'KEYWORD_CASE_SENSITIVE' : false
,'KEYWORDS' : {
'symbols' : [
'*', '+', '-', '...', '/', '<', '<=', '>=', 'abs', 'acos',
'and', 'angle', 'apply', 'asin', 'assoc', 'assq', 'assv',
'atan', 'begin', 'boolean?', 'caar', 'cadr',
'call-with-current-continuetion', 'call-with-input-file',
'call-with-output-file', 'call-with-values', 'call/cc',
'car', 'case', 'catch', 'cdddar', 'cddddr', 'cdr',
'ceiling', 'char->integer', 'char-alphabetic?',
'char-ci<=?', 'char-ci<?', 'char-ci=?', 'char-ci>=?',
'char-ci>?', 'char-downcase', 'char-lower-case?',
'char-numeric?', 'char-ready?', 'char-upcase',
'char-upper-case?', 'char-whitespace', 'char<=?', 'char<?',
'char=?', 'char>=?', 'char>?', 'char?', 'close-input-port',
'close-output-port', 'complex?', 'cond', 'cons', 'cos',
'current-input-port', 'current-output-port', 'define',
'define-syntax', 'delay', 'denominator', 'display', 'do',
'dynamic-wind', 'else', 'eof-object?', 'eq?', 'equal?',
'eqv?', 'eval', 'even?', 'exact->inexact', 'exact?', 'exp',
'expt', 'floor', 'for-each', 'force', 'gcd', 'if', 'img-part',
'inexact->exact', 'inexact?', 'input-port?', 'integer->char',
'integer?', 'intaraction-environment', 'lambda', 'lcm',
'length', 'let', 'let*', 'let-syntax', 'letrec',
'letrec-syntax', 'list', 'list->string', 'list->vector',
'list-ref', 'list-tail', 'list?', 'load', 'log', 'magnitude',
'make-polar', 'make-rectanglar', 'make-string', 'make-vector',
'map', 'max', 'membar', 'memq', 'min', 'modulo', 'negative?',
'newline', 'not', 'null-environment', 'null?', 'number->string',
'number?', 'numerator', 'odd?', 'open-input-file',
'open-output-file', 'or', 'output-port?', 'pair?', 'peek-char',
'port?', 'positive?', 'procedure?', 'quasiquote', 'quote',
'quotient', 'rational?', 'rationalize', 'read', 'read-char',
'real-part', 'real?', 'remainder', 'reverse', 'round',
'scheme-report-environment', 'set!', 'set-car!', 'set-cdr!',
'setcar', 'sin', 'sqrt', 'string', 'string->list',
'string->number', 'string->symbol', 'string-append',
'string-ci<=?', 'string-ci<?', 'string-ci=?', 'string-ci>=?',
'string-ci>?', 'string-copy', 'string-fill!', 'string-length',
'string-ref', 'string-set!', 'string<=?', 'string<?',
'string=?', 'string>=?', 'string>?', 'string?', 'substring',
'symbol->string', 'symbol?', 'syntax-rules', 'tan',
'transcript-off', 'transcript-on', 'truncate', 'unquote',
'unquote-splicing', 'values', 'vector', 'vector->list',
'vector-fill!', 'vector-length', 'vector-ref', 'vector-set!',
'vector?', 'with-input-from-file', 'with-output-to-file',
'write', 'write-char', 'zero?'
]
}
,'OPERATORS' :[
]
,'DELIMITERS' :[ // Array: the block code delimiters to highlight
'(', ')'
]
,'STYLES' : {
// Array: an array of array, containing all style to apply for categories defined before.
// Better to define color style only.
'COMMENTS': 'color: #D46633;'
,'QUOTESMARKS': 'color: #009933;'
,'KEYWORDS' : {
'symbols' : 'color: #00BBDD;'
}
,'OPERATORS' : 'color: #FF00FF;'
,'DELIMITERS' : 'color: #0038E1;'
}
};
|
document.addEventListener('DOMContentLoaded',function(){
// var data = {
// list: [
// {name:' guokai', show: true},
// {name:' benben', show: false},
// {name:' dierbaby', show: true},
// {age:'123'}
// ],
// blah: [
// {num: 1},
// {num: 2},
// {num: 3, inner:[
// {'time': '15:00'},
// {'time': '16:00'},
// {'time': '17:00'},
// {'time': '18:00'}
// ]},
// {num: 4}
// ]
// };
var data = {
"info_list": [{
"info_id": "FIN2016102500876403",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500876403 2FFIN2016102500876403_pc.shtml",
"title": "前两轮人民币贬值引A股大跌 20这次不同?"
}, {
"info_id": "FIN2016102500823101",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500823101 2FFIN2016102500823101_pc.shtml",
"title": "惊人相似的牛市能否重演?两角度对比把握深港通机遇"
}, {
"info_id": "FIN2016102500549904",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500549904 2FFIN2016102500549904_pc.shtml",
"title": "恒大“准举牌” 20国民技术 20或跃升至第一大股东"
}, {
"info_id": "FIN2016102500573601",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500573601 2FFIN2016102500573601_pc.shtml",
"title": "深港通新一轮全网测试本周末举行"
}, {
"info_id": "FIN2016102500497902",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500497902 2FFIN2016102500497902_pc.shtml",
"title": "港股早报:大市突破关键点位 20市场活跃度再提升"
}, {
"info_id": "FIN2016102500205402",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500205402 2FFIN2016102500205402_pc.shtml",
"title": "安哥拉取代俄罗斯成中国最大原油供应国"
}, {
"info_id": "FIN2016102500452701",
"info_time": "2016-10-25",
"link": " 2Fstatic 2Fetf_news 2F20161025 2FFIN2016102500452701 2FFIN2016102500452701_pc.shtml",
"title": "证监会缩短重组期初显正面效果 20停牌3个月公司总数锐减"
}]
}
console.log(data)
var tpl = document.getElementById('tpl').innerHTML;
var html = juicer(tpl, data);
var li = document.querySelector('.infolist');
li.innerHTML = html;
},false);
// var fs = require('fs');
// var url = require('url');
// var info = fs.readFileSync('json/info.json');
// info = JSON.parse(info);
// console.log(typeof info) |
version https://git-lfs.github.com/spec/v1
oid sha256:60c4151a84bbab8127be57222ba3679f88d5c6a5012a8615c5f29edcb8bad0b4
size 1707
|
import ajax from './ajax';
export default (url) => {
return ajax( url, '' )
.then( ( str ) => JSON.parse( str ) );
}; |
'use strict';
var originalMobile = typeof Mobile === 'undefined' ? undefined : Mobile;
var mockMobile = require('../lib/MockMobile');
var net = require('net');
var tape = require('../lib/thaliTape');
var ThaliTCPServersManager = require('thali/NextGeneration/mux/thaliTcpServersManager');
var makeIntoCloseAllServer = require('thali/NextGeneration/makeIntoCloseAllServer');
var Promise = require('lie');
var assert = require('assert');
var logger = require('../lib/testLogger')('testCreatePeerListener');
// Every call to Mobile trips this warning
/* jshint -W064 */
// Does not currently work in coordinated
// environment, because uses fixed port numbers.
if (tape.coordinated) {
return;
}
var applicationPort = 4242;
var nativePort = 4040;
var serversManager = null;
var nativeServer = null;
var appServer = null;
var test = tape({
setup: function (t) {
global.Mobile = mockMobile;
nativeServer = makeIntoCloseAllServer(net.createServer(), true);
nativeServer.listen(0, function () {
appServer = makeIntoCloseAllServer(net.createServer(), true);
appServer.listen(0, function () {
serversManager = new ThaliTCPServersManager(appServer.address().port);
t.end();
});
});
},
teardown: function (t) {
(serversManager ? serversManager.stop() : Promise.resolve())
.catch(function (err) {
t.fail('serversManager had stop error ' + err);
})
.then(function () {
var promise = nativeServer ? nativeServer.closeAllPromise() :
Promise.resolve();
nativeServer = null;
return promise;
})
.then(function () {
var promise = appServer ? appServer.closeAllPromise() :
Promise.resolve();
appServer = null;
return promise;
})
.then(function () {
global.Mobile = originalMobile;
t.end();
});
}
});
test('calling createPeerListener without calling start produces error',
function (t) {
serversManager.start()
.then(function () {
t.end();
});
});
test('calling createPeerListener after calling stop produces error',
function (t) {
serversManager.start()
.then(function () {
t.end();
});
});
test('can call createPeerListener', function (t) {
serversManager.start()
.then(function () {
serversManager.createPeerListener('peerId')
.then(function (peerPort) {
t.ok(peerPort > 0 && peerPort <= 65535, 'port must be in range');
t.end();
});
})
.catch(function () {
t.fail('server should not get error');
t.end();
});
});
test('calling createPeerListener twice with same peerIdentifier should ' +
'return the same port', function (t) {
serversManager.start()
.then(function () {
var promise1 = serversManager.createPeerListener('peer1');
var promise2 = serversManager.createPeerListener('peer1');
var promise3 = serversManager.createPeerListener('peer1');
return Promise.all([promise1, promise2, promise3]);
})
.then(function (promiseResultArray) {
t.equal(promiseResultArray[0], promiseResultArray[1],
'port values should be the same');
t.end();
})
.catch(function (err) {
t.fail('oops ' + err);
t.end();
});
});
var validateIncomingData = function (t, socket, desiredMessage, cb) {
var done = false;
var collectedData = new Buffer(0);
socket.on('data', function (data) {
if (done) {
t.fail('Got too much data');
}
collectedData = Buffer.concat([collectedData, data]);
if (collectedData.length < desiredMessage.length) {
return;
}
done = true;
if (collectedData.length > desiredMessage.length) {
t.fail('Got too much data');
cb && cb();
return;
}
t.ok(Buffer.compare(collectedData, desiredMessage) === 0,
'Data should be of same length and content');
cb && cb();
});
};
function connectAndFail(t, failLogic) {
var firstPort = null;
var gotClose = false;
var gotListenerRecreated = false;
var timeOut = null;
var haveQuit = false;
var quit = function (error) {
function exit() {
haveQuit = true;
clearTimeout(timeOut);
serversManager.removeAllListeners('listenerRecreatedAfterFailure');
t.end();
}
if (haveQuit) {
return;
}
if (error) {
t.fail(error);
exit();
}
if (!(gotClose && gotListenerRecreated)) {
return;
}
exit();
};
timeOut = setTimeout(function () {
quit(new Error('Test timed out'));
}, 60 * 1000);
serversManager.on('listenerRecreatedAfterFailure', function (record) {
t.equal('peer2', record.peerIdentifier, 'same peer ID');
t.notEqual(firstPort, record.portNumber, 'different ports');
gotListenerRecreated = true;
quit();
});
appServer.on('connection', function (socket) {
validateIncomingData(t, socket, new Buffer('test'));
socket.on('data', function () {
failLogic(nativeServer);
});
});
serversManager.start()
.then(function (incomingMuxListenerPort) {
nativeServer.on('connection', function (socket) {
var outgoing = net.createConnection(incomingMuxListenerPort);
outgoing.pipe(socket).pipe(outgoing);
socket.on('error', function (err) {
logger.debug('Got error in test socket - ' + err);
});
socket.on('close', function () {
outgoing.destroy();
});
outgoing.on('error', function (err) {
logger.debug('Got error in outgoing test - ' + err);
});
outgoing.on('close', function () {
socket.destroy();
});
});
// Have the next Mobile("connect") call complete with a forward
// connection
Mobile('connect').nextNative(function (peerIdentifier, cb) {
cb(null, Mobile.createListenerOrIncomingConnection(
nativeServer.address().port));
});
return serversManager.createPeerListener('peer2');
})
.then(function (port) {
firstPort = port;
var socket = net.connect(port, function () {
socket.write(new Buffer('test'));
});
socket.on('close', function () {
gotClose = true;
quit();
});
})
.catch(function (err) {
quit(err);
});
nativeServer.on('error', function (err) {
if (err) {
quit(new Error('nativeServer should not fail'));
}
});
}
test('createPeerListener - closing connection to native listener closes ' +
'everything and triggers new listener',
function (t) {
connectAndFail(t, function (nativeServer) {
nativeServer.closeAll();
});
});
test('createPeerListener - closing mux closes listener and triggers ' +
'a new listener', function (t) {
connectAndFail(t, function () {
serversManager._peerServers.peer2.server._mux.destroy();
});
});
/*
//////////////////////////////////////////////////////////////////////////
Now we get to the complex stuff
//////////////////////////////////////////////////////////////////////////
///////////////////////
Some utility functions
*/
function waitForPeerAvailabilityChanged(t, serversManager, dontFail, then) {
Mobile('peerAvailabilityChanged').registerToNative(function (peers) {
peers.forEach(function (peer) {
if (peer.peerAvailable) {
serversManager.createPeerListener(peer.peerIdentifier)
.then(function (peerPort) {
if (then) {
then(peerPort);
}
})
.catch(function (err) {
if (!dontFail) {
t.fail('Unexpected rejection creating peer listener' + err);
console.warn(err);
}
});
}
});
});
}
function startAdvertisingAndListening(t, applicationPort) {
Mobile('startUpdateAdvertisingAndListening').callNative(
applicationPort,
function (err) {
t.notOk(err, 'Can call startUpdateAdvertisingAndListening without error');
Mobile('startListeningForAdvertisements').callNative(function (err) {
t.notOk(err, 'Can call startListeningForAdvertisements without error');
Mobile('peerAvailabilityChanged').callRegistered([{
peerIdentifier : 'peer1',
peerAvailable : true
}]);
});
});
}
function startServersManager(t, serversManager) {
serversManager.start().then(function () {
})
.catch(function (err) {
t.fail('server should not get error: ' + err);
});
}
function setUp(t, serversManager, appPort, nativePort, dontFail, then) {
waitForPeerAvailabilityChanged(t, serversManager, dontFail, then);
startServersManager(t, serversManager);
assert(nativePort !== 0, 'Check for old reverse connection logic');
Mobile('connect').nextNative(function (peerIdentifier, cb) {
cb(null,
Mobile.createListenerOrIncomingConnection(nativePort));
});
startAdvertisingAndListening(t, appPort);
}
/*
End of Utility functions
/////////////////////////
*/
test('peerListener - no native server',
function (t) {
var firstConnection = false;
// We expect 'failedConnection' since there's no native listener
serversManager.on('failedConnection', function (err) {
t.ok(firstConnection, 'Should not get event until connection is made');
t.equal(err.error.message, 'Cannot Connect To Peer',
'reason should be as expected');
t.end();
});
setUp(t, serversManager, applicationPort, nativePort, false,
function (peerPort) {
t.notEqual(peerPort, nativePort, 'peerPort should not be nativePort');
net.createConnection(peerPort);
firstConnection = true;
});
}
);
test('peerListener - with native server',
function (t) {
var firstConnection = false;
serversManager.on('failedConnection', function () {
t.fail('connection shouldn\'t fail');
});
var nativeServer = net.createServer(function (socket) {
t.ok(firstConnection, 'Should not get unexpected connection');
nativeServer.close();
socket.end();
t.end();
});
nativeServer.listen(nativePort, function (err) {
if (err) {
t.fail('nativeServer should not fail');
t.end();
}
});
setUp(t, serversManager, applicationPort, nativePort, false,
function (peerPort) {
t.notEqual(peerPort, nativePort, 'peerPort != nativePort');
// Need to connect a socket to force the outgoing
net.createConnection(peerPort);
firstConnection = true;
}
);
}
);
test('peerListener - with native server and data transfer',
function (t) {
var timer = setTimeout(function () {
t.fail('Timed out');
exit();
}, 30 * 1000);
var exitCalled = false;
function exit() {
if (exitCalled) {
return;
}
clearTimeout(timer);
exitCalled = true;
t.end();
}
var data = new Buffer(10000);
var connectionCount = 0;
appServer.on('connection', function (socket) {
++connectionCount;
if (connectionCount !== 1) {
t.fail('Got more than one conntection');
return exit();
}
validateIncomingData(t, socket, data, function () {
socket.write(data);
});
});
serversManager.start()
.then(function (incomingNativeListenerPort) {
Mobile('connect').nextNative(function (peerIdentifier, cb) {
cb(null, Mobile.createListenerOrIncomingConnection(
incomingNativeListenerPort));
});
return serversManager.createPeerListener('peer1');
})
.then(function (localListenerPort) {
var socket = net.connect(localListenerPort, function () {
socket.write(data);
});
validateIncomingData(t, socket, data, function () {
exit();
});
})
.catch(function (err) {
t.fail(err);
exit();
});
}
);
test('createPeerListener is idempotent', function (t) {
serversManager.on('failedConnection', function () {
t.fail('connection shouldn\'t fail');
t.end();
});
waitForPeerAvailabilityChanged(t, serversManager, false, function (peerPort) {
// Create another peerListener to peer1
serversManager.createPeerListener('peer1')
.then(function (port) {
t.equal(peerPort, port,
'Second call to existing peerListener returns existing port');
t.end();
})
.catch(function (err) {
t.fail('should not get error - ' + err);
t.end();
});
});
startServersManager(t, serversManager);
startAdvertisingAndListening(t, applicationPort);
});
test('createPeerListener - ask for new peer when we are at maximum and make ' +
'sure we remove the right existing listener', function (t) {
// We need to send data across the listeners so we can control their last
// update time and then prove we close the right one, the oldest
serversManager.start()
.then(function () {
t.end();
});
});
test('createPeerListener - ask for a new peer when we are not at maximum ' +
'peers and make sure we do not remove any existing listeners', function (t){
serversManager.start()
.then(function () {
t.end();
});
});
test('createPeerListener - test timeout', function (t) {
// We have to prove to ourselves that once we connect to the listener and
// the connection is created that if the native link goes inactive long
// enough we will properly close it and clean everything up.
serversManager.start()
.then(function () {
t.end();
});
});
test('createPeerListener - multiple connections out',
function (t) {
// Create an outgoing connection and then open a bunch of TCP links to
// the server and show that they properly send everything across all the
// links to the server on the other side. Also show that when we shut things
// down we clean everything up properly.
serversManager.start()
.then(function () {
t.end();
});
});
test('createPeerListener - multiple bi-directional connections',
function (t) {
// Trigger an outgoing connection and then have multiple connections
// going in both directions (e.g. the iOS scenario) and make sure that
// everything is fine and then close it all down and make sure we clean
// up right.
serversManager.start()
.then(function () {
t.end();
});
});
test('createPeerListener - multiple parallel calls', function (t) {
// Unlike createNativeListener, it's completely legal to have multiple
// parallel calls to createPeerListener, we need to test what happens
// when we have multiple calls in parallel and make sure that nothing
// breaks.
serversManager.start()
.then(function () {
t.end();
});
});
// This is related with issue #1473.
test('createPeerListener - we shouldn\'t create a dead pipe', function (t) {
var firstConnection = false;
var firstConnectionPort;
serversManager.on('failedConnection', function () {
t.fail('connection shouldn\'t fail');
});
var nativeServer = net.createServer(function (socket) {
t.ok(firstConnection, 'Should not get unexpected connection');
// Replacing 'pipe' method on any socket.
var oldPipe = socket.__proto__.pipe;
socket.__proto__.pipe = function (targetSocket) {
if (socket.readyState === 'closed' || targetSocket.readyState === 'closed') {
t.fail('we created a new pipe with closed socket');
} else {
t.pass('we created a new pipe with valid sockets');
}
return oldPipe.apply(this, arguments);
};
serversManager.terminateOutgoingConnection('peer1', firstConnectionPort)
.then(function () {
// We are waiting until events will be fired.
setImmediate(function () {
socket.__proto__.pipe = oldPipe;
nativeServer.close();
socket.end();
t.pass('passed');
t.end();
});
});
});
nativeServer.listen(nativePort, function (error) {
if (error) {
logger.error('got error: \'%s\'', error.toString());
t.fail('nativeServer should not fail');
t.end();
return;
}
setUp(t, serversManager, applicationPort, nativePort, false,
function (peerPort) {
t.notEqual(peerPort, nativePort, 'peerPort != nativePort');
// Need to connect a socket to force the outgoing
net.createConnection(peerPort);
firstConnection = true;
firstConnectionPort = peerPort;
}
);
});
});
|
'use strict';
/**
* @ngdoc overview
* @name cpsClientApp
* @description
* # cpsClientApp
*
* Main module of the application.
*/
angular
.module('cpsClientApp', [
'cpsClientApp.services',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ui.bootstrap',
'ui.grid',
'ui.router'
])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('main',{
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.state('about',{
url: '/about',
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.state('contact',{
url: '/contact',
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
})
.state('products', {
url: '/products',
templateUrl: 'partials/products/list.html',
controller: 'ProductListController'
})
.state('viewProduct', {
url: '/products/:id/view',
templateUrl: 'partials/products/view.html',
controller: 'ProductViewController'
})
.state('newProduct', {
url: '/products/new',
templateUrl: 'partials/products/add.html',
controller: 'ProductCreateController'
})
.state('editProduct', {
url: '/products/:id/edit',
templateUrl: 'partials/products/edit.html',
controller: 'ProductEditController'
})
.state('licenses', {
url: '/licenses',
templateUrl: 'partials/licenses/list.html',
controller: 'LicenseListController'
})
.state('viewLicense', {
url: '/licenses/:id/view',
templateUrl: 'partials/licenses/view.html',
controller: 'LicenseViewController'
})
.state('newLicense', {
url: '/licenses/new',
templateUrl: 'partials/licenses/add.html',
controller: 'LicenseCreateController'
})
.state('editLicense', {
url: '/licenses/:id/edit',
templateUrl: 'partials/licenses/edit.html',
controller: 'LicenseEditController'
})
.state('generators', {
url: '/generators',
templateUrl: 'partials/generators/list.html',
controller: 'GeneratorListController'
})
.state('viewGenerator', {
url: '/generators/:id/view',
templateUrl: 'partials/generators/view.html',
controller: 'GeneratorViewController'
})
.state('newGenerator', {
url: '/generators/new',
templateUrl: 'partials/generators/add.html',
controller: 'GeneratorCreateController'
})
.state('editGenerator', {
url: '/generators/:id/edit',
templateUrl: 'partials/generators/edit.html',
controller: 'GeneratorEditController'
});
})
.run(function($state){
$state.go('main');
});
|
var init = require('../base/init');
var error = require('../base/error');
var expb = require('../express/express-base');
var userb = require('../user/user-base');
expb.core.get('/api/users/:id([0-9]+)', function (req, res, done) {
var id = parseInt(req.params.id) || 0;
var user = res.locals.user
userb.getCached(id, function (err, _tuser) {
if (err) return done(err);
var tuser;
if (user && user.admin) {
tuser = {
_id: _tuser._id,
name: _tuser.name,
home: _tuser.home,
email: _tuser.email,
status: _tuser.status,
cdate: _tuser.cdate.getTime(),
adate: _tuser.adate.getTime(),
profile: _tuser.profile
};
} else if (user && user._id == _tuser._id) {
tuser = {
_id: _tuser._id,
name: _tuser.name,
home: _tuser.home,
email: _tuser.email,
status: _tuser.status,
cdate: _tuser.cdate.getTime(),
adate: _tuser.adate.getTime(),
profile: _tuser.profile
};
} else {
tuser = {
_id: _tuser._id,
name: _tuser.name,
home: _tuser.home,
//email: _tuser.email,
status: _tuser.status,
cdate: _tuser.cdate.getTime(),
//adate: _tuser.adate.getTime(),
profile: _tuser.profile
};
}
res.json({
user: tuser
});
});
});
|
(function (root, factory) { // UMD from https://github.com/umdjs/umd/blob/master/returnExports.js
"use strict";
if (typeof exports === 'object') {
module.exports = factory();
} else {
define(factory);
}
}(this, function () {
"use strict";
// Author: Matthew Forrester <matt_at_keyboardwritescode.com>
// Copyright: Matthew Forrester
// License: MIT/BSD-style
/**
* # addLocking()
*
* Adds internal locking to an existing pseudo-classical Javascript class
*
* ## Example
*
* ```javascript
* var MyClass = function() {
* };
*
* MyClass.prototype.doSomething = function() {
* this._lockFor(1); // Lock with bitpattern '10'
* this._startSensitiveJob();
* this._lockFor(2); // Lock with bitpattern '01', Locks '11' now present.
* this._startSomethingElse();
* this._unlockFor(3); // Lock is now back at '00'
* };
*
* MyClass.prototype.doSomethingElse() {
* if (this.amILocked(2)) {
* // It safe to do something as lock '10' is not present.
* }
* };
*
* addLocking(MyClass,3); Supports locks 1 and 2
* ```
*
* ## Parameters
* * **@param {Function} `classFunc`** The class to add internal locking to.
* * **@param {Array} `maxLockingValue`** maximum bit pattern suported for locking.
*/
return function(classFunc,maxLockingValue) {
classFunc.prototype._ensureLockingData = function() {
if (!this.hasOwnProperty('_locked')) {
this._locked = 0;
}
};
/**
* ### CLASS._amILocked()
*
* Checks if SyncIt is locked.
*
* #### Parameters
*
* **@param {Number} `disregardTheseLocks`** Allowed locks to skip over.
* **@return {Boolean}** True if locks other than `disregardTheseLocks` are present.
*/
classFunc.prototype._amILocked = function(disregardTheseLocks) {
this._ensureLockingData();
return this._locked & (maxLockingValue ^ disregardTheseLocks) ? true : false;
};
/**
* ### CLASS._lockFor()
*
* Adds the lock `lockType`
*
* **@param {Number} `lockType`** The lock to add.
* **@return {Boolean}** False if the lock was already present, True otherwise.
*/
classFunc.prototype._lockFor = function(lockType) {
this._ensureLockingData();
var r = this._locked & lockType;
if (r) { return false; }
this._locked = this._locked | lockType;
return true;
};
/**
* ### CLASS._unlockFor()
*
* Removes the lock `lockType`
*
* **@param {Number} `lockType`** The lock to remove.
* **@return {Boolean}** False if the lock was not present, True otherwise.
*/
classFunc.prototype._unlockFor = function(lockType) {
this._ensureLockingData();
if (!(this._locked & lockType)) {
return false;
}
this._locked = this._locked ^ (maxLockingValue & lockType);
};
/**
* ### classFunc.isLocked()
*
* #### Returns
*
* * **@return {Boolean}** True if there are any locks
*/
classFunc.prototype.isLocked = function() {
this._ensureLockingData();
return (this._locked > 0);
};
};
}));
|
import React from 'react';
import classNames from 'classnames';
const DialogContentSection = ({ className, noMargin, title, last, children, style, rootStyles = {} }) => {
const styles = {
title: {
color: '#aaa',
fontSize: 11,
textTransform: 'uppercase'
}
};
const rootClassName = classNames({
'vm-3-b': !last && !noMargin
}, className);
return (
<div
className={rootClassName}
style={rootStyles}
>
{title && <div style={styles.title}>{title}</div>}
<div
className="row"
style={style}
>
{children}
</div>
</div>
);
};
export default DialogContentSection;
|
/**
* Created by ralphy on 29/03/17.
*/
/**
* this spell will permanantly increase player fire power
* by 10 points
* @class MANSION.SPELLS.PermaPower
*/
O2.createClass('MANSION.SPELLS.PermaPower', {
run: function(g) {
var ePerma = new Effect.PermaBonus('power');
var p = g.oLogic.getPlayerSoul();
ePerma.setSource(p);
ePerma.setTarget(p);
ePerma.setLevel(MANSION.CONST.SPELL_POWER_UP);
ePerma.setDuration(10);
var ep = g.oLogic.getEffectProcessor();
ep.applyEffect(ePerma);
g.fadeIn('rgba(250, 100, 100, 0.5)', 1500);
g.fadeIn('rgba(250, 200, 100, 0.75)', 750);
}
}); |
import Ember from 'ember';
import RequestMixin from '../mixins/request';
export default Ember.Route.extend(RequestMixin, {
model() {
return this.request({
url: 'http://reqr.es/api/users',
type: 'GET',
data: {}
})
.then((res) => res.data);
}
});
|
// Test setup
///////////////////////////////////////
var specs = require("../../SpecHelpers");
//specs.debug();
specs.ensureWindow();
specs.ensureNamespace("ExoWeb.Model");
//require("../../../src/base/core/Activity");
//require("../../../src/base/core/Function");
//require("../../../src/base/core/Functor");
//require("../../../src/base/core/Array");
//require("../../../src/base/core/Utilities");
// Imports
///////////////////////////////////////
var typeChecking = specs.require("core.TypeChecking");
specs.require("core.Utilities");
specs.require("model.Model");
// References
///////////////////////////////////////
var describe = jasmine.describe;
var it = jasmine.it;
var expect = jasmine.expect;
var beforeEach = jasmine.beforeEach;
// Test Suites
///////////////////////////////////////
describe("Model", function() {
it("tracks a collection of types, which is initially empty", function() {
// TODO: change to "types()"
var model = new Model();
expect(typeChecking.type(model._types)).toBe("object");
expect(objectToArray(model._types).length).toBe(0);
expect(typeChecking.type(model.types())).toBe("array");
expect(model.types().length).toBe(0);
});
});
// Run Tests
///////////////////////////////////////
jasmine.jasmine.getEnv().addReporter(new jasmineConsole.Reporter());
jasmine.jasmine.getEnv().execute();
|
import createEggUnits from './eggs';
import createButterUnits from './butter';
export default repository => {
createEggUnits(repository);
createButterUnits(repository);
} |
'use strict';
var defaultEnvConfig = require('./default');
module.exports = {
db: {
//uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
uri: 'mongodb://admin:n0rth725@apollo.modulusmongo.net:27017/uqIq2ina',
options: {
user: '',
pass: ''
},
// Enable mongoose debug mode
debug: process.env.MONGODB_DEBUG || false
},
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'dev',
// Stream defaults to process.stdout
// Uncomment to enable logging to a log on the file system
options: {
//stream: 'access.log'
}
},
app: {
title: defaultEnvConfig.app.title + ' - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/api/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/github/callback'
},
paypal: {
clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
callbackURL: '/api/auth/paypal/callback',
sandbox: true
},
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'
}
}
},
livereload: true
};
|
'use strict';
/**
* This 'registered' action acknowledge that the server has registered the user
* @param client
*/
module.exports = function(client) {
client.emit('registered');
};
|
import React from "react"
import { graphql } from "gatsby"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import presets, { colors } from "../utils/presets"
import { rhythm, options } from "../utils/typography"
import { WebpackIcon, ReactJSIcon, GraphQLIcon } from "../assets/logos"
import { vP } from "../components/gutters"
import Container from "../components/container"
import MastheadBg from "../components/masthead-bg"
import MastheadContent from "../components/masthead"
import Cards from "../components/cards"
import Card from "../components/card"
import UsedBy from "../components/used-by"
import CardHeadline from "../components/card-headline"
import Diagram from "../components/diagram"
import BlogPostPreviewItem from "../components/blog-post-preview-item"
import FuturaParagraph from "../components/futura-paragraph"
import Button from "../components/button"
import TechWithIcon from "../components/tech-with-icon"
import EmailCaptureForm from "../components/email-capture-form"
class IndexRoute extends React.Component {
render() {
const blogPosts = this.props.data.allMarkdownRemark
return (
<Layout location={this.props.location}>
<Helmet>
<meta
name="Description"
content="Blazing fast modern site generator for React. Go beyond static sites: build blogs, ecommerce sites, full-blown apps, and more with Gatsby."
/>
</Helmet>
<div css={{ position: `relative` }}>
<MastheadBg />
<div
css={{
display: `flex`,
flexDirection: `row`,
flexWrap: `wrap`,
justifyContent: `space-between`,
}}
>
<MastheadContent />
<UsedBy />
<div
css={{
padding: rhythm(presets.gutters.default / 2),
flex: `0 0 100%`,
maxWidth: `100%`,
[presets.Hd]: {
padding: vP,
paddingTop: 0,
},
}}
>
<main
id={`reach-skip-nav`}
css={{
display: `flex`,
flexDirection: `row`,
flexWrap: `wrap`,
justifyContent: `space-between`,
}}
>
<Cards>
<Card>
<CardHeadline>
Modern web tech without the headache
</CardHeadline>
<FuturaParagraph>
Enjoy the power of the latest web technologies –{` `}
<TechWithIcon icon={ReactJSIcon}>React.js</TechWithIcon>,
{` `}
<TechWithIcon icon={WebpackIcon}>Webpack</TechWithIcon>,
{` `}
modern JavaScript and CSS and more — all set up and waiting
for you to start building.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Bring your own data</CardHeadline>
<FuturaParagraph>
Gatsby’s rich data plugin ecosystem lets you build sites
with the data you want — from one or many sources: Pull
data from headless CMSs, SaaS services, APIs, databases,
your file system, and more directly into your pages using
{` `}
<TechWithIcon icon={GraphQLIcon}>GraphQL</TechWithIcon>.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Scale to the entire internet</CardHeadline>
<FuturaParagraph>
Gatsby.js is Internet Scale. Forget complicated deploys
with databases and servers and their expensive,
time-consuming setup costs, maintenance, and scaling
fears. Gatsby.js builds your site as “static” files which
can be deployed easily on dozens of services.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Future-proof your website</CardHeadline>
<FuturaParagraph>
Do not build a website with last decade’s tech. The future
of the web is mobile, JavaScript and APIs—the {` `}
<a href="https://jamstack.org/">JAMstack</a>. Every
website is a web app and every web app is a website.
Gatsby.js is the universal JavaScript framework you’ve
been waiting for.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>
<em css={{ color: colors.gatsby, fontStyle: `normal` }}>
Static
</em>
{` `}
Progressive Web Apps
</CardHeadline>
<FuturaParagraph>
Gatsby.js is a static PWA (Progressive Web App) generator.
You get code and data splitting out-of-the-box. Gatsby
loads only the critical HTML, CSS, data, and JavaScript so
your site loads as fast as possible. Once loaded, Gatsby
prefetches resources for other pages so clicking around
the site feels incredibly fast.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Speed past the competition</CardHeadline>
<FuturaParagraph>
Gatsby.js builds the fastest possible website. Instead of
waiting to generate pages when requested, pre-build pages
and lift them into a global cloud of servers — ready to be
delivered instantly to your users wherever they are.
</FuturaParagraph>
</Card>
<Diagram />
<div css={{ flex: `1 1 100%` }}>
<Container hasSideBar={false}>
<div
css={{
textAlign: `center`,
padding: `${rhythm(1)} 0 ${rhythm(2)}`,
}}
>
<h1 css={{ marginTop: 0 }}>Curious yet?</h1>
<FuturaParagraph>
It only takes a few minutes to get up and running!
</FuturaParagraph>
<Button
secondary
to="/docs/"
overrideCSS={{ marginTop: `1rem` }}
>
Get Started
</Button>
</div>
</Container>
</div>
<div
css={{
borderTop: `1px solid ${colors.ui.light}`,
flex: `1 1 100%`,
[presets.Tablet]: {
paddingTop: rhythm(1),
},
}}
>
<Container
hasSideBar={false}
overrideCSS={{
maxWidth: rhythm(30),
paddingBottom: `0 !important`,
}}
>
<EmailCaptureForm
signupMessage="Want to keep up to date with the latest posts on our blog? Subscribe to our newsletter!"
overrideCSS={{
marginTop: 0,
marginBottom: rhythm(2),
border: `none`,
}}
/>
<h2
css={{
textAlign: `left`,
marginTop: 0,
color: colors.gatsby,
[presets.Tablet]: {
paddingBottom: rhythm(1),
},
}}
>
Latest from the Gatsby blog
</h2>
{blogPosts.edges.map(({ node }) => (
<BlogPostPreviewItem
post={node}
key={node.fields.slug}
css={{ marginBottom: rhythm(2) }}
/>
))}
<Button
secondary
to="/blog/"
overrideCSS={{
marginBottom: rhythm(options.blockMarginBottom * 2),
}}
>
Read More
</Button>
</Container>
</div>
</Cards>
</main>
</div>
</div>
</div>
</Layout>
)
}
}
export default IndexRoute
export const pageQuery = graphql`
query {
file(relativePath: { eq: "gatsby-explanation.png" }) {
childImageSharp {
fluid(maxWidth: 870) {
src
srcSet
sizes
}
}
}
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
limit: 3
filter: {
frontmatter: { draft: { ne: true } }
fileAbsolutePath: { regex: "/docs.blog/" }
}
) {
edges {
node {
...BlogPostPreview_item
}
}
}
}
`
|
module.exports = {
theme: {
},
variants: {},
plugins: []
}
|
(function() {
'use strict';
angular
.module('jhbookz')
.config(compileServiceConfig);
compileServiceConfig.$inject = ['$compileProvider','DEBUG_INFO_ENABLED'];
function compileServiceConfig($compileProvider,DEBUG_INFO_ENABLED) {
// disable debug data on prod profile to improve performance
$compileProvider.debugInfoEnabled(DEBUG_INFO_ENABLED);
/*
If you wish to debug an application with this information
then you should open up a debug console in the browser
then call this method directly in this console:
angular.reloadWithDebugInfo();
*/
}
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:e33f1e0b0b9b38b5649aa36f088b24b87dce7496e7f39d32c4422c81b29f1864
size 1614475
|
var CILJS = require("../CilJs.Runtime/Runtime");
var asm1 = {};
var asm = asm1;
var asm0 = CILJS.findAssembly("mscorlib");
asm.FullName = "IsInstDelegate.cs.ciljs, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";/* TResult FuncX`2.Invoke(T)*/
asm.x6000002 = CILJS.delegateInvoke;;/* System.IAsyncResult FuncX`2.BeginInvoke(T,AsyncCallback,Object)*/
asm.x6000003 = CILJS.delegateBeginInvoke;;/* TResult FuncX`2.EndInvoke(IAsyncResult)*/
asm.x6000004 = CILJS.delegateEndInvoke;;/* FuncX`2..ctor(Object,IntPtr)*/
asm.x6000001 = CILJS.delegateCtor;;/* T FuncX`1.Invoke()*/
asm.x6000006 = CILJS.delegateInvoke;;/* System.IAsyncResult FuncX`1.BeginInvoke(AsyncCallback,Object)*/
asm.x6000007 = CILJS.delegateBeginInvoke;;/* T FuncX`1.EndInvoke(IAsyncResult)*/
asm.x6000008 = CILJS.delegateEndInvoke;;/* FuncX`1..ctor(Object,IntPtr)*/
asm.x6000005 = CILJS.delegateCtor;;/* static System.Void Program.Main()*/
asm.x6000009_init = function ()
{
(asm1["Program+<>c"]().init)();
(asm1["FuncX`2"](asm0["System.Object"](),asm0["System.Object"]()).init)();
(asm1["FuncX`2"](asm0["System.Int32"](),asm0["System.Object"]()).init)();
(asm1["FuncX`2"](asm0["System.String"](),asm0["System.Object"]()).init)();
asm.x6000009 = asm.x6000009_;
};;
asm.x6000009 = function ()
{
asm.x6000009_init();
return asm.x6000009_();
};;
asm.x6000009_ = function Main()
{
var t0;
var t1;
var t2;
var t3;
var t4;
var t5;
var t6;
var st_00;
var st_01;
var st_02;
var st_03;
var st_04;
var st_05;
var st_06;
var st_07;
var in_block_0;
var __pos__;
var loc0;
CILJS.initBaseTypes();
t0 = asm1["Program+<>c"]();
t1 = asm0["System.Object"]();
t2 = asm1["FuncX`2"](t1,t1);
t3 = asm0["System.Int32"]();
t4 = asm1["FuncX`2"](t3,t1);
t5 = asm0["System.String"]();
t6 = asm1["FuncX`2"](t5,t1);
in_block_0 = true;
__pos__ = 0x0;
while (in_block_0){
switch (__pos__){
case 0x0:
/* IL_00: nop */
asm1.x600000e();
/* IL_01: ldsfld FuncX`2 <>9__0_0 */
st_00 = t0["<>9__0_0"];
/* IL_06: dup */
st_07 = st_02 = st_01 = st_00;
/* IL_07: brtrue.s IL_20 */
if (st_01){
__pos__ = 0x20;
continue;
}
/* IL_09: pop */
asm1.x600000e();
/* IL_0A: ldsfld <>c <>9 */
st_03 = t0["<>9"];
/* IL_10: ldftn Object <Main>b__0_0(System.Object) */
st_04 = asm1.x6000010;
/* IL_15: newobj Void .ctor(System.Object, System.IntPtr) */
st_05 = CILJS.newobj(t2,asm1.x6000001,[null, st_03, st_04]);
/* IL_1A: dup */
st_07 = st_06 = st_05;
asm1.x600000e();
/* IL_1B: stsfld FuncX`2 <>9__0_0 */
t0["<>9__0_0"] = st_06;
case 0x20:
/* IL_20: stloc.0 */
loc0 = st_07;
/* IL_21: ldstr Lambda: */
/* IL_26: ldc.i4.0 */
/* IL_27: newarr System.Object */
/* IL_2C: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("Lambda:"),CILJS.newArray(t1,0));
/* IL_31: nop */
/* IL_32: ldloc.0 */
/* IL_33: call Void WriteType(System.Delegate) */
asm1.x600000d(loc0);
/* IL_38: nop */
/* IL_39: ldstr Method (object): */
/* IL_3E: ldc.i4.0 */
/* IL_3F: newarr System.Object */
/* IL_44: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("Method (object):"),CILJS.newArray(t1,0));
/* IL_49: nop */
/* IL_4A: ldnull */
/* IL_4C: ldftn Object MethodObj(System.Object) */
/* IL_51: newobj Void .ctor(System.Object, System.IntPtr) */
/* IL_56: call Void WriteType(System.Delegate) */
asm1.x600000d(CILJS.newobj(t2,asm1.x6000001,[null, null, asm1.x600000a]));
/* IL_5B: nop */
/* IL_5C: ldstr Method (object): */
/* IL_61: ldc.i4.0 */
/* IL_62: newarr System.Object */
/* IL_67: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("Method (object):"),CILJS.newArray(t1,0));
/* IL_6C: nop */
/* IL_6D: ldnull */
/* IL_6F: ldftn Object MethodInt(System.Int32) */
/* IL_74: newobj Void .ctor(System.Object, System.IntPtr) */
/* IL_79: call Void WriteType(System.Delegate) */
asm1.x600000d(CILJS.newobj(t4,asm1.x6000001,[null, null, asm1.x600000b]));
/* IL_7E: nop */
/* IL_7F: ldstr Method (object): */
/* IL_84: ldc.i4.0 */
/* IL_85: newarr System.Object */
/* IL_8A: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("Method (object):"),CILJS.newArray(t1,0));
/* IL_8F: nop */
/* IL_90: ldnull */
/* IL_92: ldftn Object MethodString(System.String) */
/* IL_97: newobj Void .ctor(System.Object, System.IntPtr) */
/* IL_9C: call Void WriteType(System.Delegate) */
asm1.x600000d(CILJS.newobj(t6,asm1.x6000001,[null, null, asm1.x600000c]));
/* IL_A1: nop */
/* IL_A2: ret */
return ;
}
}
};/* static System.Object Program.MethodObj(Object)*/
asm.x600000a = function MethodObj(arg0)
{
var loc0;
/* IL_00: nop */
/* IL_01: ldnull */
/* IL_02: stloc.0 */
loc0 = null;
/* IL_05: ldloc.0 */
/* IL_06: ret */
return loc0;
};;/* static System.Object Program.MethodInt(Int32)*/
asm.x600000b = function MethodInt(arg0)
{
var loc0;
/* IL_00: nop */
/* IL_01: ldnull */
/* IL_02: stloc.0 */
loc0 = null;
/* IL_05: ldloc.0 */
/* IL_06: ret */
return loc0;
};;/* static System.Object Program.MethodString(String)*/
asm.x600000c = function MethodString(arg0)
{
var loc0;
/* IL_00: nop */
/* IL_01: ldnull */
/* IL_02: stloc.0 */
loc0 = null;
/* IL_05: ldloc.0 */
/* IL_06: ret */
return loc0;
};;/* static System.Void Program.WriteType(Delegate)*/
asm.x600000d_init = function (arg0)
{
(asm1["FuncX`1"](asm0["System.Object"]()).init)();
(asm1["FuncX`2"](asm0["System.Object"](),asm0["System.Object"]()).init)();
(asm1["FuncX`2"](asm0["System.String"](),asm0["System.Object"]()).init)();
(asm1["FuncX`2"](asm0["System.Int32"](),asm0["System.Object"]()).init)();
asm.x600000d = asm.x600000d_;
};;
asm.x600000d = function (arg0)
{
asm.x600000d_init(arg0);
return asm.x600000d_(arg0);
};;
asm.x600000d_ = function WriteType(arg0)
{
var t0;
var t1;
var t2;
var t3;
var t4;
var t5;
var t6;
var in_block_0;
var __pos__;
var loc0;
var loc1;
var loc2;
var loc3;
t0 = asm0["System.Object"]();
t1 = asm1["FuncX`1"](t0);
t2 = asm1["FuncX`2"](t0,t0);
t3 = asm0["System.String"]();
t4 = asm1["FuncX`2"](t3,t0);
t5 = asm0["System.Int32"]();
t6 = asm1["FuncX`2"](t5,t0);
in_block_0 = true;
__pos__ = 0x0;
while (in_block_0){
switch (__pos__){
case 0x0:
/* IL_00: nop */
/* IL_01: ldarg.0 */
/* IL_02: isinst FuncX`1[System.Object] */
/* IL_07: ldnull */
/* IL_09: cgt.un */
/* IL_0A: stloc.0 */
loc0 = ((t1.IsInst(arg0) !== null) ? 1 : 0);
/* IL_0B: ldloc.0 */
/* IL_0C: brfalse.s IL_21 */
if ((!(loc0))){
__pos__ = 0x21;
continue;
}
/* IL_0E: nop */
/* IL_0F: ldstr FuncX<object> */
/* IL_14: ldc.i4.0 */
/* IL_15: newarr System.Object */
/* IL_1A: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("FuncX<object>"),CILJS.newArray(t0,0));
/* IL_1F: nop */
/* IL_20: nop */
case 0x21:
/* IL_21: ldarg.0 */
/* IL_22: isinst FuncX`2[System.Object,System.Object] */
/* IL_27: ldnull */
/* IL_29: cgt.un */
/* IL_2A: stloc.1 */
loc1 = ((t2.IsInst(arg0) !== null) ? 1 : 0);
/* IL_2B: ldloc.1 */
/* IL_2C: brfalse.s IL_41 */
if ((!(loc1))){
__pos__ = 0x41;
continue;
}
/* IL_2E: nop */
/* IL_2F: ldstr FuncX<object, object> */
/* IL_34: ldc.i4.0 */
/* IL_35: newarr System.Object */
/* IL_3A: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("FuncX<object, object>"),CILJS.newArray(t0,0));
/* IL_3F: nop */
/* IL_40: nop */
case 0x41:
/* IL_41: ldarg.0 */
/* IL_42: isinst FuncX`2[System.String,System.Object] */
/* IL_47: ldnull */
/* IL_49: cgt.un */
/* IL_4A: stloc.2 */
loc2 = ((t4.IsInst(arg0) !== null) ? 1 : 0);
/* IL_4B: ldloc.2 */
/* IL_4C: brfalse.s IL_61 */
if ((!(loc2))){
__pos__ = 0x61;
continue;
}
/* IL_4E: nop */
/* IL_4F: ldstr FuncX<string, object> */
/* IL_54: ldc.i4.0 */
/* IL_55: newarr System.Object */
/* IL_5A: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("FuncX<string, object>"),CILJS.newArray(t0,0));
/* IL_5F: nop */
/* IL_60: nop */
case 0x61:
/* IL_61: ldarg.0 */
/* IL_62: isinst FuncX`2[System.Int32,System.Object] */
/* IL_67: ldnull */
/* IL_69: cgt.un */
/* IL_6A: stloc.3 */
loc3 = ((t6.IsInst(arg0) !== null) ? 1 : 0);
/* IL_6B: ldloc.3 */
/* IL_6C: brfalse.s IL_81 */
if ((!(loc3))){
__pos__ = 0x81;
continue;
}
/* IL_6E: nop */
/* IL_6F: ldstr FuncX<int, object> */
/* IL_74: ldc.i4.0 */
/* IL_75: newarr System.Object */
/* IL_7A: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(CILJS.newString("FuncX<int, object>"),CILJS.newArray(t0,0));
/* IL_7F: nop */
/* IL_80: nop */
case 0x81:
/* IL_81: ret */
return ;
}
}
};/* System.Object <>c.<Main>b__0_0(Object)*/
asm.x6000010 = function _Main_b__0_0(arg0, arg1)
{
/* IL_00: ldnull */
/* IL_01: ret */
return null;
};;/* static <>c..cctor()*/
asm.x600000e_init = function ()
{
(asm1["Program+<>c"]().init)();
asm.x600000e = asm.x600000e_;
};;
asm.x600000e = function ()
{
asm.x600000e_init();
return asm.x600000e_();
};;
asm.x600000e_ = function _cctor()
{
var t0;
if (asm1["Program+<>c"]().FieldsInitialized){
return;
}
asm1["Program+<>c"]().FieldsInitialized = true;
t0 = asm1["Program+<>c"]();
asm1.x600000e();
/* IL_00: newobj Void .ctor() */
/* IL_05: stsfld <>c <>9 */
t0["<>9"] = CILJS.newobj(t0,asm1.x600000f,[null]);
/* IL_0A: ret */
return ;
};/* <>c..ctor()*/
asm.x600000f = function _ctor(arg0)
{
/* IL_00: ldarg.0 */
/* IL_01: call Void .ctor() */
/* IL_06: nop */
/* IL_07: ret */
return ;
};;
asm["FuncX`2"] = CILJS.declareType(
["T", "TResult"],
function (T, TResult)
{
return {};
},
function (type, T, TResult)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"FuncX`2",false,false,false,true,false,[],[
[asm1, "x6000002", "Invoke"],
[asm1, "x6000003", "BeginInvoke"],
[asm1, "x6000004", "EndInvoke"]
],asm0["System.MulticastDelegate"](),CILJS.isInstDefault(type),Array,"asm1.t2000002",null);
(type.GenericArguments)["asm1.t2000002"] = [T, TResult];
type.TypeMetadataName = ("asm1.t2000002<" + ((T.TypeMetadataName + TResult.TypeMetadataName) + ">"));
CILJS.declareVirtual(type,"asm1.x6000002",asm1,"x6000002");
CILJS.declareVirtual(type,"asm1.x6000003",asm1,"x6000003");
CILJS.declareVirtual(type,"asm1.x6000004",asm1,"x6000004");
CILJS.declareVirtual(type,"asm0.x600003c",asm0,"x60000b1");
CILJS.declareVirtual(type,"asm0.x600003b",asm0,"x60000b2");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600003d");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x6000040");
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
},
function (T, TResult)
{
return function FuncX_2()
{
FuncX_2.init();
this._invocationList = null;
this._methodPtr = null;
this._target = null;
};
});
asm["FuncX`1"] = CILJS.declareType(
["T"],
function (T)
{
return {};
},
function (type, T)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"FuncX`1",false,false,false,true,false,[],[
[asm1, "x6000006", "Invoke"],
[asm1, "x6000007", "BeginInvoke"],
[asm1, "x6000008", "EndInvoke"]
],asm0["System.MulticastDelegate"](),CILJS.isInstDefault(type),Array,"asm1.t2000003",null);
(type.GenericArguments)["asm1.t2000003"] = [T];
type.TypeMetadataName = ("asm1.t2000003<" + (T.TypeMetadataName + ">"));
CILJS.declareVirtual(type,"asm1.x6000006",asm1,"x6000006");
CILJS.declareVirtual(type,"asm1.x6000007",asm1,"x6000007");
CILJS.declareVirtual(type,"asm1.x6000008",asm1,"x6000008");
CILJS.declareVirtual(type,"asm0.x600003c",asm0,"x60000b1");
CILJS.declareVirtual(type,"asm0.x600003b",asm0,"x60000b2");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600003d");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x6000040");
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
},
function (T)
{
return function FuncX_1()
{
FuncX_1.init();
this._invocationList = null;
this._methodPtr = null;
this._target = null;
};
});
asm.Program = CILJS.declareType(
[],
function ()
{
return asm0["System.Object"]();
},
function (type)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"Program",false,false,false,false,false,[],[],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000004",null);
type.TypeMetadataName = "asm1.t2000004";
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f");
},
function ()
{
return function Program()
{
Program.init();
};
});
asm["Program+<>c"] = CILJS.declareType(
[],
function ()
{
return asm0["System.Object"]();
},
function (type)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"Program+<>c",false,false,false,false,false,[],[],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000005",null);
type["<>9"] = null;
type["<>9__0_0"] = null;
type.TypeMetadataName = "asm1.t2000005";
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f");
},
function ()
{
return function __c()
{
__c.init();
};
});
asm.entryPoint = asm.x6000009;
CILJS.declareAssembly("IsInstDelegate.cs.ciljs",asm);
if (typeof module != "undefined"){
module.exports = asm1;
}
//# sourceMappingURL=IsInstDelegate.cs.ciljs.exe.js.map
|
export default {
Currency: '货币',
Amount: '金额',
Balance: '余额',
Deposit: '储值卡',
Type: '类型',
Default: '默认',
'Income Record': '收支记录',
Credit: '积分',
Withdraw: '提现',
Note: '备注',
Actions: '操作',
Reject: '拒绝',
Accept: '接受',
'Accept Withdraw': '接受提现',
'Reject Withdraw': '拒绝提现',
'Reject Reason': '拒绝原因',
'Missing reject reason': '请输入拒绝原因',
Accepted: '已接受',
Rejected: '已拒绝',
'Withdraw Rejected': '提现拒绝',
'Insufficient balance': '余额不足',
state: '状态',
Target: '目标'
};
|
'use strict';
module.exports = function (value) {
return `${value}%`;
};
|
'use strict';
module.exports = {
db: 'mongodb://localhost/gadgetboy-dev',
app: {
title: 'gadgetboy - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || '750701491722559',
clientSecret: process.env.FACEBOOK_SECRET || '0678f654f3f4e001fea07e3af7e53d44',
callbackURL: '/api/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'Gadgetboy',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'Gmail',
auth: {
user: process.env.MAILER_EMAIL_ID || 'gadgetboy.shop@gmail.com',
pass: process.env.MAILER_PASSWORD || 'gadmusiclift3089'
}
}
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:0218be47602a2c4a7b193148b0b2dea5e1bc13e3b135056a383953b48bbb39c6
size 4306
|
const _ = require('lodash');
const {
User,
Student,
Ticket,
Team,
NotificationSubscription,
} = require('../models');
const constant = require('../constants');
const populateAdmin = async () => [constant.adminScope];
const populateStudent = async (decoded) => {
const { userId } = decoded;
const student = await Student.findById(userId, {
include: [
{ model: Ticket, as: 'tickets' },
{ model: Team, as: 'teams', required: false },
{ model: NotificationSubscription, as: 'notificationSubscriptions', required: false },
]
});
if (!student) return false;
let scope = [constant.userScope, constant.studentScope, `${constant.userScope}-${student.id}`];
scope = _.concat(scope, student.tickets.map(ticket => `${constant.ticketScope}-${ticket.id}`));
scope = _.concat(scope, student.tickets.map(ticket => `${constant.eventScope}-${ticket.eventId}`));
scope = _.concat(scope, student.teams.map(team => `${constant.teamScope}-${team.id}`));
scope = _.concat(scope, student.notificationSubscriptions.map(sub => `${constant.subscriptionScope}-${sub.id}`));
return scope;
};
const populateUser = async (decoded) => {
const { userId } = decoded;
const user = await User.findById(userId);
if (!user) return false;
return [constant.userScope, `${constant.userScope}-${user.id}`];
};
module.exports = async (decoded) => {
const { type } = decoded;
const populateType = {
[constant.adminType]: populateAdmin,
[constant.userType]: populateUser,
[constant.studentType]: populateStudent,
};
if (!populateType[type]) return { isValid: false };
const scope = await populateType[type](decoded);
if (!scope) return { isValid: false };
const id = decoded.userId || '';
return {
isValid: true,
credentials: {
id,
type,
scope
}
};
};
|
//Copied from test.js in node-hpka
var http = require('http');
var hpka = require('hpka');
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
//In-memory list of registered users and sessions
var userList = {};
var sessions = {};
var httpPort = 2500;
var maxSessionsLife = 7 * 24 * 3600;
var yell = false;
var server;
var hpkaMiddleware;
var applicationToUse;
function log(m){
if (yell) console.log(m);
}
function writeRes(res, body, headers, statusCode){
headers = headers || {};
var bodyLength;
if (typeof body == 'object' && !Buffer.isBuffer(body)){
body = JSON.stringify(body);
headers['Content-Type'] = 'application/json';
}
if (Buffer.isBuffer(body)){
bodyLength = Buffer.byteLength(body);
} else { //Assuming string
bodyLength = body.length;
}
headers['Content-Length'] = bodyLength;
res.writeHead(statusCode || 200, headers);
res.write(body);
res.end();
}
function writeHpkaErr(res, message, errorCode){
writeRes(res, message, {'HPKA-Error': errorCode}, 445);
}
var getHandler = function(req, res){
var headers = {'Content-Type': 'text/plain'};
var body;
if (req.username){
//console.log(req.method + ' ' + req.url + ' authenticated request by ' + req.username);
body = 'Authenticated as : ' + req.username;
//Manual signature verification
var hpkaReq = req.headers['hpka-req'];
var hpkaSig = req.headers['hpka-signature'];
var method = req.method;
var reqUrl = 'http://' + (req.headers.hostname || req.headers.host) + req.url
//console.log('HpkaReq: ' + hpkaReq + '; HpkaSig: ' + hpkaSig + '; ' + method + '; reqUrl: ' + reqUrl);
if (hpkaReq && hpkaSig){
hpka.verifySignature(hpkaReq, hpkaSig, reqUrl, method, function(err, isValid, username, hpkaReq){
if (err) console.error('Error in hpkaReq: ' + err);
if (!isValid) console.log('External validation failed');
//else console.log('External validation success: ' + username + ': ' + JSON.stringify(hpkaReq));
});
}
} else {
//console.log(req.method + ' ' + req.url + ' anonymous request');
body = 'Anonymous user';
}
writeRes(res, body, headers, 200);
};
var postHandler = function(req, res){
if (req.body && Object.keys(req.body).length > 0){
//console.log('Testing req values');
assert.equal(req.body['field-one'], 'test', 'Unexpected form content');
assert.equal(req.body['field-two'], 'test 2', 'Unexpected form content');
assert.equal(req.headers.test, '1', 'Unexpected value the "test" header');
}
//console.log('Received form data: ' + JSON.stringify(req.body));
//console.log('"test" header value: ' + req.headers.test);
if (req.username){
res.send(200, 'OK');
} else {
res.send(401, 'Not authenticated');
}
};
var loginCheck = function(HPKAReq, req, res, callback){
if (userList[HPKAReq.username] && typeof userList[HPKAReq.username] == 'object' && HPKAReq.checkPublicKeyEqualityWith(userList[HPKAReq.username])){
callback(true);
//console.log('Authenticated request');
} else callback(false);
};
var registration = function(HPKAReq, req, res){
var username = HPKAReq.username;
var keyInfo = HPKAReq.getPublicKey();
userList[username] = keyInfo;
//console.log('User registration');
var body = 'Welcome ' + username + ' !';
res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': body.length});
res.write(body);
res.end();
};
var deletion = function(HPKAReq, req, res){
if (typeof userList[HPKAReq.username] != 'object') return;
if (!HPKAReq.checkPublicKeyEqualityWith(userList[HPKAReq.username])){
writeHpkaErr(res, 'Invalid user key', 3);
return;
}
userList[HPKAReq.username] = undefined;
var headers = {'Content-Type': 'text/plain'};
var body = HPKAReq.username + ' has been deleted!';
//console.log('User deletion');
headers['Content-Length'] = body.length;
res.writeHead(200, headers);
res.write(body);
res.end();
};
var keyRotation = function(HPKAReq, newKeyReq, req, res){
var headers = {'Content-Type': 'text/plain'};
var body;
var errorCode;
//Check that the username exists
if (typeof userList[HPKAReq.username] != 'object'){
body = 'Unregistered user';
errorCode = 445;
headers['HPKA-Error'] = 4;
} else {
//Check that the actual key is correct
if (HPKAReq.checkPublicKeyEqualityWith(userList[HPKAReq.username])){
//Replace the actual ke by the new key
userList[HPKAReq.username] = newKeyReq.getPublicKey();
body = 'Keys have been rotated!';
} else {
body = 'Invalid public key'
errorCode = 445;
headers['HPKA-Error'] = 3;
}
}
headers['Content-Length'] = body.length;
res.writeHead(errorCode || 200, headers);
res.write(body);
res.end();
};
var sessionCheck = function(SessionReq, req, res, callback){
var username = SessionReq.username;
var sessionId = SessionReq.sessionIdBuffer.toString('hex');
if (!sessions[username]){
callback(false);
return;
}
var validId = false;
for (var i = 0; i < sessions[username].length; i++){
if (sessions[username][i] == sessionId){
validId = true;
break;
}
}
callback(validId);
};
var sessionAgreement = function(HPKAReq, req, callback){
var username = HPKAReq.username;
var sessionId = HPKAReq.sessionIdBuffer.toString('hex');
//Expiration date agreement
var finalSessionExpiration;
var n = Math.floor(Date.now() / 1000);
var currentMaxExpiration = maxSessionsLife + n;
//User-provided expiration date for the sessionId
var userSetExpiration = HPKAReq.sessionExpiration || 0;
if (maxSessionsLife == 0){ //If the server doesn't impose a TTL, take the user-provided value as TTL
finalSessionExpiration = userSetExpiration;
} else if (userSetExpiration == 0 || userSetExpiration > currentMaxExpiration){ //Server-set TTL. Enforce lifespan
finalSessionExpiration = currentMaxExpiration;
} else {
finalSessionExpiration = userSetExpiration;
}
//Check keys
if (HPKAReq.checkPublicKeyEqualityWith(userList[username])){
//Accept a sessionId
if (sessions[username]){
//Save the sessionId in the existing array
//But before that, check that it's not already in the array
var alreadyAgreed = false;
for (var i = 0; i < sessions[username].length; i++) if (sessions[username][i] == sessionId){
alreadyAgreed = true;
break;
}
if (!alreadyAgreed) sessions[username].push(sessionId);
} else {
sessions[username] = [sessionId];
}
callback(true, finalSessionExpiration);
} else callback(false);
};
var sessionRevocation = function(HPKAReq, req, callback){
var username = HPKAReq.username;
var sessionId = HPKAReq.sessionIdBuffer.toString('hex');
//Check keys
if (HPKAReq.checkPublicKeyEqualityWith(userList[username])){
//Revoke sessionId
var currentSessionList = sessions[username];
if (currentSessionList){
if (currentSessionList.length == 0) sessions[username] = null;
else {
//Check that the sessionId is in the array and remove it
for (var i = 0; i < currentSessionList.length; i++){
if (currentSessionList[i] == sessionId){
currentSessionList.splice(i, 1);
break;
}
}
}
}
callback(true);
} else callback(false);
};
exports.setup = function(strictMode, disallowSessions){
if (disallowSessions){
hpkaMiddleware = hpka.expressMiddleware(loginCheck, registration, deletion, keyRotation, strictMode);
} else {
hpkaMiddleware = hpka.expressMiddleware(loginCheck, registration, deletion, keyRotation, strictMode, sessionCheck, sessionAgreement, sessionRevocation);
}
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/', express.static(__dirname));
app.use(hpkaMiddleware);
app.get('/', getHandler);
app.post('/', postHandler);
applicationToUse = app;
};
exports.clear = function(){
userList = {};
sessions = {};
};
exports.start = function(cb){
if (cb && typeof cb != 'function') throw new TypeError('when defined, cb must be a function');
if (!hpkaMiddleware) throw new TypeError('server not yet set up');
server = http.createServer(applicationToUse);
server.listen(httpPort, function(){
if (cb) cb();
});
};
exports.stop = function(cb){
if (cb && typeof cb != 'function') throw new TypeError('when defined, cb must be a function');
if (!server){
if (cb) cb();
return;
}
server.close();
server = undefined;
if (cb) cb();
};
exports.getServerPort = function(){
return httpPort;
};
exports.setServerPort = function(p){
if (!(typeof p == 'number' && p > 0 && p < 65536 && p == Math.floor(p))) throw new TypeError('p must be an integer number, in the [1-65535] range');
httpPort = p;
};
exports.getMaxSessionLife = function(){
return maxSessionsLife;
};
exports.setMaxSessionLife = function(ttl){
if (!(typeof ttl == 'number' && ttl >= 0 && ttl == Math.floor(ttl))) throw new TypeError('n must be a positive integer number');
maxSessionsLife = ttl;
};
exports.setYell = function(_y){
yell = _y;
};
/*
console.log('Starting the server');
var server = http.createServer(hpka.httpMiddleware(requestHandler, loginCheck, registration, deletion, keyRotation, true));
server.listen(httpPort, function(){
console.log('Server started on port ' + httpPort);
});
*/
if (!module.parent){
//Stand-alone execution
exports.setup();
exports.start(function(){
console.log('Server started on port ' + httpPort);
});
}
|
import feathers from 'feathers/client';
import socketio from 'feathers-socketio/client';
import hooks from 'feathers-hooks';
import io from 'socket.io-client';
import auth from 'feathers-authentication/client';
import decode from 'jwt-decode';
import rxjs from 'rxjs';
import rx from 'feathers-reactive';
const host = '';
const socket = io(host, {
transports: ['websocket'],
forceReconnect: true
});
const app = feathers()
.configure(rx(rxjs))
.configure(hooks())
.configure(socketio(socket))
.configure(auth({
storage: window.localStorage
}));
app.getSession = function(){
let token = app.get('token'),
session;
if (token) {
session = decode(token);
}
return session;
};
export default app;
|
define([
'../util/Class',
'./BaseView',
'../util/Helper',
'../util/DomEvent'
], function (Class, BaseView, helper, DomEvent) {
"use strict";
var protectedAttrs = ['addChild', 'set', 'get', 'attachTo', 'detach', '_addProtectedAttribute',
'style', 'resize', 'on', 'off', 'once', 'focus', 'blur'];
/**
* @class com.sesamtv.core.ui.BaseComponent
* @extends com.sesamtv.core.BaseView
* @requires com.sesamtv.core.util.Helper
* @requires com.sesamtv.core.util.DomEvent
* @cfg {Object} args
* @cfg {Object} args.parent
* @cfg {String} args.type
* @cfg {String} args.baseClass
* @cfg {Boolean} args.autoImport if import items automatically
* @cfg {Object} args.importCmp Component while instantiate the child items
* @cfg {Object} args.importArgs arguments to be passed to the child items
* @cfg {String} args.itemSelector
* @cfg {HTMLElement} [node]
*/
var BaseComponent = Class({
extend: BaseView,
constructor: function (args, node) {
this.config = Class.mixin({
type:'component',
baseClass:'component'
},this.config || {});
BaseView.call(this, args,node);
},
animate: function (animation, callbackMehod, beforeTraitement) {
beforeTraitement && beforeTraitement();
callbackMehod && DomEvent.once(this.node, 'webkitAnimationEnd', callbackMehod, false);
//this[animation]();
this.set('animation', animation);
return this;
}
});
return BaseComponent;
})
; |
exports.randeats = function(req, res){
var key = req.query.key;
var location = encodeURIComponent(req.query.location);
var radius = 16000;
var sensor = false;
var types = "restaurant";
var keyword = "fast";
var https = require('https');
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + "key=" + key + "&location=" + location + "&radius=" + radius + "&sensor=" + sensor + "&types=" + types + "&keyword=" + keyword;
console.log(url);
https.get(url, function(response) {
var body ='';
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
var places = JSON.parse(body);
var locations = places.results;
var randLoc = locations[Math.floor(Math.random() * locations.length)];
res.json(randLoc);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
autoIncrement = require('mongoose-auto-increment');
autoIncrement.initialize(mongoose);
/**
* Parameters Schema
*/
var ParametersSchema = new Schema({
_id: {type: String},
name: { type: String, required: 'Nombre del parametro requerido', unique: true, trim: true},
parent: {type: String, default: '', ref: 'Parameters'},
description: {type: String, default: ''},
companyId: {type: String, ref: 'Partner'},
ancestors: [{type: String, ref: 'Parameters'}],
sucursalId: { type: String, ref: 'Sucursal', default: null},
isActive: {type: Boolean, default:true},
systemParam: {type: Boolean, default:false},
createdDate: { type: Date, default: Date.now},
craetedUser: { type: Schema.ObjectId, ref: 'User'},
updatedDate: {type: Date},
updatedUser: { type: Schema.ObjectId, ref: 'User'}
});
ParametersSchema.plugin(autoIncrement.plugin, {
model: 'Parameters',
field: 'parameterId',
startAt: 100,
incrementBy: 1
}
);
mongoose.model('Parameters', ParametersSchema); |
module.exports = function (kingo, student) {
it('.getRegistrations', function (done) {
kingo.getRegistrations(function (error, registrations) {
var registration = registrations.pop();
registration.should.have.property('行政班级', student.className);
registration.should.have.property('院(系)/部', student.college);
done();
});
});
};
|
const initialState = {
login: false,
authorization: false
};
const OPEN_POPUP_AUTHORIZATION = 'OPEN_POPUP_AUTHORIZATION';
const OPEN_POPUP_LOGIN = 'OPEN_POPUP_LOGIN';
const CLOSE_POPUP = 'CLOSE_POPUP';
export function openLogin() {
return {
type: OPEN_POPUP_LOGIN
}
}
export function openAuthorization() {
return {
type: OPEN_POPUP_AUTHORIZATION
}
}
export function closePopup(popup) {
return {
type: CLOSE_POPUP,
popup
}
}
export default function userstate(state = initialState, action) {
switch (action.type) {
case OPEN_POPUP_AUTHORIZATION:
return { ...state, authorization: true }
case OPEN_POPUP_LOGIN:
return { ...state, login: true }
case CLOSE_POPUP:
return { ...state, [action.popup]: false }
default:
return state;
}
}
|
import Ember from 'ember';
import distance from 'npm:@turf/distance';
import helpers from 'npm:@turf/helpers';
import booleanContains from 'npm:@turf/boolean-contains';
import area from 'npm:@turf/area';
import intersect from 'npm:@turf/intersect';
import { getLeafletCrs } from '../utils/leaflet-crs';
import html2canvasClone from '../utils/html2canvas-clone';
import state from '../utils/state';
import SnapDraw from './snap-draw';
import ClipperLib from 'npm:clipper-lib';
import jsts from 'npm:jsts';
import { geometryToJsts } from '../utils/layer-to-jsts';
import { downloadFile, downloadBlob } from '../utils/download-file';
import { getCrsByName } from '../utils/get-crs-by-name';
export default Ember.Mixin.create(SnapDraw, {
/**
Service for managing map API.
@property mapApi
@type MapApiService
*/
mapApi: Ember.inject.service(),
/**
Shows layers specified by IDs.
@method showLayers.
@param {Array} layerIds Array of layer IDs.
@return {Promise}
*/
showLayers(layerIds) {
return this._setVisibility(layerIds, true);
},
/**
Hides layers specified by IDs.
@method hideLayers.
@param {Array} layerIds Array of layer IDs.
@return nothing
*/
hideLayers(layerIds) {
return this._setVisibility(layerIds, false);
},
/**
Shows objects for layer.
@method showLayerObjects
@param {string} layerId Layer id.
@param {string[]} objectIds Array of objects IDs.
@return nothing
*/
showLayerObjects(layerId, objectIds) {
return this._setVisibilityObjects(layerId, objectIds, true);
},
/**
Hides objects for layer.
@method hideLayerObjects
@param {string} layerId Layer id.
@param {Array} objectIds Array of objects IDs.
@return nothing
*/
hideLayerObjects(layerId, objectIds) {
return this._setVisibilityObjects(layerId, objectIds, false);
},
/**
Show all layer objects.
@method showAllLayerObjects
@param {string} layerId Layer id.
@return {Promise}
*/
showAllLayerObjects(layerId) {
return new Ember.RSVP.Promise((resolve, reject) => {
const layer = this.get('mapLayer').findBy('id', layerId);
if (Ember.isNone(layer)) {
reject(`Layer '${layerId}' not found.`);
}
const leafletObject = Ember.get(layer, '_leafletObject');
if (!Ember.isNone(leafletObject) && typeof leafletObject.showAllLayerObjects === 'function') {
leafletObject.showAllLayerObjects().then((result) => {
resolve(result);
});
} else {
resolve('Is not a vector layer');
}
});
},
/**
Hide all layer objects.
@method hideAllLayerObjects
@param {string} layerId Layer id.
@return nothing
*/
hideAllLayerObjects(layerId) {
const layer = this.get('mapLayer').findBy('id', layerId);
if (Ember.isNone(layer)) {
throw `Layer '${layerId}' not found.`;
}
const leafletObject = Ember.get(layer, '_leafletObject');
if (!Ember.isNone(leafletObject) && typeof leafletObject.hideAllLayerObjects === 'function') {
leafletObject.hideAllLayerObjects();
} else {
throw 'Is not a vector layer';
}
},
/**
Creates new layer with specified options.
@method createNewLayer.
@param {Object} options
@return Layer ID.
*/
createNewLayer(options) {
options = options || {};
const store = this.get('store');
let layer = store.createRecord('new-platform-flexberry-g-i-s-map-layer', options);
layer.set('map', this);
return layer.save().then(() => {
const layers = this.get('hierarchy');
layers.addObject(layer);
return layer.get('id');
});
},
/**
Remove object from layer.
@method deleteLayerObject.
@param {String} layerId Layer ID.
@param {String} featureId Object ID.
@return Promise.
*/
deleteLayerObject(layerId, featureId) {
this.deleteLayerObjects(layerId, [featureId]);
},
/**
Remove shapes from layer.
@method deleteLayerObjects.
@param {string} layerId Layer ID.
@param {Object[]} featureIds Array of objects IDs.
@return Promise.
*/
deleteLayerObjects(layerId, featureIds) {
return new Ember.RSVP.Promise((resolve, reject) => {
let ids = [];
this._getModelLayerFeature(layerId, featureIds, true).then(([layer, leafletObject]) => {
leafletObject.eachLayer(function (shape) {
const id = this._getLayerFeatureId(layer, shape);
if (!Ember.isNone(id) && featureIds.indexOf(id) !== -1) {
ids.push(id);
leafletObject.removeLayer(shape);
}
}.bind(this));
const deleteLayerFromAttrPanelFunc = this.get('mapApi').getFromApi('_deleteLayerFromAttrPanel');
ids.forEach((id) => {
if (typeof deleteLayerFromAttrPanelFunc === 'function') {
deleteLayerFromAttrPanelFunc(id, layer);
}
});
resolve();
}).catch((e) => {
reject(e);
});
});
},
/**
Gets intersected features.
@method getIntersectionObjects
@param {Object} feature GeoJson Feature.
@param {string} crsName Name of coordinate reference system, in which to give coordinates.
@param {Array} layerIds Array of layers IDs.
@return {Promise} Array of layers and objects which intersected selected object.
*/
getIntersectionObjects(feature, crsName, layerIds) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (!Ember.isNone(feature) && feature.hasOwnProperty('geometry')) {
const leafletMap = this.get('mapApi').getFromApi('leafletMap');
let layersIntersect = [];
layerIds.forEach(id => {
const layer = this.get('mapLayer').findBy('id', id);
if (!Ember.isNone(layer)) {
if (layer.get('settingsAsObject.identifySettings.canBeIdentified')) {
layersIntersect.push(layer);
}
}
});
let crs = crsName || 'EPSG:4326';
let featureCrs = crs === 'EPSG:4326' ? feature : this._convertObjectCoordinates(crs, feature);
let featureLayer = L.GeoJSON.geometryToLayer(featureCrs);
let latlng = featureLayer instanceof L.Marker || featureLayer instanceof L.CircleMarker ?
featureLayer.getLatLng() : featureLayer.getBounds().getCenter();
let e = {
latlng: latlng,
polygonLayer: featureLayer,
bufferedMainPolygonLayer: featureLayer,
excludedLayers: [],
layers: layersIntersect,
results: Ember.A()
};
if (e.layers.length > 0) {
leafletMap.fire('flexberry-map:identify', e);
}
e.results = Ember.isArray(e.results) ? e.results : Ember.A();
let promises = Ember.A();
// Handle each result.
// Detach promises from already received features.
e.results.forEach((result) => {
if (Ember.isNone(result)) {
return;
}
promises.pushObject(Ember.get(result, 'features'));
});
// Wait for all promises to be settled & call '_finishIdentification' hook.
Ember.RSVP.allSettled(promises).then(() => {
resolve(e.results);
});
}
});
},
/**
Get the nearest object
@method getNearObject
@param {string} layerId Layer ID of the selected object.
@param {string} layerObjectId Object ID of the selected object.
@param {Array} layerIds Array of layers IDs in which to search.
@return {Promise} Object constains distance, layer and layer object.
*/
getNearObject(layerId, layerObjectId, layerIds) {
return new Ember.RSVP.Promise((resolve, reject) => {
this._getModelLayerFeature(layerId, [layerObjectId]).then(([, leafletObject, layerObject]) => {
const leafletMap = this.get('mapApi').getFromApi('leafletMap');
let layersGetNeatObject = [];
layerIds.forEach(id => {
const layer = this.get('mapLayer').findBy('id', id);
layersGetNeatObject.push(layer);
});
let e = {
featureLayer: layerObject[0],
featureId: layerObjectId,
layerObjectId: layerId,
layers: layersGetNeatObject,
results: Ember.A()
};
if (e.layers.length > 0) {
leafletMap.fire('flexberry-map:getNearObject', e);
}
e.results = Ember.isArray(e.results) ? e.results : Ember.A();
let promises = Ember.A();
// Handle each result.
// Detach promises from already received features.
e.results.forEach((result) => {
if (Ember.isNone(result)) {
return;
}
promises.pushObject(Ember.get(result, 'features'));
});
Ember.RSVP.allSettled(promises).then((results) => {
const rejected = results.filter((item) => { return item.state === 'rejected'; }).length > 0;
if (rejected) {
return reject('Failed to get nearest object');
}
let res = null;
results.forEach((item) => {
if (Ember.isNone(res) || item.value.distance < res.distance) {
res = item.value;
}
});
resolve(res);
});
});
});
},
getObjectCenter(object) {
const type = Ember.get(object, 'feature.geometry.type');
if (type === 'Point') {
return object._latlng;
} else {
return object.getBounds().getCenter();
}
},
/**
Get distance between objects
@method _getDistanceBetweenObjects
@param {Object} firstLayerObject First layer object.
@param {Object} secondLayerObject Second layer object.
@return {number} Distance between objects in meters.
*/
_getDistanceBetweenObjects(firstLayerObject, secondLayerObject) {
const firstPoint = this.getObjectCenter(firstLayerObject);
const firstObject = helpers.point([firstPoint.lat, firstPoint.lng]);
const secondPoint = this.getObjectCenter(secondLayerObject);
const secondObject = helpers.point([secondPoint.lat, secondPoint.lng]);
// Get distance in meters.
return distance.default(firstObject, secondObject, { units: 'kilometers' }) * 1000;
},
/**
Get distance between objects
@method getDistanceBetweenObjects
@param {string} firstLayerId First layer id.
@param {string} firstLayerObjectId First layer object id.
@param {string} secondLayerId Second layer id.
@param {string} secondLayerObjectId Second layer object id.
@return {Promise} Distance between objects in meters.
*/
getDistanceBetweenObjects(firstLayerId, firstLayerObjectId, secondLayerId, secondLayerObjectId) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.RSVP.all([
this._getModelLayerFeature(firstLayerId, [firstLayerObjectId]),
this._getModelLayerFeature(secondLayerId, [secondLayerObjectId])
]).then((result) => {
let objA = result[0][2][0];
let objB = result[1][2][0];
resolve(this._getDistanceBetweenObjects(objA, objB));
}).catch((e) => {
reject(e);
});
});
},
/**
Get layer object attributes and coordinates.
@method getLayerObjectOptions
@param {String} layerId Layer ID.
@param {String} featureId Object ID.
@param {String} crsName Name of coordinate reference system, in which to give coordinates.
@return {Promise} Attributes and coordinates
*/
getLayerObjectOptions(layerId, featureId, crsName) {
return new Ember.RSVP.Promise((resolve, reject) => {
let result;
this._getModelLayerFeature(layerId, [featureId]).then(([, leafletLayer, features]) => {
let featureLayer = features[0];
if (leafletLayer && featureLayer) {
result = Object.assign({}, featureLayer.feature.properties);
if (crsName) {
let NewObjCrs = this._convertObjectCoordinates(leafletLayer.options.crs.code, featureLayer.feature, crsName);
result.geometry = NewObjCrs.geometry.coordinates;
} else {
result.geometry = featureLayer.feature.geometry.coordinates;
}
let jstsGeoJSONReader = new jsts.io.GeoJSONReader();
let featureLayerGeoJSON = featureLayer.toProjectedGeoJSON(leafletLayer.options.crs);
let jstsGeoJSON = jstsGeoJSONReader.read(featureLayerGeoJSON);
result.area = jstsGeoJSON.geometry.getArea();
resolve(result);
}
}).catch((e) => {
reject(e);
});
});
},
/**
Check if object A contains object B.
@method isContainsObject
@param {String} layerAId First layer ID.
@param {String} objectAId First object ID.
@param {String} layerBId Second layer ID.
@param {String} objectBId Second object ID.
@return {Promise} true or false.
*/
isContainsObject(layerAId, objectAId, layerBId, objectBId) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.RSVP.all([
this._getModelLayerFeature(layerAId, [objectAId]),
this._getModelLayerFeature(layerBId, [objectBId])
]).then((result) => {
let objA = result[0][2][0].feature;
let objB = result[1][2][0].feature;
let leafletLayerA = result[0][1];
let leafletLayerB = result[1][1];
if (objA && objB && leafletLayerA && leafletLayerB) {
let feature1 = leafletLayerA.options.crs.code === 'EPSG:4326' ? objA : this._convertObjectCoordinates(leafletLayerA.options.crs.code, objA);
let feature2 = leafletLayerB.options.crs.code === 'EPSG:4326' ? objB : this._convertObjectCoordinates(leafletLayerB.options.crs.code, objB);
if (feature1.geometry.type === 'MultiPolygon') {
feature1 = L.polygon(feature1.geometry.coordinates[0]).toGeoJSON();
}
if (feature2.geometry.type === 'MultiPolygon') {
feature2 = L.polygon(feature2.geometry.coordinates[0]).toGeoJSON();
}
resolve(booleanContains(feature1, feature2));
}
}).catch((e) => {
reject(e);
});
});
},
/**
Calculate the area of object B that extends beyond the boundaries of object A.
@method getAreaExtends
@param {String} layerAId First layer ID.
@param {String} objectAId First object ID.
@param {String} layerBId Second layer ID.
@param {String} objectBId Second object ID.
@return {Promise} Area
*/
getAreaExtends(layerAId, objectAId, layerBId, objectBId) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.RSVP.all([
this._getModelLayerFeature(layerAId, [objectAId]),
this._getModelLayerFeature(layerBId, [objectBId])
]).then((result) => {
let objA = result[0][2][0].feature;
let objB = result[1][2][0].feature;
let layerObjectA = result[0][1];
let layerObjectB = result[1][1];
let feature1 = layerObjectA.options.crs.code === 'EPSG:4326' ? objA : this._convertObjectCoordinates(layerObjectA.options.crs.code, objA);
let feature2 = layerObjectB.options.crs.code === 'EPSG:4326' ? objB : this._convertObjectCoordinates(layerObjectB.options.crs.code, objB);
let intersectionRes = intersect.default(feature2, feature1);
if (intersectionRes) {
let resultArea = area(feature2) - area(intersectionRes);
resolve(resultArea);
} else {
resolve(area(feature2));
}
}).catch((e) => {
reject(e);
});
});
},
/**
Get layer type.
@method _getTypeLayer
@param {Object} layerModel layer model.
@return {Object} layer type
*/
_getTypeLayer(layerModel) {
let className = Ember.get(layerModel, 'type');
let layerType = Ember.getOwner(this).knownForType('layer', className);
return layerType;
},
_setVisibility(layerIds, visibility = false) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (Ember.isArray(layerIds)) {
const leafletMap = this.get('mapApi').getFromApi('leafletMap');
let currentLayerIds = [];
layerIds.forEach(id => {
const layer = this.get('mapLayer').findBy('id', id);
if (layer) {
layer.set('visibility', visibility);
currentLayerIds.push(id);
} else {
Ember.run.later(this, () => { reject(`Layer '${id}' not found.`); }, 1);
}
});
if (visibility) {
if (currentLayerIds.length > 0) {
let e = {
layers: currentLayerIds,
results: Ember.A()
};
leafletMap.fire('flexberry-map:moveend', e);
e.results = Ember.isArray(e.results) ? e.results : Ember.A();
let promises = Ember.A();
e.results.forEach((result) => {
if (Ember.isNone(result)) {
return;
}
promises.pushObject(Ember.get(result, 'promise'));
});
Ember.RSVP.allSettled(promises).then(() => {
Ember.run.later(this, () => { resolve('success'); }, 1);
});
} else {
Ember.run.later(this, () => { reject('all layerIds is not found'); }, 1);
}
} else {
Ember.run.later(this, () => { resolve('success'); }, 1);
}
} else {
reject('Parametr is not a Array');
}
});
},
/**
Get object id by object and layer.
@method _getLayerFeatureId
@param {Object} layer Layer.
@param {Object} layerObject Object.
@return {number} Object ID.
*/
_getLayerFeatureId(layer, layerObject) {
let field = this._getPkField(layer);
if (layerObject.state !== state.insert) {
if (layerObject.feature.properties.hasOwnProperty(field)) {
return Ember.get(layerObject, 'feature.properties.' + field);
}
return Ember.get(layerObject, 'feature.id');
} else {
return null;
}
},
/**
Determine the visibility of the specified objects by id for the layer.
@method _setVisibilityObjects
@param {string} layerId Layer ID.
@param {string[]} objectIds Array of objects IDs.
@param {boolean} [visibility=false] visibility Object Visibility.
@return {Ember.RSVP.Promise}
*/
_setVisibilityObjects(layerId, objectIds, visibility = false) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (Ember.isArray(objectIds)) {
let [layer, leafletObject] = this._getModelLeafletObject(layerId);
if (Ember.isNone(layer)) {
return reject(`Layer '${layerId}' not found.`);
}
if (!Ember.isNone(leafletObject) && typeof leafletObject._setVisibilityObjects === 'function') {
leafletObject._setVisibilityObjects(objectIds, visibility).then((result) => {
resolve(result);
});
} else {
return reject('Layer type not supported');
}
}
});
},
/**
To copy Object from Source layer to Destination.
@method copyObject
@param {Object} source Object with source settings
{
layerId, //{string} Layer ID
objectId, //{string} Object ID
shouldRemove //{Bool} Should remove object from source layer
}
@param {Object} destination Object with destination settings
{
layerId, //{string} Layer ID
properties //{Object} Properties of new object.
}
@return {Promise} Object in Destination layer
*/
copyObject(source, destination) {
return new Ember.RSVP.Promise((resolve, reject) => {
this._getModelLayerFeature(source.layerId, [source.objectId], source.shouldRemove).then(([, sourceLeafletLayer, obj]) => {
let sourceFeature = obj[0];
let [destLayerModel, destLeafletLayer] = this._getModelLeafletObject(destination.layerId);
let destFeature;
switch (destLayerModel.get('settingsAsObject.typeGeometry').toLowerCase()) {
case 'polygon':
destFeature = L.polygon(sourceFeature.getLatLngs());
break;
case 'polyline':
destFeature = L.polyline(sourceFeature.getLatLngs());
break;
case 'marker':
destFeature = L.marker(sourceFeature.getLatLng());
break;
default:
reject(`Unknown layer type: '${destLayerModel.get('settingsAsObject.typeGeometry')}`);
}
if (!Ember.isNone(destFeature)) {
destFeature.feature = {
properties: Object.assign({}, sourceFeature.feature.properties, destination.properties || {})
};
if (sourceLeafletLayer.geometryField) {
delete destFeature.feature.properties[sourceLeafletLayer.geometryField];
}
if (destLeafletLayer.geometryField) {
delete destFeature.feature.properties[destLeafletLayer.geometryField];
}
let e = { layers: [destFeature], results: Ember.A() };
destLeafletLayer.fire('load', e);
Ember.RSVP.allSettled(e.results).then(() => {
if (source.shouldRemove) {
sourceLeafletLayer.removeLayer(sourceFeature);
}
resolve(destFeature);
});
}
}).catch((e) => {
reject(e);
});
});
},
/**
To copy Objects from Source layer to Destination.
@method copyObjectsBatch
@param {Object} source Object with source settings
{
layerId, //{string} Layer ID
objectIds, //{array} Objects ID
shouldRemove //{Bool} Should remove object from source layer
}
@param {Object} destination Object with destination settings
{
layerId, //{string} Layer ID
withProperties //{Bool} To copy objects with it properties.
}
@return {Promise} Object in Destination layer
*/
copyObjectsBatch(source, destination) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (Ember.isNone(source.layerId) || Ember.isNone(source.objectIds) || Ember.isNone(destination.layerId)) {
reject('Check the parameters you are passing');
} else {
let loadPromise = new Ember.RSVP.all(this.loadingFeaturesByPackages(source.layerId, source.objectIds, source.shouldRemove));
loadPromise.then((res) => {
let destFeatures = [];
let sourceFeatures = [];
let [destLayerModel, destLeafletLayer] = this._getModelLeafletObject(destination.layerId);
let [sourceModel, sourceLeafletLayer] = this._getModelLeafletObject(source.layerId);
let objects = [];
if (source.shouldRemove) {
sourceLeafletLayer.eachLayer(shape => {
if (source.objectIds.indexOf(this._getLayerFeatureId(sourceModel, shape)) !== -1) {
objects.push(shape);
}
});
} else {
res.forEach(result => {
objects = objects.concat(result[2]);
});
}
objects.forEach(sourceFeature => {
let destFeature;
switch (destLayerModel.get('settingsAsObject.typeGeometry').toLowerCase()) {
case 'polygon':
destFeature = L.polygon(sourceFeature.getLatLngs());
break;
case 'polyline':
destFeature = L.polyline(sourceFeature.getLatLngs());
break;
case 'marker':
destFeature = L.marker(sourceFeature.getLatLng());
break;
default:
reject(`Unknown layer type: '${destLayerModel.get('settingsAsObject.typeGeometry')}`);
}
if (!Ember.isNone(destFeature)) {
destFeature.feature = { properties: {} };
if (destination.withProperties) {
destFeature.feature.properties = Object.assign({}, sourceFeature.feature.properties);
if (sourceLeafletLayer.geometryField) {
delete destFeature.feature.properties[sourceLeafletLayer.geometryField];
}
if (destLeafletLayer.geometryField) {
delete destFeature.feature.properties[destLeafletLayer.geometryField];
}
}
destFeatures.push(destFeature);
if (source.shouldRemove) {
sourceFeatures.push(sourceFeature);
}
}
});
let e = { layers: destFeatures, results: Ember.A() };
destLeafletLayer.fire('load', e);
Ember.RSVP.allSettled(e.results).then(() => {
if (source.shouldRemove) {
sourceFeatures.forEach(sourceFeature => {
sourceLeafletLayer.removeLayer(sourceFeature);
});
}
resolve(destFeatures);
});
}).catch(e => reject(e));
}
});
},
/**
Calculate the area of intersection between object A and objects in array B.
@method getIntersectionArea
@param {String} layerAId First layer ID.
@param {String} objectAId First object ID.
@param {String} layerBId Second layer ID.
@param {Array} objectBIds Array of object IDs in second layer.
@param {Bool} showOnMap flag indicates if intersection area will be displayed on map.
@return {Promise} If showOnMap = true, return objects, which show on map in serviceLayer, and area, else only area.
*/
getIntersectionArea(layerAId, objectAId, layerBId, objectBIds, showOnMap) {
return new Ember.RSVP.Promise((resolve, reject) => {
let result = Ember.A();
Ember.RSVP.all([
this._getModelLayerFeature(layerAId, [objectAId]),
this._getModelLayerFeature(layerBId, objectBIds)
]).then((res) => {
let layerObjectA = res[0][1];
let layerObjectB = res[1][1];
let objA = res[0][2][0].feature;
let feature1 = layerObjectA.options.crs.code === 'EPSG:4326' ? objA : this._convertObjectCoordinates(layerObjectA.options.crs.code, objA);
let featuresB = res[1][2];
featuresB.forEach((feat) => {
let objB = feat.feature;
let feature2 = layerObjectB.options.crs.code === 'EPSG:4326' ? objB : this._convertObjectCoordinates(layerObjectB.options.crs.code, objB);
let intersectionRes = intersect.default(feature1, feature2);
if (intersectionRes) {
let object = {
id: objB.properties.primarykey,
area: area(intersectionRes)
};
if (showOnMap) {
let obj = L.geoJSON(intersectionRes, {
style: { color: 'green' }
});
let serviceLayer = this.get('mapApi').getFromApi('serviceLayer');
obj.addTo(serviceLayer);
object.objectIntesect = obj;
}
result.pushObject(object);
} else {
result.pushObject({
id: objB.properties.primarykey,
area: 'Intersection not found'
});
}
});
if (!Ember.isNone(result)) {
resolve(result);
}
}).catch((e) => {
reject(e);
});
});
},
/**
Cleans the service layer.
@method clearServiceLayer
@return nothing
*/
clearServiceLayer() {
let serviceLayer = this.get('mapApi').getFromApi('serviceLayer');
serviceLayer.clearLayers();
},
/**
Create image for layer object.
@method getSnapShot
@param {Object} source Object with settings
{
layerId, //{string} Layer ID.
objectId, //{string} Object ID.
layerArrIds, //{Array} Array of layers IDs.
options {
width, //{number} width image
height //{number} height image
}
}
@return {Promise} Image url.
*/
getSnapShot({ layerId, objectId, layerArrIds, options }) {
return new Ember.RSVP.Promise((resolve, reject) => {
this._getModelLayerFeature(layerId, [objectId]).then(([layerModel, leafletObject, featureLayer]) => {
let allLayers = this.get('mapLayer.canonicalState');
let allLayersIds = allLayers.map((l) => l.id);
if (layerArrIds) {
let showLayersIds = layerArrIds;
showLayersIds.push(layerId);
this.showLayers(showLayersIds);
let hideLayersIds = allLayersIds.filter((i) => { return showLayersIds.indexOf(i) < 0; });
this.hideLayers(hideLayersIds);
}
const leafletMap = this.get('mapApi').getFromApi('leafletMap');
let $mapPicture = Ember.$(leafletMap._container);
let heightMap = $mapPicture.height();
let widthMap = $mapPicture.width();
let heightNew = heightMap;
let widthNew = widthMap;
if (!Ember.isNone(options)) {
heightNew = Ember.isNone(options.height) ? heightMap : options.height;
widthNew = Ember.isNone(options.width) ? widthMap : options.width;
}
$mapPicture.height(heightNew);
$mapPicture.width(widthNew);
let load = [];
let ids = Ember.isEmpty(layerArrIds) ? allLayersIds : layerArrIds;
if (ids) {
ids.forEach((lid) => {
if (lid !== layerId) {
let [, layerObject] = this._getModelLeafletObject(lid);
layerObject.statusLoadLayer = true;
load.push(layerObject);
}
});
}
leafletObject.statusLoadLayer = true;
load.push(leafletObject);
leafletMap.once('moveend', () => {
Ember.run.later(() => {
document.getElementsByClassName('leaflet-control-zoom leaflet-bar leaflet-control')[0].style.display = 'none';
document.getElementsByClassName('history-control leaflet-bar leaflet-control horizontal')[0].style.display = 'none';
Ember.$(document).find('.leaflet-top.leaflet-left').css('display', 'none');
Ember.$(document).find('.leaflet-top.leaflet-right').css('display', 'none');
Ember.$(document).find('.leaflet-bottom.leaflet-right').css('display', 'none');
let promises = load.map((object) => {
return !Ember.isNone(leafletObject.promiseLoadLayer) && (leafletObject.promiseLoadLayer instanceof Ember.RSVP.Promise);
});
Ember.RSVP.allSettled(promises).then((e) => {
load.forEach((obj) => {
obj.statusLoadLayer = false;
obj.promiseLoadLayer = null;
});
let html2canvasOptions = Object.assign({
useCORS: true,
onclone: function (clonedDoc) {
html2canvasClone(clonedDoc);
}
});
window.html2canvas($mapPicture[0], html2canvasOptions)
.then((canvas) => {
let type = 'image/png';
var image64 = canvas.toDataURL(type);
resolve(image64);
})
.catch((e) => reject(e))
.finally(() => {
document.getElementsByClassName('leaflet-control-zoom leaflet-bar leaflet-control')[0].style.display = 'block';
document.getElementsByClassName('history-control leaflet-bar leaflet-control horizontal')[0].style.display = 'block';
Ember.$(document).find('.leaflet-top.leaflet-left').css('display', 'block');
Ember.$(document).find('.leaflet-top.leaflet-right').css('display', 'block');
Ember.$(document).find('.leaflet-bottom.leaflet-right').css('display', 'block');
$mapPicture.height(heightMap);
$mapPicture.width(widthMap);
});
});
});
});
let bounds = featureLayer[0].getBounds();
if (!Ember.isNone(bounds)) {
leafletMap.fitBounds(bounds.pad(0.5));
}
}).catch((e) => {
reject(e);
});
});
},
/**
Download image for layer object.
@method downloadSnapShot
@param {Object} source Object with settings
{
layerId, //{string} Layer ID.
objectId, //{string} Object ID.
layerArrIds, //{Array} Array of layers IDs.
options {
width, //{number} width image
height //{number} height image
},
fileName //{string} File name.
}
@return {File} Image file.
*/
downloadSnapShot({ layerId, objectId, layerArrIds, options, fileName }) {
this.getSnapShot({ layerId, objectId, layerArrIds, options }).then((uri) => {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = fileName;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
});
},
/**
Get a rhumb object for [LineString, MultiLineString, Polygon, MultiPolygon]. Parameters is object in GeoJSON
format and name of coordinate reference system. Calculates rhumb between points. Use jsts libraries to calculate distance between points.
Distance calculation in units of coordinate reference system. Names of direction is [NE, SE, NW, SW]. Angle calculation in degree.
Returns array of object:
```javascript
[{
type - type of object is [LineString, Polygon],
crs - name of coordinate reference system of start point,
startPoint - coordinates of start point,
skip - how many rhumb skip from beginning (always 0),
points - array objects of rhumbs,
hole - if this part is hole then true else false. Only Polygon and MultiPolygon have it.
}]
```
Objects of rhumbs consist from angle, distance and direction of rhumb. Example:
```javascript
{
rhumb: 'NE',
angle: 45,
distance: 1000
}
```
Example of method call:
```javascript
var feature = {
type: "Feature",
geometry:
{
"type": "Polygon",
"coordinates": [
[[56.09419, 58.08895], [56.093588, 58.088632], [56.094269, 58.088632], [56.094269, 58.088902], [56.09419, 58.08895]]
]
}
};
var result = mapApi.mapModel.getRhumb(feature, 'EPSG:4326');
```
@method getRhumb
@param {Object} feature GeoJson Feature.
@param {string} crsName Name of coordinate reference system, in which to give coordinates.
@return {Array} Array object rhumb.
*/
getRhumb(feature, crsName) {
let coords = feature.geometry.coordinates;
let result = [];
var calcRhumb = function (point1, point2) {
// Get distance
let geojson1 = {
type: 'Point',
coordinates: point1
};
let geojson2 = {
type: 'Point',
coordinates: point2
};
let jsts1 = geometryToJsts(geojson1);
let jsts2 = geometryToJsts(geojson2);
const distance = jsts1.distance(jsts2);
// Get the angle.
var getAngle = function (p1, p2) {
return Math.atan2(p1[1] - p2[1], p1[0] - p2[0]) / Math.PI * 180;
};
const bearing = getAngle(point2, point1);
let rhumb;
let angle;
// Calculates rhumb.
if (bearing <= 90 && bearing >= 0) {
// NE
rhumb = 'NE';
angle = 90 - bearing;
} else if (bearing <= 180 && bearing >= 90) {
// NW
rhumb = 'NW';
angle = (bearing - 90);
} else if (bearing >= -180 && bearing <= -90) {
// SW
rhumb = 'SW';
angle = (-1 * bearing - 90);
} if (bearing <= 0 && bearing >= -90) {
// SE
rhumb = 'SE';
angle = (90 + bearing);
}
return {
rhumb: rhumb,
angle: angle,
distance: distance
};
};
let coordToRhumbs = function(type, coords) {
let startPoint = null;
let n;
let point1;
let point2;
let rhumbs = [];
for (let i = 0; i < coords.length - 1; i++) {
startPoint = i === 0 ? coords[i] : startPoint;
point1 = coords[i];
n = !Ember.isNone(coords[i + 1]) ? i + 1 : 0;
point2 = coords[n];
rhumbs.push(calcRhumb(point1, point2));
}
return {
type: type,
crs: crsName,
startPoint: startPoint,
skip: 0,
points: rhumbs
};
};
switch (feature.geometry.type) {
case 'LineString':
result.push(coordToRhumbs('LineString', coords));
break;
case 'MultiLineString':
for (let i = 0; i < coords.length; i++) {
result.push(coordToRhumbs('LineString', coords[i]));
}
break;
case 'Polygon':
for (let i = 0; i < coords.length; i++) {
result.push(coordToRhumbs('Polygon', coords[i]));
result[i].hole = i > 0 ? true : false;
}
break;
case 'MultiPolygon':
for (let i = 0; i < coords.length; i++) {
for (let j = 0; j < coords[i].length; j++) {
result.push(coordToRhumbs('Polygon', coords[i][j]));
result[result.length - 1].hole = j > 0 ? true : false;
}
}
break;
}
return result;
},
/**
Add a layer to the group.
@method layerToGroup
@parm {string} layerId Layer ID.
@parm {string} layerGroupId Group layer ID.
@return nothing
*/
moveLayerToGroup(layerId, layerGroupId) {
const layer = this.get('mapLayer').findBy('id', layerGroupId);
if (Ember.isNone(layer)) {
throw (`Group layer '${layerGroupId}' not found`);
}
let layerModel = this.getLayerModel(layerId);
if (Ember.isNone(layerModel)) {
throw (`Layer '${layerId}' not found`);
}
layerModel.set('parent', layer);
},
/**
Edit object layer.
@method editLayerObject
@param {String} layerId Layer ID.
@param {String} objectId Object ID.
@param {String} polygon Сoordinates of the new object in geoJSON format.
@param {String} crsName Name of coordinate reference system.
@return {Promise} Layer object.
*/
editLayerObject(layerId, objectId, polygon, crsName) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (polygon) {
this._getModelLayerFeature(layerId, [objectId], true).then(([, leafletLayer, featureLayer]) => {
if (leafletLayer && featureLayer) {
let crs = leafletLayer.options.crs;
if (!Ember.isNone(crsName)) {
crs = getLeafletCrs('{ "code": "' + crsName.toUpperCase() + '", "definition": "" }', this);
}
let coordsToLatLng = function (coords) {
return crs.unproject(L.point(coords));
};
let geoJSON = null;
if (!Ember.isNone(crs) && crs.code !== 'EPSG:4326') {
geoJSON = L.geoJSON(polygon, { coordsToLatLng: coordsToLatLng.bind(this) }).getLayers()[0];
} else {
geoJSON = L.geoJSON(polygon).getLayers()[0];
}
if (!Ember.isNone(Ember.get(geoJSON, 'feature.geometry'))) {
if (Ember.get(geoJSON, 'feature.geometry.type').toLowerCase() !== 'point') {
featureLayer[0].setLatLngs(geoJSON._latlngs);
} else {
featureLayer[0].setLatLng(geoJSON._latlng);
}
if (typeof leafletLayer.editLayer === 'function') {
leafletLayer.editLayer(featureLayer[0]);
resolve(featureLayer[0]);
}
} else {
reject(`Unable to convert coordinates for this CRS '${crsName}'`);
}
} else if (leafletLayer) {
reject(`Layer '${layerId}' not found`);
} else if (featureLayer[0]) {
reject(`Object '${objectId}' not found`);
}
}).catch((e) => {
reject(e);
});
} else {
reject('new object settings not passed');
}
});
},
/**
Upload file.
@method uploadFile
@param {File} file.
@return {Promise} Object in geoJSON format
*/
uploadFile(file) {
let config = Ember.getOwner(this).resolveRegistration('config:environment');
let data = new FormData();
data.append(file.name, file);
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: `${config.APP.backendUrl}/controls/FileUploaderHandler.ashx?FileName=${file.name}`,
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function (data) {
resolve(data);
},
error: function (e) {
reject(e);
}
});
});
},
_isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
},
/**
Convert coordinates of object to wgs84, or other crsName.
@method convertObjectCoordinates
@param {featureLayer} object.
@return {featureLayer} Returns provided object with converted coordinates
@private
*/
_convertObjectCoordinates(projection, object, crsName = null) {
// copy from https://stackoverflow.com/a/48218209/2014079 for replace $.extend
// such as it is not properly work with Proxy properties
var mergeDeep = function (...objects) {
const isObject = obj => obj && typeof obj === 'object';
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach(key => {
const pVal = prev[key];
const oVal = obj[key];
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal);
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeDeep(pVal, oVal);
} else {
prev[key] = oVal;
}
});
return prev;
}, {});
};
let knownCrs = Ember.getOwner(this).knownForType('coordinate-reference-system');
let knownCrsArray = Ember.A(Object.values(knownCrs));
let firstProjection = projection ? projection : 'EPSG:4326';
let secondProjection = crsName ? crsName : 'EPSG:4326';
let firstCrs = knownCrsArray.findBy('code', firstProjection);
let secondCrs = knownCrsArray.findBy('code', secondProjection);
if (firstCrs && secondCrs) {
let firstDefinition = Ember.get(firstCrs, 'definition');
let secondDefinition = Ember.get(secondCrs, 'definition');
if (firstDefinition && secondDefinition) {
if (firstDefinition !== secondDefinition) {
let result = mergeDeep({}, object);
let coordinatesArray = [];
if (result.geometry.type !== 'Point') {
result.geometry.coordinates.forEach(arr => {
var arr1 = [];
if (result.geometry.type.indexOf('Multi') !== -1) {
arr.forEach(pair => {
if (result.geometry.type === 'MultiPolygon') {
let arr2 = [];
pair.forEach(cords => {
let transdormedCords = proj4(firstDefinition, secondDefinition, cords);
arr2.push(transdormedCords);
});
arr1.push(arr2);
} else {
let cords = proj4(firstDefinition, secondDefinition, pair);
arr1.push(cords);
}
});
coordinatesArray.push(arr1);
} else {
if (result.geometry.type === 'Polygon') {
arr.forEach(cords => {
let transdormedCords = proj4(firstDefinition, secondDefinition, cords);
arr1.push(transdormedCords);
});
coordinatesArray.push(arr1);
} else {
let cords = proj4(firstDefinition, secondDefinition, arr);
coordinatesArray.push(cords);
}
}
});
} else {
coordinatesArray = proj4(firstDefinition, secondDefinition, result.geometry.coordinates);
}
result.geometry.coordinates = coordinatesArray;
return result;
} else {
return object;
}
}
} else {
throw 'unknown coordinate reference system';
}
},
/*
Get the field to search for objects
@method getPkField
@param {Object} layer.
@return {String} Field name.
*/
_getPkField(layer) {
if (!Ember.isNone(layer) && !Ember.isNone(layer._leafletObject) && typeof layer._leafletObject.getPkField === 'function') {
return layer._leafletObject.getPkField(layer);
} else {
throw 'Layer is not VectorLayer';
}
},
/**
Get coordinates point.
@method getCoordPoint
@param {String} crsName Name of coordinate reference system, in which to give coordinates.
@param {Boolean} snap Snap or not
@param {Array} snapLayers Layers for snap
@param {Integer} snapDistance in pixels
@param {Boolean} snapOnlyVertex or segments too
@return {Promise} Coordinate.
*/
getCoordPoint(crsName, snap, snapLayers, snapDistance, snapOnlyVertex) {
return new Ember.RSVP.Promise((resolve, reject) => {
const leafletMap = this.get('mapApi').getFromApi('leafletMap');
Ember.$(leafletMap._container).css('cursor', 'crosshair');
var getCoord = (e) => {
if (snap) {
this._drawClick(e);
}
leafletMap.off('mousemove', this._handleSnapping, this);
let layers = this.get('_snapLayersGroups');
if (layers) {
layers.forEach((l, i) => {
l.off('load', this._setSnappingFeatures, this);
});
}
this._cleanupSnapping();
Ember.$(leafletMap._container).css('cursor', '');
let crs = Ember.get(leafletMap, 'options.crs');
if (!Ember.isNone(crsName)) {
crs = getLeafletCrs('{ "code": "' + crsName.toUpperCase() + '", "definition": "" }', this);
}
resolve(crs.project(e.latlng));
};
if (snap) {
let layers = snapLayers.map((id) => {
let [, leafletObject] = this._getModelLeafletObject(id);
return leafletObject;
}).filter(l => !!l);
layers.forEach((l, i) => {
l.on('load', this._setSnappingFeatures, this);
});
this.set('_snapLayersGroups', layers);
this._setSnappingFeatures();
if (snapDistance) {
this.set('_snapDistance', snapDistance);
}
if (!Ember.isNone(snapOnlyVertex)) {
this.set('_snapOnlyVertex', snapOnlyVertex);
}
let editTools = this._getEditTools();
leafletMap.on('mousemove', this._handleSnapping, this);
this.set('_snapMarker', L.marker(leafletMap.getCenter(), {
icon: editTools.createVertexIcon({ className: 'leaflet-div-icon leaflet-drawing-icon' }),
opacity: 1,
zIndexOffset: 1000
}));
}
leafletMap.once('click', getCoord);
});
},
/**
Loading features by packages
@method loadingFeaturesByPackages
@param {String} layerId Layer ID.
@param {Array} objectIds Object IDs.
@return {Promise}
*/
loadingFeaturesByPackages(layerId, objectIds, shouldRemove = false) {
let packageSize = 100;
let layerPromises = [];
let startPackage = 0;
while (startPackage < objectIds.length) {
let endPackage = (startPackage + packageSize) <= objectIds.length ? startPackage + packageSize : objectIds.length;
let objectsPackage = [];
for (var i = startPackage; i < endPackage; i++) {
objectsPackage.push(objectIds[i]);
}
layerPromises.push(this._getModelLayerFeature(layerId, objectsPackage, shouldRemove));
startPackage = endPackage;
}
return layerPromises;
},
/**
Get merged geometry. Loads objects from a layers by packages of 100 units each.
Waits when all objects successfully load. Transform objects into JSTS objects.
First it merges geometry of objects on first layer using _getMulti method, then on second layer.
Result of combining objects in each layer is merged into a common geometry using createMulti method.
@method getMergedGeometry
@param {String} layerAId First layer ID.
@param {Array} objectAIds First layer object IDs.
@param {String} layerBId Second layer ID.
@param {Array} objectBIds Second layer object IDs.
@param {Boolean} failIfInvalid Fail when has invalid geometry.
@param {Boolean} forceMulti Flag: indicates whether to make geometries as multi..
@return {Promise} GeoJson Feature.
*/
getMergedGeometry(layerAId, objectAIds, layerBId, objectBIds, isUnion = false, failIfInvalid = false, forceMulti = true) {
return new Ember.RSVP.Promise((resolve, reject) => {
let layerAPromises = this.loadingFeaturesByPackages(layerAId, objectAIds);
let layerBPromises = this.loadingFeaturesByPackages(layerBId, objectBIds);
Ember.RSVP.allSettled(
layerAPromises.concat(layerBPromises)
).then((layerFeatures) => {
const rejected = layerFeatures.filter((item) => { return item.state === 'rejected'; }).length > 0;
if (rejected) {
reject('Error loading objects');
}
let count = 0;
let scale = this.get('mapApi').getFromApi('precisionScale');
let resultObjs = Ember.A();
layerFeatures.forEach((r, i) => {
let geometries = Ember.A();
r.value[2].forEach((obj, ind) => {
if (Ember.get(obj, 'feature.geometry') && Ember.get(obj, 'options.crs.code')) {
let feature = obj.toJsts(obj.options.crs, scale);
geometries.pushObject(feature);
}
});
count += 1;
// если вся геометрия невалидна, то будет null
let merged = this._getMulti(geometries, isUnion, failIfInvalid);
if (merged) {
resultObjs.pushObject(merged);
}
});
let resultObj = resultObjs.length > 0 ? this.createMulti(resultObjs, isUnion, failIfInvalid, true, forceMulti) : null;
resolve(resultObj ? resultObj : null);
}).catch((e) => {
reject(e);
});
});
},
/**
Add to array points and feature.
@method _addToArrayPointsAndFeature
@param {String} layerId Layer ID.
@param {String} crsName Name of coordinate reference system, in which to conver coordinates.
@return {Promise} array of points and feature.
*/
_addToArrayPointsAndFeature(layerId, crsName) {
return new Ember.RSVP.Promise((resolve, reject) => {
this._getModelLayerFeature(layerId, null).then(([, layerObject, layerFeatures]) => {
if (!Ember.isEmpty(layerFeatures)) {
let arrPoints = Ember.A();
let features = Ember.A();
layerFeatures.forEach((layer) => {
let obj = layer.feature;
if (!Ember.isNone(crsName)) {
obj = this._convertObjectCoordinates(layerObject.options.crs.code, obj, crsName);
}
let featureLayer = L.GeoJSON.geometryToLayer(obj);
arrPoints.push(this._coordsToPoints(featureLayer.getLatLngs()));
features.push(layer);
});
resolve({ arrPoints, features });
} else {
reject('Error to load objects');
}
}).catch((e) => {
reject(e);
});
});
},
/**
Difference layers.
@method differenceLayers
@param {String} layerAId First layer ID.
@param {String} layerBId Second layer ID.
@return {Promise} array of Object { diffFeatures, layerAFeatures, layerBFeatures }.
*/
differenceLayers(layerAId, layerBId) {
return new Ember.RSVP.Promise((resolve, reject) => {
let crsA = this._getModelLeafletObject(layerAId)[1].options.crs.code;
let crsB = this._getModelLeafletObject(layerBId)[1].options.crs.code;
let arrayPointsAndFeaturePromises = [this._addToArrayPointsAndFeature(layerAId), this._addToArrayPointsAndFeature(layerBId)];
if (crsA !== crsB) {
arrayPointsAndFeaturePromises = [this._addToArrayPointsAndFeature(layerAId), this._addToArrayPointsAndFeature(layerBId, crsA)];
}
Ember.RSVP.all(arrayPointsAndFeaturePromises).then((res) => {
let subj = res[0].arrPoints; // layer A
let clip = res[1].arrPoints; // layer B
let solution = ClipperLib.Paths();
let cpr = new ClipperLib.Clipper(); // The Clipper constructor creates an instance of the Clipper class
// Add 'Subject' paths - layer A
for (let s = 0, slen = subj.length; s < slen; s++) {
if (Ember.isArray(subj[s])) { // multipolygon
for (let k = 0, klen = subj[s].length; k < klen; k++) {
cpr.AddPaths(subj[s][k], ClipperLib.PolyType.ptSubject, true);
}
} else { // polygon
cpr.AddPaths(subj[s], ClipperLib.PolyType.ptSubject, true);
}
}
// Add 'Clipping' paths - layer B
for (let c = 0, clen = clip.length; c < clen; c++) {
if (Ember.isArray(clip[c])) { // multipolygon
for (let k = 0, klen = clip[c].length; k < klen; k++) {
cpr.AddPaths(clip[c][k], ClipperLib.PolyType.ptClip, true);
}
} else { // polygon
cpr.AddPaths(clip[c], ClipperLib.PolyType.ptClip, true);
}
}
// Performing the clipping operation - Difference, result operation be return in solution
cpr.Execute(ClipperLib.ClipType.ctDifference, solution);
// filtering 'solution' by area !== 0, transformating of geometry in jsts for comparison and calculate area, filtering after transformation by area > 0
if (!Ember.isEmpty(solution)) {
let jstsGeoJSONReader = new jsts.io.GeoJSONReader();
let diffNotNullArea = solution.filter((geom) => {
return ClipperLib.Clipper.Area(geom) !== 0;
}).map((geom) => {
let feature = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [this._pointsToCoords(geom)],
}
};
let jstsFeature = jstsGeoJSONReader.read(feature);
if (jstsFeature.geometry.isValid()) {
let area = jstsFeature.geometry.getArea();
return { feature, jstsGeometry: jstsFeature.geometry, area };
} else {
return { feature, jstsGeometry: jstsFeature.geometry, area: 0 };
}
}).filter((diff) => {
return diff.area > 0;
});
resolve({ diffFeatures: diffNotNullArea, layerA: res[0].features, layerB: res[1].features });
} else {
resolve('The difference is not found');
}
}).catch((e) => {
reject(e);
});
});
},
/**
Compare layers.
@method compareLayers
@param {String} layerAId First layer ID.
@param {String} layerBId Second layer ID.
@param {String} condition Comparison conditions ["contains", "intersects", "notIntersects"].
@param {Boolean} showOnMap flag indicates if difference area will be displayed on map.
@return {Promise} array of objects with {areaDifference, objectDifference, id of layerB, that matches the condition}.
*/
compareLayers(layerAId, layerBId, condition, showOnMap) {
return new Ember.RSVP.Promise((resolve, reject) => {
let result = Ember.A();
let cond = ['contains', 'intersects', 'notIntersects'];
let diffLayerPromise = this.differenceLayers(layerAId, layerBId);
if (!cond.includes(condition)) {
reject('The comparison condition is set incorrectly. It must be ["contains", "intersects", "notIntersects"].');
} else if (condition === cond[2]) {
diffLayerPromise = this.differenceLayers(layerBId, layerAId);
}
diffLayerPromise.then((res) => {
if (res.hasOwnProperty('diffFeatures')) {
let jstsGeoJSONReader = new jsts.io.GeoJSONReader();
res.diffFeatures.forEach((diff) => {
if (!cond.includes(condition)) {
reject('The comparison condition is set incorrectly. It must be ["contains", "intersects", "notIntersects"].');
}
let layerFeatures = res.layerB;
if (condition === cond[2]) {
layerFeatures = res.layerA;
}
let crs = res.layerA[0].options.crs;
let coordsToLatLng = function(coords) {
return crs.unproject(L.point(coords));
};
let featureLayer = L.geoJSON(diff.feature, { coordsToLatLng: coordsToLatLng.bind(this) }).getLayers()[0];
let object = {
areaDifference: diff.area,
objectDifference: featureLayer
};
layerFeatures.every((feat) => {
let jstsFeat = jstsGeoJSONReader.read(feat.feature);
if (jstsFeat.geometry.isValid()) {
switch (condition) {
case cond[0]:
if (jstsFeat.geometry.contains(diff.jstsGeometry)) {
object.id = jstsFeat.properties.primarykey;
return false;
} else {
return true;
}
break;
case cond[1]:
if (jstsFeat.geometry.intersects(diff.jstsGeometry) && !jstsFeat.geometry.contains(diff.jstsGeometry)) {
object.id = jstsFeat.properties.primarykey;
return false;
} else {
return true;
}
break;
case cond[2]:
if (jstsFeat.geometry.intersects(diff.jstsGeometry)) {
object.id = jstsFeat.properties.primarykey;
return false;
} else {
return true;
}
break;
default:
return true;
}
} else {
return true;
}
});
if (showOnMap) {
let serviceLayer = this.get('mapApi').getFromApi('serviceLayer');
featureLayer.addTo(serviceLayer);
}
result.pushObject(object);
});
resolve(result);
} else {
reject(res);
}
}).catch((e) => {
reject(e);
});
});
},
/**
Exponentiation.
@method _pointAmplifier
@return {Number} 100000000.
*/
_pointAmplifier() {
return Math.pow(10, 8);
},
/**
Transform coordinates in points.
@method _coordsToPoints
@param {Array} polygons Array of coordinates.
@return {Array} Array of points.
*/
_coordsToPoints(polygons) {
let amp = this._pointAmplifier();
if (Array.isArray(polygons[0]) || (!(polygons instanceof L.LatLng) && (polygons[0] instanceof L.LatLng))) {
let coords = [];
for (let i = 0; i < polygons.length; i++) {
coords.push(this._coordsToPoints(polygons[i]));
}
return coords;
}
return { X: Math.round(polygons.lng * amp), Y: Math.round(polygons.lat * amp) };
},
/**
Transform points in coordinates.
@method _pointsToCoords
@param {Array} points Array of points.
@return {Array} Array of coordinates.
*/
_pointsToCoords(points) {
let amp = this._pointAmplifier();
if (Array.isArray(points[0]) || (!(points instanceof ClipperLib.IntPoint) && (points[0] instanceof ClipperLib.IntPoint))) {
let coord = [];
for (let i = 0; i < points.length; i++) {
coord.push(this._pointsToCoords(points[i]));
}
// closing polygon
if (!Array.isArray(coord[0][0])) {
let first = coord[0];
coord.push(first);
}
return coord;
}
return [points.X / amp, points.Y / amp];
},
_requestDownloadFile(layerModel, objectIds, outputFormat, crsOuput, crsLayer, url) {
return new Ember.RSVP.Promise((resolve, reject) => {
downloadFile(layerModel, objectIds, outputFormat, crsOuput, crsLayer, url).then((res) => {
resolve(res);
}).catch((e) => {
reject(e);
});
});
},
/**
Download file.
@method downloadFile
@param {String} layerId.
@param {Array} objectIds.
@param {String} outputFormat.
@param {String} crsName.
@param {boolean} isFile flag indicates if return file or blob. By default 'true'.
@return {Promise} Object consist of fileName and blob. If isFile = true then returns file too.
*/
downloadFile(layerId, objectIds, outputFormat, crsName, isFile = true) {
let config = Ember.getOwner(this).resolveRegistration('config:environment');
let url = config.APP.backendUrls.featureExportApi;
return new Ember.RSVP.Promise((resolve, reject) => {
const layerModel = this.get('mapLayer').findBy('id', layerId);
if (Ember.isNone(layerModel)) {
reject(`Layer '${layerId}' not found.`);
}
let crsOuput = getCrsByName(crsName, this);
let crsLayer = getCrsByName(layerModel.get('crs').code, this);
this._requestDownloadFile(layerModel, objectIds, outputFormat, crsOuput, crsLayer, url).then((res) => {
if (isFile) {
downloadBlob(res.fileName, res.blob);
}
resolve(res);
}).catch((e) => {
reject(e);
});
});
},
setLayerFilter(layerId, filter) {
let layerModel = this.getLayerModel(layerId);
if (Ember.isNone(layerModel)) {
return;
}
layerModel.set('filter', filter);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.