code
stringlengths
2
1.05M
export default class AmpEnvelope { constructor(context, gain = 0) { this.context = context; this.output = this.context.createGain(); this.output.gain.value = gain; this.partials = []; this.velocity = 0; this.gain = gain; this._attack = 0; this._decay = 0.001; this._sustain = this.output.gain.value; this._release = 0.001; this.maxTime = 2; } on(velocity) { this.velocity = velocity / 127; this.start(this.context.currentTime); } off(MidiEvent) { return this.stop(this.context.currentTime); } start(time) { var attackTime = this.attack * this.maxTime; var decayTime = this.decay * this.maxTime; this.output.gain.setValueAtTime(0, 0); this.output.gain.linearRampToValueAtTime(this.velocity, this.context.currentTime + attackTime); this.output.gain.linearRampToValueAtTime(this.sustain * this.velocity, this.context.currentTime + attackTime + decayTime); } stop(time) { this.output.gain.cancelScheduledValues(0); this.output.gain.linearRampToValueAtTime(0, time + (this.release * this.maxTime)); } set attack(value) { this._attack = value; } get attack() { return this._attack } set decay(value) { this._decay = value; } get decay() { return this._decay; } set sustain(value) { this.gain = value; this._sustain; } get sustain() { return this.gain; } set release(value) { this._release = value; } get release() { return this._release; } connect(destination) { this.output.connect(destination); } }
define([ "omega/_Widget", "text!./templates/Select.html", "omega/widgets/Select" ], function(_Widget, template) { return _Widget.extend({ templateString: template, startup: function() { this.inherited(arguments); this._selectNode.on("change", this._selectChange, this); }, _selectChange: function(e) { this._outputNode.html("Label: " + e.option.getLabel() + " value: " + e.option.getValue()); this._outputNode.append("<br />" + this._selectNode.getSelectedIndex()); } }) });
/** * @param {string} value * @returns {RegExp} * */ /** * @param {RegExp | string } re * @returns {string} */ function source(re) { if (!re) return null; if (typeof re === "string") return re; return re.source; } /** * @param {RegExp | string } re * @returns {string} */ function lookahead(re) { return concat('(?=', re, ')'); } /** * @param {RegExp | string } re * @returns {string} */ function optional(re) { return concat('(', re, ')?'); } /** * @param {...(RegExp | string) } args * @returns {string} */ function concat(...args) { const joined = args.map((x) => source(x)).join(""); return joined; } /** * Any of the passed expresssions may match * * Creates a huge this | this | that | that match * @param {(RegExp | string)[] } args * @returns {string} */ function either(...args) { const joined = '(' + args.map((x) => source(x)).join("|") + ")"; return joined; } /* Language: HTML, XML Website: https://www.w3.org/XML/ Category: common */ /** @type LanguageFn */ function xml(hljs) { // Element names can contain letters, digits, hyphens, underscores, and periods const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]+:/), /[A-Z0-9_.-]*/); const XML_IDENT_RE = '[A-Za-z0-9\\._:-]+'; const XML_ENTITIES = { className: 'symbol', begin: '&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;' }; const XML_META_KEYWORDS = { begin: '\\s', contains: [ { className: 'meta-keyword', begin: '#?[a-z_][a-z1-9_-]+', illegal: '\\n' } ] }; const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, { begin: '\\(', end: '\\)' }); const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { className: 'meta-string' }); const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { className: 'meta-string' }); const TAG_INTERNALS = { endsWithParent: true, illegal: /</, relevance: 0, contains: [ { className: 'attr', begin: XML_IDENT_RE, relevance: 0 }, { begin: /=\s*/, relevance: 0, contains: [ { className: 'string', endsParent: true, variants: [ { begin: /"/, end: /"/, contains: [ XML_ENTITIES ] }, { begin: /'/, end: /'/, contains: [ XML_ENTITIES ] }, { begin: /[^\s"'=<>`]+/ } ] } ] } ] }; return { name: 'HTML, XML', aliases: [ 'html', 'xhtml', 'rss', 'atom', 'xjb', 'xsd', 'xsl', 'plist', 'wsf', 'svg' ], case_insensitive: true, contains: [ { className: 'meta', begin: '<![a-z]', end: '>', relevance: 10, contains: [ XML_META_KEYWORDS, QUOTE_META_STRING_MODE, APOS_META_STRING_MODE, XML_META_PAR_KEYWORDS, { begin: '\\[', end: '\\]', contains: [ { className: 'meta', begin: '<![a-z]', end: '>', contains: [ XML_META_KEYWORDS, XML_META_PAR_KEYWORDS, QUOTE_META_STRING_MODE, APOS_META_STRING_MODE ] } ] } ] }, hljs.COMMENT( '<!--', '-->', { relevance: 10 } ), { begin: '<!\\[CDATA\\[', end: '\\]\\]>', relevance: 10 }, XML_ENTITIES, { className: 'meta', begin: /<\?xml/, end: /\?>/, relevance: 10 }, { className: 'tag', /* The lookahead pattern (?=...) ensures that 'begin' only matches '<style' as a single word, followed by a whitespace or an ending braket. The '$' is needed for the lexeme to be recognized by hljs.subMode() that tests lexemes outside the stream. */ begin: '<style(?=\\s|>)', end: '>', keywords: { name: 'style' }, contains: [ TAG_INTERNALS ], starts: { end: '</style>', returnEnd: true, subLanguage: [ 'css', 'xml' ] } }, { className: 'tag', // See the comment in the <style tag about the lookahead pattern begin: '<script(?=\\s|>)', end: '>', keywords: { name: 'script' }, contains: [ TAG_INTERNALS ], starts: { end: /<\/script>/, returnEnd: true, subLanguage: [ 'javascript', 'handlebars', 'xml' ] } }, // we need this for now for jSX { className: 'tag', begin: /<>|<\/>/ }, // open tag { className: 'tag', begin: concat( /</, lookahead(concat( TAG_NAME_RE, // <tag/> // <tag> // <tag ... either(/\/>/, />/, /\s/) )) ), end: /\/?>/, contains: [ { className: 'name', begin: TAG_NAME_RE, relevance: 0, starts: TAG_INTERNALS } ] }, // close tag { className: 'tag', begin: concat( /<\//, lookahead(concat( TAG_NAME_RE, />/ )) ), contains: [ { className: 'name', begin: TAG_NAME_RE, relevance: 0 }, { begin: />/, relevance: 0 } ] } ] }; } module.exports = xml;
/* globals $ */ 'use strict'; angular.module('ucllApp') .directive('passwordStrengthBar', function () { return { replace: true, restrict: 'E', template: '<div id="strength">' + '<small translate="global.messages.validate.newpassword.strength">Password strength:</small>' + '<ul id="strengthBar">' + '<li class="point"></li><li class="point"></li><li class="point"></li><li class="point"></li><li class="point"></li>' + '</ul>' + '</div>', link: function (scope, iElement, attr) { var strength = { colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'], mesureStrength: function (p) { var _force = 0; var _regex = /[$-/:-?{-~!"^_`\[\]]/g; // " var _lowerLetters = /[a-z]+/.test(p); var _upperLetters = /[A-Z]+/.test(p); var _numbers = /[0-9]+/.test(p); var _symbols = _regex.test(p); var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols]; var _passedMatches = $.grep(_flags, function (el) { return el === true; }).length; _force += 2 * p.length + ((p.length >= 10) ? 1 : 0); _force += _passedMatches * 10; // penality (short password) _force = (p.length <= 6) ? Math.min(_force, 10) : _force; // penality (poor variety of characters) _force = (_passedMatches === 1) ? Math.min(_force, 10) : _force; _force = (_passedMatches === 2) ? Math.min(_force, 20) : _force; _force = (_passedMatches === 3) ? Math.min(_force, 40) : _force; return _force; }, getColor: function (s) { var idx = 0; if (s <= 10) { idx = 0; } else if (s <= 20) { idx = 1; } else if (s <= 30) { idx = 2; } else if (s <= 40) { idx = 3; } else { idx = 4; } return { idx: idx + 1, col: this.colors[idx] }; } }; scope.$watch(attr.passwordToCheck, function (password) { if (password) { var c = strength.getColor(strength.mesureStrength(password)); iElement.removeClass('ng-hide'); iElement.find('ul').children('li') .css({ 'background': '#DDD' }) .slice(0, c.idx) .css({ 'background': c.col }); } }); } }; });
import router from './router'; export default router;
'use strict'; module.exports = function(app){ var users = require('../../app/controllers/users.server.controller'); var images = require('../../app/controllers/images.server.controller'); app.route('/images') .get(images.list) .post(users.requiresLogin, images.create); app.route('/images/category/:cat').get(images.catList); app.route('/images/:pid').get(images.imageById); };
import { ethers } from "ethers"; import { deployConfig, defaultNetwork, loadContracts } from "~/networkConfig"; export const state = () => { return { accounts: {}, activeAccount: '', ads: [], adsPixels: 0, ownedAds: {}, halfWrapped: {}, pixelsOwned: 0, grid: null, // lazy load previewAd: null, vis: 'grid', loadedNetwork: null, loadedBlockNumber: 0, loadedBlockTimestamp: 0, networkConfig: {}, // deployConfig of active network, set during clearAds offlineMode: false, } }; export const strict = false; // 😭 Publish preview mutates ads, and it's too annoying to fix rn. function normalizeAddr(addr) { if (!addr) return addr; return addr.toLowerCase(); } function normalizeAd(rawAd) { let normalized = {idx: undefined, owner: undefined, x: undefined, y: undefined, width: undefined, height: undefined, link: "", image: "", title: "", NSFW: false, forceNSFW: false, wrapped: false}; for (const key in normalized) { const value = rawAd[key]; if (value !== undefined) { if (value._isBigNumber) { normalized[key] = value.toNumber(); } else { normalized[key] = value; } } } normalized.owner = normalizeAddr(normalized.owner); // Flip NSFW always if forceNSFW is set if (normalized.forceNSFW) { normalized.NSFW = true; } return normalized; } export const mutations = { loadState(state, loadState) { for (const [k, v] of Object.entries(loadState)) { state[k] = v; } }, initGrid(state) { if (state.grid === null) { // Compute grid and cache it state.grid = filledGrid(grid_array2d(100, 100), state.ads); } }, setAccount(state, account) { account = normalizeAddr(account); state.activeAccount = account; }, addAccount(state, account) { account = normalizeAddr(account); for (const ad of state.ads) { // TODO get our ads from NFT here as well if (normalizeAddr(ad.owner) === account) { addAdOwned.call(this, state, ad); } } state.ownedAds = Object.assign({}, state.ownedAds); }, updatePreview(state, ad) { state.vis = 'grid'; // Buy button forces grid view state.previewAd = Object.assign(state.previewAd || {}, ad); }, clearPreview(state) { state.previewAd = null; }, clearAds(state, networkConfig) { state.grid = null; state.ads = []; state.adsPixels = 0; state.ownedAds = {}; state.pixelsOwned = 0; state.loadedBlockNumber = 0; state.networkConfig = networkConfig; }, setVis(state, vis) { // Valid values: 'grid' and 'list', default to 'grid' state.vis = vis; }, setAdsLength(state, len) { state.ads.length = len; }, importAds(state, ads) { // Bulk version of addAd for (const ad of ads) { appendAd.call(this, state, ad); } if (isSoldOut(state)) state.grid = null; }, addAd(state, ad) { appendAd.call(this, state, ad); }, updateAds(state, updates) { for (const {idx, update} of updates) { const ad = state.ads[idx]; if (ad !== undefined) { let updatedAd = normalizeAd({...ad, ...update}); this._vm.$set(state.ads, idx, updatedAd); if (state.accounts[updatedAd.owner]) { addAdOwned.call(this, state, updatedAd); } else if (state.accounts[ad.owner]) { removeAdOwned.call(this, state, ad.idx); } } } }, setLoadedNetwork(state, {network, blockNumber, timestamp}) { state.offlineMode = blockNumber === 0; state.loadedNetwork = network; if (blockNumber !== 0) { state.loadedBlockNumber = blockNumber; state.loadedBlockTimestamp = timestamp; } console.info("Contract loaded", state.ads.length, "ads until block number", blockNumber, "from", network); }, addHalfWrapped(state, {idx, account}) { this._vm.$set(state.halfWrapped, idx, account); this._vm.$delete(state.ownedAds, idx); }, removeHalfWrapped(state, idx) { this._vm.$delete(state.halfWrapped, idx); }, } export const getters = { isColliding: (state) => (x1, y1, x2, y2) => { if (isSoldOut(state)) return true; // Sold out, always colliding if (state.grid === null) { throw "state.grid not initialized" } // Returns true if has collision, inclusive. if (x1 < 0 || y1 < 0 || x2 >= 100 || y2 >= 100) return true; for (let x = Number(x1); x <= x2; x++) { for (let y = Number(y1); y <= y2; y++) { if (state.grid[x][y]) return true; } } return false; }, numAds: state => { return state.ads.length; }, numWrapped: state => { return state.ads.filter(ad => ad.wrapped).length;; }, numOwned: state => { return Object.keys({...state.ownedAds, ...state.halfWrapped}).length; }, numOwnedWrapped: state => { return Object.values(state.ownedAds).filter(ad => ad.wrapped).length; }, numHalfWrapped: state => { return Object.keys(state.halfWrapped).length; }, numNSFW: state => { return state.ads.filter(ad => ad.NSFW).length; }, isSoldOut: state => { return isSoldOut(state); }, precomputeEscrow: state => ({ idx, KH, KNFT }) => { // This should only be used for client-side confirmation or recovery. For actual // predictedAddress derivation, use the on-chain contract function. const address = state.activeAccount; // Normalize to be consistant const salt = ethers.utils.soliditySha256(["address"], [address]); const wrappedPayload = KH.interface.encodeFunctionData("setAdOwner", [idx, KNFT.address]); const bytecodeHash = ethers.utils.solidityKeccak256(["bytes", "bytes"], [ state.networkConfig.flashEscrowInitCode, ethers.utils.defaultAbiCoder.encode(["address", "bytes"], [KH.address, wrappedPayload]) ]); return ethers.utils.getCreate2Address(KNFT.address, salt, bytecodeHash); } } export const actions = { async nuxtServerInit({ dispatch }, { route }) { // This runs during nuxt generate, we need it to generate initState.json // TODO: refactor this since it shares code with App.vue if (process.dev) return; // Don't preload ads in dev mode so we don't spam Infura 😥 if (route.name !== 'index') return; // We only want to preload ads for the index route const web3Fallback = deployConfig[defaultNetwork].web3Fallback || "http://localhost:8545/"; const provider = new ethers.providers.StaticJsonRpcProvider(web3Fallback); const activeNetwork = (await provider.getNetwork()).name; const networkConfig = deployConfig[activeNetwork]; const contracts = loadContracts(networkConfig, provider) await dispatch('loadAds', contracts); }, async initState({ commit, state }, activeNetwork) { if (process.server) { // TODO: Server-side version of fetch return; } // Only load state on network change and on mainnet if (activeNetwork != "homestead" || activeNetwork == state.loadedNetwork) return; let s = await window.fetch('/initState.json').then(res => res.json()) s.offlineMode = true; if (isSoldOut(s)) s.grid = null; // Skip grid commit('loadState', s); console.log('Loaded cached initial state'); }, async reset({ commit, state }, activeNetwork) { console.info("Active network mismatch, resetting:", state.loadedNetwork, "!=", activeNetwork); commit('clearAds', deployConfig[activeNetwork]); commit('initGrid'); }, async loadAds({ commit, state, dispatch }, {contract, ketherNFT, ketherView}) { // TODO: we can optimize this by only loading from a blockNumber let activeNetwork; let latestBlock = {number: 0, timestamp: 0}; try { activeNetwork = (await contract.provider.getNetwork()).name; latestBlock = await contract.provider.getBlock('latest'); } catch (e) { // TODO: More specific exception console.error("Failed to get provider network, switching to offline mode:", e); activeNetwork = state.loadedNetwork; } const blockNumber = latestBlock.number; const blockTimestamp = latestBlock.timestamp; if (state.loadedNetwork !== activeNetwork) { await dispatch('reset', activeNetwork); } const loadFromKetherView = !!state.networkConfig.ketherViewAddr && state.loadedNetwork != activeNetwork; // Only use View contract if deployed & we haven't loaded already const loadFromEvents = true; // Okay to do it always? or should we do: state.loadedBlockNumber > 0 if (loadFromKetherView) { console.log("Loading from KetherView"); const loadKetherView = async (offset, limit, retries = 0) => { try { const ads = await ketherView.allAds(contract.address, ketherNFT.address, offset, limit); commit('importAds', ads); } catch (err) { // TODO: catch specific errors here if (retries < 1) { console.log("retrying loading of ", offset); await loadKetherView(offset, limit, retries + 1); } else { console.error("Exhausted retries for ", offset, err); } } } const limit = 165; // 10 queries to load 1621 ads on mainnet. 4 queries works too, but maybe flakey? const len = await contract.getAdsLength(); commit('setAdsLength', len); let promises = []; for (let offset = 0; offset < len; offset+=limit) { promises.push(loadKetherView(offset, limit)); } await Promise.all(promises); } else if (loadFromEvents) { // Skip loading and use event filter instead (does 4 query to eth_logs) const [buyEvents, publishEvents, setAdOwnerEvents, transferEvents] = await Promise.all([ contract.queryFilter(contract.filters.Buy(), state.loadedBlockNumber), contract.queryFilter(contract.filters.Publish(), state.loadedBlockNumber), contract.queryFilter(contract.filters.SetAdOwner(), state.loadedBlockNumber), ketherNFT.queryFilter(ketherNFT.filters.Transfer(), state.loadedBlockNumber) ]); // load the Buy events first as they set the grid await dispatch('processBuyEvents', buyEvents); await Promise.all([ dispatch('processPublishEvents', publishEvents), dispatch('processSetAdOwnerEvents', setAdOwnerEvents), dispatch('processTransferEvents', transferEvents) ]); console.info("Loaded additional", buyEvents.length + publishEvents.length + setAdOwnerEvents.length + transferEvents.length, "events since cached state from block number:", state.loadedBlockNumber); } commit('setLoadedNetwork', {network: activeNetwork, blockNumber: blockNumber, timestamp: blockTimestamp}); }, async addAccount({ commit, state }, account) { account = normalizeAddr(account); if (!state.activeAccount) commit('setAccount', account); if (state.accounts[account] === true) return; // Already added this._vm.$set(state.accounts, account, true); commit('addAccount', account); }, async detectHalfWrapped({ state, commit }, { ketherContract, nftContract, numBlocks }) { // FIXME: Probably should move this into Wrap or a ResumeWrap component, no need to pollute global state const account = state.activeAccount; if (!account) { return; } if (numBlocks === undefined) { numBlocks = -(10 * 60 * 24 * 7); // Look 7 days back } else if (numBlocks === "all") { numBlocks = undefined; } let ids = {}; const eventFilter = [ ketherContract.filters.SetAdOwner() ]; const events = await ketherContract.queryFilter(eventFilter, numBlocks); console.log("Looking for half-wrapped ads, processing", events.length, "events from", numBlocks || "all", "blocks"); for (const evt of events.reverse()) { // Only look at events from your account (alas not indexed so we can't filter above) if (normalizeAddr(evt.args.from) !== normalizeAddr(account)) continue; const idx = evt.args.idx.toNumber(); if (ids[idx] !== undefined) continue; ids[idx] = true; } for (const idx in ids) { // Skip ads already wrapped successfully if (state.ads[idx].wrapped) continue; if (state.ownedAds[idx]) continue; try { // Confirm it's not minted on-chain (local state is stale) // Is there a better way to do this without throwing an exception? await nftContract.ownerOf(idx); } catch(err) { commit('addHalfWrapped', {idx: idx, account: account}); } } }, async processBuyEvents({ state, commit }, events) { const ads = events.map((e) => { const [idx, owner, x, y, width, height] = e.args; if (state.previewAd && Number(x*10) == state.previewAd.x && Number(y*10) == state.previewAd.y) { // Colliding ad purchased commit('clearPreview'); } return {idx: idx.toNumber(), owner, x: x.toNumber(), y: y.toNumber(), width: width.toNumber(), height: height.toNumber()}; }); commit('importAds', ads) console.log(`[KetherHomepage] ${events.length} Buy event processed.`); }, async processPublishEvents({ commit }, events) { const updates = events.map((e) => { const [idx, link, image, title, NSFW] = e.args; return {idx: idx.toNumber(), update: {link, image, title, NSFW}} }); commit('updateAds', updates); console.log(`[KetherHomepage] ${events.length} Publish event processed.`); }, async processSetAdOwnerEvents({ state, commit }, events) { const updates = events.map((e) => { const [idx, from, to] = e.args; if (normalizeAddr(to) === normalizeAddr(state.networkConfig.ketherNFTAddr)) { // Only record updated owner if it's not the NFT, otherwise we will get it from the transfer event. return {idx: idx.toNumber(), update: {wrapped: true}}; } else if (normalizeAddr(from) === normalizeAddr(state.networkConfig.ketherNFTAddr)) { // Only record updated owner if it's not the NFT, otherwise we will get it from the transfer event. return {idx: idx.toNumber(), update: {wrapped: false}}; } else { return {idx: idx.toNumber(), update: {owner: to, wrapped: false}}; } }); commit('updateAds', updates); console.log(`[KetherHomepage] ${events.length} SetAdOwner event processed.`); }, async processTransferEvents({ commit }, events) { const updates = events.flatMap((e) => { const [_from, to, idx] = e.args; if (to !== '0x0000000000000000000000000000000000000000') { // Only record updated owner if it's not being burned, otherwise we will get it from the setAdOwner event. return {idx: idx.toNumber(), update: {owner: to, wrapped: true}}; } else { // Skip event return []; } }); commit('updateAds', updates); console.log(`[KetherNFT] ${events.length} Transfer event processed.`); }, } //// Helpers // TODO: Rewrite this into a proper class thing or something, so that there's fewer warnings function grid_array2d(w, h) { const grid = []; grid.length = h; for (let x = 0; x < w; x++) { const row = []; row.length = w; for (let y = 0; y < h; y++) row[y] = 0; grid[x] = row; } return grid; } function filledGrid(grid, ads) { for (let ad of ads) { // Ad properties might be BigNumbers maybe which don't play well with +'s... // TODO: Fix this in a more general way? const x2 = Number(ad.x) + Number(ad.width) - 1; const y2 = Number(ad.y) + Number(ad.height) - 1; setBox(grid, ad.x, ad.y, x2, y2); } return grid; } function setBox(grid, x1, y1, x2, y2) { for (let x = Number(x1); x <= x2; x++) { for (let y = Number(y1); y <= y2; y++) { grid[x][y] = 1; } } } function addAdOwned(state, ad) { if (state.ownedAds[ad.idx] === undefined) { state.pixelsOwned += ad.width * ad.height * 100; } this._vm.$set(state.ownedAds, ad.idx, ad); } function removeAdOwned(state, idx) { this._vm.$delete(state.ownedAds, idx); } // TODO: this is only used when loading with N calls to the contract // delete it now that we have loading via events and the view function toAd(i, r) { return { idx: i, owner: r[0].toLowerCase(), x: Number(r[1]), y: Number(r[2]), width: Number(r[3]), height: Number(r[4]), link: r[5] || "", image: r[6] || "", title: r[7], NSFW: r[8] || r[9], forceNSFW: r[9], } } function appendAd(state, rawAd) { let ad = normalizeAd(rawAd); if (state.accounts[ad.owner]) { addAdOwned.call(this, state, ad); } // If we haven't added this ad before and it's not a Publish event, count the pixels if (ad.width === undefined || state.ads[ad.idx] === undefined) { state.adsPixels += ad.width * ad.height * 100; if (state.grid !== null) { // If the grid is already cached, update to include new ad. // Ad properties might be BigNumbers maybe which don't play well with +'s... // TODO: Fix this in a more general way? const x1 = Number(ad.x); const x2 = x1 + Number(ad.width) - 1; const y1 = Number(ad.y); const y2 = y1 + Number(ad.height) - 1; setBox(state.grid, x1, y1, x2, y2); } } // Force reactivity this._vm.$set(state.ads, ad.idx, ad); return state; } function isSoldOut(state) { return state.adsPixels === 1000000; }
var path=require("path");module.exports=function(e,t){var n=t.moduleDirectory||"node_modules",r="/";/^([A-Za-z]:)/.test(e)?r="":/^\\\\/.test(e)&&(r="\\\\");var i=process.platform==="win32"?/[\/\\]/:/\/+/,s=e.split(i),o=[];for(var u=s.length-1;u>=0;u--){if(s[u]===n)continue;var a=path.join(path.join.apply(path,s.slice(0,u+1)),n);o.push(r+a)}return o.concat(t.paths)};
var set = Ember.set, App, originalAdapter = Ember.Test.adapter; function cleanup(){ Ember.Test.adapter = originalAdapter; if (App) { App.removeTestHelpers(); Ember.run(App, App.destroy); App = null; } Ember.run(function(){ Ember.$(document).off('ajaxStart'); Ember.$(document).off('ajaxStop'); }); Ember.TEMPLATES = {}; } function assertHelpers(application, helperContainer, expected){ if (!helperContainer) { helperContainer = window; } if (expected === undefined) { expected = true; } function checkHelperPresent(helper, expected){ var presentInHelperContainer = !!helperContainer[helper], presentInTestHelpers = !!application.testHelpers[helper]; expect(presentInHelperContainer).toEqual(expected); expect(presentInTestHelpers).toEqual(expected); } checkHelperPresent('visit', expected); checkHelperPresent('click', expected); checkHelperPresent('keyEvent', expected); checkHelperPresent('fillIn', expected); checkHelperPresent('wait', expected); if (Ember.FEATURES.isEnabled("ember-testing-triggerEvent-helper")) { checkHelperPresent('triggerEvent', expected); } } function assertNoHelpers(application, helperContainer) { assertHelpers(application, helperContainer, false); } describe("ember-testing Helpers", function() { beforeEach(function() { cleanup(); }); afterEach(function() { cleanup(); }); it("Ember.Application#injectTestHelpers/#removeTestHelpers", function() { App = Ember.run(Ember.Application, Ember.Application.create); assertNoHelpers(App); App.injectTestHelpers(); assertHelpers(App); App.removeTestHelpers(); assertNoHelpers(App); }); it("Ember.Application#setupForTesting", function() { Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); expect(App.__container__.lookup('router:main').location.implementation).toEqual("none"); }); it("Ember.Application.setupForTesting sets the application to `testing`.", function(){ Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); expect(App.testing).toEqual(true); }); it("Ember.Application.setupForTesting leaves the system in a deferred state.", function(){ Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); expect(App._readinessDeferrals).toEqual(1); }); it("App.reset() after Application.setupForTesting leaves the system in a deferred state.", function(){ Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); expect(App._readinessDeferrals).toEqual(1); App.reset(); expect(App._readinessDeferrals).toEqual(1); }); it("`visit` advances readiness.", function(){ Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); App.injectTestHelpers(); }); expect(App._readinessDeferrals).toEqual(1); App.testHelpers.visit('/').then(function(){ expect(App._readinessDeferrals).toEqual(0); }); }); it("`wait` helper can be passed a resolution value", function() { var promise, wait; promise = new Ember.RSVP.Promise(function(resolve) { Ember.run(null, resolve, 'promise'); }); Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); wait = App.testHelpers.wait; wait('text').then(function(val) { expect(val).toEqual("text"); return wait(1); }).then(function(val) { expect(val).toEqual(1); return wait({ age: 10 }); }).then(function(val) { expect(val).toBeDeepEqual({ age: 10 }); return wait(promise); }).then(function(val) { expect(val).toEqual("promise"); }); }); it("`click` triggers appropriate events in order", function() { var click, wait, events; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.IndexView = Ember.View.extend({ classNames: 'index-view', didInsertElement: function() { this.$().on('mousedown focusin mouseup click', function(e) { events.push(e.type); }); }, Checkbox: Ember.Checkbox.extend({ click: function() { events.push('click:' + this.get('checked')); }, change: function() { events.push('change:' + this.get('checked')); } }) }); Ember.TEMPLATES.index = Ember.Handlebars.compile('{{input type="text"}} {{view view.Checkbox}} {{textarea}}'); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); click = App.testHelpers.click; wait = App.testHelpers.wait; wait().then(function() { events = []; return click('.index-view'); }).then(function() { expect(events).toBeDeepEqual(['mousedown', 'mouseup', 'click']); }).then(function() { events = []; return click('.index-view input[type=text]'); }).then(function() { expect(events).toBeDeepEqual( ['mousedown', 'focusin', 'mouseup', 'click']); }).then(function() { events = []; return click('.index-view textarea'); }).then(function() { expect(events).toBeDeepEqual( ['mousedown', 'focusin', 'mouseup', 'click']); }).then(function() { // In IE (< 8), the change event only fires when the value changes before element focused. Ember.$('.index-view input[type=checkbox]').focus(); events = []; return click('.index-view input[type=checkbox]'); }).then(function() { // i.e. mousedown, mouseup, change:true, click, click:true // Firefox differs so we can't assert the exact ordering here. // See https://bugzilla.mozilla.org/show_bug.cgi?id=843554. expect(events.length).toEqual(5); }); }); it("Ember.Application#injectTestHelpers", function() { var documentEvents; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); documentEvents = Ember.$._data(document, 'events'); if (!documentEvents) { documentEvents = {}; } expect(documentEvents['ajaxStart']).toBeUndefined(); expect(documentEvents['ajaxStop']).toBeUndefined(); App.injectTestHelpers(); documentEvents = Ember.$._data(document, 'events'); expect(documentEvents['ajaxStart'].length).toEqual(1); expect(documentEvents['ajaxStop'].length).toEqual(1); }); it("Ember.Application#injectTestHelpers calls callbacks registered with onInjectHelpers", function(){ var injected = 0; Ember.Test.onInjectHelpers(function(){ injected++; }); Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); expect(injected).toEqual(0); App.injectTestHelpers(); expect(injected).toEqual(1); }); it("Ember.Application#injectTestHelpers adds helpers to provided object.", function(){ var helpers = {}; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(helpers); assertHelpers(App, helpers); App.removeTestHelpers(); assertNoHelpers(App, helpers); }); it("Ember.Application#removeTestHelpers resets the helperContainer's original values", function(){ var helpers = {visit: 'snazzleflabber'}; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(helpers); expect(helpers["visit"]).not.toEqual("snazzleflabber"); App.removeTestHelpers(); expect(helpers["visit"]).toEqual("snazzleflabber"); }); it("`wait` respects registerWaiters", function() { var counter=0; function waiter() { return ++counter > 2; } Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); Ember.Test.registerWaiter(waiter); App.testHelpers.wait().then(function() { expect(waiter()).toBeTrue(); Ember.Test.unregisterWaiter(waiter); expect(Ember.Test.waiters.length).toEqual(0); }); }); it("`wait` waits for outstanding timers", function() { var wait_done = false; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); Ember.run.later(this, function() { wait_done = true; }, 500); App.testHelpers.wait().then(function() { expect(wait_done).toBeTrue(); }); }); it("`wait` respects registerWaiters with optional context", function() { var obj = { counter: 0, ready: function() { return ++this.counter > 2; } }; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); Ember.Test.registerWaiter(obj, obj.ready); App.testHelpers.wait().then(function() { expect(obj.ready()).toBeTrue(); Ember.Test.unregisterWaiter(obj, obj.ready); expect(Ember.Test.waiters.length).toEqual(0); }); }); }); if (Ember.FEATURES.isEnabled('ember-testing-routing-helpers')){ describe("ember-testing routing helpers", function() { beforeEach(function() { cleanup(); Ember.run(function() { App = Ember.Application.create(); App.Router = Ember.Router.extend({ location: 'none' }); App.Router.map(function() { this.resource("posts", function() { this.route("new"); }); }); App.setupForTesting(); }); App.injectTestHelpers(); Ember.run(App, 'advanceReadiness'); }); afterEach(function() { cleanup(); }); it("currentRouteName for '/'", function(){ App.testHelpers.visit('/').then(function(){ expect(App.testHelpers.currentRouteName()).toEqual('index'); expect(App.testHelpers.currentPath()).toEqual('index'); expect(App.testHelpers.currentURL()).toEqual('/'); }); }); it("currentRouteName for '/posts'", function(){ App.testHelpers.visit('/posts').then(function(){ expect(App.testHelpers.currentRouteName()).toEqual('posts.index'); expect(App.testHelpers.currentPath()).toEqual('posts.index'); expect(App.testHelpers.currentURL()).toEqual('/posts'); }); }); it("currentRouteName for '/posts/new'", function(){ App.testHelpers.visit('/posts/new').then(function(){ expect(App.testHelpers.currentRouteName()).toEqual('posts.new'); expect(App.testHelpers.currentPath()).toEqual('posts.new'); expect(App.testHelpers.currentURL()).toEqual('/posts/new'); }); }); }); } describe("ember-testing pendingAjaxRequests", function() { beforeEach(function() { cleanup(); Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.injectTestHelpers(); }); afterEach(function() { cleanup(); }); it("pendingAjaxRequests is incremented on each document ajaxStart event", function() { Ember.Test.pendingAjaxRequests = 0; Ember.run(function(){ Ember.$(document).trigger('ajaxStart'); }); expect(Ember.Test.pendingAjaxRequests).toEqual(1); }); it("pendingAjaxRequests is decremented on each document ajaxStop event", function() { Ember.Test.pendingAjaxRequests = 1; Ember.run(function(){ Ember.$(document).trigger('ajaxStop'); }); expect(Ember.Test.pendingAjaxRequests).toEqual(0); }); it("it should raise an assertion error if ajaxStop is called without pendingAjaxRequests", function() { Ember.Test.pendingAjaxRequests = 0; expectAssertion(function() { Ember.run(function(){ Ember.$(document).trigger('ajaxStop'); }); }); }); }); if (Ember.FEATURES.isEnabled("ember-testing-triggerEvent-helper")) { it("`trigger` can be used to trigger arbitrary events", function() { var triggerEvent, wait, event; Ember.run(function() { App = Ember.Application.create(); App.setupForTesting(); }); App.IndexView = Ember.View.extend({ template: Ember.Handlebars.compile('{{input type="text" id="foo"}}'), didInsertElement: function() { this.$('#foo').on('blur change', function(e) { event = e; }); } }); App.injectTestHelpers(); Ember.run(App, App.advanceReadiness); triggerEvent = App.testHelpers.triggerEvent; wait = App.testHelpers.wait; wait().then(function() { return triggerEvent('#foo', 'blur'); }).then(function() { expect(event.type).toEqual("blur"); expect(event.target.getAttribute("id")).toEqual("foo"); }); }); }
// Copyright (c) Dyoub Applications. All rights reserved. // Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE). (function () { function Service($http, Customer) { this.$http = $http; this.Customer = Customer; } Service.prototype.find = function (rentContractId) { return this.$http.post('/rent-contracts/customer', { id: rentContractId }); }; Service.prototype.saveOrder = function (rentContractCustomer) { return this.$http.post('/rent-contracts/customer/update', { rentContractId: rentContractCustomer.rentContractId, customerId: rentContractCustomer.customerId }); }; Service.prototype.save = function (rentContractCustomer) { var service = this; if (rentContractCustomer.customer) { return this.Customer.save(rentContractCustomer.customer).then(function (response) { rentContractCustomer.customerId = response.data.id; return service.saveOrder(rentContractCustomer); }); } else { return service.saveOrder(rentContractCustomer); } }; angular.module('dyoub.app').service('RentContractCustomer', [ '$http', 'Customer', Service ]); })();
'use strict'; Session.set('add-customers-deposit', 0); Session.set('add-customers-rent', 0); AutoForm.hooks({ addCustomers: { onSuccess: function() { Session.set('add-customers-deposit', 0); Session.set('add-customers-rent', 0); } } }); Template.addCustomers.helpers({ housesAvailable: function() { return db.houses.find({ isRented: false }, { fields: { _id: 1 } }).fetch().length > 0; }, deposit: function() { return +Session.get('add-customers-deposit'); }, rent: function() { return +Session.get('add-customers-rent'); }, }); Template.addCustomers.events({ 'change select[name="house"]': function(event) { var house = db.houses.findOne({ address: event.target.value }, { fields: { deposit: 1, rent: 1 } }); if (house) { Session.set('add-customers-deposit', house.deposit); Session.set('add-customers-rent', house.rent); } else { Session.set('add-customers-deposit', ''); Session.set('add-customers-rent', ''); } }, });
(()=>{ let $=new Formatrix('app://scripts~?/',{ init:{ config:{ locator:{ app:'./rsrc/app/', lib:'../../rsrc/lib/', }, }, // init-preloads use:['lib://webons.io/fx/PageConstructor/0.2.0~?/'], }, }); //************************************************************************> join $.use({ page:'lib://webons.io/fx/PageConstructor/0.2.0~?/', }); //************************************************************************> autorun $.run(function(){ console.log("%c---[app/index]---", "color:#99a;"); $.page.setup.start(); console.log($); console.log($.page); $.page.setup.close(); }); //************************************************************************> public $.pub({ get page(){return $.page;}, init(){ return 'hello world'; } }); //************************************************************************> })();
/* eslint-env mocha */ "use strict"; var assert = require("chai").assert; var proxyquire = require("proxyquire"); var mockStore = require("../mock-store"); describe("raw-transactions/package-raw-transaction", function () { var test = function (t) { it(t.description, function (done) { var store = mockStore(t.state || {}); var packageRawTransaction = proxyquire("../../src/raw-transactions/package-raw-transaction.js", { "../encode-request/package-request": proxyquire("../../src/encode-request/package-request.js", { "./get-estimated-gas-with-buffer": proxyquire("../../src/encode-request/get-estimated-gas-with-buffer.js", { "../wrappers/eth": t.stub.eth, }), }), }); store.dispatch(packageRawTransaction(t.params.payload, t.params.address, t.params.networkID, function (err, packagedRawTransaction) { t.assertions(err, packagedRawTransaction); done(); })); }); }; test({ description: "Gas not specified in payload", params: { payload: { name: "addMarketToBranch", signature: ["int256", "int256"], params: [101010, "0xa1"], to: "0x71dc0e5f381e3592065ebfef0b7b448c1bdfdd68", from: "0xb0b", send: true, }, address: "0xb0b", networkID: "7", }, stub: { eth: { estimateGas: function (p, callback) { assert.deepEqual(p, { from: "0x0000000000000000000000000000000000000b0b", to: "0x71dc0e5f381e3592065ebfef0b7b448c1bdfdd68", data: "0x772a646f0000000000000000000000000000000000000000000000000000000000018a9200000000000000000000000000000000000000000000000000000000000000a1", value: "0x0", }); assert.isFunction(callback); callback(null, "0x123456"); }, }, }, assertions: function (err, packaged) { assert.isNull(err); assert.deepEqual(packaged, { from: "0x0000000000000000000000000000000000000b0b", to: "0x71dc0e5f381e3592065ebfef0b7b448c1bdfdd68", data: "0x772a646f0000000000000000000000000000000000000000000000000000000000018a9200000000000000000000000000000000000000000000000000000000000000a1", gas: "0x16c16b", nonce: 0, value: "0x0", chainId: 7, }); }, }); test({ description: "Gas specified in payload", params: { payload: { name: "addMarketToBranch", signature: ["int256", "int256"], params: [101010, "0xa1"], to: "0x71dc0e5f381e3592065ebfef0b7b448c1bdfdd68", from: "0xb0b", send: true, gas: "0x123457", }, address: "0xb0b", networkID: "7", }, stub: { eth: { estimateGas: assert.fail, }, }, assertions: function (err, packaged) { assert.isNull(err); assert.deepEqual(packaged, { from: "0x0000000000000000000000000000000000000b0b", to: "0x71dc0e5f381e3592065ebfef0b7b448c1bdfdd68", data: "0x772a646f0000000000000000000000000000000000000000000000000000000000018a9200000000000000000000000000000000000000000000000000000000000000a1", gas: "0x123457", nonce: 0, value: "0x0", chainId: 7, }); }, }); });
'use strict'; const EventEmitter = require('events'); const promiseRetry = require('promise-retry'); const CHECK_CONCURRENCY_TIMER = 10000; /** * Class to be used on any emitter error to pass a reason and the current message */ class ErrorMessage extends Error { constructor(message, status, queueMessage) { super(message); this.status = status; this.queueMessage = queueMessage; this.originalAzureError = message; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = (new Error(message)).stack; } } } class DebugMessage { /** * * @param {String} message * @param {Object} metadata */ constructor(message, metadata = null) { this.message = message; this.metadata = metadata; } } /** * Event errors that can be emitted this library */ const ON_ERROR_READ_MESSAGE_FROM_AZURE = 'on_error_read_message_from_azure'; const QUEUE_NOT_FOUND = 'queue_not_found'; const ON_UNLOCK_MESSAGE_FROM_AZURE = 'on_unlock_message_from_azure'; const ON_REMOVE_MESSAGE_FROM_AZURE = 'on_remove_unlock_message_from_azure'; const ON_UNLOCK_MESSAGE_FROM_AZURE_MAX_ATTEMPTS = 'on_unlock_message_from_azure_max_attempts'; const ON_DELETE_MESSAGE_FROM_AZURE_MAX_ATTEMPTS = 'on_delete_message_from_azure_max_attempts'; const MAX_THREADS_EXCEEDED = 'max_threads_exceeded'; /** * Operational errors (to be used with ErrorMessage) */ const AZURE_NO_MESSAGES = 'No messages to receive'; /** * The options argument is an object which maps to the retry module options: * retries: The maximum amount of times to retry the operation. Default is 10. * factor: The exponential factor to use. Default is 2. * minTimeout: The number of milliseconds before starting the first retry. Default is 1000. * maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity. * randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is false. */ const optionRetryPromise = { retries: 3, maxTimeout: 4000, }; /** * Private methods to be used inside this module * getQueueData */ class ServiceBusPrivate { constructor(azureServiceBus) { this.serviceBus = azureServiceBus; this.getQueueData = this.getQueueData.bind(this); this.unlockMessage = this.unlockMessage.bind(this); this.removeMessage = this.removeMessage.bind(this); } /** * @param {Object} azureBus * @param {String} queueName * @result {Object} queueData or null */ getQueueData(queueName) { return new Promise((resolve, reject) => { this.serviceBus.listQueues((err, remoteQueues) => { if (err) { return reject(err); } if (!Array.isArray(remoteQueues)) { return reject(`remoteQueues is not an array: ${remoteQueues}`); } const myQueues = remoteQueues.filter((queue) => { return queue.QueueName === queueName; }); const myQueue = myQueues.length !== 0 ? myQueues[0] : null; return resolve(myQueue); }); }); } unlockMessage(message) { return new Promise((resolve, reject) => { this.serviceBus.unlockMessage(message, (err, data) => { if (err !== null && typeof err === 'object') { if (err.code === '404') { return reject(new ErrorMessage(err, ON_UNLOCK_MESSAGE_FROM_AZURE, message)); } } if (err) { return reject(err); } return resolve(data); }); }); } removeMessage(message) { return new Promise((resolve, reject) => { this.serviceBus.deleteMessage(message, (err, data) => { if (err !== null && typeof err === 'object') { if (err.code === '404') { return reject(new ErrorMessage(err, ON_REMOVE_MESSAGE_FROM_AZURE, message)); } } if (err) { return reject(err); } return resolve(data); }); }); } } class ServiceBusAzureWatcher { constructor(azureServiceBus, queueName, concurrency = 1) { this.serviceBus = azureServiceBus; this.queueName = queueName; this.concurrency = concurrency; this.onMessageCallback = () => {}; this.queueData = null; this.myEmitter = new EventEmitter(); this.sbPrivate = new ServiceBusPrivate(this.serviceBus); /** * state variables to know what action to do in checkConcurrency */ this.isStartRunning = false; this.maxThreadsCreated = 0; /** * stats information */ this.lastReadMessageAt = null; this.lastReadMessage = null; this.lastReadErrorMessage = null; this.lastJobDoneAt = null; this.lastJobDone = null; this.lastJobErrorDone = null; // bind methods this.getWatcherInfo = this.getWatcherInfo.bind(this); this.start = this.start.bind(this); this.startReceivingMessages = this.startReceivingMessages.bind(this); this.checkConcurrency = this.checkConcurrency.bind(this); this.readOneMessage = this.readOneMessage.bind(this); this.onMessage = this.onMessage.bind(this); this.onError = this.onError.bind(this); this.onDebug = this.onDebug.bind(this); } getWatcherInfo() { return ({ isStartRunning: this.isStartRunning, queueName: this.queueName, concurrency: this.concurrency, maxThreadsCreated: this.maxThreadsCreated || -2, queueData: this.queueData || null, currentMessagesInQueue: this.queueData ? (parseInt(this.queueData.CountDetails['d2p1:ActiveMessageCount'], 10) || 0) : -1, history: { onReadOneMessage: { lastReadMessageAt: this.lastReadMessageAt || null, lastReadMessage: this.lastReadMessage || null, lastReadErrorMessage: this.lastReadErrorMessage || null, }, onJobDone: { lastJobDoneAt: this.lastJobDoneAt || null, lastJobDone: this.lastJobDone || null, lastJobErrorDone: this.lastJobErrorDone || null, }, }, }); } /** * Starts reading pool messages from azure * 1. Check if queue exist * 2. Start receiving messages */ start() { this.sbPrivate.getQueueData(this.queueName).then((queueData) => { if (queueData === null) { return this.myEmitter.emit('error', new ErrorMessage(`queue not found: ${this.queueName}`, QUEUE_NOT_FOUND, null)); } this.queueData = queueData; this.startReceivingMessages(); setTimeout(() => { this.myEmitter.emit('debug', new DebugMessage('starting concurrency checker')); this.checkConcurrency(); }, CHECK_CONCURRENCY_TIMER); }).catch((err) => { this.myEmitter.emit('error', 'start_error', new ErrorMessage(err, 'start_error', null)); }); } /** * Special method that must be run each X seconds to check if we have enough messages * to enable the multi option process (call readOneMessage more than once after), scenario: * 1. nodejs run and there is 0 messages in queue * 2. node js just run one process to check if there are messages and pass it to user callback * 3. then, there are a lot of messages in queue * 4. so, it's necessary create max CONCURRENCY process to attendee that requests */ checkConcurrency() { if (this.queueData) { this.sbPrivate.getQueueData(this.queueName).then((queueData) => { if (queueData === null) { setTimeout(() => { this.checkConcurrency(); }, CHECK_CONCURRENCY_TIMER); return this.myEmitter.emit('error', new ErrorMessage(`queue not found: ${this.queueName}`, QUEUE_NOT_FOUND, null)); } this.queueData = queueData; const currentMessagesInQueue = parseInt(queueData.CountDetails['d2p1:ActiveMessageCount'], 10) || 0; if (currentMessagesInQueue === 0) { setTimeout(() => { this.checkConcurrency(); }, CHECK_CONCURRENCY_TIMER); this.maxThreadsCreated = 1; return null; } if (currentMessagesInQueue > this.concurrency && this.maxThreadsCreated < this.concurrency) { while (this.maxThreadsCreated < this.concurrency) { this.maxThreadsCreated = this.maxThreadsCreated + 1; this.readOneMessage(); } } else if (currentMessagesInQueue < this.maxThreadsCreated) { this.maxThreadsCreated = currentMessagesInQueue; } setTimeout(() => { this.checkConcurrency(); }, CHECK_CONCURRENCY_TIMER); }).catch((err) => { this.myEmitter.emit('error', 'start_error', new ErrorMessage(err, 'start_error', null)); setTimeout(() => { this.checkConcurrency(); }, CHECK_CONCURRENCY_TIMER); }); } } /** * Start reading max concurrency messages but putting a small delay * to avoid network bottle necks in azure */ startReceivingMessages() { /** * Variables to keep a small delay between request to avoid network bottlenecks */ let delay = 0; let i = 0; this.isStartRunning = true; this.maxThreadsCreated = 0; /** * If there are no messages in the queue, we tried to read just one message * becasue readOneMessage function has a mechanism to lock for new messages * each X time * 'd2p1:ActiveMessageCount' is the pending messages to be deliver in the queue * (no the number of dead letters) */ const currentMessagesInQueue = parseInt(this.queueData.CountDetails['d2p1:ActiveMessageCount'], 10) || 0; if (currentMessagesInQueue === 0) { this.maxThreadsCreated = this.maxThreadsCreated + 1; return this.readOneMessage(); } /** * If there are messages, try to read them keeping concurrency and * dont create more requests than messages in the queue */ let maxCallsInvoked = -1; while (++ maxCallsInvoked < this.concurrency && maxCallsInvoked < currentMessagesInQueue && this.maxThreadsCreated < this.concurrency) { this.maxThreadsCreated = this.maxThreadsCreated + 1; delay = i + 25; setTimeout(() => { this.readOneMessage(); }, delay); } this.isStartRunning = false; } readOneMessage() { if (this.maxThreadsCreated > this.concurrency) { this.maxThreadsCreated = this.concurrency; this.myEmitter.emit('error', new ErrorMessage(MAX_THREADS_EXCEEDED, MAX_THREADS_EXCEEDED, null)); return; } this.serviceBus.receiveQueueMessage(this.queueName, { isPeekLock: true }, (err, message) => { this.lastReadMessageAt = Date.now(); this.lastReadMessage = message; this.lastReadErrorMessage = err; if (err === AZURE_NO_MESSAGES) { setTimeout(() => { return this.readOneMessage(); }, 500); return; } if (err) { this.myEmitter.emit('error', new ErrorMessage(err, ON_ERROR_READ_MESSAGE_FROM_AZURE, message)); setTimeout(() => { return this.readOneMessage(); }, 500); return; } /** * @param {Object} originalMessage Raw message received from Azure Bus Service * @return {Function} done Function to be called when the user finish to process the given message to * released it (in case of error) or to delete it (in succesful case) */ const done = ((originalMessage) => { this.lastJobDoneAt = Date.now(); this.lastJobDone = originalMessage; return (err) => { /** * After user finish, if exist some error sent by user, unlock the message to be processed again * later by the worker (message will remain in the Azure Bus service) */ if (err) { return promiseRetry((retry, attempts) => { this.myEmitter.emit('debug', new DebugMessage('retry unlockMessage')); return this.sbPrivate.unlockMessage(originalMessage).catch((err) => { this.lastJobErrorDone = err; /** * avoid retry if is a non recoverable error * like unlock invalid or message doesnt exist * */ if (err instanceof ErrorMessage) { this.myEmitter.emit('error', err); return Promise.resolve(); } return retry(err); }); }, optionRetryPromise).then(() => { this.readOneMessage(); }, (err) => { this.lastJobErrorDone = err; this.myEmitter.emit('error', new ErrorMessage(err, ON_UNLOCK_MESSAGE_FROM_AZURE_MAX_ATTEMPTS, message)); this.readOneMessage(); }); } /** * After user finish, if doenst exist any error sent by user, delete the message * from Azure Bus Service */ return promiseRetry((retry, attempts) => { return this.sbPrivate.removeMessage(originalMessage).then((data) => { this.myEmitter.emit('debug', new DebugMessage('messageDeleted', originalMessage)); }).catch((err) => { this.lastJobErrorDone = err; // avoid retry if is a well know error if (err instanceof ErrorMessage) { this.myEmitter.emit('error', err); return Promise.resolve(); } return retry(err); }); }, optionRetryPromise).then(() => { this.readOneMessage(); }, (err) => { this.lastJobErrorDone = err; this.myEmitter.emit('error', new ErrorMessage(err, ON_DELETE_MESSAGE_FROM_AZURE_MAX_ATTEMPTS, message)); this.readOneMessage(); }); }; })(message); this.onMessageCallback(message, done); }); } /** * Mehtod to be invoked after a message received * @param {Function} callback */ onMessage(callback) { this.onMessageCallback = callback; } onError(callback) { this.myEmitter.on('error', callback); } onDebug(callback) { this.myEmitter.on('debug', callback); } } module.exports = ServiceBusAzureWatcher;
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')({ pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del'] }); module.exports = function(options) { gulp.task('partials', function () { return gulp.src([ options.src + '/app/**/*.html', options.tmp + '/serve/app/**/*.html' ]) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true })) .pipe($.angularTemplatecache('templateCacheHtml.js', { module: 'angularCharts', root: 'app' })) .pipe(gulp.dest(options.tmp + '/partials/')); }); gulp.task('html', ['inject', 'partials'], function () { var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false }); var partialsInjectOptions = { starttag: '<!-- inject:partials -->', ignorePath: options.tmp + '/partials', addRootSlash: false }; var htmlFilter = $.filter('*.html'); var jsFilter = $.filter('**/*.js'); var cssFilter = $.filter('**/*.css'); var assets; return gulp.src(options.tmp + '/serve/*.html') .pipe($.inject(partialsInjectFile, partialsInjectOptions)) .pipe(assets = $.useref.assets()) .pipe($.rev()) .pipe(jsFilter) .pipe($.ngAnnotate()) .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify')) .pipe(jsFilter.restore()) .pipe(cssFilter) .pipe($.csso()) .pipe(cssFilter.restore()) .pipe(assets.restore()) .pipe($.useref()) .pipe($.revReplace()) .pipe(htmlFilter) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true, conditionals: true })) .pipe(htmlFilter.restore()) .pipe(gulp.dest(options.dist + '/')) .pipe($.size({ title: options.dist + '/', showFiles: true })); }); // Only applies for fonts from bower dependencies // Custom fonts are handled by the "other" task gulp.task('fonts', function () { return gulp.src($.mainBowerFiles()) .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}')) .pipe($.flatten()) .pipe(gulp.dest(options.dist + '/fonts/')); }); gulp.task('other', function () { return gulp.src([ options.src + '/**/*', '!' + options.src + '/**/*.{html,css,js,styl}' ]) .pipe(gulp.dest(options.dist + '/')); }); gulp.task('clean', function (done) { $.del([options.dist + '/', options.tmp + '/'], done); }); gulp.task('build', ['html', 'fonts', 'other']); };
var User = require('../models/Users'), bcrypt = require('bcrypt'), passport = require('passport'); module.exports = function (app) { app.post('/api/register', function(req, res) { User.register(new User({ username: req.body.username }), req.body.password, function(err, account) { if (err) { return res.status(500).json({err: err}); } passport.authenticate('local')(req, res, function () { return res.status(200).json({status: 'Registration successful!'}); }); }); }); }
(function (app) { 'use strict'; app.controller('menuDetailsCtrl', menuDetailsCtrl); menuDetailsCtrl.$inject = ['$scope', '$location', '$routeParams', '$modal', 'apiService', 'notificationService']; function menuDetailsCtrl($scope, $location, $routeParams, $modal, apiService, notificationService) { $scope.pageClass = 'page-menu'; $scope.movie = {}; $scope.loadingMovie = true; $scope.loadingRentals = true; $scope.isReadOnly = true; $scope.openRentDialog = openRentDialog; $scope.returnMovie = returnMovie; $scope.rentalHistory = []; $scope.getStatusColor = getStatusColor; $scope.clearSearch = clearSearch; $scope.isBorrowed = isBorrowed; function loadMovie() { $scope.loadingMovie = true; apiService.get('/api/menu/details/' + $routeParams.id, null, movieLoadCompleted, movieLoadFailed); } function loadRentalHistory() { $scope.loadingRentals = true; apiService.get('/api/rentals/' + $routeParams.id + '/rentalhistory', null, rentalHistoryLoadCompleted, rentalHistoryLoadFailed); } function loadMovieDetails() { loadMovie(); loadRentalHistory(); } function returnMovie(rentalID) { apiService.post('/api/rentals/return/' + rentalID, null, returnMovieSucceeded, returnMovieFailed); } function isBorrowed(rental) { return rental.Status == 'Borrowed'; } function getStatusColor(status) { if (status == 'Borrowed') return 'red' else { return 'green'; } } function clearSearch() { $scope.filterRentals = ''; } function movieLoadCompleted(result) { $scope.movie = result.data; $scope.loadingMovie = false; } function movieLoadFailed(response) { notificationService.displayError(response.data); } function rentalHistoryLoadCompleted(result) { console.log(result); $scope.rentalHistory = result.data; $scope.loadingRentals = false; } function rentalHistoryLoadFailed(response) { notificationService.displayError(response); } function returnMovieSucceeded(response) { notificationService.displaySuccess('Movie returned to HomeCinema succeesfully'); loadMovieDetails(); } function returnMovieFailed(response) { notificationService.displayError(response.data); } function openRentDialog() { $modal.open({ templateUrl: 'scripts/app/rental/rentMovieModal.html', controller: 'rentMovieCtrl', scope: $scope }).result.then(function ($scope) { loadMovieDetails(); }, function () { }); } loadMovieDetails(); } })(angular.module('myRestaurant'));
'use strict'; /** * @ngdoc overview * @name abraFeApp * @description * # abraFeApp * * Main module of the application. */ angular .module('abraFeApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .when('/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl', controllerAs: 'about' }) .otherwise({ redirectTo: '/' }); });
/* * * Home actions * */ import { GET_COWORKS, GET_COWORKS_SUCCESS, GET_COWORKS_ERROR, } from './constants'; export const getCoworks = () => ({ type: GET_COWORKS }); export const coworksLoaded = (coworks) => ({ type: GET_COWORKS_SUCCESS, coworks }); export const coworksLoadingError = (error) => ({ type: GET_COWORKS_ERROR, error }); export const actions = { getCoworks, coworksLoaded, coworksLoadingError, };
import { expect } from 'chai'; import styleFunctionSx from './styleFunctionSx'; describe('styleFunctionSx', () => { const breakpointsValues = { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, }; const round = (value) => Math.round(value * 1e5) / 1e5; const theme = { spacing: (val) => `${val * 10}px`, breakpoints: { keys: ['xs', 'sm', 'md', 'lg', 'xl'], values: breakpointsValues, up: (key) => { return `@media (min-width:${breakpointsValues[key]}px)`; }, }, unit: 'px', palette: { primary: { main: 'rgb(0, 0, 255)', }, secondary: { main: 'rgb(0, 255, 0)', }, }, typography: { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontWeightLight: 300, fontSize: 14, body1: { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '1rem', letterSpacing: `${round(0.15 / 16)}em`, fontWeight: 400, lineHeight: 1.5, }, body2: { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: `${14 / 16}rem`, letterSpacing: `${round(0.15 / 14)}em`, fontWeight: 400, lineHeight: 1.43, }, }, }; describe('system', () => { it('resolves system ', () => { const result = styleFunctionSx({ theme, sx: { color: 'primary.main', bgcolor: 'secondary.main', m: 2, p: 1, fontFamily: 'default', fontWeight: 'light', fontSize: 'fontSize', maxWidth: 'sm', displayPrint: 'block', border: [1, 2, 3, 4, 5], }, }); expect(result).to.deep.equal({ color: 'rgb(0, 0, 255)', backgroundColor: 'rgb(0, 255, 0)', margin: '20px', padding: '10px', fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontWeight: 300, fontSize: 14, maxWidth: 600, '@media print': { display: 'block', }, '@media (min-width:0px)': { border: '1px solid' }, '@media (min-width:600px)': { border: '2px solid' }, '@media (min-width:960px)': { border: '3px solid' }, '@media (min-width:1280px)': { border: '4px solid' }, '@media (min-width:1920px)': { border: '5px solid' }, }); }); it('resolves system typography', () => { const result = styleFunctionSx({ theme, sx: { typography: ['body2', 'body1'] }, }); expect(result).to.deep.equal({ '@media (min-width:0px)': { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: `${14 / 16}rem`, letterSpacing: `${round(0.15 / 14)}em`, fontWeight: 400, lineHeight: 1.43, }, '@media (min-width:600px)': { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '1rem', letterSpacing: `${round(0.15 / 16)}em`, fontWeight: 400, lineHeight: 1.5, }, }); }); it('allow values to be `null` or `undefined`', () => { const result = styleFunctionSx({ theme, sx: { typography: null, m: 0, p: null, transform: null }, }); expect(result).to.deep.equal({ margin: '0px', }); }); }); it('resolves non system CSS properties if specified', () => { const result = styleFunctionSx({ theme, sx: { background: 'rgb(0, 0, 255)', '&:hover': { backgroundColor: 'primary.main', opacity: { xs: 0.1, sm: 0.2, md: 0.3, lg: 0.4, xl: 0.5, }, translate: ['transform(10px)', 'transform(20px)'], border: [1, 2, 3], borderColor: (t) => [t.palette.secondary.main, t.palette.primary.main], }, }, }); expect(result).to.deep.equal({ background: 'rgb(0, 0, 255)', '&:hover': { backgroundColor: 'rgb(0, 0, 255)', '@media (min-width:0px)': { opacity: 0.1, border: '1px solid', borderColor: 'rgb(0, 255, 0)', translate: 'transform(10px)', }, '@media (min-width:600px)': { opacity: 0.2, border: '2px solid', borderColor: 'rgb(0, 0, 255)', translate: 'transform(20px)', }, '@media (min-width:960px)': { opacity: 0.3, border: '3px solid' }, '@media (min-width:1280px)': { opacity: 0.4 }, '@media (min-width:1920px)': { opacity: 0.5 }, }, }); }); describe('breakpoints', () => { const breakpointsExpectedResult = { '@media (min-width:0px)': { border: '1px solid' }, '@media (min-width:600px)': { border: '2px solid' }, '@media (min-width:960px)': { border: '3px solid' }, '@media (min-width:1280px)': { border: '4px solid' }, '@media (min-width:1920px)': { border: '5px solid' }, }; it('resolves breakpoints array', () => { const result = styleFunctionSx({ theme, sx: { border: [1, 2, 3, 4, 5] }, }); expect(result).to.deep.equal(breakpointsExpectedResult); }); it('resolves breakpoints object', () => { const result = styleFunctionSx({ theme, sx: { border: { xs: 1, sm: 2, md: 3, lg: 4, xl: 5, }, }, }); expect(result).to.deep.equal(breakpointsExpectedResult); }); it('merges multiple breakpoints object', () => { const result = styleFunctionSx({ theme, sx: { m: [1, 2, 3], p: [5, 6, 7] }, }); expect(result).to.deep.equal({ '@media (min-width:0px)': { padding: '50px', margin: '10px' }, '@media (min-width:600px)': { padding: '60px', margin: '20px' }, '@media (min-width:960px)': { padding: '70px', margin: '30px' }, }); }); it('writes breakpoints in correct order', () => { const result = styleFunctionSx({ theme, sx: { m: { md: 1, lg: 2 }, p: { xs: 0, sm: 1, md: 2 } }, }); // Test the order expect(Object.keys(result)).to.deep.equal([ '@media (min-width:0px)', '@media (min-width:600px)', '@media (min-width:960px)', '@media (min-width:1280px)', ]); expect(result).to.deep.equal({ '@media (min-width:0px)': { padding: '0px' }, '@media (min-width:600px)': { padding: '10px' }, '@media (min-width:960px)': { padding: '20px', margin: '10px' }, '@media (min-width:1280px)': { margin: '20px' }, }); }); }); describe('theme callback', () => { it('works on CSS properties', () => { const result = styleFunctionSx({ theme, sx: { background: (t) => t.palette.primary.main, }, }); // Test the order expect(result).to.deep.equal({ background: 'rgb(0, 0, 255)' }); }); it('works on pseudo selectors', () => { const result = styleFunctionSx({ theme, sx: { ':hover': (t) => ({ background: t.palette.primary.main }), }, }); // Test the order expect(result).to.deep.equal({ ':hover': { background: 'rgb(0, 0, 255)' } }); }); it('works on nested selectors', () => { const result = styleFunctionSx({ theme, sx: { '& .test-classname': (t) => ({ background: t.palette.primary.main }), }, }); // Test the order expect(result).to.deep.equal({ '& .test-classname': { background: 'rgb(0, 0, 255)' } }); }); }); describe('`sx` of function type', () => { it('resolves system padding', () => { const result = styleFunctionSx({ theme, sx: () => ({ p: 1, }), }); expect(result).to.deep.equal({ padding: '10px', }); }); it('resolves theme object', () => { const result = styleFunctionSx({ theme, sx: (userTheme) => userTheme.typography.body1, }); expect(result).to.deep.equal({ fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '1rem', letterSpacing: `${round(0.15 / 16)}em`, fontWeight: 400, lineHeight: 1.5, }); }); it('resolves a mix of theme object and system padding', () => { const result = styleFunctionSx({ theme, sx: (userTheme) => ({ p: 1, ...userTheme.typography.body1 }), }); expect(result).to.deep.equal({ padding: '10px', fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '1rem', letterSpacing: `${round(0.15 / 16)}em`, fontWeight: 400, lineHeight: 1.5, }); }); }); describe('`sx` of array type', () => { it('resolves system props', () => { const result = styleFunctionSx({ theme, sx: [ { bgcolor: 'background.paper', boxShadow: 1, borderRadius: 1, p: 2, minWidth: 300, }, { bgcolor: 'primary.main', }, ], }); expect(result).to.deep.equal([ { backgroundColor: 'background.paper', borderRadius: 4, boxShadow: 1, minWidth: 300, padding: '20px', }, { backgroundColor: 'rgb(0, 0, 255)', }, ]); }); it('works with function inside array', () => { const result = styleFunctionSx({ theme, sx: [ { bgcolor: 'primary.main' }, (t) => ({ borderRadius: t.spacing(1), }), ], }); expect(result).to.deep.equal([ { backgroundColor: 'rgb(0, 0, 255)' }, { borderRadius: '10px' }, ]); }); it('works with media query syntax', () => { const result = styleFunctionSx({ theme, sx: [{ border: [1, 2, 3, 4, 5] }, { m: [1, 2, 3], p: [5, 6, 7] }], }); expect(result).to.deep.equal([ { '@media (min-width:0px)': { border: '1px solid' }, '@media (min-width:600px)': { border: '2px solid' }, '@media (min-width:960px)': { border: '3px solid' }, '@media (min-width:1280px)': { border: '4px solid' }, '@media (min-width:1920px)': { border: '5px solid' }, }, { '@media (min-width:0px)': { padding: '50px', margin: '10px' }, '@media (min-width:600px)': { padding: '60px', margin: '20px' }, '@media (min-width:960px)': { padding: '70px', margin: '30px' }, }, ]); }); it('does not crash if the result is undefined', () => { expect(() => styleFunctionSx({ theme, sx: [(t) => t.typography.unknown], }), ).not.to.throw(); }); }); });
'use strict'; //Setting up route angular.module('topics').config(['$stateProvider', function($stateProvider) { // Topics state routing $stateProvider. state('listTopics', { url: '/topics', templateUrl: 'modules/topics/views/list-topics.client.view.html' }). state('createTopic', { url: '/topics/create', templateUrl: 'modules/topics/views/create-topic.client.view.html' }). state('viewTopic', { url: '/topics/:topicId', templateUrl: 'modules/topics/views/view-topic.client.view.html' }). state('editTopic', { url: '/topics/:topicId/edit', templateUrl: 'modules/topics/views/edit-topic.client.view.html' }); } ]);
'use strict'; var exec = require('child_process').exec; module.exports = function remote (cb) { exec('git remote -v', function (err, stdout, stderr) { if (err) return cb(err.stack); if (stderr) return cb(stderr); var m = stdout.match( /origin\s+(?:git@github\.com:|(?:https?|git):\/\/(?:.+@)?github\.com\/)(\S+)/ ); if (!m) return cb('no github remote found'); cb(null, m[1].replace(/\.git$/, '')); }); };
function construtorObser() { var obj = {} obj.listaObser = obj.listaObser || []; obj.contador = obj.contador || 0; obj.addListener = function(evento) { this.listaObser.push(evento); }; obj.execEventos = function() { this.contador++; for (var i = 0; i < this.listaObser.length; i++) { this.listaObser[i](); } } return obj; } var obser = construtorObser(); var evento1 = function () { console.log("evento 1") }; obser.addListener(evento1); obser.execEventos(); console.log(obser.contador); var evento2 = function () { console.log("evento 2") }; obser.addListener(evento2); obser.execEventos(); console.log(obser.contador);
var uuid = require('node-uuid'); var gapiUtil = require('./util/gapi-util'); var l = require("./logger"); var status = require('./status'); var config = require('./config'); var prefs = require('./prefs'); var exportTimer = require('./export-timer'); var driveUtil = require('./drive-util'); var drive = require('./drive'); var about = require('./about'); var Tree = require('./Tree'); var shared = require('./shared'); var exporter = require('./exporter'); var appUtil = require('./app-util'); var SESSION_TIMEOUT_MS = 1000 * 60 * 60.0; var postMethods = {}; var sessionId; var lastActivity; exports.handlePost = function(request, response) { // rem, if the browser cookie expires, it will be empty var browserSessionId = request.cookies.sessionId ? request.cookies.sessionId : ''; var action = request.body.action; l.i('[SERVICE]', '[host]', request.headers.host, '[request url]', request.url, '[action]', action); // debugging info // var sb = browserSessionId.substr(0, 3); // var ss = sessionId ? sessionId.substr(0, 3) : '-'; // var min = (new Date().getTime() - lastActivity) / 1000 / 60; // l.i('[SERVICE]', '[browser sid]', sb, '[server sid]', ss, '[minutes since last request]', min); var sessionsMatch = sessionId && sessionId == request.cookies.sessionId; var timedOut = new Date().getTime() - lastActivity > SESSION_TIMEOUT_MS; // separate treatment for login if (action == 'login') { if (!sessionId || timedOut || sessionsMatch) { return login(request, response); } else { var dontAllowSessionOverwrite = false; // it's probably impractical to not allow this... if (dontAllowSessionOverwrite) { return appUtil.sendResponse(response, null, 'A session is already in progress'); } else { return login(request, response); } } } if (timedOut) return appUtil.sendResponse(response, null, 'Session expired'); if (! sessionsMatch) return appUtil.sendResponse(response, null, 'Session mismatch'); // at this point, we know it's a legal logged-in user routePost(action, request, response); }; var routePost = function (action, request, response) { for (var s in postMethods) { if (action == s) { lastActivity = new Date().getTime(); var method = postMethods[s]; return method(request, response); } } // no match appUtil.sendResponse(response, null, 'Bad request'); }; /** * Client expects most all responses to send as much 'state' as possible: * - prefs object * - status object * - simpleFolderList (must be authorized and have drive data) * - simpleFileList (must be authorized, have drive data, and have a selected base folder) */ makeStateObject = function() { var o = {}; o.prefs = prefs.objectForService(); o.status = status.objectForService(); // rem, these two lists are just so the client make dropdowns // they are not needed internally for the export step if (drive.simpleFolderList()) { o.simpleFolderList = drive.simpleFolderList(); } if (prefs.driveBaseFolderId() && shared.tree() && shared.tree().simpleFileList()) { o.simpleFileList = shared.tree().simpleFileList(); } return o; }; // --------------------------------------------------------------------------------------------------------------------- // POST METHODS var login = function (request, response) { var un = request.body.un; // unused (just for show) var pw = request.body.pw; if (pw != config.password()) { return appUtil.sendResponse(response, null, 'No'); } sessionId = uuid.v4(); lastActivity = new Date().getTime(); l.i("[SERVICE] USER LOGGED IN ", sessionId); response.cookie('sessionId', sessionId, { maxAge: SESSION_TIMEOUT_MS }); appUtil.sendResponse(response, makeStateObject()); }; postMethods.logout = function (request, response) { sessionId = ''; l.i("[SERVICE] USER LOGGED OUT ", sessionId); // erase cookie of session id response.cookie('sessionId', sessionId, { maxAge: -1 }); appUtil.sendResponse(response, {} ); }; /** * Client sends id and secret, as well as the redirect url (which is the url of the page itself!) * Server inits the oauthclient, and sends back the encoded consent url */ postMethods.startAuth = function (request, response) { if (status.isExporting) { // shouldn't happen return appUtil.sendResponse(response, null, 'Server is currently exporting'); } var clientId = request.body.id; var clientSecret = request.body.secret; var redirectUrl = request.body.redirectUrl if (! clientId || ! clientSecret || ! redirectUrl) { return appUtil.sendResponse(response, null, 'Missing value/s'); } // save gapi settings var isDifferentClientId = (clientId != prefs.googleApiClientId()); prefs.setGoogleApiClientId(clientId); prefs.setGoogleApiClientSecret(clientSecret); prefs.setGoogleApiRedirectUrl(redirectUrl); if (isDifferentClientId) { prefs.setDriveBaseFolderId(null); prefs.setDriveDefaultDocumentId(null); } prefs.save(); // clear 'state' exportTimer.stop(); status.resetExportStatus(); shared.setTree(null); // init oauth client with new settings gapiUtil.initOauthClient(clientId, clientSecret, redirectUrl); var o = makeStateObject(); o.consentUrl = gapiUtil.consentUrl( config.driveScopeUrl() ); l.v('startAuth - consentUrl:', o.consentUrl); appUtil.sendResponse(response, o); }; // Client has gone to Google consent page, come back, and is sending server the auth code. // postMethods.setCode = function (request, response) { if (! request.body.value) return appUtil.sendResponse(response, null, 'No code received'); var onResult = function (err, refreshToken) { if (err) return appUtil.sendResponse(response, null, err.toString()); prefs.setRefreshToken(refreshToken); prefs.save(); appUtil.sendResponse(response, makeStateObject()); }; gapiUtil.authorizeWithCallbackCode(request.body.value, onResult); }; postMethods.deauth = function (request, response) { if (! prefs.refreshToken()) return appUtil.sendResponse(response, null, 'Nothing to revoke'); var cb = function (errorDesc) { if (errorDesc) return appUtil.sendResponse(response, null, errorDesc); l.v('deauth success'); prefs.setRefreshToken(null); prefs.setDriveBaseFolderId(null); prefs.setDriveDefaultDocumentId(null); prefs.save(); gapiUtil.clearOauthClient(); exportTimer.stop(); appUtil.sendResponse(response, makeStateObject()); }; gapiUtil.revokeToken(prefs.refreshToken(), cb); }; postMethods.getState = function (request, response) { appUtil.sendResponse(response, makeStateObject()); }; postMethods.getStatus = function (request, response) { // send only the status object (client is requesting status on a quick interval) var o = { status: status.objectForService() }; appUtil.sendResponse(response, o); }; // Gets the full files list for drive // postMethods.getDriveDataAndMakeTree = function (request, response) { var onResponse = function (error) { if (error) { if (error == 'invalid_grant') { // a more user-friendly error message error = "Bad refresh token. You will need to re-authorize your Google API account."; } return appUtil.sendResponse(response, null, error); } appUtil.sendResponse(response, makeStateObject() ); }; driveUtil.getDriveDataAndMakeTree(onResponse); }; postMethods.setBaseFolderId = function (request, response) { // prereq check if (! drive.data()) return appUtil.sendResponse(response, null, 'Drive data required'); var id = request.body.value; if (! id) return appUtil.sendResponse(response, null, 'id required'); var o = drive.findItemById(id); if (! o) return appUtil.sendResponse(response, null, 'No such folder'); // prefs.setDriveBaseFolderId(id); prefs.setDriveDefaultDocumentId(''); prefs.save(); // we can now make the file structure var tree = Tree.makeFromDriveData(o, prefs.mimeTypesToExport(), drive.data()); shared.setTree(tree); appUtil.sendResponse(response, makeStateObject()); }; postMethods.setDefaultDocumentId = function (request, response) { // prereq check if (! drive.data()) { return appUtil.sendResponse(response, null, 'Drive data required'); } if (! shared.tree() || ! shared.tree().simpleFileList()) { return appUtil.sendResponse(response, null, 'Tree not set'); } var id = (! request.body.value || request.body.value == 'none') ? '' : request.body.value; if (id.length > 0 && ! shared.tree().hasFileItemWithId(id)) return appUtil.sendResponse(response, null, 'No such document'); prefs.setDriveDefaultDocumentId(id); prefs.save(); appUtil.sendResponse(response, makeStateObject()); }; postMethods.setWikiTitle = function (request, response) { prefs.setWikiTitle(request.body.value || ''); prefs.save(); appUtil.sendResponse(response, makeStateObject()); }; postMethods.setRefreshIntervalCode = function (request, response) { var value = request.body.value; var ok = (value >= -1 && value < prefs.REFRESH_INTERVAL_HOURS.length); if (! ok) return appUtil.sendResponse(response, null, 'Bad value'); prefs.setRefreshIntervalCode(value); prefs.save(); exportTimer.setWithCode(value); appUtil.sendResponse(response, makeStateObject()); }; postMethods.exportWiki = function (request, response) { if (status.isGenerating) { return appUtil.sendResponse(response, null, 'Service is already generating files'); } // Immediately send a response; client will start polling for status appUtil.sendResponse(response, makeStateObject()); // Start exporting exporter.exportWiki(); }; /** * Debugging */ postMethods.wait = function (request, response) { setTimeout(function() { appUtil.sendResponse(response, makeStateObject()); }, 2500); };
// // # Mongodb GridFs API Endpoint // var ObjectID = mongo.ObjectID; (exports = module.exports = function(house, options){ // This endpoint requires a data source var ds = options.ds; var filesRoot = ds.options.filesCol || options.collection; var col = filesRoot+'.files'; var usersCol = 'users'; var imagesCol = 'images'; var tagsCol = options.collectionTags || 'tags'; var ensureIndexes = function() { var collection = ds.db.collection(col); collection.ensureIndex({"uploadDate": -1}, function(){ house.log.debug('index ensured for files uploadDate'); }); }; if(!house.config.forkedFeedFetcher) { ds.connected(function(){ ensureIndexes(); }); } var updateFileId = function(fileId, updateFileDoc, callback) { ds.update(col, {"_id": fileId}, updateFileDoc, function(err, updateData) { if(err) { callback(err); } else { ds.find(col, {"_id": fileId}, function(err, updatedFile) { if(err) { callback(err); } else { if(updatedFile.length > 0) { if(callback) { callback(null, _.first(updatedFile)); } } } }); } }); } var updateUserIdWithDoc = function(userId, doc, cb) { ds.update(usersCol, {_id: userId}, doc, function(err, data) { if(err) { console.log(err); } else { if(cb) cb(); } }); } var incUserFileBytes = function(userId, b) { var updateDoc = {"$inc":{"fileBytes": b}}; updateUserIdWithDoc(userId, updateDoc); } var incUserFileCount = function(userId, c) { var updateDoc = {"$inc":{"fileCount": c}}; updateUserIdWithDoc(userId, updateDoc); } var handleReq = function(req, res, next) { var path = req.hasOwnProperty('urlRouted') ? req.urlRouted : req.url; var feedEndPoint = house.api.getEndPointByName("feed"); var parseQuery = function(query) { if(query.contentType && query.contentType.indexOf('/') === 0) { var opts = query.contentType.substr(query.contentType.lastIndexOf('/')+1); query.contentType = new RegExp(query.contentType.substr(1, query.contentType.lastIndexOf('/')-1), opts); } if(query.filename && query.filename.indexOf('/') === 0) { var opts = query.filename.substr(query.filename.lastIndexOf('/')+1); query.filename = new RegExp(query.filename.substr(1, query.filename.lastIndexOf('/')-1), opts); } if(query.hasOwnProperty('metadata.proc[$exists]')) { if(query['metadata.proc[$exists]'] == 'false') { query['metadata.proc'] = {"$exists": false}; } else { query['metadata.proc'] = {"$exists": true}; } delete query['metadata.proc[$exists]']; } if(query.hasOwnProperty('metadata.fav') && (query['metadata.fav'] === 'true' || query['metadata.fav'] === '1')) { query['metadata.fav'] = true; } if(query.hasOwnProperty('metadata.tags')) { query["metadata.tags.name"] = query["metadata.tags"]; delete query["metadata.tags"]; } if(req.session.data.groups && req.session.data.groups.indexOf('admin') !== -1) { if(query.hasOwnProperty('metadata.owner.id')) { query["metadata.owner.id"] = new ObjectID(query["metadata.owner.id"]); } } else { if(req.session.data.user) { if(query.hasOwnProperty('metadata.owner.id')) { query["metadata.owner.id"] = new ObjectID(query["metadata.owner.id"]); query["metadata.groups"] = 'public'; } else { query["metadata.owner.id"] = req.session.data.user; } } else { if(query.hasOwnProperty('metadata.owner.id')) { query["metadata.owner.id"] = new ObjectID(query["metadata.owner.id"]); } query["metadata.groups"] = 'public'; } } return query; } var countQuery = function(query) { query = parseQuery(query); ds.count(col, query, function(err, data){ if(err) { house.log.err(err); } else { res.setHeader('X-Count', data); res.data({}); } }); } var findQuery = function(query, callback) { if(query.id) { query._id = query.id; delete query.id; } if(query.hasOwnProperty('_id') && typeof query._id == 'string') { try { query._id = new ObjectID(query._id); } catch(e) { console.log('bad object id'); } } if(query.limit) { query.limit = parseInt(query.limit, 10); } if(!query.limit || query.limit > 1000) { query.limit = 25; } query = parseQuery(query); ds.find(col, query, function(err, data){ if(err) { house.log.err(err); } else if(data) { res.data(data); } else { house.log.err(new Error('no data from mongo')); } }); } var insertDocToFeed = function(doc, callback) { var newFeedItem = { "ref": {"col": "files", "id": doc.id}, "file": doc, "groups": doc.groups, "owner": doc.owner, "at": doc.at, } feedEndPoint({session: req.session, method: 'POST', url: '', fields: newFeedItem}, {end:function(){}, data:function(newFeedData){ if(_.isArray(newFeedData)) { newFeedData = _.first(newFeedData); } ds.update(col, {"_id": doc.id}, {"$set": {"feed": {id:newFeedData.id,at:newFeedData.at}}}, function(err, data) { if(callback) { callback(newFeedData); } }); },writeHead:function(){}}); } var updateDocInFeed = function(doc) { var updateDoc = { "$set": { "file": doc, "groups": doc.groups, "owner": doc.owner, "at": doc.at, } } feedEndPoint({session: req.session, method: 'PUT', url: '/'+doc.feed.id, fields: updateDoc}, {end:function(){}, data:function(newFeedData){ if(_.isArray(newFeedData)) { newFeedData = _.first(newFeedData); } },writeHead:function(){}}); } var removeDocFromFeed = function(doc) { if(doc.feed && doc.feed.id) { feedEndPoint({session: req.session, method: 'DELETE', url: '/'+doc.feed.id, fields: {delete: true}}, {end:function(){}, data:function(newFeedData){ },writeHead:function(){}}); } else if(doc.id) { var feedQuery = {"ref": {"col": "files", "id": doc.id}}; ds.find('feed', feedQuery, function(err, data) { _.each(data, function(e) { var doc_Id = e.id; house.io.rooms.in('feed').emit('deletedFeed', doc_Id); }); ds.remove('feed', feedQuery, function(err, data) { }); }); } } var docId; var query = req.query || {}; var subPath = false; var tagsStr = 'metadata.tags'; var tagsPrefix = '/' + tagsStr; var srcPostfix = '/src'; // console.log(query) // ex. api/files/[filename] // ex. api/files/[file_id]/metadata.tags // ex. api/files/[file_id]/metadata.tags/[tag_id] // console.log(path.indexOf(srcPostfix)) // console.log(path.length); // console.log(srcPostfix.length); if(path.length > 1 && (path.indexOf(tagsPrefix) !== -1)) { docId = path.substr(1, path.indexOf(tagsPrefix)); var subSlashI = docId.lastIndexOf('/'); if(subSlashI !== -1) { docId = docId.substr(0, subSlashI); docId = new ObjectID(docId); subPath = path.substr(subSlashI + 1); } else { // docId = new ObjectID(docId); } house.log.debug('files endpoint - subPath: '+subPath); } else if(path.length > 1 && path.indexOf(srcPostfix) === path.length - srcPostfix.length) { docId = path.substr(1, path.indexOf(srcPostfix)); var subSlashI = docId.lastIndexOf('/'); if(subSlashI !== -1) { docId = docId.substr(0, subSlashI); docId = new ObjectID(docId); subPath = path.substr(subSlashI + 1); } else { // docId = new ObjectID(docId); } house.log.debug('files endpoint - src path: '+subPath); } if(req.method == 'GET' || req.method == 'HEAD') { // console.log(path); if(path === '' || path === '/' || path.substr(0,1) === '?') { if(subPath && subPath === tagsPrefix) { house.log.debug('tag subpath'); query._id = docId; ds.find(col, query, function(err, data) { if(err) { house.log.err(err); } else if(data) { res.data(_.first(data).metadata.tags); } else { house.log.err(new Error('no data from mongo')); } }); } else { // console.log('query') // console.log(query) if(req.method == 'HEAD') { countQuery(query); } else { findQuery(query); } } } else { var filename = decodeURIComponent(path.substr(1)); mongo.GridStore.exist(ds.db, filename, filesRoot, function(err, result) { if(result) { house.utils.media.gridfs.getReadableFile(ds.db, filesRoot, filename).open(function(err, gs){ if(err) { house.log.err('err house.utils.media.gridfs.getReadableFile'); house.log.err(err); return; } var resCode = 200; var offset = 0; var etag = '"'+gs.length+'-'+gs.uploadDate+'"'; var headerFields = { 'Content-Type': gs.contentType , 'Date': gs.uploadDate , 'ETag': etag }; // check for permission to the file var hasPermission = false; var meta = gs.metadata; if(meta) { if(req.session.data.user && req.session.data.groups && req.session.data.groups.indexOf('admin') !== -1) { hasPermission = true; } else if(req.session.data.user && meta.hasOwnProperty('owner') && (meta.owner.id.toString() == req.session.data.user.toString())) { hasPermission = true; } else if(meta.hasOwnProperty('groups')) { if(meta.groups && meta.groups.indexOf('public') != -1) { hasPermission = true; } else if(req.session.data.hasOwnProperty('groups')) { if(req.session.data.groups.indexOf('admin') !== -1) { hasPermission = true; } else if(meta.groups) { for(var g in meta.groups) { var group = meta.groups[g]; if(req.session.data.groups.indexOf(group) !== -1) { hasPermission = true; break; } } } } } } if(!hasPermission) { // throw them out var name = req.session.data ? req.session.data.name : ''; house.log.debug('user '+name+' does not have permission to: '+gs.filename); //house.log.debug(req.session.data); if(meta) { //house.log.debug(meta); } next(); return; } if(req.method == 'HEAD') { //console.log('HEAD'); headerFields["Content-Length"] = gs.length; headerFields["Accept-Ranges"] = 'bytes'; gs.close(function(){ //house.log.debug('gridstore closed'); res.writeHead(200, headerFields); res.end(''); }); return; } if(req.headers['if-none-match'] == etag){ resCode = 304; headerFields['Content-Length'] = 0; gs.close(function(){ res.writeHead(resCode, headerFields); res.end(); }); return; } var contentLen = gs.length; var bytStr = 'bytes='; var chunkSize = 4096 , lengthRemaining = gs.length; if(req.headers.range && req.headers.range.substr(0,bytStr.length) == bytStr) { house.log.debug('range '+req.headers.range); var rangeString = ''; var bytSelection = req.headers.range.substr(bytStr.length); var bytDashPos = bytSelection.indexOf('-'); var bytPreDash = bytSelection.substr(0, bytDashPos); var bytEndDash = bytSelection.substr(bytDashPos+1); resCode = 206; delete headerFields['ETag']; if(bytPreDash == '0') { if(bytEndDash) { var reqRangeLen = parseInt(bytEndDash); if(reqRangeLen > contentLen) { house.log.debug('accept asking for invalid range') rangeString = bytPreDash + '-' + (contentLen-1); } else { contentLen = reqRangeLen+1; rangeString = bytPreDash + '-' + bytEndDash; } } else { rangeString = '0-' + (gs.length-1).toString(); } } else if(bytEndDash != '' && bytPreDash != '') { contentLen = (parseInt(bytEndDash)+1) - parseInt(bytPreDash); offset = parseInt(bytPreDash); rangeString = bytPreDash + '-' + bytEndDash; } else if(bytEndDash == '' && bytPreDash != '') { // ex, 1234- contentLen = contentLen - parseInt(bytPreDash); offset = parseInt(bytPreDash) - 1; rangeString = bytPreDash + '-' + (gs.length - 1).toString(); } headerFields["Content-Range"] = 'bytes ' + rangeString+'/'+gs.length; // needs to always be the full content length? // req.headers.range; //bytSelection; // should include bytes= ??? headerFields["Vary"] = "Accept-Encoding"; lengthRemaining = contentLen; } house.log.debug(resCode+' '+filename+' as: '+gs.contentType+' with length: ' + contentLen, resCode); headerFields["Content-Length"] = contentLen; //headerFields["Accept-Ranges"] = 'bytes'; // enables scrubbing in chrome //house.log.debug(headerFields); res.writeHead(resCode, headerFields); if(lengthRemaining < chunkSize) { chunkSize = lengthRemaining; } var gridStoreReadChunk = function(gs) { var readAndSend = function(chunk) { gs.read(chunk, function(err, data) { if(err) { house.log.err('file read err: '+filename); house.log.err(err); gs.close(function(){ //house.log.debug('gridstore closed'); }); res.end(); return; } else { res.write(data, 'binary'); lengthRemaining = lengthRemaining - chunk; if(lengthRemaining < chunkSize) { chunkSize = lengthRemaining; } } if(lengthRemaining == 0) { // close the gridstore gs.close(function(){ //house.log.debug('gridstore closed'); }); res.end(); } else { readAndSend(chunkSize); } }); // read } if(chunkSize > 0) { readAndSend(chunkSize); } } if(offset != 0) { gs.seek(offset, function(err, gs) { if(err) { house.log.err('err'); } gridStoreReadChunk(gs); }); } else { gridStoreReadChunk(gs); } }); } else { if(err) { house.log.err(err); res.end('error'); } else { try { var fid = new ObjectID(filename); findQuery({_id: fid}); } catch(e) { if(req.query && path.indexOf('?') === 0) { if(req.method == 'HEAD') { countQuery(req.query); } else { findQuery(req.query); } } else { console.log(e); res.end('file does not exist'); } } //res.end('file does not exist'); } } }); } } else if(req.method == 'POST') { if(subPath && subPath === tagsPrefix) { house.log.debug('files endpoing POST to tags'); var newObject = req.fields; console.log(newObject) if(!newObject.title) { newObject.title = newObject.name; } newObject.name = house.utils.string.slugify(newObject.name); var findOrInsertTag = function(tag, callback) { var tagQuery = { name: tag.name, "user.id": req.session.data.user } ds.find(tagsCol, tagQuery, function(err, data){ if(err) { callback(err); } else if(data) { if(data.length > 0) { var doc = _.first(data); ds.update(tagsCol, {_id: doc.id}, {$inc:{"filesCount": 1}}, function(err, data){ }); callback(null, doc); } else { newObject.filesCount = 1; newObject.at = new Date(); newObject.user = { id: req.session.data.user, name: req.session.data.name } ds.insert(tagsCol, newObject, function(err, data){ if(err) { callback(err); } else if(data) { ds.find(tagsCol, tagQuery, function(err, data){ if(err) { callback(err); } else if(data) { if(data.length > 0) { callback(null, _.first(data)); } } }); } }) } } }); } findOrInsertTag(newObject, function(err, tag){ if(err) { } else if(tag) { delete tag.user; delete tag.at; var query = {}; if(docId) { query._id = docId; ds.update(col, query, {$push: {"metadata.tags": tag}}, function(err, data){ res.data(tag); }); } } }); newObject.at = new Date(); //console.log(req.session.data); return; } house.log.debug('POST to files (upload)'); var procFile = function(file, callback) { var fileMeta = {}; if(req.hasOwnProperty('fields') && req.fields.hasOwnProperty('metadata')) { try { var meta = JSON.parse(req.fields.metadata); for(var meta_field in meta) { fileMeta[meta_field] = meta[meta_field]; } } catch(e) { house.log.err(e); } } if(req.session.data) { var owner = { id: req.session.data.user, name: req.session.data.name } fileMeta.owner = owner; house.utils.media.gridfs.importFile(ds.db, filesRoot, 'uploads/'+file.filename, file.path, file.type, fileMeta, function(err, gridStore){ house.log.debug('--post to files complete'); //console.log(gridStore) var data = house.utils.media.gridfs.getDocFromGridStore(gridStore); if(err) { house.log.err('--file upload err'); house.log.err(err); } else { // inc users fileBytes incUserFileBytes(owner.id, data.length); // inc users fileCount incUserFileCount(owner.id, 1); if(data.contentType.indexOf('audio') === 0) { //console.log('proces audio upload'); house.utils.media.exif.getFromPath(file.path).result(function(exif){ //console.log('metadata'); //console.log(exif); var fileMeta = { } var newSong = { file_id: data.id, filename: data.filename, ss: '' } if(exif.Title) { fileMeta['metadata.title'] = exif.Title; newSong.title = exif.Title; newSong.ss += exif.Title; } if(exif.Album) { fileMeta['metadata.album'] = exif.Album; newSong.album = exif.Album; newSong.ss += ' '+exif.Album; } if(exif.Artist) { fileMeta['metadata.artist'] = exif.Artist; newSong.artist = exif.Artist; newSong.ss += ' '+exif.Artist; } if(exif.Year) { newSong.year = exif.Year; } if(exif.Genre) { newSong.genre = exif.Genre; } if(exif.Duration) { fileMeta['metadata.duration'] = house.utils.media.exif.getDurationTime(exif.Duration); newSong.duration = house.utils.media.exif.getDurationTime(exif.Duration); } if(exif.Lyrics) { newSong.lyrics = exif.Lyrics; } if(exif.Track) { newSong.trackSeq = exif.Track; } // picture // track // lyrics // user uploading the song newSong.owner = owner; ds.insert('songs', newSong, function(err, songData) { //console.log('new song!'); if(_.size(fileMeta) > 0) { updateFileId(data.id, {"$set": fileMeta}, function(err, updatedFileDoc){ if(err) { house.log.err(err); } else if(updatedFileDoc) { console.log('updated file doc with song metadata'); console.log(updatedFileDoc); house.ioi.emitDocToRoomOwnerGroup('files', 'inserted', updatedFileDoc, updatedFileDoc.metadata.owner.id, updatedFileDoc.metadata.groups); callback({song: songData, file: updatedFileDoc}); } }); } else { house.ioi.emitDocToRoomOwnerGroup('files', 'inserted', data, data.metadata.owner.id, data.metadata.groups); callback({song: songData, file: data}); } }); }); } else if(data.contentType.indexOf('image') === 0) { house.utils.media.exif.getFromPath(file.path, function(exif){ processImage(data, exif, function(newImageData, updatedFile){ // house.ioi.emitDocToRoomOwnerGroup('images', 'inserted', newImageData, updatedFile.metadata.owner.id, updatedFile.metadata.groups); house.ioi.emitDocToRoomOwnerGroup('files', 'inserted', updatedFile, updatedFile.metadata.owner.id, updatedFile.metadata.groups); callback({image: newImageData, file: updatedFile}); }); }); } else { house.log.debug('--non-media upload done'); house.ioi.emitDocToRoomOwnerGroup('files', 'inserted', data, data.metadata.owner.id, data.metadata.groups); callback({file:data}); } } }); } } if(path == '') { var datas = []; var requestFiles = []; if(req.files) { for(var i in req.files) { requestFiles.push(req.files[i]); } var procNextFile = function(){ var file = requestFiles.pop(); procFile(file, function(data){ datas.push(data); fs.unlink(file.path, function(){ //house.log.debug('file unlinked from tmp'); }); if(requestFiles.length > 0) { procNextFile(); } else { // done res.data(datas, 'json'); } }); }(); } } } else if(req.method == 'PUT') { if(!req.session.data.user) { res.writeHead(403); res.end('{}'); return; } house.log.debug('files endpoint - PUT from user '+req.session.data.user); // house.log.debug(req.fields); query = {}; if(path.length > 1 && path.indexOf('/') === 0) { docId = path.substr(1); try { var objDocId = new ObjectID(docId); docId = objDocId; } catch(e) { house.log.debug('not a good ObjectID'); } } if(docId) { house.log.debug('files endpoint - docId: '+docId); query._id = docId; if(req.session.data.groups && req.session.data.groups.indexOf('admin') !== -1) { } else { query['metadata.owner.id'] = req.session.data.user; } if(req.fields.hasOwnProperty('$set') && req.fields['$set'].hasOwnProperty('metadata.proc')) { ds.find(col, query, function(err, data) { //house.log.debug(data) if(err) { house.log.err(err); } else { if(data.length > 0) { data = _.first(data); if(data.contentType.indexOf('audio') === 0) { res.data(data); } else if(data.contentType.indexOf('image') === 0) { processImage(data, function(newImageData, updatedFile){ house.log.debug('proc image from PUT complete'); //console.log(arguments); res.data({file: updatedFile, image: newImageData}); }); } else { res.data(data); } } else { res.data(data); } } }); } else { house.log.debug('files endpoint - query and req.fields '); house.log.debug(query); house.log.debug(req.fields); ds.update(col, query, req.fields, function(err, data){ if(err) { house.log.err(err); res.end('error'); } else { //house.log.debug(data); // res.data(data); ds.find(col, query, function(err, data) { //house.log.debug(data) if(err) { house.log.err(err); } else { if(data.length > 0) { data = _.first(data); } res.data(data); } }); } }); } } } else if(req.method == 'DELETE') { house.log.debug('files DELETE'); if(!req.session.data.user) { res.writeHead(403); res.end('{}'); return; } query = {}; var ownerId = req.session.data.user; if(docId && subPath && subPath.indexOf(tagsPrefix) === 0) { var tag_id = new ObjectID(subPath.substr(tagsPrefix.length + 1)); house.log.debug('delete tag_id:'); console.log(tag_id); ds.update(col, {_id: docId}, {$pull: {"metadata.tags": {id: tag_id}}}, function(err, data){ ds.update(tagsCol, {_id: tag_id}, {$inc:{"filesCount": -1}}, function(err, data){ }); res.data(data); }); return; } // console.log('0000000------'); // console.log(docId); // console.log(subPath); // console.log(path); var srcPostfix = '/src'; var deleteRef = function(ref, callback) { house.log.debug('delete ref from collection: '+ref.col); try { var refEndPoint = house.api.getEndPointByName(ref.col); refEndPoint.call(this, { session: req.session, method: 'DELETE', url: '/' + ref.id, fields: { "delete": true } }, { end: function() {}, data: function(resData) { callback(resData); }, writeHead: function() {} }); } catch (e) { house.log.err(e); } } if(!docId && path.length > 1 && path.indexOf('/') === 0) { docId = path.substr(1); try { var objDocId = new ObjectID(docId); docId = objDocId; } catch(e) { house.log.debug('not a good ObjectID'); } } if(docId) { query._id = docId; house.log.debug('id: '+docId); if(req.session.data.groups && req.session.data.groups.indexOf('admin') !== -1) { } else { query["metadata.owner.id"] = ownerId; } ds.find(col, query, function(err, data){ if(err) { house.log.err(err); } else if(data.length > 0) { var file = _.first(data); var meta = _.clone(file.metadata); house.log.debug('filename: '+file.filename); // subPath && subPath.indexOf(tagsPrefix) === 0) { // dec users file bytes used incUserFileBytes(ownerId, (file.length * -1)); // dec users fileCount incUserFileCount(ownerId, -1); mongo.GridStore.unlink(ds.db, file.filename, {root: filesRoot}, function(err, gridStore){ if(err) { house.log.err(err); res.end('error'); } else { house.log.debug('deleted file'); if(house.ioi) { house.log.debug('emit delete '+col+' to owner '+meta.owner.id); // house.io.emitToRoomDocAndOwnerId('files', 'deleted', docId, meta.owner.id); // client is coded to 'files' but db might be different house.ioi.emitDocToRoomOwnerGroup('files', 'deleted', docId, meta.owner.id, meta.groups); } if(path.substr(path.length-srcPostfix.length) === srcPostfix) { var srcRef = false; for(var i in meta.refs) { var ref = meta.refs[i]; if(ref.col && ref.col === meta.src) { var refCol = meta.src; srcRef = ref; } } if(srcRef) { deleteRef(srcRef, function(data){ house.log.debug('src ref deleted'); res.data({}); }); } else { res.data({}); } } else { res.data({}); } } }); } else { res.data({}); // house.log.err(new Error('no data from mongo')); } }); } } else if(req.method == 'OPTIONS') { console.log('OPTIONS'); } else { if(req.method) { console.log('bad method '+req.method); } else { console.log('NO method!'); } } var processImage = function(file, exif, callback) { //house.log.debug('processImage '+file.filename) var newImage = { "filename": file.filename , "ref": {"col": col, "id": file.id} } if(typeof exif == 'object') { newImage.exif = exif; } else if(typeof exif == 'function') { callback = exif; } if(file.metadata.hasOwnProperty('exif')) { newImage.exif = file.metadata.exif; } if(file.metadata.hasOwnProperty('groups')) { newImage.groups = file.metadata.groups; } if(file.metadata.subject) { newImage["caption"] = file.metadata.subject; } if(file.metadata.body) { // parse body for tags and groups var b = file.metadata.body; //newImage["tags"] = file.metadata.subject; var blines = b.split('\n'); for(var i in blines) { var bline = blines[i]; var tags; var groups; var ts = 'Tags: '; var gs = 'Groups: '; if(bline.indexOf(ts) === 0) { tags = bline.substring(ts.length); tags = tags.split(', '); for(var t in tags) { tags[t] = tags[t].trim(); } } if(bline.indexOf(gs) === 0) { groups = bline.substring(gs.length); groups = groups.split(', '); for(var g in groups) { groups[g] = groups[g].trim(); } } } if(tags) { newImage["tags"] = tags; } if(groups) { newImage["groups"] = groups; } } if(file.metadata.src === "urls") { newImage.feed = 0; } var imagesEndPoint = house.api.getEndPointByName(imagesCol); imagesEndPoint.call(this, {session: req.session, method: 'POST', url: '', fields: newImage}, {end:function(){}, data:function(newImageData){ // house.log.debug('images response for newImage '+newImage.filename); //console.log(newImageData); var updateFileDoc = { "$push": { "metadata.refs": { "col": imagesCol , "id": newImageData.id } } , "$set": { "metadata.proc": 1 } }; ds.update(col, {"_id": file.id}, updateFileDoc, function(err, updateData) { ds.find(col, {"_id": file.id}, function(err, updatedFile) { if(updatedFile.length > 0) { if(callback) { callback(newImageData, _.first(updatedFile)); } } }); }); },writeHead:function(){}}); //ds.insert(imagesCol, newImage, function(err, newImageData) { //}); } } if(house.config.google && house.config.google.analytics && house.config.google.analytics.id) { var ga = require('node-ga-plus')(house.config.google.analytics.id, { safe : false, cookie_name: "SID" }); } if(ga) { var shouldRecordRequest = function(req) { // Only log mp3's for now if(req.method == 'GET' && /.mp3$/.test(req.url)) { var bytZeroStr = 'bytes=0'; if(req.headers.range && req.headers.range.indexOf(bytZeroStr) === 0) { house.log.debug('shouldRecordRequest range check '+req.headers.range); return true; // only the first range request of multiple GET should be tracked } else if(!req.headers.range) { return true; // normal GET } else { return false; // non 0- range request } } else { // no HEAD requests } return false; } var analyticsReq = function(req, res, next) { if(shouldRecordRequest(req)) { ga(req, res, function() { handleReq(req,res,next); }); } else { handleReq(req,res,next); } } house.log.info('using google analytics for files endpoint'); return analyticsReq; } else { return handleReq; } });
(function () { 'use strict'; var mod = angular.module('cla.states.operator'); mod.config(['AppSettings', function (AppSettings) { var states = mod.states || angular.module('cla.states').states; states.FeedbackList = { name: 'feedback_list', parent: 'layout', url: AppSettings.BASE_URL + 'feedback/?page?start?end?hide_resolved', templateUrl: 'call_centre/feedback_list.html', controller: 'FeedbackListCtrl', resolve: { feedback: ['$stateParams', 'Feedback', function($stateParams, Feedback){ var params = { start: $stateParams.start, end: $stateParams.end, page: $stateParams.page }; if ($stateParams.hide_resolved === 'True') { params.resolved = 'False'; } return Feedback.query(params).$promise; }] } }; mod.states = states; }]); })();
#!/usr/bin/env node const cli = require('commander') cli .version(require(`${__dirname}/../package.json`).version) .on('--help', () => { console.log(' Examples:'); console.log(); console.log(' $ publicify server 3000'); console.log(' $ publicify agent ysk.im:3000 localhost:8000'); console.log(); }) cli .command('server <port>') .description('Starts the remote server') .option("-b, --basicAuth <username:password>", "Set basic authentication", val => {const b = val.split(':'); return {user:b[0],pass:b[1]}}) .option("-a, --agentAuth <username:password>", "Set basic authentication for publicify agent", val => {const b = val.split(':'); return {user:b[0],pass:b[1]}}) .option("-l, --log", "Show server access log on stdout") .action((port, options) => { require(`${__dirname}/../server`)({ port, log: options.log, agentAuth: options.agentAuth, basicAuth: options.basicAuth }) }) .on('--help', () => { console.log(' Examples:'); console.log(); console.log(' $ publicify server 3000 --basicAuth testuser:testpass'); console.log(' $ publicify server 3000 --agentAuth agentUser:agentPass'); console.log(' $ publicify server 3000 --log'); console.log(); }) cli .command('agent <remotehost> <localhost>') .description('Proxy access for server to local') .option('-i, --indexFile <file>', 'Set index file when access to /') .option('-a, --agentAuth <username:password>', 'Set basic authentication') .option('-l, --log', 'Show access log on stdout') .action((remotehost, localhost, options) => { require(`${__dirname}/../agent`)({ remote: remotehost, local: localhost, log: options.log, agentAuth: options.agentAuth, index: options.indexFile }) }) .on('--help', () => { console.log(' Examples:'); console.log(); console.log(' $ publicify agent ysk.im:3000 localhost:8000 --indexFile mypage.html'); console.log(' $ publicify agent ysk.im:3000 localhost:8000 --agentAuth agentUser:agentPass'); console.log(' $ publicify agent ysk.im:3000 localhost:8000 --log'); console.log(); }) cli.parse(process.argv) if (!process.argv.slice(2).length) { cli.outputHelp() }
var fbServerMiddleware = require('./test/middleware/firebase-server.middleware.js'); module.exports = function (config) { config.set({ frameworks: ['mocha', 'chai'], files: ['./test_dist/test.bundle.js'], reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, browsers: ['ChromeHeadless'], autoWatch: false, concurrency: Infinity, beforeMiddleware: ['custom'], plugins: [ 'karma-*', { 'middleware:custom': ['factory', function (config) { return fbServerMiddleware; }], }, ], }) }
'use strict' var request = require('browser-request') var leases = (function () { var dhcp_widget = document.getElementById('dhcp') var dhcp_leases = document.getElementById('total-ip-leases') var fetch_data = function (url) { request(url, function (err, response, body) { if (err) throw err console.log(body) var json = JSON.parse(body) update_leases(json["summary"]["used"]) }) } var update_leases = function (amount) { dhcp_leases.innerHTML = amount } var runner = function (url) { fetch_data(url) window.setTimeout(function () { runner(url) }, 5000) } return { init: function () { var url = 'http://dolly.pp24.polarparty.no:81/cgi-bin/leases.cgi' runner(url) } } })() module.exports = leases
var db = require('../config/db.js'); var Schema = db.Schema; // common Objects or Schemas var logObj = require('./common/log'); // ***** USER ***** var userSchema = new Schema({ dtInsert: {type: Date, required: true, default: Date.now }, name: {type: String, required: true}, mail: {type: String, required: true}, role: {type: String, required: true, default: 'user' }, username: {type: String, required: true}, password: {type: String, required: true, default: 'nuova Password'}, active: Boolean, log: logObj, deleted: {type:Boolean, required: true, default: false} }, { collection: 'users' }); module.exports.user = db.model('User', userSchema); // ***** USER RESET ***** var userResetSchema = new Schema({ dtInsert: {type: Date, required: true, default: Date.now }, dtUpdate: {type: Date, required: true, default: Date.now }, username: {type: String, required: true}, mail: {type: String, required: true}, ip: {type: String, required: true}, token: {type: String, required: true}, status: {type: String, required: true, default: 'toSend'} }, { collection: 'users_reset' }); module.exports.reset = db.model('UsersReset', userResetSchema);
const path = require("path"); const CopyPlugin = require("copy-webpack-plugin"); module.exports = { mode: process.env.NODE_ENV || "development", entry: { contentscript: path.join(__dirname, "src/contentscript.ts"), }, output: { path: path.join(__dirname, "dist/js"), filename: "[name].js", }, module: { rules: [ { test: /\.ts$/, use: "ts-loader", exclude: /node_modules/, }, ], }, resolve: { extensions: [".ts", ".js"], }, plugins: [ new CopyPlugin({ patterns: [{ from: '.', to: '../', context: 'public' }], }), ], };
var _ = require('lodash'), Aggregate = require('./aggregate'), hop = _.has; // Temporary injections var utils = { caseInsensitive: function (val) { return val; } } /** * Query Constructor * * Normalizes Waterline queries to work with Mongo. * * @param {Object} options * @api private */ var Query = module.exports = function Query(options, schema) { // Flag as an aggregate query or not this.aggregate = false; // Cache the schema for use in parseTypes this.schema = schema; // Check for Aggregate Options this.checkAggregate(options); // Normalize Criteria this.criteria = this.normalizeCriteria(options); return this; }; /** * Check For Aggregates * * Checks the options to determine if an aggregate query is needed. * * @param {Object} options * @api private */ Query.prototype.checkAggregate = function checkAggregate(options) { var aggregateOptions = ['groupBy', 'sum', 'average', 'min', 'max']; var aggregates = _.intersection(aggregateOptions, Object.keys(options)); if (aggregates.length === 0) return options; this.aggregateGroup = new Aggregate(options); this.aggregate = true; }; /** * Normalize Criteria * * Transforms a Waterline Query into a query that can be used * with MongoDB. For example it sets '>' to $gt, etc. * * @param {Object} options * @return {Object} * @api private */ Query.prototype.normalizeCriteria = function normalizeCriteria(options) { "use strict"; var self = this; if (_.isString(options)) { var opts; try { opts = JSON.parse(options); opts = { where: opts }; } catch (err) { opts = null; } options = opts || options; } return _.mapValues(options, function (original, key) { if (key === 'where') return self.parseWhere(original); if (key === 'sort') return self.parseSort(original); return original; }); }; /** * Parse Where * * <where> ::= <clause> * * @api private * * @param original * @returns {*} */ Query.prototype.parseWhere = function parseWhere(original) { "use strict"; var self = this; // Fix an issue with broken queries when where is null if (_.isNull(original)) return {}; return self.parseClause(original); }; /** * Parse Clause * * <clause> ::= { <clause-pair>, ... } * * <clause-pair> ::= <field> : <expression> * | or|$or: [<clause>, ...] * | $or : [<clause>, ...] * | $and : [<clause>, ...] * | $nor : [<clause>, ...] * | like : { <field>: <expression>, ... } * * @api private * * @param original * @returns {*} */ Query.prototype.parseClause = function parseClause(original) { "use strict"; var self = this; return _.reduce(original, function parseClausePair(obj, val, key) { "use strict"; // Normalize `or` key into mongo $or if (key.toLowerCase() === 'or') key = '$or'; // handle Logical Operators if (['$or', '$and', '$nor'].indexOf(key) !== -1) { // Value of $or, $and, $nor require an array, else ignore if (_.isArray(val)) { val = _.map(val, function (clause) { return self.parseClause(clause); }); obj[key] = val; } } // handle Like Operators for WQL (Waterline Query Language) else if (key.toLowerCase() === 'like') { // transform `like` clause into multiple `like` operator expressions _.extend(obj, _.reduce(val, function parseLikeClauses(likes, expression, field) { likes[field] = self.parseExpression(field, { like: expression }); return likes; }, {})); } // Default else { val = self.parseExpression(key, val); // Normalize `id` key into mongo `_id` //if (key === 'id' && !hop(this, '@id')) key = '@id'; obj[key] = val; } return obj; }, {}, original); }; /** * Parse Expression * * <expression> ::= { <!|not>: <value> | [<value>, ...] } * | { <$not>: <expression>, ... } * | { <modifier>: <value>, ... } * | [<value>, ...] * | <value> * @api private * * @param field * @param expression * @returns {*} */ Query.prototype.parseExpression = function parseExpression(field, expression) { "use strict"; var self = this; // Recursively parse nested unless value is a date if (_.isPlainObject(expression) && !_.isDate(expression)) { return _.reduce(expression, function (obj, val, modifier) { // Handle `not` by transforming to $not, $ne or $nin if (modifier === '!' || modifier.toLowerCase() === 'not') { if (_.isPlainObject(val) && !_.has(val, '_bsontype')) { obj['$not'] = self.parseExpression(field, val); return obj; } val = self.parseValue(field, modifier, val); modifier = _.isArray(val) ? '$nin' : '$ne'; obj[modifier] = val; return obj; } // WQL Evaluation Modifiers for String if (_.isString(val)) { // Handle `contains` by building up a case insensitive regex if (modifier === 'contains') { val = '*' + val + '*'; obj['$regex'] = val; return obj; } // Handle `like` if (modifier === 'like') { val = val.replace(/%/g, '*'); obj['$regex'] = val; return obj; } // Handle `startsWith` by setting a case-insensitive regex if (modifier === 'startsWith') { val = val + '*'; obj['$regex'] = val; return obj; } // Handle `endsWith` by setting a case-insensitive regex if (modifier === 'endsWith') { val = '*' + val; obj['$regex'] = val; return obj; } } // Handle `lessThan` by transforming to $lt if (modifier === '<' || modifier === 'lessThan' || modifier.toLowerCase() === 'lt') { obj['$lt'] = self.parseValue(field, modifier, val); return obj; } // Handle `lessThanOrEqual` by transforming to $lte if (modifier === '<=' || modifier === 'lessThanOrEqual' || modifier.toLowerCase() === 'lte') { obj['$lte'] = self.parseValue(field, modifier, val); return obj; } // Handle `greaterThan` by transforming to $gt if (modifier === '>' || modifier === 'greaterThan' || modifier.toLowerCase() === 'gt') { obj['$gt'] = self.parseValue(field, modifier, val); return obj; } // Handle `greaterThanOrEqual` by transforming to $gte if (modifier === '>=' || modifier === 'greaterThanOrEqual' || modifier.toLowerCase() === 'gte') { obj['$gte'] = self.parseValue(field, modifier, val); return obj; } obj[modifier] = self.parseValue(field, modifier, val); return obj; }, {}); } // <expression> ::= [value, ...], normalize array into mongo $in operator expression if (_.isArray(expression)) { return { $in: self.parseValue(field, '$in', expression) }; } // <expression> ::= <value>, default equal expression return self.parseValue(field, undefined, expression); }; /** * Parse Value * * <value> ::= RegExp | Number | String * | [<value>, ...] * | <plain object> * * @api private * * @param field * @param modifier * @param val * @returns {*} */ Query.prototype.parseValue = function parseValue(field, modifier, val) { "use strict"; var self = this; // Look and see if the key is in the schema, id attribute and all association // attributes are objectid type by default (@see { @link collection._parseDefinition }). if (hop(self.schema, field)) { if (self.schema[field].primaryKey && self['@metadata'] && self['@metadata']['@id']) { return self['@metadata']['@id']; } if (_.isString(val)) { // If we can verify that the field is NOT a string type, translate // certain values into booleans or null. Otherwise they'll be left // as strings. if (self.schema[field].type != 'string') { if (val === "false") { return false; } if (val === "true") { return true; } if (val === "null") { return null; } } if (modifier === '$ne') { if (val.indexOf(' ') > -1) { return '-"' + val + '"'; } else { return val; } } else { if (val.indexOf(' ') > -1) { return '"' + val + '"'; } else { return val; } } } // Array, RegExp, plain object, number return val; } }; /** * Parse Sort * * @param original * @returns {*} */ Query.prototype.parseSort = function parseSort(original) { "use strict"; return _.reduce(original, function (sort, order, field) { // Handle Sorting Order with binary or -1/1 values sort[field] = ([0, -1].indexOf(order) > -1) ? -1 : 1; return sort; }, {}); };
/*! * fancyBox - jQuery Plugin * version: 2.1.5 (Fri, 14 Jun 2013) * requires jQuery v1.6 or later * * Examples at http://fancyapps.com/fancybox/ * License: www.fancyapps.com/fancybox/#license * * Copyright 2012 Janis Skarnelis - janis@fancyapps.com * */ ; (function (window, document, $, undefined) { "use strict"; var H = $("html"), W = $(window), D = $(document), F = $.fancybox = function () { F.open.apply(this, arguments); }, IE = navigator.userAgent.match(/msie/i), didUpdate = null, isTouch = document.createTouch !== undefined, isQuery = function (obj) { return obj && obj.hasOwnProperty && obj instanceof $; }, isString = function (str) { return str && $.type(str) === "string"; }, isPercentage = function (str) { return isString(str) && str.indexOf('%') > 0; }, isScrollable = function (el) { return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight))); }, getScalar = function (orig, dim) { var value = parseInt(orig, 10) || 0; if (dim && isPercentage(orig)) { value = F.getViewport()[dim] / 100 * value; } return Math.ceil(value); }, getValue = function (value, dim) { return getScalar(value, dim) + 'px'; }; $.extend(F, { // The current version of fancyBox version: '2.1.5', defaults: { padding: 15, margin: 20, width: 800, height: 600, minWidth: 100, minHeight: 100, maxWidth: 9999, maxHeight: 9999, pixelRatio: 1, // Set to 2 for retina display support autoSize: true, autoHeight: false, autoWidth: false, autoResize: true, autoCenter: !isTouch, fitToView: true, aspectRatio: false, topRatio: 0.5, leftRatio: 0.5, scrolling: 'auto', // 'auto', 'yes' or 'no' wrapCSS: '', arrows: true, closeBtn: true, closeClick: false, nextClick: false, mouseWheel: true, autoPlay: false, playSpeed: 3000, preload: 3, modal: false, loop: true, ajax: { dataType: 'html', headers: { 'X-fancyBox': true } }, iframe: { scrolling: 'auto', preload: true }, swf: { wmode: 'transparent', allowfullscreen: 'true', allowscriptaccess: 'always' }, keys: { next: { 13: 'left', // enter 34: 'up', // page down 39: 'left', // right arrow 40: 'up' // down arrow }, prev: { 8: 'right', // backspace 33: 'down', // page up 37: 'right', // left arrow 38: 'down' // up arrow }, close: [27], // escape key play: [32], // space - start/stop slideshow toggle: [70] // letter "f" - toggle fullscreen }, direction: { next: 'left', prev: 'right' }, scrollOutside: true, // Override some properties index: 0, type: null, href: null, content: null, title: null, // HTML templates tpl: { wrap: '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>', image: '<img class="fancybox-image" src="{href}" alt="" />', iframe: '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>', error: '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>', closeBtn: '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>', next: '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>', prev: '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>', loading: '<div id="fancybox-loading"><div></div></div>' }, // Properties for each animation type // Opening fancyBox openEffect: 'fade', // 'elastic', 'fade' or 'none' openSpeed: 250, openEasing: 'swing', openOpacity: true, openMethod: 'zoomIn', // Closing fancyBox closeEffect: 'fade', // 'elastic', 'fade' or 'none' closeSpeed: 250, closeEasing: 'swing', closeOpacity: true, closeMethod: 'zoomOut', // Changing next gallery item nextEffect: 'elastic', // 'elastic', 'fade' or 'none' nextSpeed: 250, nextEasing: 'swing', nextMethod: 'changeIn', // Changing previous gallery item prevEffect: 'elastic', // 'elastic', 'fade' or 'none' prevSpeed: 250, prevEasing: 'swing', prevMethod: 'changeOut', // Enable default helpers helpers: { overlay: true, title: true }, // Callbacks onCancel: $.noop, // If canceling beforeLoad: $.noop, // Before loading afterLoad: $.noop, // After loading beforeShow: $.noop, // Before changing in current item afterShow: $.noop, // After opening beforeChange: $.noop, // Before changing gallery item beforeClose: $.noop, // Before closing afterClose: $.noop // After closing }, //Current state group: {}, // Selected group opts: {}, // Group options previous: null, // Previous element coming: null, // Element being loaded current: null, // Currently loaded element isActive: false, // Is activated isOpen: false, // Is currently open isOpened: false, // Have been fully opened at least once wrap: null, skin: null, outer: null, inner: null, player: { timer: null, isActive: false }, // Loaders ajaxLoad: null, imgPreload: null, // Some collections transitions: {}, helpers: {}, /* * Static methods */ open: function (group, opts) { if (!group) { return; } if (!$.isPlainObject(opts)) { opts = {}; } // Close if already active if (false === F.close(true)) { return; } // Normalize group if (!$.isArray(group)) { group = isQuery(group) ? $(group).get() : [group]; } // Recheck if the type of each element is `object` and set content type (image, ajax, etc) $.each(group, function (i, element) { var obj = {}, href, title, content, type, rez, hrefParts, selector; if ($.type(element) === "object") { // Check if is DOM element if (element.nodeType) { element = $(element); } if (isQuery(element)) { obj = { href: element.data('fancybox-href') || element.attr('href'), title: $('<div/>').text(element.data('fancybox-title') || element.attr('title') || '').html(), isDom: true, element: element }; if ($.metadata) { $.extend(true, obj, element.metadata()); } } else { obj = element; } } href = opts.href || obj.href || (isString(element) ? element : null); title = opts.title !== undefined ? opts.title : obj.title || ''; content = opts.content || obj.content; type = content ? 'html' : (opts.type || obj.type); if (!type && obj.isDom) { type = element.data('fancybox-type'); if (!type) { rez = element.prop('class').match(/fancybox\.(\w+)/); type = rez ? rez[1] : null; } } if (isString(href)) { // Try to guess the content type if (!type) { if (F.isImage(href)) { type = 'image'; } else if (F.isSWF(href)) { type = 'swf'; } else if (href.charAt(0) === '#') { type = 'inline'; } else if (isString(element)) { type = 'html'; content = element; } } // Split url into two pieces with source url and content selector, e.g, // "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id" if (type === 'ajax') { hrefParts = href.split(/\s+/, 2); href = hrefParts.shift(); selector = hrefParts.shift(); } } if (!content) { if (type === 'inline') { if (href) { content = $(isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href); //strip for ie7 } else if (obj.isDom) { content = element; } } else if (type === 'html') { content = href; } else if (!type && !href && obj.isDom) { type = 'inline'; content = element; } } $.extend(obj, { href: href, type: type, content: content, title: title, selector: selector }); group[i] = obj; }); // Extend the defaults F.opts = $.extend(true, {}, F.defaults, opts); // All options are merged recursive except keys if (opts.keys !== undefined) { F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false; } F.group = group; return F._start(F.opts.index); }, // Cancel image loading or abort ajax request cancel: function () { var coming = F.coming; if (coming && false === F.trigger('onCancel')) { return; } F.hideLoading(); if (!coming) { return; } if (F.ajaxLoad) { F.ajaxLoad.abort(); } F.ajaxLoad = null; if (F.imgPreload) { F.imgPreload.onload = F.imgPreload.onerror = null; } if (coming.wrap) { coming.wrap.stop(true, true).trigger('onReset').remove(); } F.coming = null; // If the first item has been canceled, then clear everything if (!F.current) { F._afterZoomOut(coming); } }, // Start closing animation if is open; remove immediately if opening/closing close: function (event) { F.cancel(); if (false === F.trigger('beforeClose')) { return; } F.unbindEvents(); if (!F.isActive) { return; } if (!F.isOpen || event === true) { $('.fancybox-wrap').stop(true).trigger('onReset').remove(); F._afterZoomOut(); } else { F.isOpen = F.isOpened = false; F.isClosing = true; $('.fancybox-item, .fancybox-nav').remove(); F.wrap.stop(true, true).removeClass('fancybox-opened'); F.transitions[F.current.closeMethod](); } }, // Manage slideshow: // $.fancybox.play(); - toggle slideshow // $.fancybox.play( true ); - start // $.fancybox.play( false ); - stop play: function (action) { var clear = function () { clearTimeout(F.player.timer); }, set = function () { clear(); if (F.current && F.player.isActive) { F.player.timer = setTimeout(F.next, F.current.playSpeed); } }, stop = function () { clear(); D.unbind('.player'); F.player.isActive = false; F.trigger('onPlayEnd'); }, start = function () { if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) { F.player.isActive = true; D.bind({ 'onCancel.player beforeClose.player': stop, 'onUpdate.player': set, 'beforeLoad.player': clear }); set(); F.trigger('onPlayStart'); } }; if (action === true || (!F.player.isActive && action !== false)) { start(); } else { stop(); } }, // Navigate to next gallery item next: function (direction) { var current = F.current; if (current) { if (!isString(direction)) { direction = current.direction.next; } F.jumpto(current.index + 1, direction, 'next'); } }, // Navigate to previous gallery item prev: function (direction) { var current = F.current; if (current) { if (!isString(direction)) { direction = current.direction.prev; } F.jumpto(current.index - 1, direction, 'prev'); } }, // Navigate to gallery item by index jumpto: function (index, direction, router) { var current = F.current; if (!current) { return; } index = getScalar(index); F.direction = direction || current.direction[(index >= current.index ? 'next' : 'prev')]; F.router = router || 'jumpto'; if (current.loop) { if (index < 0) { index = current.group.length + (index % current.group.length); } index = index % current.group.length; } if (current.group[index] !== undefined) { F.cancel(); F._start(index); } }, // Center inside viewport and toggle position type to fixed or absolute if needed reposition: function (e, onlyAbsolute) { var current = F.current, wrap = current ? current.wrap : null, pos; if (wrap) { pos = F._getPosition(onlyAbsolute); if (e && e.type === 'scroll') { delete pos.position; wrap.stop(true, true).animate(pos, 200); } else { wrap.css(pos); current.pos = $.extend({}, current.dim, pos); } } }, update: function (e) { var type = (e && e.originalEvent && e.originalEvent.type), anyway = !type || type === 'orientationchange'; if (anyway) { clearTimeout(didUpdate); didUpdate = null; } if (!F.isOpen || didUpdate) { return; } didUpdate = setTimeout(function () { var current = F.current; if (!current || F.isClosing) { return; } F.wrap.removeClass('fancybox-tmp'); if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) { F._setDimension(); } if (!(type === 'scroll' && current.canShrink)) { F.reposition(e); } F.trigger('onUpdate'); didUpdate = null; }, (anyway && !isTouch ? 0 : 300)); }, // Shrink content to fit inside viewport or restore if resized toggle: function (action) { if (F.isOpen) { F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView; // Help browser to restore document dimensions if (isTouch) { F.wrap.removeAttr('style').addClass('fancybox-tmp'); F.trigger('onUpdate'); } F.update(); } }, hideLoading: function () { D.unbind('.loading'); $('#fancybox-loading').remove(); }, showLoading: function () { var el, viewport; F.hideLoading(); el = $(F.opts.tpl.loading).click(F.cancel).appendTo('body'); // If user will press the escape-button, the request will be canceled D.bind('keydown.loading', function (e) { if ((e.which || e.keyCode) === 27) { e.preventDefault(); F.cancel(); } }); if (!F.defaults.fixed) { viewport = F.getViewport(); el.css({ position: 'absolute', top: (viewport.h * 0.5) + viewport.y, left: (viewport.w * 0.5) + viewport.x }); } F.trigger('onLoading'); }, getViewport: function () { var locked = (F.current && F.current.locked) || false, rez = { x: W.scrollLeft(), y: W.scrollTop() }; if (locked && locked.length) { rez.w = locked[0].clientWidth; rez.h = locked[0].clientHeight; } else { // See http://bugs.jquery.com/ticket/6724 rez.w = isTouch && window.innerWidth ? window.innerWidth : W.width(); rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height(); } return rez; }, // Unbind the keyboard / clicking actions unbindEvents: function () { if (F.wrap && isQuery(F.wrap)) { F.wrap.unbind('.fb'); } D.unbind('.fb'); W.unbind('.fb'); }, bindEvents: function () { var current = F.current, keys; if (!current) { return; } // Changing document height on iOS devices triggers a 'resize' event, // that can change document height... repeating infinitely W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update); keys = current.keys; if (keys) { D.bind('keydown.fb', function (e) { var code = e.which || e.keyCode, target = e.target || e.srcElement; // Skip esc key if loading, because showLoading will cancel preloading if (code === 27 && F.coming) { return false; } // Ignore key combinations and key events within form elements if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) { $.each(keys, function (i, val) { if (current.group.length > 1 && val[code] !== undefined) { F[i](val[code]); e.preventDefault(); return false; } if ($.inArray(code, val) > -1) { F[i](); e.preventDefault(); return false; } }); } }); } if ($.fn.mousewheel && current.mouseWheel) { F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) { var target = e.target || null, parent = $(target), canScroll = false; while (parent.length) { if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) { break; } canScroll = isScrollable(parent[0]); parent = $(parent).parent(); } if (delta !== 0 && !canScroll) { if (F.group.length > 1 && !current.canShrink) { if (deltaY > 0 || deltaX > 0) { F.prev(deltaY > 0 ? 'down' : 'left'); } else if (deltaY < 0 || deltaX < 0) { F.next(deltaY < 0 ? 'up' : 'right'); } e.preventDefault(); } } }); } }, trigger: function (event, o) { var ret, obj = o || F.coming || F.current; if (obj) { if ($.isFunction(obj[event])) { ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1)); } if (ret === false) { return false; } if (obj.helpers) { $.each(obj.helpers, function (helper, opts) { if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) { F.helpers[helper][event]($.extend(true, {}, F.helpers[helper].defaults, opts), obj); } }); } } D.trigger(event); }, isImage: function (str) { return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i); }, isSWF: function (str) { return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i); }, _start: function (index) { var coming = {}, obj, href, type, margin, padding; index = getScalar(index); obj = F.group[index] || null; if (!obj) { return false; } coming = $.extend(true, {}, F.opts, obj); // Convert margin and padding properties to array - top, right, bottom, left margin = coming.margin; padding = coming.padding; if ($.type(margin) === 'number') { coming.margin = [margin, margin, margin, margin]; } if ($.type(padding) === 'number') { coming.padding = [padding, padding, padding, padding]; } // 'modal' propery is just a shortcut if (coming.modal) { $.extend(true, coming, { closeBtn: false, closeClick: false, nextClick: false, arrows: false, mouseWheel: false, keys: null, helpers: { overlay: { closeClick: false } } }); } // 'autoSize' property is a shortcut, too if (coming.autoSize) { coming.autoWidth = coming.autoHeight = true; } if (coming.width === 'auto') { coming.autoWidth = true; } if (coming.height === 'auto') { coming.autoHeight = true; } /* * Add reference to the group, so it`s possible to access from callbacks, example: * afterLoad : function() { * this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); * } */ coming.group = F.group; coming.index = index; // Give a chance for callback or helpers to update coming item (type, title, etc) F.coming = coming; if (false === F.trigger('beforeLoad')) { F.coming = null; return; } type = coming.type; href = coming.href; if (!type) { F.coming = null; //If we can not determine content type then drop silently or display next/prev item if looping through gallery if (F.current && F.router && F.router !== 'jumpto') { F.current.index = index; return F[F.router](F.direction); } return false; } F.isActive = true; if (type === 'image' || type === 'swf') { coming.autoHeight = coming.autoWidth = false; coming.scrolling = 'visible'; } if (type === 'image') { coming.aspectRatio = true; } if (type === 'iframe' && isTouch) { coming.scrolling = 'scroll'; } // Build the neccessary markup coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo(coming.parent || 'body'); $.extend(coming, { skin: $('.fancybox-skin', coming.wrap), outer: $('.fancybox-outer', coming.wrap), inner: $('.fancybox-inner', coming.wrap) }); $.each(["Top", "Right", "Bottom", "Left"], function (i, v) { coming.skin.css('padding' + v, getValue(coming.padding[i])); }); F.trigger('onReady'); // Check before try to load; 'inline' and 'html' types need content, others - href if (type === 'inline' || type === 'html') { if (!coming.content || !coming.content.length) { return F._error('content'); } } else if (!href) { return F._error('href'); } if (type === 'image') { F._loadImage(); } else if (type === 'ajax') { F._loadAjax(); } else if (type === 'iframe') { F._loadIframe(); } else { F._afterLoad(); } }, _error: function (type) { $.extend(F.coming, { type: 'html', autoWidth: true, autoHeight: true, minWidth: 0, minHeight: 0, scrolling: 'no', hasError: type, content: F.coming.tpl.error }); F._afterLoad(); }, _loadImage: function () { // Reset preload image so it is later possible to check "complete" property var img = F.imgPreload = new Image(); img.onload = function () { this.onload = this.onerror = null; F.coming.width = this.width / F.opts.pixelRatio; F.coming.height = this.height / F.opts.pixelRatio; F._afterLoad(); }; img.onerror = function () { this.onload = this.onerror = null; F._error('image'); }; img.src = F.coming.href; if (img.complete !== true) { F.showLoading(); } }, _loadAjax: function () { var coming = F.coming; F.showLoading(); F.ajaxLoad = $.ajax($.extend({}, coming.ajax, { url: coming.href, error: function (jqXHR, textStatus) { if (F.coming && textStatus !== 'abort') { F._error('ajax', jqXHR); } else { F.hideLoading(); } }, success: function (data, textStatus) { if (textStatus === 'success') { coming.content = data; F._afterLoad(); } } })); }, _loadIframe: function () { var coming = F.coming, iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime())) .attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling) .attr('src', coming.href); // This helps IE $(coming.wrap).bind('onReset', function () { try { $(this).find('iframe').hide().attr('src', '//about:blank').end().empty(); } catch (e) { } }); if (coming.iframe.preload) { F.showLoading(); iframe.one('load', function () { $(this).data('ready', 1); // iOS will lose scrolling if we resize if (!isTouch) { $(this).bind('load.fb', F.update); } // Without this trick: // - iframe won't scroll on iOS devices // - IE7 sometimes displays empty iframe $(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show(); F._afterLoad(); }); } coming.content = iframe.appendTo(coming.inner); if (!coming.iframe.preload) { F._afterLoad(); } }, _preloadImages: function () { var group = F.group, current = F.current, len = group.length, cnt = current.preload ? Math.min(current.preload, len - 1) : 0, item, i; for (i = 1; i <= cnt; i += 1) { item = group[(current.index + i) % len]; if (item.type === 'image' && item.href) { new Image().src = item.href; } } }, _afterLoad: function () { var coming = F.coming, previous = F.current, placeholder = 'fancybox-placeholder', current, content, type, scrolling, href, embed; F.hideLoading(); if (!coming || F.isActive === false) { return; } if (false === F.trigger('afterLoad', coming, previous)) { coming.wrap.stop(true).trigger('onReset').remove(); F.coming = null; return; } if (previous) { F.trigger('beforeChange', previous); previous.wrap.stop(true).removeClass('fancybox-opened') .find('.fancybox-item, .fancybox-nav') .remove(); } F.unbindEvents(); current = coming; content = coming.content; type = coming.type; scrolling = coming.scrolling; $.extend(F, { wrap: current.wrap, skin: current.skin, outer: current.outer, inner: current.inner, current: current, previous: previous }); href = current.href; switch (type) { case 'inline': case 'ajax': case 'html': if (current.selector) { content = $('<div>').html(content).find(current.selector); } else if (isQuery(content)) { if (!content.data(placeholder)) { content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter(content).hide()); } content = content.show().detach(); current.wrap.bind('onReset', function () { if ($(this).find(content).length) { content.hide().replaceAll(content.data(placeholder)).data(placeholder, false); } }); } break; case 'image': content = current.tpl.image.replace(/\{href\}/g, href); break; case 'swf': content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>'; embed = ''; $.each(current.swf, function (name, val) { content += '<param name="' + name + '" value="' + val + '"></param>'; embed += ' ' + name + '="' + val + '"'; }); content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>'; break; } if (!(isQuery(content) && content.parent().is(current.inner))) { current.inner.append(content); } // Give a chance for helpers or callbacks to update elements F.trigger('beforeShow'); // Set scrolling before calculating dimensions current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling)); // Set initial dimensions and start position F._setDimension(); F.reposition(); F.isOpen = false; F.coming = null; F.bindEvents(); if (!F.isOpened) { $('.fancybox-wrap').not(current.wrap).stop(true).trigger('onReset').remove(); } else if (previous.prevMethod) { F.transitions[previous.prevMethod](); } F.transitions[F.isOpened ? current.nextMethod : current.openMethod](); F._preloadImages(); }, _setDimension: function () { var viewport = F.getViewport(), steps = 0, canShrink = false, canExpand = false, wrap = F.wrap, skin = F.skin, inner = F.inner, current = F.current, width = current.width, height = current.height, minWidth = current.minWidth, minHeight = current.minHeight, maxWidth = current.maxWidth, maxHeight = current.maxHeight, scrolling = current.scrolling, scrollOut = current.scrollOutside ? current.scrollbarWidth : 0, margin = current.margin, wMargin = getScalar(margin[1] + margin[3]), hMargin = getScalar(margin[0] + margin[2]), wPadding, hPadding, wSpace, hSpace, origWidth, origHeight, origMaxWidth, origMaxHeight, ratio, width_, height_, maxWidth_, maxHeight_, iframe, body; // Reset dimensions so we could re-check actual size wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp'); wPadding = getScalar(skin.outerWidth(true) - skin.width()); hPadding = getScalar(skin.outerHeight(true) - skin.height()); // Any space between content and viewport (margin, padding, border, title) wSpace = wMargin + wPadding; hSpace = hMargin + hPadding; origWidth = isPercentage(width) ? (viewport.w - wSpace) * getScalar(width) / 100 : width; origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height; if (current.type === 'iframe') { iframe = current.content; if (current.autoHeight && iframe.data('ready') === 1) { try { if (iframe[0].contentWindow.document.location) { inner.width(origWidth).height(9999); body = iframe.contents().find('body'); if (scrollOut) { body.css('overflow-x', 'hidden'); } origHeight = body.outerHeight(true); } } catch (e) { } } } else if (current.autoWidth || current.autoHeight) { inner.addClass('fancybox-tmp'); // Set width or height in case we need to calculate only one dimension if (!current.autoWidth) { inner.width(origWidth); } if (!current.autoHeight) { inner.height(origHeight); } if (current.autoWidth) { origWidth = inner.width(); } if (current.autoHeight) { origHeight = inner.height(); } inner.removeClass('fancybox-tmp'); } width = getScalar(origWidth); height = getScalar(origHeight); ratio = origWidth / origHeight; // Calculations for the content minWidth = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth); maxWidth = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth); minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight); maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight); // These will be used to determine if wrap can fit in the viewport origMaxWidth = maxWidth; origMaxHeight = maxHeight; if (current.fitToView) { maxWidth = Math.min(viewport.w - wSpace, maxWidth); maxHeight = Math.min(viewport.h - hSpace, maxHeight); } maxWidth_ = viewport.w - wMargin; maxHeight_ = viewport.h - hMargin; if (current.aspectRatio) { if (width > maxWidth) { width = maxWidth; height = getScalar(width / ratio); } if (height > maxHeight) { height = maxHeight; width = getScalar(height * ratio); } if (width < minWidth) { width = minWidth; height = getScalar(width / ratio); } if (height < minHeight) { height = minHeight; width = getScalar(height * ratio); } } else { width = Math.max(minWidth, Math.min(width, maxWidth)); if (current.autoHeight && current.type !== 'iframe') { inner.width(width); height = inner.height(); } height = Math.max(minHeight, Math.min(height, maxHeight)); } // Try to fit inside viewport (including the title) if (current.fitToView) { inner.width(width).height(height); wrap.width(width + wPadding); // Real wrap dimensions width_ = wrap.width(); height_ = wrap.height(); if (current.aspectRatio) { while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) { if (steps++ > 19) { break; } height = Math.max(minHeight, Math.min(maxHeight, height - 10)); width = getScalar(height * ratio); if (width < minWidth) { width = minWidth; height = getScalar(width / ratio); } if (width > maxWidth) { width = maxWidth; height = getScalar(width / ratio); } inner.width(width).height(height); wrap.width(width + wPadding); width_ = wrap.width(); height_ = wrap.height(); } } else { width = Math.max(minWidth, Math.min(width, width - (width_ - maxWidth_))); height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_))); } } if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) { width += scrollOut; } inner.width(width).height(height); wrap.width(width + wPadding); width_ = wrap.width(); height_ = wrap.height(); canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight; canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight)); $.extend(current, { dim: { width: getValue(width_), height: getValue(height_) }, origWidth: origWidth, origHeight: origHeight, canShrink: canShrink, canExpand: canExpand, wPadding: wPadding, hPadding: hPadding, wrapSpace: height_ - skin.outerHeight(true), skinSpace: skin.height() - height }); if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) { inner.height('auto'); } }, _getPosition: function (onlyAbsolute) { var current = F.current, viewport = F.getViewport(), margin = current.margin, width = F.wrap.width() + margin[1] + margin[3], height = F.wrap.height() + margin[0] + margin[2], rez = { position: 'absolute', top: margin[0], left: margin[3] }; if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) { rez.position = 'fixed'; } else if (!current.locked) { rez.top += viewport.y; rez.left += viewport.x; } rez.top = getValue(Math.max(rez.top, rez.top + ((viewport.h - height) * current.topRatio))); rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width) * current.leftRatio))); return rez; }, _afterZoomIn: function () { var current = F.current; if (!current) { return; } F.isOpen = F.isOpened = true; F.wrap.css('overflow', 'visible').addClass('fancybox-opened').hide().show(0); F.update(); // Assign a click event if (current.closeClick || (current.nextClick && F.group.length > 1)) { F.inner.css('cursor', 'pointer').bind('click.fb', function (e) { if (!$(e.target).is('a') && !$(e.target).parent().is('a')) { e.preventDefault(); F[current.closeClick ? 'close' : 'next'](); } }); } // Create a close button if (current.closeBtn) { $(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb', function (e) { e.preventDefault(); F.close(); }); } // Create navigation arrows if (current.arrows && F.group.length > 1) { if (current.loop || current.index > 0) { $(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev); } if (current.loop || current.index < F.group.length - 1) { $(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next); } } F.trigger('afterShow'); // Stop the slideshow if this is the last item if (!current.loop && current.index === current.group.length - 1) { F.play(false); } else if (F.opts.autoPlay && !F.player.isActive) { F.opts.autoPlay = false; F.play(true); } }, _afterZoomOut: function (obj) { obj = obj || F.current; $('.fancybox-wrap').trigger('onReset').remove(); $.extend(F, { group: {}, opts: {}, router: false, current: null, isActive: false, isOpened: false, isOpen: false, isClosing: false, wrap: null, skin: null, outer: null, inner: null }); F.trigger('afterClose', obj); } }); /* * Default transitions */ F.transitions = { getOrigPosition: function () { var current = F.current, element = current.element, orig = current.orig, pos = {}, width = 50, height = 50, hPadding = current.hPadding, wPadding = current.wPadding, viewport = F.getViewport(); if (!orig && current.isDom && element.is(':visible')) { orig = element.find('img:first'); if (!orig.length) { orig = element; } } if (isQuery(orig)) { pos = orig.offset(); if (orig.is('img')) { width = orig.outerWidth(); height = orig.outerHeight(); } } else { pos.top = viewport.y + (viewport.h - height) * current.topRatio; pos.left = viewport.x + (viewport.w - width) * current.leftRatio; } if (F.wrap.css('position') === 'fixed' || current.locked) { pos.top -= viewport.y; pos.left -= viewport.x; } pos = { top: getValue(pos.top - hPadding * current.topRatio), left: getValue(pos.left - wPadding * current.leftRatio), width: getValue(width + wPadding), height: getValue(height + hPadding) }; return pos; }, step: function (now, fx) { var ratio, padding, value, prop = fx.prop, current = F.current, wrapSpace = current.wrapSpace, skinSpace = current.skinSpace; if (prop === 'width' || prop === 'height') { ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start); if (F.isClosing) { ratio = 1 - ratio; } padding = prop === 'width' ? current.wPadding : current.hPadding; value = now - padding; F.skin[prop](getScalar(prop === 'width' ? value : value - (wrapSpace * ratio))); F.inner[prop](getScalar(prop === 'width' ? value : value - (wrapSpace * ratio) - (skinSpace * ratio))); } }, zoomIn: function () { var current = F.current, startPos = current.pos, effect = current.openEffect, elastic = effect === 'elastic', endPos = $.extend({ opacity: 1 }, startPos); // Remove "position" property that breaks older IE delete endPos.position; if (elastic) { startPos = this.getOrigPosition(); if (current.openOpacity) { startPos.opacity = 0.1; } } else if (effect === 'fade') { startPos.opacity = 0.1; } F.wrap.css(startPos).animate(endPos, { duration: effect === 'none' ? 0 : current.openSpeed, easing: current.openEasing, step: elastic ? this.step : null, complete: F._afterZoomIn }); }, zoomOut: function () { var current = F.current, effect = current.closeEffect, elastic = effect === 'elastic', endPos = { opacity: 0.1 }; if (elastic) { endPos = this.getOrigPosition(); if (current.closeOpacity) { endPos.opacity = 0.1; } } F.wrap.animate(endPos, { duration: effect === 'none' ? 0 : current.closeSpeed, easing: current.closeEasing, step: elastic ? this.step : null, complete: F._afterZoomOut }); }, changeIn: function () { var current = F.current, effect = current.nextEffect, startPos = current.pos, endPos = { opacity: 1 }, direction = F.direction, distance = 200, field; startPos.opacity = 0.1; if (effect === 'elastic') { field = direction === 'down' || direction === 'up' ? 'top' : 'left'; if (direction === 'down' || direction === 'right') { startPos[field] = getValue(getScalar(startPos[field]) - distance); endPos[field] = '+=' + distance + 'px'; } else { startPos[field] = getValue(getScalar(startPos[field]) + distance); endPos[field] = '-=' + distance + 'px'; } } // Workaround for http://bugs.jquery.com/ticket/12273 if (effect === 'none') { F._afterZoomIn(); } else { F.wrap.css(startPos).animate(endPos, { duration: current.nextSpeed, easing: current.nextEasing, complete: F._afterZoomIn }); } }, changeOut: function () { var previous = F.previous, effect = previous.prevEffect, endPos = { opacity: 0.1 }, direction = F.direction, distance = 200; if (effect === 'elastic') { endPos[direction === 'down' || direction === 'up' ? 'top' : 'left'] = (direction === 'up' || direction === 'left' ? '-' : '+') + '=' + distance + 'px'; } previous.wrap.animate(endPos, { duration: effect === 'none' ? 0 : previous.prevSpeed, easing: previous.prevEasing, complete: function () { $(this).trigger('onReset').remove(); } }); } }; /* * Overlay helper */ F.helpers.overlay = { defaults: { closeClick: true, // if true, fancyBox will be closed when user clicks on the overlay speedOut: 200, // duration of fadeOut animation showEarly: true, // indicates if should be opened immediately or wait until the content is ready css: {}, // custom CSS properties locked: !isTouch, // if true, the content will be locked into overlay fixed: true // if false, the overlay CSS position property will not be set to "fixed" }, overlay: null, // current handle fixed: false, // indicates if the overlay has position "fixed" el: $('html'), // element that contains "the lock" // Public methods create: function (opts) { var parent; opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.close(); } parent = F.coming ? F.coming.parent : opts.parent; this.overlay = $('<div class="fancybox-overlay"></div>').appendTo(parent && parent.length ? parent : 'body'); this.fixed = false; if (opts.fixed && F.defaults.fixed) { this.overlay.addClass('fancybox-overlay-fixed'); this.fixed = true; } }, open: function (opts) { var that = this; opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.overlay.unbind('.overlay').width('auto').height('auto'); } else { this.create(opts); } if (!this.fixed) { W.bind('resize.overlay', $.proxy(this.update, this)); this.update(); } if (opts.closeClick) { this.overlay.bind('click.overlay', function (e) { if ($(e.target).hasClass('fancybox-overlay')) { if (F.isActive) { F.close(); } else { that.close(); } return false; } }); } this.overlay.css(opts.css).show(); }, close: function () { W.unbind('resize.overlay'); if (this.el.hasClass('fancybox-lock')) { $('.fancybox-margin').removeClass('fancybox-margin'); this.el.removeClass('fancybox-lock'); W.scrollTop(this.scrollV).scrollLeft(this.scrollH); } $('.fancybox-overlay').remove().hide(); $.extend(this, { overlay: null, fixed: false }); }, // Private, callbacks update: function () { var width = '100%', offsetWidth; // Reset width/height so it will not mess this.overlay.width(width).height('100%'); // jQuery does not return reliable result for IE if (IE) { offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth); if (D.width() > offsetWidth) { width = D.width(); } } else if (D.width() > W.width()) { width = D.width(); } this.overlay.width(width).height(D.height()); }, // This is where we can manipulate DOM, because later it would cause iframes to reload onReady: function (opts, obj) { var overlay = this.overlay; $('.fancybox-overlay').stop(true, true); if (!overlay) { this.create(opts); } if (opts.locked && this.fixed && obj.fixed) { obj.locked = this.overlay.append(obj.wrap); obj.fixed = false; } if (opts.showEarly === true) { this.beforeShow.apply(this, arguments); } }, beforeShow: function (opts, obj) { if (obj.locked && !this.el.hasClass('fancybox-lock')) { if (this.fixPosition !== false) { $('*').filter(function () { return ($(this).css('position') === 'fixed' && !$(this).hasClass("fancybox-overlay") && !$(this).hasClass("fancybox-wrap")); }).addClass('fancybox-margin'); } this.el.addClass('fancybox-margin'); this.scrollV = W.scrollTop(); this.scrollH = W.scrollLeft(); this.el.addClass('fancybox-lock'); W.scrollTop(this.scrollV).scrollLeft(this.scrollH); } this.open(opts); }, onUpdate: function () { if (!this.fixed) { this.update(); } }, afterClose: function (opts) { // Remove overlay if exists and fancyBox is not opening // (e.g., it is not being open using afterClose callback) if (this.overlay && !F.coming) { this.overlay.fadeOut(opts.speedOut, $.proxy(this.close, this)); } } }; /* * Title helper */ F.helpers.title = { defaults: { type: 'float', // 'float', 'inside', 'outside' or 'over', position: 'bottom' // 'top' or 'bottom' }, beforeShow: function (opts) { var current = F.current, text = current.title, type = opts.type, title, target; if ($.isFunction(text)) { text = text.call(current.element, current); } if (!isString(text) || $.trim(text) === '') { return; } title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">' + text + '</div>'); switch (type) { case 'inside': target = F.skin; break; case 'outside': target = F.wrap; break; case 'over': target = F.inner; break; default: // 'float' target = F.skin; title.appendTo('body'); if (IE) { title.width(title.width()); } title.wrapInner('<span class="child"></span>'); //Increase bottom margin so this title will also fit into viewport F.current.margin[2] += Math.abs(getScalar(title.css('margin-bottom'))); break; } title[(opts.position === 'top' ? 'prependTo' : 'appendTo')](target); } }; // jQuery plugin initialization $.fn.fancybox = function (options) { var index, that = $(this), selector = this.selector || '', run = function (e) { var what = $(this).blur(), idx = index, relType, relVal; if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) { relType = options.groupAttr || 'data-fancybox-group'; relVal = what.attr(relType); if (!relVal) { relType = 'rel'; relVal = what.get(0)[relType]; } if (relVal && relVal !== '' && relVal !== 'nofollow') { what = selector.length ? $(selector) : that; what = what.filter('[' + relType + '="' + relVal + '"]'); idx = what.index(this); } options.index = idx; // Stop an event from bubbling if everything is fine if (F.open(what, options) !== false) { e.preventDefault(); } } }; options = options || {}; index = options.index || 0; if (!selector || options.live === false) { that.unbind('click.fb-start').bind('click.fb-start', run); } else { D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run); } this.filter('[data-fancybox-start=1]').trigger('click'); return this; }; // Tests that need a body at doc ready D.ready(function () { var w1, w2; if ($.scrollbarWidth === undefined) { // http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth $.scrollbarWidth = function () { var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'), child = parent.children(), width = child.innerWidth() - child.height(99).innerWidth(); parent.remove(); return width; }; } if ($.support.fixedPosition === undefined) { $.support.fixedPosition = (function () { var elem = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'), fixed = (elem[0].offsetTop === 20 || elem[0].offsetTop === 15); elem.remove(); return fixed; }()); } $.extend(F.defaults, { scrollbarWidth: $.scrollbarWidth(), fixed: $.support.fixedPosition, parent: $('body') }); //Get real width of page scroll-bar w1 = $(window).width(); H.addClass('fancybox-lock-test'); w2 = $(window).width(); H.removeClass('fancybox-lock-test'); $("<style type='text/css'>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head"); }); }(window, document, jQuery));
var Stream = require('stream') function bight(streams) { if (!Array.isArray(streams)) { streams = Array.prototype.slice.call(arguments) } if (!(this instanceof bight)) { return new bight(streams) } var inStream = new Stream() inStream.writable = true inStream.readable = true inStream.write = function (data) { innerStream.emit('data', data) } inStream.end = function (data) { inStream.writable = false innerStream.emit('end', typeof data === 'undefined' ? null : data) } var innerStream = new Stream() innerStream.writable = true innerStream.readable = true innerStream.write = function (data) { inStream.emit('data', data) } innerStream.end = function (data) { innerStream.writable = false inStream.emit('end', typeof data === 'undefined' ? null : data) } var end = streams.reduce(function (prev, next) { return prev.pipe(next) }, innerStream).pipe(innerStream) return inStream } module.exports = bight
define(["../var/strundefined","../var/support"],function(strundefined,support){return function(){var shrinkWrapBlocksVal;support.shrinkWrapBlocks=function(){if(null!=shrinkWrapBlocksVal)return shrinkWrapBlocksVal;shrinkWrapBlocksVal=!1;var div,body,container;return body=document.getElementsByTagName("body")[0],body&&body.style?(div=document.createElement("div"),container=document.createElement("div"),container.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",body.appendChild(container).appendChild(div),typeof div.style.zoom!==strundefined&&(div.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",div.appendChild(document.createElement("div")).style.width="5px",shrinkWrapBlocksVal=3!==div.offsetWidth),body.removeChild(container),shrinkWrapBlocksVal):void 0}}(),support});
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({"esri/widgets/Editor/nls/Editor":{widgetLabel:"Edytor",multipleFeaturesTemplate:"Wiele obiekt\u00f3w ({total})",untitledFeatureTemplate:"Obiekt bez nazwy {id}",editFeatures:"Edytuj obiekty",editFeature:"Edytuj obiekt",addFeature:"Dodaj obiekt",featureAttachments:"\u0142_Feature attachments____________________\u0105",attachmentsButtonLabel:"\u0142_Attachments____________\u0105",attachments:"\u0142_Attachments____________\u0105",addAttachment:"\u0142_Add attachment_______________\u0105",editAttachment:"\u0142_Manage attachment__________________\u0105", selectTemplate:"Wybierz typ obiektu",selectFeatureToEdit:"Wybierz obiekt, aby go edytowa\u0107.",selectFeature:"Wybierz obiekt",placeFeature:"Rozmie\u015b\u0107 obiekt",placeFeatureOnMap:"Rozmie\u015b\u0107 obiekt na mapie.",add:"Dodaj",discardEdits:"Odrzu\u0107 zmiany",discardFeature:"Odrzu\u0107 obiekt",edit:"Edycja",keepAttachment:"\u0142_Keep attachment________________\u0105",keepFeature:"Zachowaj obiekt",continueAdding:"Kontynuuj dodawanie",continueEditing:"Kontynuuj edycj\u0119",editing:"Edycja", warning:"Uwaga",retry:"Pon\u00f3w pr\u00f3b\u0119",ignore:"Ignoruj",deleteWarningTitle:"Czy usun\u0105\u0107 ten obiekt?",deleteAttachmentWarningTitle:"\u0142_Delete this attachment________________________\u0105?",deleteWarningMessage:"Ten obiekt zostanie trwale usuni\u0119ty.",deleteAttachmentWarningMessage:"\u0142_This attachment will be permanently removed_______________________\u0105.",cancelEditTitle:"Odrzuci\u0107 zmiany?",cancelAddTitle:"Czy odrzuci\u0107 obiekt?",cancelAddWarningMessage:"Ten obiekt zostanie utracony.", cancelEditWarningMessage:"Aktualizacje tego obiektu zostan\u0105 utracone.",cancelRequestTitle:"Anulowa\u0107 procedur\u0119 wykonywania zada\u0144?",cancelRequestWarningMessage:"Za\u017c\u0105dano anulowania tej procedury wykonywania zada\u0144.",errorWarningTitle:"Przepraszamy, wyst\u0105pi\u0142y problemy",errorWarningMessageTemplate:"Nie mo\u017cna zapisa\u0107 zmian: {errorMessage}",clickToFinishTemplate:"Kliknij przycisk {button}, aby zako\u0144czy\u0107.",tips:{clickToStart:"Kliknij, aby rozpocz\u0105\u0107 rysowanie.", clickToContinue:"Kliknij, aby kontynuowa\u0107 rysowanie.",clickToAddPoint:"Kliknij, aby doda\u0107 punkt.",clickToContinueThenDoubleClickToEnd:"Kliknij, aby kontynuowa\u0107 rysowanie, a nast\u0119pnie kliknij dwukrotnie, aby zako\u0144czy\u0107 prac\u0119.",clickToAddFeature:"Kliknij, aby doda\u0107 obiekt."},_localized:{}},"esri/widgets/FeatureTemplates/nls/FeatureTemplates":{widgetLabel:"Szablony obiekt\u00f3w",filterPlaceholder:"Typy filtr\u00f3w",noMatches:"Nie znaleziono \u017cadnych element\u00f3w", noItems:"Brak szablon\u00f3w do wy\u015bwietlenia",_localized:{}},"esri/widgets/FeatureForm/nls/FeatureForm":{widgetLabel:"Formularz obiektu",empty:"- puste -",validationErrors:{cannotBeNull:"Wprowad\u017a warto\u015b\u0107",outsideRange:"Warto\u015b\u0107 powinna mie\u015bci\u0107 si\u0119 w granicach {min} i {max}",invalidCodedValue:"Warto\u015b\u0107 powinna by\u0107 r\u00f3wna jednej z wyszczeg\u00f3lnionych warto\u015bci.",invalidType:"Nieprawid\u0142owa warto\u015b\u0107"},_localized:{}},"dojo/cldr/nls/gregorian":{"dateFormatItem-Ehm":"E, h:mm a", "days-standAlone-short":"niedz. pon. wt. \u015br. czw. pt. sob.".split(" "),"months-format-narrow":"slmkmclswplg".split(""),"field-second-relative+0":"teraz","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"dzie\u0144 tygodnia","dateFormatItem-yQQQ":"QQQ y","dateFormatItem-yMEd":"E, d.MM.y","field-wed-relative+0":"w t\u0119 \u015brod\u0119","field-wed-relative+1":"w przysz\u0142\u0105 \u015brod\u0119","dateFormatItem-GyMMMEd":"E, d.MM.y G","dateFormatItem-MMMEd":"E, d.MM",eraNarrow:["p.n.e.", "BCE","n.e.","CE"],"field-tue-relative+-1":"w zesz\u0142y wtorek","days-format-short":"niedz. pon. wt. \u015br. czw. pt. sob.".split(" "),"dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","dateFormat-long":"d MMMM y","field-fri-relative+-1":"w zesz\u0142y pi\u0105tek","field-wed-relative+-1":"w zesz\u0142\u0105 \u015brod\u0119","months-format-wide":"stycznia lutego marca kwietnia maja czerwca lipca sierpnia wrze\u015bnia pa\u017adziernika listopada grudnia".split(" "),"dateTimeFormat-medium":"{1}, {0}", "dayPeriods-format-wide-pm":"PM","dateFormat-full":"EEEE, d MMMM y","field-thu-relative+-1":"w zesz\u0142y czwartek","dateFormatItem-Md":"d.MM","dayPeriods-format-abbr-am":"AM","dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","dayPeriods-format-wide-noon":"w po\u0142udnie","dateFormatItem-yMd":"d.MM.y","field-era":"era","dateFormatItem-yM":"MM.y","months-standAlone-wide":"stycze\u0144 luty marzec kwiecie\u0144 maj czerwiec lipiec sierpie\u0144 wrzesie\u0144 pa\u017adziernik listopad grudzie\u0144".split(" "), "timeFormat-short":"HH:mm","quarters-format-wide":["I kwarta\u0142","II kwarta\u0142","III kwarta\u0142","IV kwarta\u0142"],"dateFormatItem-yQQQQ":"QQQQ y","timeFormat-long":"HH:mm:ss z","field-year":"rok","dateFormatItem-yMMM":"MM.y","dateTimeFormats-appendItem-Era":"{1} {0}","field-hour":"godzina","months-format-abbr":"sty lut mar kwi maj cze lip sie wrz pa\u017a lis gru".split(" "),"field-sat-relative+0":"w t\u0119 sobot\u0119","field-sat-relative+1":"w przysz\u0142\u0105 sobot\u0119","timeFormat-full":"HH:mm:ss zzzz", "dateTimeFormats-appendItem-Week":"{0} ({2}: {1})","field-day-relative+0":"dzisiaj","field-thu-relative+0":"w ten czwartek","field-day-relative+1":"jutro","field-thu-relative+1":"w przysz\u0142y czwartek","dateFormatItem-GyMMMd":"d.MM.y G","dateFormatItem-H":"HH","months-standAlone-abbr":"sty lut mar kwi maj cze lip sie wrz pa\u017a lis gru".split(" "),"quarters-format-abbr":["K1","K2","K3","K4"],"quarters-standAlone-wide":["I kwarta\u0142","II kwarta\u0142","III kwarta\u0142","IV kwarta\u0142"], "dateFormatItem-Gy":"y G","dateFormatItem-M":"L","days-standAlone-wide":"niedziela poniedzia\u0142ek wtorek \u015broda czwartek pi\u0105tek sobota".split(" "),"dayPeriods-format-abbr-noon":"noon","timeFormat-medium":"HH:mm:ss","field-sun-relative+0":"w t\u0119 niedziel\u0119","dateFormatItem-Hm":"HH:mm","field-sun-relative+1":"w przysz\u0142\u0105 niedziel\u0119","quarters-standAlone-abbr":["1 kw.","2 kw.","3 kw.","4 kw."],eraAbbr:["p.n.e.","BCE","n.e.","CE"],"field-minute":"minuta","field-dayperiod":"rano / po po\u0142udniu / wieczorem", "days-standAlone-abbr":"niedz. pon. wt. \u015br. czw. pt. sob.".split(" "),"dateFormatItem-d":"d","dateFormatItem-ms":"mm:ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"wczoraj","dateTimeFormat-long":"{1} {0}","dayPeriods-format-narrow-am":"a","dateFormatItem-h":"h a","dateFormatItem-MMMd":"d.MM","dateFormatItem-MEd":"E, d.MM","dateTimeFormat-full":"{1} {0}","field-fri-relative+0":"w ten pi\u0105tek","field-fri-relative+1":"w przysz\u0142y pi\u0105tek","field-day":"dzie\u0144", "days-format-wide":"niedziela poniedzia\u0142ek wtorek \u015broda czwartek pi\u0105tek sobota".split(" "),"field-zone":"strefa czasowa","months-standAlone-narrow":"slmkmclswplg".split(""),"dateFormatItem-y":"y","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","field-year-relative+-1":"w zesz\u0142ym roku","field-month-relative+-1":"w zesz\u0142ym miesi\u0105cu","dateTimeFormats-appendItem-Year":"{1} {0}","dateFormatItem-hm":"h:mm a","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dayPeriods-format-abbr-pm":"PM", "days-format-abbr":"niedz. pon. wt. \u015br. czw. pt. sob.".split(" "),eraNames:["p.n.e.","BCE","n.e.","CE"],"dateFormatItem-yMMMd":"d.MM.y","days-format-narrow":"NPW\u015aCPS".split(""),"field-month":"miesi\u0105c","days-standAlone-narrow":"NPW\u015aCPS".split(""),"dateFormatItem-MMM":"LLL","field-tue-relative+0":"w ten wtorek","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})","field-tue-relative+1":"w przysz\u0142y wtorek","dayPeriods-format-wide-am":"AM","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})", "dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-EHm":"E, HH:mm","field-mon-relative+0":"w ten poniedzia\u0142ek","field-mon-relative+1":"w przysz\u0142y poniedzia\u0142ek","dateFormat-short":"dd.MM.y","dateFormatItem-EHms":"E, HH:mm:ss","dateFormatItem-Ehms":"E, h:mm:ss a","dayPeriods-format-narrow-noon":"n","field-second":"sekunda","field-sat-relative+-1":"w zesz\u0142\u0105 sobot\u0119","dateFormatItem-yMMMEd":"E, d.MM.y","field-sun-relative+-1":"w zesz\u0142\u0105 niedziel\u0119", "field-month-relative+0":"w tym miesi\u0105cu","field-month-relative+1":"w przysz\u0142ym miesi\u0105cu","dateTimeFormats-appendItem-Timezone":"{0} {1}","dateFormatItem-Ed":"E, d","field-week":"tydzie\u0144","dateFormat-medium":"dd.MM.y","field-week-relative+-1":"w zesz\u0142ym tygodniu","field-year-relative+0":"w tym roku","field-year-relative+1":"w przysz\u0142ym roku","dayPeriods-format-narrow-pm":"p","dateTimeFormat-short":"{1}, {0}","dateFormatItem-Hms":"HH:mm:ss","dateFormatItem-hms":"h:mm:ss a", "dateFormatItem-GyMMM":"MM.y G","field-mon-relative+-1":"w zesz\u0142y poniedzia\u0142ek","field-week-relative+0":"w tym tygodniu","field-week-relative+1":"w przysz\u0142ym tygodniu","dateFormatItem-yMM":"MM.y","dayPeriods-format-wide-earlyMorning":"nad ranem","dayPeriods-format-wide-morning":"rano","dayPeriods-format-wide-evening":"wieczorem","dateFormatItem-MMdd":"d.MM","field-day-relative+2":"pojutrze","dateFormatItem-MMMMd":"d MMMM","dayPeriods-format-wide-night":"w nocy","field-day-relative+-2":"przedwczoraj", "dayPeriods-format-wide-lateMorning":"przed po\u0142udniem","dateFormatItem-yMMMM":"LLLL y","dayPeriods-format-wide-afternoon":"po po\u0142udniu",_localized:{}}});
import React, {PropTypes} from 'react'; import Draggable from 'react-draggable'; // import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import classNames from 'classnames'; import styles from './Window.scss'; export const MIN = 1; export const MAX = 2; export const CLOSE = 4; export const ALL = (MAX | MIN | CLOSE); const borderSizeDefault = 7; const resize = { NONE: 'default', TOP:'n-resize', BOTTOM: 'n-resize', LEFT: 'e-resize', RIGHT: 'e-resize', TOPLEFT: 'se-resize', TOPRIGHT: 'sw-resize', BOTTOMLEFT: 'sw-resize', BOTTOMRIGHT: 'se-resize' }; class Window extends React.Component { static propTypes = { children: PropTypes.any, active: PropTypes.number, onChangePos: PropTypes.func, onActive: PropTypes.func, onClose: PropTypes.func, onMax: PropTypes.func, onMin: PropTypes.func, footer: PropTypes.node, header: PropTypes.node, controls: PropTypes.any, disabled: PropTypes.any, config: PropTypes.any, onStopDrag: PropTypes.func }; constructor(props) { super(props); this.state = { resizeType: 'NONE', isDrag: false, isResize: false, resizeStartPos: [0, 0] }; } onActive() { if (this.props.onActive) { this.props.onActive(this.props.config.id); } } _handleStart(event, ui) { this.setState({ isDrag: true }); // console.log('Event: ', event); // console.log('Position: ', ui.position); } _handleDrag(event, ui) { // console.log('Event: ', event); //console.warn('Position: ', ui); const conf = this.props.config; const pos = { left: ui.node.offsetWidth, top: ui.node.offsetHeight }; if (this.props.onChangePos) { this.props.onChangePos({position: ui.position, id: conf.id}); } } _handleStop(event, ui) { this.setState({ isDrag: false }); if (this.props.onStopDrag) { this.props.onStopDrag(this.props.config) } // console.log('Event: ', event); /* if (this.props.onChangePos) { this.props.onChangePos({position: ui.position, id: this.props.config.id}); }*/ } _borderMouseDown(e) { if (e.button === 0 && this.state.resizeType !== 'NONE') { this.setState({ isResize: true, resizeStartPos: [e.clinetX, e.clientY] }); } } _borderMouseUp(e) { this.setState({ isResize: false }); } _borderMouseMove(e) { if (this.state.isDrag) return false const {left, top, width, height} = this.props.config const x = e.clientX const y = e.clientY /* console.info(`events: [${x}, ${y}]`); console.info(`pos: [${left}, ${top}]`); console.info(`size: [${left+width}, ${top+height}]`);*/ const _top = (y - borderSizeDefault * 2 <= top) ? 1 : 0 const _bottom = (y >= top + height + borderSizeDefault) ? 3 : 0 const _left = (x - borderSizeDefault <= left) ? 7 : 0 const _right = (x >= left + width - borderSizeDefault) ? 11 : 0 /*eslint-disable */ const resizeType = ([ 'NONE' , 'TOP' , null , 'BOTTOM' , null , null , null , 'LEFT' , 'TOPLEFT' , null , 'BOTTOMLEFT' , 'RIGHT' , 'TOPRIGHT' , null , 'BOTTOMRIGHT' , null , ])[_top + _left + _right + _bottom]; /*eslint-enable */ /* if (resizeType.left && resizeType.top) { resizeType = 'TOPLEFT'; } else if (resizeType.left && resizeType.bottom) { resizeType = 'BOTTOMLEFT'; } else if (resizeType.right && resizeType.top) { resizeType = 'TOPRIGHT'; } else if (resizeType.right && resizeType.bottom) { resizeType = 'BOTTOMRIGHT'; } else if (!resizeType.right && !resizeType.bottom && !resizeType.left && !resizeType.top) { resizeType = 'NONE'; } else if (resizeType.right) { resizeType = 'RIGHT'; } else if (resizeType.left) { resizeType = 'LEFT'; } else if (resizeType.top) { resizeType = 'TOP'; } else if (resizeType.bottom) { resizeType = 'BOTTOM'; }*/ if (e.buttons === 1) { if (this.state.isDrag !== true) { console.info('Resize start', e.pageX, e.pageY); this.state.isDrag = true; this.state.resizeStartPos = [e.pageX, e.pageY]; } else { //console.info('Resize progress', e.pageX, e.pageY); // this.state.left = this.state.resizeStartPos[0] - e.pageX; // this.state.top = this.state.resizeStartPos[1] - e.pageY; } } else { // console.info('Resize stop'); this.state.isDrag = false; } this.state.resizeType = resizeType; this.setState(this.state); } _checkIsDrag(e) { if (e.button === 0) { this.setState({ isDrag: false }) } } // Todo: move style to class render() { const {left, top, width, height, title, id, max, min, sort} = this.props.config; const controls = this.props.controls || ALL; const disabled = this.props.disabled || 0; const onClose = () => !this.props.onClose || this.props.onClose(id); const onMin = () => !this.props.onMin || this.props.onMin(id); const onMax = () => !this.props.onMax || this.props.onMax(id); const borderSize = borderSizeDefault; //this.state.isDrag ? 1000 : borderSizeDefault; const className = classNames({ 'window-wrapper': true, 'window-min': (min && (disabled ^ MIN)), 'window-max': (max && (disabled ^ MAX)) }); const draggable_fix_style = {display: this.state.isDrag ? 'block' : 'none'} // console.log(className, this.props); return ( <Draggable handle='.window>header>.title,.window>header>.title>*' start={{x: left, y: top}} moveOnStartChange={false} zIndex={1800} onStart={this._handleStart.bind(this)} onDrag={this._handleDrag.bind(this)} onStop={this._handleStop.bind(this)} bounds="parent" > <div style={{ width: `${(width + borderSize * 2)}px`, height: `${(height + borderSize * 2)}px`, zIndex: (1000 + (500 - sort)), cursor: resize[this.state.resizeType], position: 'fixed' }} className={className} onMouseMove={this._borderMouseMove.bind(this)} > <div onMouseDown={this.onActive.bind(this)} className={`window ${styles.window}`} style={{borderRadius: '6px', position: 'fixed !important', margin: `${borderSize}px`}} > <header className="toolbar toolbar-header" style={{borderRadius: '6px 6px 0 0'}}> <h1 className="title" style={{borderRadius: '6px 6px 0 0'}}> {title} <div className={styles.controls}> {!(controls & MIN) || <div onClick={onMin} className={(disabled & MIN) ? `${styles.disabled} ${styles.min}` : styles.min}/>} {!(controls & MAX) || <div onClick={onMax} className={(disabled & MAX) ? `${styles.disabled} ${styles.max}` : styles.max}/>} {!(controls & CLOSE) || <div onClick={onClose} className={(disabled & CLOSE) ? `${styles.disabled} ${styles.close}` : styles.close}/>} </div> </h1> {!this.props.header || <div className="toolbar-actions"> {this.props.header} </div>} </header> <div className="window-content"> <div className={styles.draggable_fix} onMouseMove={this._checkIsDrag.bind(this)} style={draggable_fix_style} /> {this.props.children} {/*<iframe frameBorder="0" src="http://rawgit.com/IamNotUrKitty/fiveteen_React.js/master/public/" scrolling="no" style={{width: '100%', height: '100%'}} />*/} </div> {!this.props.footer || <footer className="toolbar toolbar-footer"> <div className="toolbar-actions"> {this.props.footer} </div> </footer>} </div> </div> </Draggable> ); } } Window.MIN = MIN; Window.MAX = MAX; Window.CLOSE = CLOSE; Window.ALL = ALL; export default Window;
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "env": { "browser": true, "jasmine": true, "node": true, "jest": true }, "plugins": [ "react" ], "rules": { "prefer-arrow-callback": 0, "func-names": 0, "import/no-extraneous-dependencies": 0, "no-underscore-dangle": 0, "no-unused-expressions": 0, "no-use-before-define": 0, "react/sort-comp": 0, "react/no-multi-comp": 0, "react/require-extension": 0, "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "react/prefer-stateless-function": 0, "comma-dangle": ["error", { "arrays": "always-multiline", "objects": "always-multiline", "imports": "always-multiline", "exports": "always-multiline", "functions": "ignore", }] } };
// All symbols in the Mahjong Tiles block as per Unicode v6.2.0: [ '\uD83C\uDC00', '\uD83C\uDC01', '\uD83C\uDC02', '\uD83C\uDC03', '\uD83C\uDC04', '\uD83C\uDC05', '\uD83C\uDC06', '\uD83C\uDC07', '\uD83C\uDC08', '\uD83C\uDC09', '\uD83C\uDC0A', '\uD83C\uDC0B', '\uD83C\uDC0C', '\uD83C\uDC0D', '\uD83C\uDC0E', '\uD83C\uDC0F', '\uD83C\uDC10', '\uD83C\uDC11', '\uD83C\uDC12', '\uD83C\uDC13', '\uD83C\uDC14', '\uD83C\uDC15', '\uD83C\uDC16', '\uD83C\uDC17', '\uD83C\uDC18', '\uD83C\uDC19', '\uD83C\uDC1A', '\uD83C\uDC1B', '\uD83C\uDC1C', '\uD83C\uDC1D', '\uD83C\uDC1E', '\uD83C\uDC1F', '\uD83C\uDC20', '\uD83C\uDC21', '\uD83C\uDC22', '\uD83C\uDC23', '\uD83C\uDC24', '\uD83C\uDC25', '\uD83C\uDC26', '\uD83C\uDC27', '\uD83C\uDC28', '\uD83C\uDC29', '\uD83C\uDC2A', '\uD83C\uDC2B', '\uD83C\uDC2C', '\uD83C\uDC2D', '\uD83C\uDC2E', '\uD83C\uDC2F' ];
const combine = require('stream-combiner') const through = require('through2') const split = require('split2') const Message = require('./Message') const debug = require('debug')('ircs:MessageParser') module.exports = function MessageParser () { return combine( split('\r\n'), through.obj(parse) ) /** * Parses an individual IRC command. * * @param {string} line IRC command string. * @return {Message} */ function parse (line, enc, cb) { debug('parsing', line) let prefix let command let params if (line[0] === ':') { let prefixEnd = line.indexOf(' ') prefix = line.slice(1, prefixEnd) line = line.slice(prefixEnd + 1) } let colon = line.indexOf(' :') if (colon !== -1) { let append = line.slice(colon + 2) line = line.slice(0, colon) params = line.split(/ +/g).concat([ append ]) } else { params = line.split(/ +/g) } command = params.shift() cb(null, new Message(prefix, command, params)) } }
Ext.define("Libertor.view.component.LocalFolderSelector", { extend: "Ext.window.Window", alias: "widget.localfolderselector", title: "Choose a folder", modal: true, bodyPadding: 5, layout: "vbox", items: [ { xtype: "treepanel", width: 400, store: "LocalFileSystem" }, { xtype: "fieldcontainer", layout: "hbox", margin: "5 0 0 0", items: [ { xtype: "textfield", fieldLabel: "Path", labelWidth: 40 }, { xtype: "button", text: "OK", margin: "0 0 0 5" } ] } ] });
'use strict'; require('rootpath')(); require('src/server').start();
import HomeModule from './home' import HomeController from './home.controller'; import HomeComponent from './home.component'; import HomeTemplate from './home.html'; import _ from 'lodash'; describe('Home', () => { let $rootScope, makeController; beforeEach(window.module(HomeModule.name)); beforeEach(inject((_$rootScope_) => { $rootScope = _$rootScope_; makeController = () => { return new HomeController(); }; })); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Controller', () => { }); describe('Template', () => { }); describe('Component', () => { // component/directive specs let component = HomeComponent; it('includes the intended template',() => { expect(component.template).to.equal(HomeTemplate); }); it('uses `controllerAs` syntax', () => { expect(component).to.have.property('controllerAs'); }); it('invokes the right controller', () => { expect(component.controller).to.equal(HomeController); }); }); });
/** * Copyright (C) 2012 Matt McDonald. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @see http://www.fortybelow.ca/projects/JavaScript/Utils/ */ var Utils = Utils || {}, global = global || this; /** * @title Matt's DOM Utils * @see http://www.fortybelow.ca/projects/JavaScript/Utils/ * * @description * A collection of widely tested DOM utilities and modules * that work in a maximal amount of environments. * * @author Matt McDonald * @contact ["Utils".toLowerCase();]@fortybelow.ca * @see http://www.fortybelow.ca */ if (typeof Utils === "object" && Utils) { (function () { /** * @module * Utils.create * * @description * Various creation method wrappers. * * @dependencies * * null */ var hostTypes, doc, createElement, createElementNS, createText, createProcessingInstruction, createComment, canUseDocFrag, canCallDocFrag, createDocumentFragment; /** * @private * * @description * Object containing "normal" types associated with * host objects (exludes "unknown"). */ hostTypes = { "object": true, "function": true }; /** * @private * * @description * Method that returns a boolean asserting if the * specified object is a host-like object (by passing * one of two assertions: * a) a `typeof` result of "object" or "function" * along with "truthiness"; * b) a `typeof` result of "unknown". * * @param obj Object * An object to assert. */ function isHostObject( obj ) { var type = typeof obj, normal = hostTypes[type] && obj; return !!(normal || type === "unknown"); } /** * @private * * @closure * * @description * Variable containing the current document * node-like object. */ doc = global.document; /** * @private * * @description * Wrapper method for `createElement`; returns the * wrapped method's result or `null` if not * applicable. * * @param doc Object * A document node-like object to create an element * node-like object in. * * @param tag String * A string representing the `tagName` of the created * element node-like object. * * @see `Document::createElement`. */ function createElementNode( doc, tag ) { var key = "createElement"; return doc[key]( tag ); } /** * @public `Utils.create.element`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createElementNode` or `null` * if not applicable. * * @param doc Object * A document node-like object to create an element * node-like object in. * * @param tag String * A string representing the `tagName` of the created * element node-like object. * * @see `createElementNode`. */ createElement = (function () { var key = "createElement", result = null; if (isHostObject(doc[key])) { result = createElementNode; } return result; }()); /** * @private * * @description * Wrapper method for `createElementNS`; returns the * wrapped method's result or `null` if not * applicable. * * @param doc Object * A document node-like object to create an element * node-like object in. * * @param uri String * A string representing the namespace URI of the * element node-like object to be created. * * @param name String * A string representing the qualified name * ([namespace:]local) of the element node-like object * to be created. * * @see `Document::createElementNS`. */ function createElementNodeNS( doc, uri, name ) { var key = "createElementNS"; return doc[key]( uri, name ); } /** * @public `Utils.create.elementNS`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createElementNodeNS` or `null` * if not applicable. * * @param uri String * A string representing the namespace URI of the * element node-like object to be created. * * @param name String * A string representing the qualified name * ([namespace:]local) of the element node-like object * to be created. * * @see `createElementNodeNS`. */ createElementNS = (function () { var key = "createElementNS", result = null; if (isHostObject(doc[key])) { result = createElementNodeNS; } return result; }()); /** * @private * * @description * Wrapper method for `createTextNode`; returns the * wrapped method's result or `null` if not * applicable. * * @param doc Object * A document node-like object to create a text * node-like object in. * * @param text String * A string representing the `nodeValue` of the * text node-like object to be created. * * @see `Document::createTextNode`. */ function createTextNode( doc, text ) { var key = "createTextNode"; return doc[key]( text ); } /** * @public `Utils.create.text`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createTextNode` or `null` * if not applicable. * * @param doc Object * A document node-like object to create a text * node-like object in. * * @param text String * A string representing the `nodeValue` of the * text node-like object to be created. * * @see `createTextNode`. */ createText = (function () { var key = "createTextNode", result = null; if (isHostObject(doc[key])) { result = createTextNode; } return result; }()); /** * @private * * @description * Wrapper method for `createProcessingInstruction`; * returns the wrapped method's result or `null` if * not applicable. * * @param doc Object * A document node-like object to create a * processing instruction node-like object in. * * @param target String * A string representing the `target` of the created * processing instruction node-like object. * * @param text String * A string representing the `nodeValue` of the created * processing instruction node-like object. * * @see `Document::createProcessingInstruction`. */ function createPINode( doc, target, text ) { var key = "createProcessingInstruction"; return doc[key]( target, text ); } /** * @public `Utils.create.processingInstruction`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createPINode` or * `null` if not applicable. * * @param doc Object * A document node-like object to create a * processing instruction node-like object in. * * @param target String * A string representing the `target` of the created * processing instruction node-like object. * * @param text String * A string representing the `nodeValue` of the created * processing instruction node-like object. * * @see `createPINode`. */ createProcessingInstruction = (function () { var key = "createProcessingInstruction", result = null; if (isHostObject(doc[key])) { result = createPINode; } return result; }()); /** * @private * * @description * Wrapper method for `createComment`; returns the * wrapped method's result or `null` if not * applicable. * * @param doc Object * A document node-like object to create a comment * node-like object in. * * @param text String * A string representing the `nodeValue` of the created * comment node-like object. * * @see `Document::createComment`. */ function createCommentNode( doc, text ) { var key = "createComment"; return doc[key]( text ); } /** * @public `Utils.create.comment`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createCommentNode` or `null` * if not applicable. * * @param doc Object * A document node-like object to create a comment * node-like object in. * * @param text String * A string representing the `nodeValue` of the created * comment node-like object. * * @see `createCommentNode`. */ createComment = (function () { var key = "createComment", result = null; if (isHostObject(doc[key])) { result = createCommentNode; } return result; }()); /** * @private * * @closure * * @description * Boolean asserting if `createDocumentFragment` * is available. */ canUseDocFrag = (function () { var key = "createDocumentFragment", result = false; if (isHostObject(doc[key])) { result = true; } return result; }()); /** * @private * * @closure * * @description * Boolean asserting if `createDocumentFragment` * does not err when called. */ canCallDocFrag = (function () { var key = "createDocumentFragment", result = canUseDocFrag; if (canUseDocFrag) { try { doc[key](); } catch (err) { result = false; } } return result; }()); /** * @private * * @description * Wrapper method for `createDocumentFragment`; * returns the wrapped method's result or `null` if * not applicable. * * @param doc Object * A document node-like object to create a * document fragment node-like object in. * * @see `Document::createDocumentFragment`. */ function createDocFragNode( doc ) { var key = "createDocumentFragment"; return doc[key](); } /** * @public `Utils.create.documentFragment`. * * @closure * * @description * Wrapper method that returns (via a closure) * the result of `createDocFragNode` or `null` * if not applicable. * * @param doc Object * A document node-like object to create a * document fragment node-like object in. * * @see `createDocFragNode`. */ createDocumentFragment = (function () { var result = null; if (canCallDocFrag) { result = createDocFragNode; } return result; }()); doc = null; Utils.create = Utils.create || { "element": createElement, "elementNS": createElementNS, "text": createText, "processingInstruction": createProcessingInstruction, "comment": createComment, "documentFragment": createDocumentFragment }; }()); } if (typeof Utils === "object" && Utils) { (function () { /** * @module * Utils.node * * @description * Various DOM node method wrappers. * * @dependencies * * null */ var nodeTypes, valueSetters, hostTypes; /** * @private * * @description * Object of documented `nodeType`s. * * @see DOM 4 Spec 5.3 (Node, nodeType). */ nodeTypes = { "ELEMENT_NODE": 1, "ATTRIBUTE_NODE": 2, "TEXT_NODE": 3, "CDATA_SECTION_NODE": 4, "ENTITY_REFERENCE_NODE": 5, "ENTITY_NODE": 6, "PROCRESSING_INSTRUCTION_NODE": 7, "COMMENT_NODE": 8, "DOCUMENT_NODE": 9, "DOCUMENT_TYPE_NODE": 10, "DOCUMENT_FRAGMENT_NODE": 11, "NOTATION_NODE": 12 }; /** * @private * * @description * Object of `nodeTypes` that can set the * `nodeValue` property. * * @see DOM 4 Spec 5.3 (Node, nodeValue). */ valueSetters = (function () { var result = {}; result[nodeTypes.TEXT_NODE] = true; result[nodeTypes.PROCESSING_INSTRUCTION_NODE] = true; result[nodeTypes.COMMENT_NODE] = true; return result; }()); /** * @private * * @description * Object containing "normal" types associated with * host objects (exludes "unknown"). */ hostTypes = { "object": true, "function": true }; /** * @private * * @description * Method that returns a boolean asserting if the * specified object is array-like. * * @param obj Object * An object to assert. */ function isArrayLike( obj ) { var type = typeof obj, normal = hostTypes[type] && obj, result = false; if (normal || type === "unknown") { result = typeof obj.length === "number"; } return result; } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is node-like. * * @param obj Object * An object to assert. */ function isNodeLike( obj ) { var type = typeof obj, normal = hostTypes[type] && obj, result = false; if (normal || type === "unknown") { result = typeof obj.nodeType === "number"; } return result; } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is a host-like object (by passing * one of two assertions: * a) a `typeof` result of "object" or "function" * along with "truthiness"; * b) a `typeof` result of "unknown". * * @param obj Object * An object to assert. */ function isHostObject( obj ) { var type = typeof obj, normal = hostTypes[type] && obj; return !!(normal || type === "unknown"); } /** * @public `Utils.node.prepend`. * * @description * Wrapper method for `insertBefore`; returns the * wrapped method's result or `null` if not * applicable. * * @see `Node::insertBefore`. * * @param par Object * A node-like object that will attempt to prefix * a node-like object. * * @param newObj Object * A node-like object to prefix. * * @param refObj Object * A node-like object to insert before. */ function insertBefore( par, newObj, refObj ) { var key = "insertBefore", result = null; if (isNodeLike(par) && isNodeLike(newObj) && isNodeLike(refObj)) { if (isHostObject(par[key])) { result = par[key]( newObj, refObj ); } } return result; } /** * @public `Utils.node.prependList`. * * @description * Method that passes each element of an array-like * object to `insertBefore`. * * @see `insertBefore`. * * @param par Object * A node-like object that will attempt to prepend * a list of node-like objects. * * @param list Array * A list of node-like objects to prepend. * * @param refObj Object * A node-like object to prepend before. */ function insertListBefore( par, list, refObj ) { var max, aux, diff, result; if (isArrayLike(list)) { max = list.length - 1; for (aux = max; aux > -1; aux -= 1) { diff = max - aux; insertBefore( par, list[diff], refObj ); } } return result; } /** * @public `Utils.node.append` * * @description * Wrapper method for `appendChild`; returns the * wrapped method's result or `null` if not * applicable. * * @see `Node::appendChild`. * * @param par Object * A node-like object that will attempt to append * a node-like object. * * @param obj Object * A node-like object to append. */ function appendChild( par, obj ) { var key = "appendChild", result = null; if (isNodeLike(par) && isNodeLike(obj)) { if (isHostObject(par[key])) { result = par[key]( obj ); } } return result; } /** * @public `Utils.node.appendList`. * * @description * Method that passes each element of an array-like * object to `appendChild`. * * @see `appendChild`. * * @param par Object * A node-like object that will attempt to append * a list of node-like objects. * * @param list Array * A list of node-like objects to append. */ function appendList( par, list ) { var max, aux, diff, result; if (isArrayLike(list)) { max = list.length - 1; for (aux = max; aux > -1; aux -= 1) { diff = max - aux; appendChild( par, list[diff] ); } } return result; } /** * @public `Utils.node.remove`. * * @description * Wrapper method for `removeChild`; returns the * wrapped method's result or `null` if not * applicable. * * @see `Node::removeChild`. * * @param par Object * A node-like object that will attempt to remove * another node-like object. * * @param obj Object * A node-like object to be removed. */ function removeChild( par, obj ) { var key = "removeChild", result = null; if (isNodeLike(par) && isNodeLike(obj)) { if (isHostObject(par[key])) { result = par[key]( obj ); } } return result; } /** * @public `Utils.node.replace`. * * @description * Wrapper method for `replaceChild`; returns the * wrapped method's result or `null` if not * applicable. * * @see `Node::replaceChild`. * * @param par Object * A node-like object that will attempt to replace * another node-like object. * * @param newObj Object * A node-like object to replace a node-like object * with. * * @param oldObj Object * A node-like object to be replaced. */ function replaceChild( par, newObj, oldObj ) { var key = "replaceChild", result = null; if (isNodeLike(par) && isNodeLike(newObj) && isNodeLike(oldObj)) { if (isHostObject(par[key])) { result = par[key]( newObj, oldObj ); } } return result; } /** * @public `Utils.node.clone`. * * @description * Wrapper method for `cloneNode`; returns the * wrapped method's result or `null` if not * applicable. * * @see `Node::cloneNode`. * * @param obj Object * A node-like object to be cloned. * * @param deep Boolean * A boolean determining if a "deep" (recursive) * clone will occur. */ function cloneNode( obj, deep ) { var key = "cloneNode", result = null; if (isNodeLike(obj)) { if (isHostObject(obj[key])) { result = obj[key]( obj, deep ); } } return result; } /** * @private * * @description * Method that returns a boolean asserting if a * specified object can retrieve the `nodeName` * property. * * @param obj Object * An object to assert. */ function canGetName( obj ) { var result = false; if (isNodeLike(obj)) { result = typeof obj.nodeName === "string"; } return result; } /** * @public `Utils.node.getName`. * * @description * Getter method for `nodeName`; returns the * wrapped property's result or `null` if not * applicable. * * @see `Node::nodeName`. * @see `Element::tagName`. * * @param obj Object * A node-like object to retrieve the `nodeName` * property from. * * @param lower Boolean * A boolean determining if a the `nodeName` will * be returned in lower case form. */ function getName( obj, lower ) { var lowKey = "toLowerCase", upKey = "toUpperCase", result = null; if (canGetName(obj)) { result = obj.nodeName; if (lower) { result = result[lowKey](); } else if (!lower) { result = result[upKey](); } } return result; } /** * @private * * @description * Method that returns a boolean asserting if a * specified object can retrieve the `nodeValue` * property. * * @param obj Object * An object to assert. */ function canGetValue( obj ) { var result = false; if (isNodeLike(obj)) { result = typeof obj.nodeValue === "string"; } return result; } /** * @public `Utils.node.getValue`. * * @description * Getter method for `nodeValue`; returns the * wrapped property's result or `null` if not * applicable. * * @see `Node::nodeValue`. * @see `CharacterData::data`. * @see `Text::data` (inherited from above). * * @param obj Object * A node-like object to retrieve the `nodeValue` * property from. */ function getValue( obj ) { var result = null; if (canGetValue(obj)) { result = obj.nodeValue; } return result; } /** * @public `Utils.node.setValue`. * * @description * Setter method for `nodeValue`; returns the * wrapped property's result or `null` if not * applicable. * * @see `Node::nodeValue`. * @see `CharacterData::data`. * @see `Text::data`. * * @param obj Object * A node-like object to retrieve the `nodeValue` * property from. * * @param newValue String * A string containing the new value for the * `nodeValue` property. */ function setValue( obj, newValue ) { var key = "nodeValue", result = null; if (isNodeLike(obj)) { if (valueSetters[obj.nodeType]) { result = obj[key] = newValue; } } return result; } Utils.node = Utils.node || { "prepend": insertBefore, "prependList": insertListBefore, "append": appendChild, "appendList": appendList, "remove": removeChild, "replace": replaceChild, "clone": cloneNode, "getName": getName, "getValue": getValue, "setValue": setValue }; }()); } if (typeof Utils === "object" && Utils) { (function () { /** * @module * Utils.select * * @description * Various selection wrappers. * * @dependencies * * null */ var doc, hostTypes, getElementsByName, nodeTypes, getElementsByTagName, isDocument, getElementsByTagNameNS, getElementsByClassName, getElementById, getHead, getBody, selectorTypes, querySelector, querySelectorAll, getImages, getAllImages, getEmbeds, getAllEmbeds, getLinks, getAllLinks, getForms, getAllForms, getScripts, getAllScripts, getApplets, getAllApplets, getAnchors, getAllAnchors; /** * @private * * @closure * * @description * Variable containing the current document * node-like object. */ doc = global.document; /** * @private * * @description * Object containing "normal" types associated with * host objects (exludes "unknown"). */ hostTypes = { "object": true, "function": true }; /** * @private * * @description * Method that returns a boolean asserting if the * specified object is node-like. * * @param obj Object * An object to assert. */ function isNodeLike( obj ) { var type = typeof obj, normal = hostTypes[type] && obj, result = false; if (normal || type === "unknown") { result = typeof obj.nodeType === "number"; } return result; } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is a host-like object (by passing * one of two assertions: * a) a `typeof` result of "object" or "function" * along with "truthiness"; * b) a `typeof` result of "unknown". * * @param obj Object * An object to assert. */ function isHostObject( obj ) { var type = typeof obj, normal = hostTypes[type] && obj; return !!(normal || type === "unknown"); } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is array-like. * * @param obj Object * An object to assert. */ function isArrayLike( obj ) { var type = typeof obj, normal = hostTypes[type] && obj, result = false; if (normal || type === "unknown") { result = typeof obj.length === "number"; } return result; } /** * @private * * @description * Method that returns an array produced from an * iterable object. * * @param obj Object * An object to iterate. */ function makeArray( obj ) { var max, aux, diff, result = []; if (isArrayLike(obj)) { result.length = obj.length; max = obj.length - 1; for (aux = max; aux > -1; aux -= 1) { diff = max - aux; result[diff] = obj[diff]; } } return result; } /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a document node-like object. */ function getByName( method ) { var key = method; return function (doc, name) { return makeArray( doc[key](name) ); }; } /** * @public `Utils.select.byName`. * * @closure * * @description * Wrapper method that returns an array-like object * of node-like objects that match the specified * "name"; returns `null` if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getElementsByName = (function () { var key = "getElementsByName", result = null; if (isHostObject(doc[key])) { result = getByName( key ); } return result; }()); /** * @private * * @description * Object of documented `nodeType`s. * * @see DOM 4 Spec 5.3 (Node, nodeType). */ nodeTypes = { "ELEMENT_NODE": 1, "ATTRIBUTE_NODE": 2, "TEXT_NODE": 3, "CDATA_SECTION_NODE": 4, "ENTITY_REFERENCE_NODE": 5, "ENTITY_NODE": 6, "PROCRESSING_INSTRUCTION_NODE": 7, "COMMENT_NODE": 8, "DOCUMENT_NODE": 9, "DOCUMENT_TYPE_NODE": 10, "DOCUMENT_FRAGMENT_NODE": 11, "NOTATION_NODE": 12 }; /** * @private * * @description * Method that returns a boolean asserting if the * specified object has a certain value for the * `nodeType` property. * * @param obj Object * An object which will have its `nodeType` * property checked. * * @param num Number * A number to assert. */ function isNodeType( obj, num ) { var type = typeof obj, normal = hostTypes[type] && obj, result = false; if (normal || type === "unknown") { result = obj.nodeType === num; } return result; } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is a document node-like object. * * @param obj Object * An object to assert. */ function isDocumentNode( obj ) { var type = nodeTypes.DOCUMENT_NODE; return isNodeType( obj, type ); } /** * @private * * @description * Method that returns a boolean asserting if the * specified object is the current document. * * @param obj Object * An object to assert. */ function isAlmostDocument( obj ) { return obj === global.document; } /** * @private * * @closure * * @description * Wrapper method that returns (via a closure) a * boolean asserting if the specified object is a * document node-like object or the current document. * * @param obj Object * An object to assert. * * @see `isDocumentNode`. * @see `isAlmostDocument`. */ isDocument = (function () { var result = isDocumentNode; if (!isNodeLike(doc)) { result = isAlmostDocument; } return result; }()); /** * @private * * @description * Method that returns a boolean asserting if the * specified object is an element node-like object. * * @param obj Object * An object to assert. */ function isElement( obj ) { var type = nodeTypes.ELEMENT_NODE; return isNodeType( obj, type ); } /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a document node-like object or an element * node-like object. */ function getByTagName( method ) { var key = method; return function (caller, tag) { var result = null; if (isDocument(caller) || isElement(caller)) { result = makeArray( caller[key](tag) ); } return result; }; } /** * @public `Utils.select.byTagName`. * * @closure * * @description * Wrapper method that returns an array-like object * of node-like objects that match the specified * "tag"; returns `null` if not applicable. * * @param caller Object * A document node-like object or element node-like * object to access. * * @param tag String * A string containing the "tag" to find. */ getElementsByTagName = (function () { var key = "getElementsByTagName", result = null; if (isHostObject(doc[key])) { result = getByTagName( key ); } return result; }()); /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a document node-like object or an element * node-like object. */ function getByTagNameNS( method ) { var key = method; return function (caller, local, ns) { var result = null; if (isDocument(caller) || isElement(caller)) { result = makeArray( caller[key](local, ns) ); } return result; }; } /** * @public `Utils.select.byTagNameNS`. * * @closure * * @description * Wrapper method that returns an array-like object * of node-like objects that match the specified * "namespace" and/or "local name"; returns `null` * if not applicable. * * @param caller Object * A document node-like object or element node-like * object to access. * * @param local String * A string containing the "local name" to find. * * @param ns String * A string containing the "namespace" to find. */ getElementsByTagNameNS = (function () { var key = "getElementsByTagNameNS", result = null; if (isHostObject(doc[key])) { result = getByTagNameNS( key ); } return result; }()); /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a document node-like object or an element * node-like object. */ function getByClassName( method ) { var key = method; return function (caller, names) { var result = null; if (isDocument(caller) || isElement(caller)) { result = makeArray( caller[key](names) ); } return result; }; } /** * @public `Utils.select.byClassName`. * * @closure * * @description * Wrapper method that returns an array-like object * of node-like objects that match the specified * "class name(s)"; returns `null` if not applicable. * * @param caller Object * A document node-like object or element node-like * object to access. * * @param names String * A string containing the "class name(s)" to find. */ getElementsByClassName = (function () { var key = "getElementsByClassName", result = null; if (isHostObject(doc[key])) { result = getByClassName( key ); } return result; }()); /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a document node-like object. */ function getById( method ) { var key = method; return function (doc, id) { return doc[key](id); }; } /** * @public `Utils.select.byId`. * * @closure * * @description * Wrapper method that returns a node-like object. * that matches the specified "id"; returns `null` if * not applicable. * * @param doc Object * A document node-like object object to access. * * @param id String * A string containing the "id" to find. */ getElementById = (function () { var key = "getElementById", result = null; if (isHostObject(doc[key])) { result = getById( key ); } return result; }()); /** * @private * * @description * Method that returns the "head" element node-like * object for the specified document; returns * `null` if not applicable. * * @param doc Object * A document node-like object to access. */ function getNativeHead( doc ) { return doc.head; } /** * @private * * @description * Method that returns the "head" element node-like * object for the specified document; returns * `null` if not applicable. * * @param doc Object * A document node-like object to access. */ function forkHead( doc ) { var heads, result = null; heads = getElementsByTagName( doc, "head" ); if (isArrayLike(heads)) { result = heads[0]; } return result; } /** * @public `Utils.select.head`. * * @closure * * @description * Wrapper method that returns (via a closure) the * "head" element node-like object for the specified * document node-like object; returns `null` if not * applicable. * * @see `getNativeHead`. * @see `forkHead`. */ getHead = (function () { var key = "getElementsByTagName", result = null; if (isHostObject(doc.head)) { result = getNativeHead; } else if (isHostObject(doc[key])) { result = forkHead; } return result; }()); /** * @private * * @description * Method that returns the "body" element node-like * object for the specified document; returns * `null` if not applicable. * * @param doc Object * A document node-like object to access. */ function getNativeBody( doc ) { return doc.body; } /** * @private * * @description * Method that returns the "body" element node-like * object for the specified document; returns * `null` if not applicable. * * @param doc Object * A document node-like object to access. */ function forkBody( doc ) { var bodies, result = null; bodies = getElementsByTagName( doc, "body" ); if (isArrayLike(bodies)) { result = bodies[0]; } return result; } /** * @public `Utils.select.body`. * * @closure * * @description * Wrapper method that returns (via a closure) the * "body" element node-like object for the specified * document node-like object; returns `null` if not * applicable. * * @see `getNativeBody`. * @see `forkBody`. */ getBody = (function () { var key = "getElementsByTagName", result = null; if (isHostObject(doc.body)) { result = getNativeBody; } else if (isHostObject(doc[key])) { result = forkBody; } return result; }()); /** * @private * * @closure * * @description * Object containing applicable `nodeType` property * values for `querySelector*`. */ selectorTypes = (function () { var result = {}; result[nodeTypes.ELEMENT_NODE] = true; result[nodeTypes.DOCUMENT_NODE] = true; result[nodeTypes.DOCUMENT_FRAGMENT_NODE] = true; return result; }()); /** * @private * * @description * Helper method that returns a boolean asserting if * a node-like object can call `querySelector*`. * * @param obj Object * A node-like object to assert. */ function canCallSelectors( obj ) { var types = selectorTypes, result = false; if (isNodeLike(obj)) { result = typeof types[obj.nodeType] !== "undefined"; } return result; } /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a node-like object. */ function getQuerySelector( method ) { var key = method; return function (caller, selectors) { var result = null; if (canCallSelectors(caller)) { result = caller[key]( selectors ); } return result; }; } /** * @public `Utils.select.query`. * * @closure * * @description * Wrapper method that returns a node-like object. * that matches the specified "selectors"; returns * `null` if not applicable. * * @param caller Object * A node-like object object to access. * * @param selectors String * A string containing the "selectors" to find. */ querySelector = (function () { var key = "querySelector", result = null; if (canCallSelectors(doc)) { if (isHostObject(doc[key])) { result = getQuerySelector( key ); } } return result; }()); /** * @private * * @description * Method that returns a closure that wraps the * specified key, and calls it as a method. * * @param method String * A string containing the key to call as a method of * a node-like object. */ function getQuerySelectorAll( method ) { var key = method; return function (caller, selectors) { var result = null; if (canCallSelectors(caller)) { result = makeArray( caller[key](selectors) ); } return result; }; } /** * @public `Utils.select.queryAll`. * * @closure * * @description * Wrapper method that returns an array-like object * of node-like objects that match the specified * "selectors"; returns `null` if not applicable. * * @param caller Object * A node-like object object to access. * * @param selectors String * A string containing the "selectors" to find. */ querySelectorAll = (function () { var key = "querySelectorAll", result = null; if (canCallSelectors(doc)) { if (isHostObject(doc[key])) { result = getQuerySelectorAll( key ); } } return result; }()); /** * @private * * @description * Helper method that converts an `HTMLCollection` to * an array-like object if necessary and returns it. * * @param items Object * An array-like or node-like object to examine. */ function adjustItems( items ) { var result = items; if (!isNodeLike(items) && isArrayLike(items)) { result = makeArray( items ); } return result; } /** * @private * * @description * Method that returns a closure that wraps the * specified collection, and converts it to an * array-like object. * * @param collection String * A string containing the key to access as a * property of a document node-like object. */ function getDocumentCollection( collection ) { var key = collection; return function (doc) { return makeArray( doc[key] ); }; } /** * @private * * @description * Method that returns a closure that wraps the * specified key; returns `null` if not applicable. * * @param doc Object * A document node-like object to access. * * @param key String * A string containing the key to access as a * property of a document node-like object. */ function wrapCollection( doc, key ) { var result = null; if (isHostObject(doc[key])) { result = getDocumentCollection( key ); } return result; } /** * @private * * @description * Method that returns node-like objects from an * `HTMLCollection` based upon a key; returns `null` * if not applicable. * * @param collection String * A string containing the key to access as a * property of a document node-like object. */ function getNamedDocumentItem( collection ) { var key = collection; return function (doc, name) { return adjustItems( doc[key][name] ); }; } /** * @private * * @description * Method that returns a closure that wraps the * specified key; returns `null` if not applicable. * * @param doc Object * A document node-like object to access. * * @param key String * A string containing the key to access as a * property of a document node-like object. */ function wrapNamedItems( doc, key ) { var result = null; if (isHostObject(doc[key])) { result = getNamedDocumentItem( key ); } return result; } /** * @public `Utils.select.images`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `images` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getImages = (function () { return wrapNamedItems( doc, "images" ); }()); /** * @public `Utils.select.allImages`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `images` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllImages = (function () { return wrapCollection( doc, "images" ); }()); /** * @public `Utils.select.embeds`. * @public `Utils.select.plugins`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `embeds` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getEmbeds = (function () { return wrapNamedItems( doc, "embeds" ); }()); /** * @public `Utils.select.allEmbeds`. * @public `Utils.select.allPlugins`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `embeds` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllEmbeds = (function () { return wrapCollection( doc, "embeds" ); }()); /** * @public `Utils.select.links`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `links` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getLinks = (function () { return wrapNamedItems( doc, "links" ); }()); /** * @public `Utils.select.allLinks`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `links` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllLinks = (function () { return wrapCollection( doc, "links" ); }()); /** * @public `Utils.select.forms`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `forms` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getForms = (function () { return wrapNamedItems( doc, "forms" ); }()); /** * @public `Utils.select.allForms`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `forms` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllForms = (function () { return wrapCollection( doc, "forms" ); }()); /** * @public `Utils.select.scripts`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `scripts` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getScripts = (function () { return wrapNamedItems( doc, "scripts" ); }()); /** * @public `Utils.select.allScripts`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `scripts` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllScripts = (function () { return wrapCollection( doc, "scripts" ); }()); /** * @public `Utils.select.applets`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `applets` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getApplets = (function () { return wrapNamedItems( doc, "applets" ); }()); /** * @public `Utils.select.allApplets`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `applets` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllApplets = (function () { return wrapCollection( doc, "applets" ); }()); /** * @public `Utils.select.anchors`. * * @description * Method that returns an array-like object * containing the node-like objects that match the * specified "name" in a specific document node-like * object's `anchors` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. * * @param name String * A string containing the "name" to find. */ getAnchors = (function () { return wrapNamedItems( doc, "anchors" ); }()); /** * @public `Utils.select.allAnchors`. * * @description * Method that returns an array-like object * containing the specified document node-like * object's `anchors` `HTMLCollection`; returns `null` * if not applicable. * * @param doc Object * A document node-like object to access. */ getAllAnchors = (function () { return wrapCollection( doc, "anchors" ); }()); /** * @public `Utils.select.namedItem`. * * @description * Method that returns either a node-like object or * an array-like object representing the specified * name result of a specific `HTMLCollection`. * * @param obj Object * A node-like object to access. * * @param key String * A string containing the key to access as a * property of a node-like object. * * @param name String * A string containing the name to access * from the specified collection. */ function getNamedItem( obj, key, name ) { var result = null; if (obj && isHostObject(obj[key])) { result = adjustItems( obj[key][name] ); } return result; } /** * @public `Utils.select.collection`. * * @description * Method that returns an `HTMLCollection` from the * specified object converted to an array-like object. * * @param obj Object * A node-like object to access. * * @param key String * A string containing the key to access as a * property of a node-like object. */ function getCollection( obj, key ) { var result = null; if (obj && isHostObject(obj[key])) { result = makeArray( obj[key] ); } return result; } doc = null; Utils.select = Utils.select || { "byName": getElementsByName, "byTagName": getElementsByTagName, "byTagNameNS": getElementsByTagNameNS, "byClassName": getElementsByClassName, "byId": getElementById, "query": querySelector, "queryAll": querySelectorAll, "body": getBody, "head": getHead, "images": getImages, "allImages": getAllImages, "embeds": getEmbeds, "allEmbeds": getAllEmbeds, "plugins": getEmbeds, "allPlugins": getAllEmbeds, "links": getLinks, "allLinks": getAllLinks, "forms": getForms, "allForms": getAllForms, "scripts": getScripts, "allScripts": getAllScripts, "applets": getApplets, "allApplets": getAllApplets, "anchors": getAnchors, "allAnchors": getAllAnchors, "namedItem": getNamedItem, "collection": getCollection }; }()); }
/* * Challenge desc - Find the smallest LCM of two numbers such that the LCM divides all the numbers in between the given numbers evenly. * main_function : smallestCommons * level - advanced. * @author : HS<dcotre.1760@outlook.com> */ function is_prime(num){ // tell if the passed argument is a prime number or not. if(typeof num !=="number"){ throw new Error("Passed argument is not a number"); } if(num==1) return true; // if the number is 1, return true. Arguable !! for(var i = 2; i<num ; i++){ if(num%i === 0){ return false; } } return true; } function get_prime_factors(num){ // returns all the prime factors of the passed number. if(typeof num !=="number"){ throw new Error("Passed argument is not a number"); } if(is_prime(num)){ return [num]; // a prime number can not have any factors other than 1 and itself. } var prime_factors = [], factor = 2, LOOP_MAX=30, loop_counter=0; //LOOP_MAX as a control to avoid the infinite loop, if any. while(num!==1){ // num after all the division will remain to be just 1. if(is_prime(factor)){ if(num%factor===0){ // if the num is divided by the factor completely, than this prime number(factor) is recorded. prime_factors.push(factor); num /= factor; // num is updated by dividing by the factor continue; } } factor += 1; // increasing factor if it is not the prime number. loop_counter++; // updating loop_counter if(loop_counter>LOOP_MAX) throw new Error("LOOP_MAX crossed."); // again, a control to avoid any infinite loop. } return prime_factors; // returns the prime factors } function get_frequency(arr){ // accepts the result of get_prime_factors // results an object with the keys as the prime factors and the corresponding values to be thier occurence in the arr. var freq = {}; // the frequency object for(var i=0; i<arr.length; i++){ if(freq.hasOwnProperty(arr[i])){//check to see if frequency has already been started to count for the prime factor. freq[arr[i]]++; // increasing the value by one, if so. } else{ freq[arr[i]] = 1 ; // otherwise, making a new property of the frequency object accordingly. } } return freq; // returning the frequency object. } function get_common_property(ob1, ob2){ // returns the common properties/attributes of two objects represented by ob1 and ob2. // used here to get the common keys or prime factors using the frequency data. var ob1_keys = Object.keys(ob1); // getting the keys of both the objects. var ob2_keys = Object.keys(ob2); var common_keys = []; // recorder for the common keys for(var i = 0 ; i<ob1_keys.length ; i++){ for(var j = 0; j<ob2_keys.length; j++){ if(ob1_keys[i]===ob2_keys[j] && common_keys.indexOf(ob1_keys[i])<0){ // check to see if the common key has recorded the founded common key common_keys.push(ob1_keys[i]); // and if not, record it. } } } return common_keys; // return the common keys. } function get_least_common_factor(num1,num2){ // returns the LCM of num1 and num2 var num1_prime_factors = get_prime_factors(num1); //prime factors of the num1 var num2_prime_factors = get_prime_factors(num2); // prime factors of num2 var num1_frequency = get_frequency(num1_prime_factors); // frequency data of prime factors of num1 var num2_frequency = get_frequency(num2_prime_factors); //like just above step var common_keys = get_common_property(num1_frequency, num2_frequency);// common prime factors of num1 and num2 using the frequency data. for(var i = 0 ; i<common_keys.length ; i++){ //reducing the common properties to proper values if(num1_frequency[common_keys[i]]!==num2_frequency[common_keys[i]]){ num1_frequency[common_keys[i]]=Math.max(num1_frequency[common_keys[i]],num2_frequency[common_keys[i]]); // recording the maximum of two values of frequency of prime factors in common } delete num2_frequency[common_keys[i]]; // and deleting that particular prime factor property from one of the frequency data. } var num1_frequency_keys = Object.keys(num1_frequency); var num2_frequency_keys = Object.keys(num2_frequency); var num1_reduction = 1; var num2_reduction = 1; var j; for(i=0; i<num1_frequency_keys.length ; i++){ //reducing the whole frequency data into the multiple for(j = 0 ; j<num1_frequency[num1_frequency_keys[i]] ; j++){ num1_reduction *= num1_frequency_keys[i];} } for(i=0; i<num2_frequency_keys.length ; i++){ for(j = 0 ; j<num2_frequency[num2_frequency_keys[i]] ; j++){ num2_reduction *= num2_frequency_keys[i];} } var final_reduction = num1_reduction * num2_reduction ; // finally reduction return final_reduction; //returning the final reduction, the lcm. } function smallestCommons(arr) { arr = arr.sort(function(a,b){return a-b;}); //sorting the arr into ascending order var lcm = get_least_common_factor(arr[0],arr[1]); // find the lcm of the two numbers. var MAX_MULTIPLIER = 6056820, multiplier_counter=0, answer ; // MAX_MULTIPLIER to avoid the infinite loop, if any. A safe control. :) for(var i = 1; i<=MAX_MULTIPLIER ; i++){ // finds out the multiple such that the numbers between arr[0] and arr[1] divides multiple evenly. var counter_even_divisions = 0; // counts the number of even divisions var expected_even_divisions = arr[1]-arr[0]-1; // expected even number of divisions var multiple = lcm * i; // multiple for(var j = arr[0]+1 ; j< arr[1]; j++){ // see if all the numbers in between the range provided by the arr, can divide the multiple evenly. if(multiple%j===0){ // j represents the number from the range. counter_even_divisions += 1; // counts the even divisions. } } if(counter_even_divisions===expected_even_divisions){ // if counted even divisions are equal to expected which shows all the numbers in the range starting from sorted arr[0] to arr[1] divides the multiple evenly. answer = multiple; // then assigning the multiple to answer break; } } if(answer){ return answer; // returning answer } else{ throw new Error("MAX_MULTIPLIER is crossed"); // a safe control. } } //challenge function - smallestCommons //smallestCommons([8,9]);
'use strict'; var React = require('react'); module.exports = React.createClass({ render: function() { return ( /* jshint ignore:start */ <div>About Page</div> /* jshint ignore:end */ ); } });
import { SerialTimer } from 'virtjs/devices/timers/SerialTimer'; import { makeFastTick } from 'virtjs/devices/timers/utils'; export class AsyncTimer { /** * An AsyncTimer is an asynchronous timer device. You can use it to run your emulator without blocking your main thread. However, unless you really want to implement a new asynchronous device on top of a new API, you're probably looking for {@link AnimationFrameTimer} for browser environments, or {@link ImmediateTimer} for Node.js environments. * * @constructor * @implements {Timer} * * @param {object} [options] - The timer options. * @param {function} [options.prepare] - The callback that will schedule the next cycle * @param {function} [options.cancel] - The callback that will abort the next cycle * * @see {@link AnimationFrameTimer} * @see {@link ImmediateTimer} */ constructor({ prepare, cancel } = { }) { if (prepare) this.prepare = prepare; if (cancel) this.cancel = cancel; this.running = false; this.nested = false; this.loopHandler = null; this.fastLoop = null; this.timer = new SerialTimer(); } nextTick(callback) { return this.timer.nextTick(callback); } cancelTick(handler) { return this.timer.cancelTick(handler); } start(beginning, ending) { if (this.running) throw new Error(`You can't start a timer that is already running`); if (this.nested) throw new Error(`You can't start a timer from its callbacks - use resume instead`); this.running = true; let resolve; let reject; let promise = new Promise((resolveFn, rejectFn) => { resolve = resolveFn; reject = rejectFn; }); let fastTick = makeFastTick(beginning, ending, () => { this.timer.one(); }); let mainLoop = () => { if (!this.running) { resolve(); } else try { this.prepare(mainLoop); this.nested = true; fastTick(); this.nested = false; } catch (e) { this.running = false; this.nested = false; reject(e); } }; this.prepare(mainLoop); return promise; } resume() { if (!this.nested) throw new Error(`You can't resume a timer from anywhere else than its callbacks - use start instead`); if (this.running) return; this.running = true; } stop() { if (!this.running) return; this.running = false; } /** * This method should be specialized, either via subclassing, or by passing the proper parameter when instanciating the timer. * * @protected * * @type {prepareCallback} */ prepare() { throw new Error(`Unimplemented`); } /** * This method should be specialized, either via subclassing, or by passing the proper parameter when instanciating the timer. * * @protected * * @type {cancelCallback} */ cancel() { throw new Error(`Unimplemented`); } }
import Xhr from "./Xhr"; import { default as PubSub } from "pubsub-js"; describe("Xhr", () => { it("can be created and initializes", () => { let xhrMock = { open: jest.fn(), send: jest.fn() }; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); expect(psMock.subscribe.mock.calls.length).toBe(1); }); it("can process a get request", () => { let xhrMock = jest.genMockFromModule("./Xhr.mock").default; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); psMock.subscribe.mock.calls[0][1]("action.sendRequest", { id: 1, method: "GET", url: "some.url" }); expect(xhrMock.mock.instances.length).toBe(1); expect(xhrMock.mock.instances[0].open.mock.calls[0]).toEqual(["GET", "some.url"]); expect(xhrMock.mock.instances[0].send.mock.calls[0]).toEqual([]); expect(xhrMock.mock.instances[0].setRequestHeader.mock.calls[0]).toEqual(["Content-type", "application/json"]); expect(xhrMock.mock.instances[0].withCredentials).toBe(true); expect(typeof xhrMock.mock.instances[0].onload).toBe("function"); xhrMock.mock.instances[0].onload({ test: "test" }); expect(psMock.publish.mock.calls[0]).toEqual(["event.requestCompleted.1", { id: 1, data: xhr }]); }); it("can process a post request", () => { let xhrMock = jest.genMockFromModule("./Xhr.mock").default; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); psMock.subscribe.mock.calls[0][1]("action.sendRequest", { id: 1, method: "POST", url: "some.url", data: { test: "test" } }); expect(xhrMock.mock.instances.length).toBe(1); expect(xhrMock.mock.instances[0].open.mock.calls[0]).toEqual(["POST", "some.url"]); expect(xhrMock.mock.instances[0].send.mock.calls[0]).toEqual([JSON.stringify({ test: "test" })]); expect(typeof xhrMock.mock.instances[0].onload).toBe("function"); xhrMock.mock.instances[0].onload({ test: "test" }); expect(psMock.publish.mock.calls[0]).toEqual(["event.requestCompleted.1", { id: 1, data: xhr }]); }); it("produces an appropriate error message", () => { let xhrMock = jest.genMockFromModule("./Xhr.mock").default; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); psMock.subscribe.mock.calls[0][1]("action.sendRequest", { id: 1, method: "POST", url: "some.url", data: { test: "test" } }); expect(xhrMock.mock.instances.length).toBe(1); expect(typeof xhrMock.mock.instances[0].onerror).toBe("function"); xhrMock.mock.instances[0].onerror(); expect(psMock.publish.mock.calls[0]).toEqual(["event.requestCompleted.1", { id: 1, error: xhr }]); }); it("produces an appropriate timeout message", () => { let xhrMock = jest.genMockFromModule("./Xhr.mock").default; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); psMock.subscribe.mock.calls[0][1]("action.sendRequest", { id: 1, method: "POST", url: "some.url", data: { test: "test" } }); expect(xhrMock.mock.instances.length).toBe(1); expect(typeof xhrMock.mock.instances[0].ontimeout).toBe("function"); xhrMock.mock.instances[0].ontimeout(); expect(psMock.publish.mock.calls[0]).toEqual(["event.requestCompleted.1", { id: 1, error: xhr }]); }); it("produces an appropriate abort message", () => { let xhrMock = jest.genMockFromModule("./Xhr.mock").default; let psMock = jest.genMockFromModule("pubsub-js"); let xhr = new Xhr(xhrMock, psMock); psMock.subscribe.mock.calls[0][1]("action.sendRequest", { id: 1, method: "POST", url: "some.url", data: { test: "test" } }); expect(xhrMock.mock.instances.length).toBe(1); expect(typeof xhrMock.mock.instances[0].onabort).toBe("function"); xhrMock.mock.instances[0].onabort(); expect(psMock.publish.mock.calls[0]).toEqual(["event.requestCompleted.1", { id: 1, error: xhr }]); }); });
import React, { Component } from 'react' import { Button, Form, Input } from 'stardust' export default class FormSizeSmallExample extends Component { render() { return ( <Form className='small'> <Form.Fields> <Form.Field label='First name'> <Input placeholder='First name' /> </Form.Field> <Form.Field label='Last name'> <Input placeholder='Last name' /> </Form.Field> </Form.Fields> <Button type='submit'>Submit</Button> </Form> ) } }
Bridge.assembly("Bridge.ChartJS", function ($asm, globals) { "use strict"; Bridge.define("ChartJS.Extensions"); });
import React, { PropTypes } from 'react'; import { Decorator as Cerebral, Link } from 'cerebral-view-react'; import styles from './styles.css'; @Cerebral({ isRunning: 'bin.isRunning', showFullLog: 'bin.showFullLog', showLog: 'bin.showLog', isLoadingIframe: 'bin.isLoadingIframe' }) class Preview extends React.Component { constructor(props) { super(props); this.onIframeMessage = this.onIframeMessage.bind(this); } componentDidUpdate(prevProps) { if (!this.props.isLoadingIframe && prevProps.isRunning && !this.props.isRunning) { this.refreshIframe(); } } componentDidMount() { window.onmessage = this.onIframeMessage; this.refreshIframe(); } refreshIframe() { this.refs.iframe.src = [ location.protocol, '//', location.hostname.replace('www', 'sandbox'), (location.port ? ':' + location.port : ''), '/' ].join(''); this.props.signals.bin.iframeLoading(); } onIframeMessage(event) { if (event.data.type === 'loaded') { this.props.signals.bin.iframeLoaded(); } if (event.data.type === 'log') { this.props.signals.bin.logReceived({ value: event.data.value }); } if (event.data.type === 'click') { this.props.signals.bin.appClicked(); } } render() { return ( <div className={this.props.showFullLog || !this.props.showLog ? styles.wrapper : styles.halfWrapper}> <iframe className={styles.iframe} ref="iframe"/> <div className={styles.iframeLoader + (this.props.isLoadingIframe ? ' ' + styles.iframeLoaderVisible : '')}>Loading...</div> </div> ); } } export default Preview;
'use strict'; /** * Module dependencies */ var acl = require('acl'), mongoose = require('mongoose'), User = mongoose.model('User'); // Using the memory backend acl = new acl(new acl.memoryBackend()); /** * Invoke Articles Permissions */ exports.invokeRolesPolicies = function() { acl.allow([{ roles: ['admin'], allows: [{ resources: '/api/devices', permissions: '*' }, { resources: '/api/devices/:deviceId', permissions: '*' }] }, { roles: ['user'], allows: [{ resources: '/api/devices', permissions: '*' }, { resources: '/api/devices/:deviceId', permissions: '*' }] }, { roles: ['guest'], allows: [{ resources: '/api/devices', permissions: '*' }, { resources: '/api/devices/:deviceId', permissions: '*' }] }]); }; exports.userAuthenticate = function(req, res, next) { var authKey = req.headers.authorization; Device.find({ authToken: authKey }).exec(function(err, device) { if (err) res.status(500).send('Unexpected authorization error'); if (!device) { return res.status(403).json({ message: 'User is not authorized' }); } }); return next(); }; exports.isAllowed = function(req, res, next) { return next(); };
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdBorderRight(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M14 42h4v-4h-4v4zM6 10h4V6H6v4zm8 0h4V6h-4v4zm0 16h4v-4h-4v4zM6 42h4v-4H6v4zm16 0h4v-4h-4v4zM6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm16 16h4v-4h-4v4zm8-8h4v-4h-4v4zm8-20v36h4V6h-4zm-8 36h4v-4h-4v4zm0-32h4V6h-4v4zm-8 16h4v-4h-4v4zm0-16h4V6h-4v4zm0 8h4v-4h-4v4z" /> </IconBase> ); } export default MdBorderRight;
import { jsdom } from 'jsdom'; import register from 'ignore-styles'; register(['.sass', '.scss']); process.env.NODE_ENV = 'testing'; global.chai = require('chai'); global.expect = global.chai.expect; global.spyOn = global.expect.spyOn; global.document = jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; global.navigator = global.window.navigator; global.location = global.window.location;
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ preprocessors: { '**/*.coffee': ['coffee'] }, coffeePreprocessor: { // options passed to the coffee compiler options: { bare: true, sourceMap: false }, // transforming the filenames transformPath: function(path) { return path.replace(/\.coffee$/, '.js'); } }, // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine', "requirejs"], // list of files / patterns to load in the browser files: [ {pattern: 'app/bower_components/angular/angular.js', included: false }, {pattern: 'app/bower_components/angular-mocks/angular-mocks.js', included: false }, {pattern: 'app/bower_components/angular-route/angular-route.js', included: false }, {pattern: 'app/bower_components/angular-cookies/angular-cookies.js', included: false }, {pattern: 'app/bower_components/angular-sanitize/angular-sanitize.js', included: false }, {pattern: 'app/bower_components/angular-resource/angular-resource.js', included: false }, {pattern: 'app/bower_components/requirejs-text/text.js', included: false }, {pattern: 'app/bower_components/requirejs-domready/domReady.js', included: false }, {pattern: 'app/bower_components/sass-bootstrap/js/dropdown.js', included: false }, {pattern: 'app/bower_components/lodash/dist/lodash.js', included: false }, {pattern: 'app/bower_components/hammerjs/hammer.js', included: false }, {pattern: 'app/bower_components/jquery/dist/jquery.js', included: false }, {pattern: 'app/bower_components/woodman/dist/woodman-amd.js', included: false }, {pattern: '.tmp-dist/scripts/vendor/*.js', included: false }, {pattern: '.tmp-dist/scripts/*.js', included: false }, {pattern: '.tmp-dist/scripts/**/*.js', included: false }, {pattern: 'app/views/*.html', included: false }, {pattern: 'test/spec/**/*.js', included: false }, // http://karma-runner.github.io/0.10/plus/requirejs.html 'test/test-bootstrap.js' ], // list of files / patterns to exclude exclude: [ 'app/scripts/bootstrap.js' ], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing 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'], //['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
/* populate workflow pages via jsonp feed * requires jsonp feed via a php file on the wp server * REMEMBER TO CHANGE THE URL FROM DEV TO THE LIVE SITE, once ready. * slug must coorespond to the individual workflow entry */ function workflowRSS(url) { $.ajax({ // url: 'http://patricenews-dev.vbi.vt.edu/php/workflow.php?slug=example-workflow', url: url, dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'jsonpCallback', success: function(){ // alert("success"); } }); jsonpCallback = function(data){ // title area $('.workflow .wf-summary').append(data.summary[0]); $('.workflow .wf-headline').append(data.headline[0]); $('.workflow .wf-title-image').attr('src', data.summary_background_image); // bottom area $('.workflow .wf-bottom-right-headline').append(data.bottom_right_headline[0]); $('.workflow .wf-bottom-right').append(data.bottom_right[0]); $('.workflow .wf-dig-deeper-headline').append(data.bottom_left_headline[0]); // build template for tools list function toolsTemplate(title, content, image, url) { var template = '<li class="clear">' + '<figure class="figure-left">' + '<a href="' + url + '">' + '<img src="' + image + '" alt="' + title + '" /></a></figure>' + '<p>' + '<a href="' + url + '" class="upper">' + title + '</a> ' + content + '</p>' + '</li>'; return template; }; // tools list $.each(data.bottom_left, function(i, item) { // mod into two columns if ((i % 2) == 0) { $('.workflow article.tools .column:first-child ul').append(toolsTemplate(this.post_title, this.post_content, this.tool_image_thumbnail, this.tool_url)); } else { $('.workflow article.tools .column:last-child ul').append(toolsTemplate(this.post_title, this.post_content, this.tool_image_thumbnail, this.tool_url)); } }); /* BUILD STEPS */ // build template for carousel slides function slideTemplate(slide_id, title, content, image, total_slides) { var template = '<li class="slide white-bullets">' + '<div class="wrapper-inner">' + '<figure class="figure-right figure-no-border">' + '<img src="' + image + '" />' + '</figure>' + '<h2 class="far">Step ' + slide_id + ' of ' + total_slides + '</h2>' + '<p>' + content + '</p>' + '<nav class="carousel-nav">' + '<ul class="no-decoration inline prev-next">' + '<li class="prev"><a href="#">Previous</a></li>' + '<li class="next"><a href="#">Next</a></li>' + '</ul>' + '</nav>' + '</div>' + '</li>'; return template; }; // build template for callout links function calloutLinkTemplate(callout_index, title, icon, activator_link_text) { var template = '<li class="overview-open clear" data-overview="' + callout_index + '">' + '<a href="#" class="arrow-slate-e">' + '<figure class="figure-left figure-icon figure-no-border">' + '<img src="' + icon + '" />' + '</figure>' + '<span>' + activator_link_text + '</span>' + '</a>' + '</li>'; return template; }; // build template for callouts function calloutTemplate(callout_index, title, content) { var template = '<div class="overview-text" data-overview="' + callout_index + '">' + '<p>' + content + '</p>' + '</div>'; return template; }; // assemble carousel slides and return to parent slide template function getCarouselSlides(carousel) { var myCarousel = ""; var totalSlides = 0; $.each(carousel, function(i, item) { $.each(this.slides, function(j, item) { if (this.post_type) { totalSlides++; } }); }); $.each(carousel, function(i, item) { $.each(this.slides, function(j, item) { if (this.post_type) { myCarousel += slideTemplate((j + 1), this.post_title, this.post_content, this.image, totalSlides); } }); }); return myCarousel; }; // assemble callout links and return to parent slide template function getCalloutLinks(callouts) { var myLinks = ""; // console.log(callouts); $.each(callouts, function(i, item) { myLinks += calloutLinkTemplate((i + 1), this.post_title, this.icon, this.activator_link_text); }); return myLinks; }; // assemble callouts and return to parent slide template function getCallouts(callouts) { var myCallouts = ""; // console.log(callouts); $.each(callouts, function(i, item) { myCallouts += calloutTemplate((i + 1), this.post_title, this.post_content); }); return myCallouts; }; // parent step template function stepTemplate(step_id, title, content, display_title, ribbon_headline, image, carousel_activator_text, callouts, carousel) { // determine if this step has a carousel attached to it. var hasCarousel = carousel[0].post_type; //determine if this step has callouts attached to it var hasCallouts = ""; $.each(callouts, function(i, item) { hasCallouts = this.post_type; }); var template = '<div class="step">' + '<div class="ribbon upper ondark">' + '<div class="title large">' + ribbon_headline + '</div>' + '<div class="inner"></div>' + '</div>'; if(hasCarousel) { template += '<div class="carousel linkstyle-highlight-b ondark no-underline-links">' + '<p><a class="button close-slate" href="#">close</a></p>' + '<ul class="carousel-container">' + getCarouselSlides(carousel) + '</ul>' + '</div>'; // close carousel div } //endif for carousel template += '<div class="wrapper-base">' + '<div class="base">' + '<div class="inner">' + '<h2 class="xl constrain-width close2x">' + '<span class="highlight-c mega">' + step_id + '.</span>' + display_title + '</h2>'; if(hasCallouts) { template += '<ul class="overview-links no-decoration no-underline-links right">' + getCalloutLinks(callouts) + '</ul>'; } // endif for callouts (list of launchers) template += '<p class="deep-indent">' + content + '</p>' + '</div>' + // close inner '</div>' + // close base '<aside class="support">' + '<img class="overlay" src="' + image + '" />' + '<div class="wrapper-support">' + '<div class="overview ondark linkstyle-highlight-b no-underline-links">' + '<p><a class="button close-slate" href="#">Close</a></p>' + getCallouts(callouts) + '</div>' + // close callout container '<div class="see-container">'; if(hasCarousel) { template += '<p class="see linkstyle-highlight-c no-underline-links largest upper sans-alternate"><a href="#">' + carousel_activator_text + '</a></p>'; } // endif for carousel launcher ("see container") template += '</div>' + // close see container '</div>' + // close wrapper-support '</aside>' + '</div>' + // close wrapper base '</div>'; return template; }; // send step data to templates $.each(data.steps, function(i, item) { // console.log(this.callouts); $('.workflow.wf-steps').append(stepTemplate((i + 1), this.post_title, this.post_content, this.display_title, this.ribbon_headline, this.image, this.carousel_activator_text, this.callouts, this.carousel)); }); //init the carousel and wfInit after data has loaded setTimeout(function() { initwfCarousel(); wfControl(); }, 100); } }; // find a way to call this from the page, so the slug can be embedded into the page // workflowRSS('http://patricenews-dev.vbi.vt.edu/php/workflow.php?slug=example-workflow');
var mongoose = require('mongoose'), Schema = mongoose.Schema, bcrypt = require('bcrypt'), // Blowfish key cipher SALT_WORK_FACTOR = 10; var User = new Schema({ username: {type: String, required: true, index: {unique: true}}, password: {type: String, required: true}, accessToken: String, createAt: {type: Date, default: Date.now} }); // Hash the password User.pre('save', function (next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(SALT_WORK_FACTOR, function(error, salt) { if (error) return next(error); bcrypt.hash(user.password, salt, function(error, hash) { if (error) return next(error); user.password = hash; next(); }); }); }); User.methods.comparePassword = function(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, function (error, isMatch) { if (error) return callback(error); callback(null, isMatch); }); } module.exports = mongoose.model('User', User);
{ "name": "chow.js", "url": "https://github.com/F1ks3r/chow.js.git" }
const EMPTY = {}; export function assign(obj, props) { // eslint-disable-next-line guard-for-in for (let i in props) { obj[i] = props[i]; } return obj; } export function exec(url, route, opts) { let reg = /(?:\?([^#]*))?(#.*)?$/, c = url.match(reg), matches = {}, ret; if (c && c[1]) { let p = c[1].split('&'); for (let i=0; i<p.length; i++) { let r = p[i].split('='); matches[decodeURIComponent(r[0])] = decodeURIComponent(r.slice(1).join('=')); } } url = segmentize(url.replace(reg, '')); route = segmentize(route || ''); let max = Math.max(url.length, route.length); for (let i=0; i<max; i++) { if (route[i] && route[i].charAt(0)===':') { let param = route[i].replace(/(^:|[+*?]+$)/g, ''), flags = (route[i].match(/[+*?]+$/) || EMPTY)[0] || '', plus = ~flags.indexOf('+'), star = ~flags.indexOf('*'), val = url[i] || ''; if (!val && !star && (flags.indexOf('?')<0 || plus)) { ret = false; break; } matches[param] = decodeURIComponent(val); if (plus || star) { matches[param] = url.slice(i).map(decodeURIComponent).join('/'); break; } } else if (route[i]!==url[i]) { ret = false; break; } } if (opts.default!==true && ret===false) return false; return matches; } export function pathRankSort(a, b) { return ( (a.rank < b.rank) ? 1 : (a.rank > b.rank) ? -1 : (a.index - b.index) ); } // filter out VNodes without attributes (which are unrankeable), and add `index`/`rank` properties to be used in sorting. export function prepareVNodeForRanking(vnode, index) { vnode.index = index; vnode.rank = rankChild(vnode); return vnode.props; } export function segmentize(url) { return url.replace(/(^\/+|\/+$)/g, '').split('/'); } export function rankSegment(segment) { return segment.charAt(0)==':' ? (1 + '*+?'.indexOf(segment.charAt(segment.length-1))) || 4 : 5; } export function rank(path) { return segmentize(path).map(rankSegment).join(''); } function rankChild(vnode) { return vnode.props.default ? 0 : rank(vnode.props.path); }
'use strict'; const util = require('util'); const ember = require('../helpers/ember'); const fs = require('fs-extra'); const path = require('path'); let outputFile = util.promisify(fs.outputFile); let remove = util.promisify(fs.remove); let root = process.cwd(); let tmproot = path.join(root, 'tmp'); const Blueprint = require('../../lib/models/blueprint'); const BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint'); const mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in'); const chai = require('../chai'); let expect = chai.expect; let file = chai.file; describe('Acceptance: ember generate in-repo-addon', function() { this.timeout(20000); before(function() { BlueprintNpmTask.disableNPM(Blueprint); }); after(function() { BlueprintNpmTask.restoreNPM(Blueprint); }); beforeEach(async function() { const tmpdir = await mkTmpDirIn(tmproot); return process.chdir(tmpdir); }); afterEach(function() { process.chdir(root); return remove(tmproot); }); function initApp() { return ember(['init', '--name=my-app', '--skip-npm', '--skip-bower']); } async function initInRepoAddon() { await initApp(); return ember(['generate', 'in-repo-addon', 'my-addon']); } it('in-repo-addon blueprint foo inside alternate path', async function() { // build an app with an in-repo addon in a non-standard path await initApp(); await ember(['generate', 'in-repo-addon', './non-lib/other-thing']); // generate in project blueprint to allow easier testing of in-repo generation await outputFile('blueprints/foo/files/__root__/foos/__name__.js', '/* whoah, empty foo! */'); // confirm that we can generate into the non-lib path await ember(['generate', 'foo', 'bar', '--in-repo-addon=other-thing']); expect(file('non-lib/other-thing/addon/foos/bar.js')).to.exist; }); it('in-repo-addon adds path to lib', async function() { await initInRepoAddon(); expect(file('package.json')).to.contain('lib/my-addon'); }); });
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery to collapse the navbar on scroll function collapseNavbar() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } } $(window).scroll(collapseNavbar); $(document).ready(collapseNavbar); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); if( $anchor[0].hash == '#download'){ console.log('where in !') $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top + 150 }, 1500, 'easeInOutExpo'); }else { $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); } event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $(".navbar-collapse").collapse('hide'); }); // Google Maps Scripts var map = null; // When the window has finished loading create our google map below // google.maps.event.addDomListener(window, 'load', init); // google.maps.event.addDomListener(window, 'resize', function() { // map.setCenter(new google.maps.LatLng(40.6700, -73.9400)); // }); function init() { // Basic options for a simple Google Map // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions var mapOptions = { // How zoomed in you want the map to start at (always required) zoom: 15, // The latitude and longitude to center the map (always required) center: new google.maps.LatLng(40.6700, -73.9400), // New York // Disables the default Google Maps UI components disableDefaultUI: true, scrollwheel: false, draggable: false, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [{ "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }] }; // Get the HTML DOM element that will contain your map // We are using a div with id="map" seen below in the <body> var mapElement = document.getElementById('map'); // Create the Google Map using out element and options defined above map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(40.6700, -73.9400); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); }
function PositionError() { this.code = 0; this.message = ""; } PositionError.PERMISSION_DENIED = 1; PositionError.POSITION_UNAVAILABLE = 2; PositionError.TIMEOUT = 3; /** * This class provides access to device GPS data. * @constructor */ function Geolocation() { /** * The last known GPS position. */ this.lastPosition = null; this.lastError = null; }; /** * Asynchronously aquires the current position. * @param {Function} successCallback The function to call when the position * data is available * @param {Function} errorCallback The function to call when there is an error * getting the position data. * @param {PositionOptions} options The options for getting the position data * such as timeout. * PositionOptions.forcePrompt:Bool default false, * - tells iPhone to prompt the user to turn on location services. * - may cause your app to exit while the user is sent to the Settings app * PositionOptions.distanceFilter:double aka Number * - used to represent a distance in meters. PositionOptions { desiredAccuracy:Number - a distance in meters < 10 = best accuracy ( Default value ) < 100 = Nearest Ten Meters < 1000 = Nearest Hundred Meters < 3000 = Accuracy Kilometers 3000+ = Accuracy 3 Kilometers forcePrompt:Boolean default false ( iPhone Only! ) - tells iPhone to prompt the user to turn on location services. - may cause your app to exit while the user is sent to the Settings app distanceFilter:Number - The minimum distance (measured in meters) a device must move laterally before an update event is generated. - measured relative to the previously delivered location - default value: null ( all movements will be reported ) } */ Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) { var referenceTime = 0; if(this.lastError != null) { if(typeof(errorCallback) == 'function') { errorCallback.call(null,this.lastError); } this.stop(); return; } this.start(options); var timeout = 30000; // defaults var interval = 2000; if (options && options.interval) interval = options.interval; if (typeof(successCallback) != 'function') successCallback = function() {}; if (typeof(errorCallback) != 'function') errorCallback = function() {}; var dis = this; var delay = 0; var timer; var onInterval = function() { delay += interval; if(dis.lastPosition != null && dis.lastPosition.timestamp > referenceTime) { clearInterval(timer); successCallback(dis.lastPosition); } else if(delay > timeout) { clearInterval(timer); errorCallback("Error Timeout"); } else if(dis.lastError != null) { clearInterval(timer); errorCallback(dis.lastError); } } timer = setInterval(onInterval,interval); }; /** * Asynchronously aquires the position repeatedly at a given interval. * @param {Function} successCallback The function to call each time the position * data is available * @param {Function} errorCallback The function to call when there is an error * getting the position data. * @param {PositionOptions} options The options for getting the position data * such as timeout and the frequency of the watch. */ Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) { // Invoke the appropriate callback with a new Position object every time the implementation // determines that the position of the hosting device has changed. this.getCurrentPosition(successCallback, errorCallback, options); var frequency = (options && options.frequency) ? options.frequency : 10000; // default 10 second refresh var that = this; return setInterval(function() { that.getCurrentPosition(successCallback, errorCallback, options); }, frequency); }; /** * Clears the specified position watch. * @param {String} watchId The ID of the watch returned from #watchPosition. */ Geolocation.prototype.clearWatch = function(watchId) { clearInterval(watchId); }; /** * Called by the geolocation framework when the current location is found. * @param {PositionOptions} position The current position. */ Geolocation.prototype.setLocation = function(position) { this.lastError = null; this.lastPosition = position; }; /** * Called by the geolocation framework when an error occurs while looking up the current position. * @param {String} message The text of the error message. */ Geolocation.prototype.setError = function(error) { this.lastError = error; }; Geolocation.prototype.start = function(args) { PhoneGap.exec("Location.startLocation", args); }; Geolocation.prototype.stop = function() { PhoneGap.exec("Location.stopLocation"); }; // replace origObj's functions ( listed in funkList ) with the same method name on proxyObj // this is a workaround to prevent UIWebView/MobileSafari default implementation of GeoLocation // because it includes the full page path as the title of the alert prompt function __proxyObj(origObj,proxyObj,funkList) { var replaceFunk = function(org,proxy,fName) { org[fName] = function() { return proxy[fName].apply(proxy,arguments); }; }; for(var v in funkList) { replaceFunk(origObj,proxyObj,funkList[v]);} } PhoneGap.addConstructor(function() { if (typeof navigator._geo == "undefined") { navigator._geo = new Geolocation(); __proxyObj(navigator.geolocation, navigator._geo, ["setLocation","getCurrentPosition","watchPosition", "clearWatch","setError","start","stop"]); } });
var React = require('react') var Grapher = require('../lib/grapher') var cy var png = '' module.exports = React.createClass({ getInitialState: function () { return {key: '', link: ''} }, componentDidMount: function () { cy = Grapher(this.props.elements, this.refs.cy.getDOMNode()) }, handleClick: function () { png = cy.png() var node = this.refs.download.getDOMNode() node.className = 'button button-primary' node.href = png }, render: function () { return ( <div> <div className='row'> <div className='twelve columns middle'> <button className='button button-primary in-group' onClick={this.handleClick}>Generate PNG</button> <a ref='download' className='button button-primary hidden' download='graph.png'>Download PNG</a> </div> </div> <div ref='cy' className='cy outline'></div> </div> ) } })
// "Glorious Leader" game, created by Jack Dalton. // No JQuery. // No third-party libraries. // Two assets (un.png; obama.png) /* The MIT License (MIT) Copyright (c) 2015 Jack Dalton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function init() { // called on page load c = document.getElementById("canvas"); // get canvas ctx = c.getContext("2d"); // get context // c.addEventListener("mousedown", getPosition, false); startMenu(); middle = ($(window).width() / 2) - 125; } function startGame() { // game starting function playing = true; scoreLoop(); gameloop(); detectHits(); } var c, ctx, unX = [], unY = [], then = Date.now(), lost = false, score = 0, playing = false, middle, fallSpeed = 3, scInt = 100; // misc vars var obama = { // main obama var x:240, y:460, render:function() { ctx.drawImage(obamaImage, this.x, this.y, 25, 33); // draws image of obama } }; var un = { // main un var render:function() { for (var i = 0; i < unX.length; i++) { ctx.drawImage(unImage, unX[i], unY[i], 25, 29.619565217); // draws image of un } }, generate:function() { // generates new instances of un unX.push(rand(0, 460)); unY.push(rand(0, -10)); }, drop:function() { // makes un instances fall for (var i = 0; i < unY.length; i++) { unY[i] += fallSpeed; } } }; function detectHits() { // detects collisions between obama and un for (var i = 0; i < unX.length; i++) { if ( obama.x <= (unX[i] + 25) && unX[i] <= (obama.x + 25) && obama.y <= (unY[i] + 29.619565217) && unY[i] <= (obama.y + 33) ) { lost = true; // if player touches an instance of un, player loses } } window.requestAnimationFrame(detectHits); // does it all again } function scoreLoop() { // main score loop if (!lost) { // if player hasn't lost yet, their score increases score++; setTimeout(scoreLoop, scInt); // does it all again every 10th of a second } } function gameloop() { // main game loop c.width = c.width; // clears canvas if (!lost) { // if player hasn't lost un.render(); // renders un obama.render(); // renders obama if (chance10()) { // 10% chance of un instance being generated un.generate(); } un.drop(); // makes the fat man fall :) var now = Date.now(); // time delta stuff * var delta = now - then; //* move(delta / 1000); // * then = now; // * ctx.fillStyle = "red"; // sets text color ctx.fillText("Score:" + score, 10, 10); // displays score } else { lose(); startResetButton(); } window.requestAnimationFrame(gameloop); // does it all again } function lose() { // displays loss message document.getElementById("lostmessage").style.opacity = 1; document.getElementById("lostmessage").style.left = middle + "px"; document.getElementById("lostmessagetext").innerHTML = "Game Over!<br>Score:" + score + "."; } function rand(min, max) { // random number generator return Math.floor(Math.random() * (max - min + 1)) + min; } function removeItem(array, item) { // removes item from given array var e = array.indexOf(item); if (e > -1) { array.splice(e, 1); } } var move = function(m) { // movement function if (37 in keysDown && obama.x > 5) { // if left arrow key pressed, move left obama.x -= 180 * m; // obama movement } if (39 in keysDown && obama.x < 470) { // if right arrow key pressed, move right obama.x += 180 * m; // obama movement } }; function chance50() { // 50 percent chance if (rand(1,2) == 1) { return true; } else { return false; } } function chance5() { // 5 percent chance if (rand(1,20) == 1) { return true; } else { return false; } } function chance10() { // 10 percent chance if (rand(1, 10) == 1) return true; else return false; } var keysDown = {}; // keys pressed addEventListener("keydown", function(e) { // checks for keys down keysDown[e.keyCode] = true; }, false); addEventListener("keyup", function(e) { // checks for keys released delete keysDown[e.keyCode]; }, false); /*function getPosition(event) { var x = event.x; var y = event.y; x -= c.offsetLeft; y -= c.offsetTop; buttonCheck(x,y); } function buttonCheck(x,y) { if ( x >= 300 && y >= 125 && y <= 335 && x <= 475 ) { startGame(); } }*/ $(document).keydown(checkKey); //window.onkeypress = checkKey; function checkKey(e) { if (e.keyCode == 32 && playing === false) { startGame(); } if (e.keyCode == 32 && lost === true) { window.location.assign(window.location); } } function startMenu() { // starts game menu c.width = c.width; // clears canvas ctx.font = "normal 32px Verdana"; // sets up menu * ctx.strokeRect(100, 30, 300, 100); // * ctx.strokeStyle = "red"; // * ctx.strokeText("Glorious Leader", 130, 90); // * ctx.strokeStyle = "black"; // * ctx.strokeRect(125, 300, 250, 75); // * ctx.strokeText("Space to play.", 145, 350); // ** if (!playing) { // if play button has not been pressed, rerender menu window.requestAnimationFrame(startMenu); } } function startResetButton() { // sets up reset button ctx.strokeRect(125, 300, 250, 75); ctx.font = "normal 32px Verdana"; ctx.strokeText("Space to reset.", 130, 350); } function submitScore() { document.getElementById("scoreformscore").value = score; document.getElementById("scoreformuser").value = prompt("User:"); document.getElementById("scoreform").submit(); }
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var SessionStore = require('express-mysql-session'); var hbs = require('hbs'); var marked = require('marked'); var routes = require('./routes/index'); var users = require('./routes/users'); var notebooks = require('./routes/notebooks'); var tablets = require('./routes/tablets'); var phones = require('./routes/phones'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); var blocks = {}; hbs.registerHelper('extend', function(name, options) { var block = blocks[name]; if (!block) { block = blocks[name] = []; } block.push(options.fn(this)); // for older versions of handlebars, use block.push(context(this)); }); hbs.registerHelper('block', function(name) { var val = (blocks[name] || []).join('\n'); // clear the block blocks[name] = []; return val; }); hbs.registerHelper('markdown', function(options){ return marked(options.fn(this)); }); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session({ secret: 'session_cookie_secret', resave: true, saveUninitialized: true, store: new SessionStore({ host: 'localhost', port: 3306, user: 'root', password: 'p@ssw0rd', database: 'session_test' }) })); app.use('/', routes); app.use('/users', users); app.use('/notebooks', notebooks); app.use('/tablets', tablets); app.use('/phones', phones); /// catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
import * as React from 'react'; import AlarmIcon from '@material-ui/icons/Alarm'; import SnoozeIcon from '@material-ui/icons/Snooze'; import TextField from '@material-ui/core/TextField'; import ClockIcon from '@material-ui/icons/AccessTime'; import AdapterDateFns from '@material-ui/lab/AdapterDateFns'; import LocalizationProvider from '@material-ui/lab/LocalizationProvider'; import DateTimePicker from '@material-ui/lab/DateTimePicker'; import MobileDateTimePicker from '@material-ui/lab/MobileDateTimePicker'; import Stack from '@material-ui/core/Stack'; export default function CustomDateTimePicker() { const [clearedDate, setClearedDate] = React.useState(null); const [value, setValue] = React.useState(new Date('2019-01-01T18:54')); return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <Stack spacing={3}> <DateTimePicker disableFuture hideTabs showTodayButton todayText="now" openTo="hours" value={value} onChange={(newValue) => { setValue(newValue); }} minDate={new Date('2018-01-01')} components={{ LeftArrowIcon: AlarmIcon, RightArrowIcon: SnoozeIcon, OpenPickerIcon: ClockIcon, }} leftArrowButtonText="Open previous month" rightArrowButtonText="Open next month" minTime={new Date(0, 0, 0, 9)} maxTime={new Date(0, 0, 0, 20)} renderInput={(params) => ( <TextField {...params} helperText="Hardcoded helper text" /> )} /> <MobileDateTimePicker value={value} onChange={(newValue) => { setValue(newValue); }} label="With error handler" onError={console.log} minDate={new Date('2018-01-01T00:00')} inputFormat="yyyy/MM/dd hh:mm a" mask="___/__/__ __:__ _M" renderInput={(params) => <TextField {...params} />} /> <DateTimePicker clearable value={clearedDate} onChange={(newValue) => setClearedDate(newValue)} renderInput={(params) => ( <TextField {...params} helperText="Clear Initial State" /> )} /> </Stack> </LocalizationProvider> ); }
function attachEvents() { const baseUrl = 'https://baas.kinvey.com/appdata/kid_HkgoN45I-'; const kinveyUsername = 'kiril'; const kinveyPassword = 'kiril'; const base64auth = btoa(`${kinveyUsername}:${kinveyPassword}`); const authHeader = { 'Authorization': 'Basic ' + base64auth, 'Content-type': 'application/json' }; $('.load').click(loadAllCatches); $('.add').click(createCatch); function request(method, endpoint, data) { return $.ajax({ method: method, url: baseUrl + endpoint, headers: authHeader, data: JSON.stringify(data) }) } function loadAllCatches() { request('GET', '/biggestCatches') .then(displayAllCatches) .catch(handleError); } function displayAllCatches(data) { let catches = $('#catches'); catches.empty(); for(let el of data){ catches.append($(`<div class="catch" data-id="${el._id}">`) .append($('<label>') .text('Angler')) .append($(`<input type="text" class="angler" value="${el['angler']}"/>`)) .append($('<label>') .text('Weight')) .append($(`<input type="number" class="weight" value="${el['weight']}"/>`)) .append($('<label>') .text('Species')) .append($(`<input type="text" class="species" value="${el['species']}"/>`)) .append($('<label>') .text('Location')) .append($(`<input type="text" class="location" value="${el['location']}"/>`)) .append($('<label>') .text('Bait')) .append($(`<input type="text" class="bait" value="${el['bait']}"/>`)) .append($('<label>') .text('Capture Time')) .append($(`<input type="number" class="captureTime" value="${el['captureTime']}"/>`)) .append($('<button class="update">Update</button>').click(updateCatch)) .append($('<button class="delete">Delete</button>').click(deleteCatch))); } } function updateCatch() { let catchEl = $(this).parent(); let dataObj = createDataJson(catchEl); request('PUT', `/biggestCatches/${catchEl.attr('data-id')}`, dataObj) .then(loadAllCatches) .catch(handleError); } function deleteCatch() { let catchEl = $(this).parent(); request('DELETE', `/biggestCatches/${catchEl.attr('data-id')}`) .then(loadAllCatches) .catch(handleError); } function createCatch() { let catchEl = $('#addForm'); let dataObj = createDataJson(catchEl); request('POST', '/biggestCatches', dataObj) .then(loadAllCatches) .catch(handleError); } function createDataJson(catchEl) { return{ angler: catchEl.find('.angler').val(), weight: +catchEl.find('.weight').val(), // to Number species: catchEl.find('.species').val(), location: catchEl.find('.location').val(), bait: catchEl.find('.bait').val(), captureTime: +catchEl.find('.captureTime').val() // to Number } } function handleError(err) { alert(`ERROR: ${err.statusText}`); } }
//= require svg4everybody/svg4everybody.min.js // Jquery is piped into this file via Sprockets from its Bower package (/components) // so it can be updated/managed via Bower but easily referenced from /assets/javascripts/vendor
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Comment = mongoose.model('Comment'), User = mongoose.model('User'), UserFunction = require(path.resolve('./modules/users/server/controllers/users/users.role.server.controller')), DealFunction = require(path.resolve('./modules/deals/server/controllers/deals.server.controller')), _ = require('lodash'); /** * Find Comment by id */ exports.comment = function(req, res, next, id) { Comment.load(id, function(err, Comment) { if (err) return next(err); if (!Comment) return next(new Error('Failed to load Comment ' + id)); req.comment = Comment; next(); }); }; /** * Show a comment */ exports.show = function(req, res) { res.json(req.comment); }; /** * Create a Comment */ exports.create = function(req, res) { var comment = new Comment(req.body); comment.save(function(err) { if (err) { return res.json(500, { error: 'Cannot save the comment' }); } else { comment.populate({ path: 'mentionsUsers', select: 'name username' }, function(err, doc) { res.json(doc); }); } }); }; /** * Update a comment */ exports.update = function(req, res) { var comment = req.Comment; var mentions = []; var tagged_Users = []; if (req.body.mentionsUsers.length > 0) { _.map(req.body.mentionsUsers, function(mu) { // push client id (converted from string to mongo object id) into clients if (mu._id !== undefined) { tagged_Users.push(mu); mentions.push(mongoose.Types.ObjectId(mu._id)); } else mentions.push(mongoose.Types.ObjectId(mu)); }); req.body.mentionsUsers = mentions; } comment = _.extend(comment, req.body); comment.save(function(err) { if (err) { return res.json(500, { error: 'Cannot update the comment' }); } else { comment.populate({ path: 'mentionsUsers', select: 'name username' }, function(err, doc) { res.json(doc); }); } }); }; /** * Delete an Comment */ exports.destroy = function(req, res) { var comment = req.Comment; comment.remove(function(err) { if (err) { return res.json(500, { error: 'Cannot delete the comment' }); } else { res.json(comment); } }); }; /** * Fetching comments for a post */ exports.fetchByParent = function(req, res) { var parentId = req.params.parentId; var limit = req.query.limit; var query = Comment.find({ parent: parentId }) .sort({ _id: -1 }) .populate('user', 'name username') .populate('mentionsUsers', 'name username') .populate('likes', 'name username'); if (limit) { query.limit(limit); } query.exec(function(err, comments) { if (err) { res.render('error', { status: 500 }); } else { res.json(comments); } }); }; exports.allUsers = function(req, res) { User.find({ name: { $regex: req.query.term, $options: '-i' } }).limit(5).exec(function(err, users) { res.json(users); }); }; /** * Comment middleware */ exports.commentByID = function(req, res, next, id) { Comment.findById(id).populate('user', 'displayName').exec(function(err, Comment) { if (err) return next(err); if (!Comment) return next(new Error('Failed to load comment ' + id)); req.Comment = Comment; next(); }); }; exports.hasAuthorization = function(req, res, next) { if (req.Comment.user.id !== req.user.id) { return res.status(403).send({ message: 'User is not authorized' }); } next(); }; function getAlert (idComment, callback) { console.log('getAlert() : init'); Comment.findOne({'_id': idComment}).select('alert').exec(function (err, result) { if (err) { console.log('got an error'); } else{ console.log('getAlert() : findOne() : result= ', result); callback(result.alert); } }); }; /* * Manage alert on comment -> banish if necessary */ function commentAlertManager (idComment, idDeal){ DealFunction.getVisited(idDeal, function(visited){ console.log('commentAlertManager() : visited = ',visited); getAlert(idComment, function(alert){ console.log('commentAlertManager() : alert = ',alert); var threshold = 0.10; if(alert>visited*threshold){ //remove comment or at least banish ! var query = {'_id': idComment}; var update = {'body': 'ce commentaire a été supprimé par la communauté !'}; var options = {new: true}; Comment.findOneAndUpdate(query, update, options, function(err, comment) { if (err) { console.log('commentAlertManager() : findOneAndUpdate(): got an error'); } else{ console.log('commentAlertManager() : new body = ', comment.body); } }); } }); }); } exports.updateGrade = function(req, res) { console.log('updateGrade() : init'); var _id = req.query._id; var action = req.query.action; var idUser = req.query.idUser; var parentDeal = req.query.parent; var value = 0; console.log('updateGrade() : _id :', _id); console.log('updateGrade() : idUser:', idUser); console.log('updateGrade() : parentDeal:', parentDeal); console.log('updateGrade() : action:', action); console.log('updateGrade() : type of action:', typeof(action)); if(action && _id && idUser){ console.log('updateGrade() : before updateUserPoints()'); if(action == 'plus'){ //here, we will be setting the value according to user role: UserFunction.updateUserPoints(idUser, 2); value = 1; } else if(action == 'minus') { // case 'minus': UserFunction.updateUserPoints(idUser, -1); value = -1; } else if(action == 'alert') { // case 'minus': UserFunction.updateUserPoints(idUser, -2); commentAlertManager(_id, parentDeal); value = 1; } console.log('updateGrade() : value = ', value) //update grade according to value : var query = {"_id": _id}; var update = {$inc: {'grade': value}}; if(action == 'alert'){ update = {$inc: {'alert': value}}; } var options = {new: true}; Comment.findOneAndUpdate(query, update, options, function(err, comment) { if (err) { console.log('updateGrade(): findOneAndUpdate() : got an error'); } else{ console.log('updateGrade() : new Grade = ', comment.grade); res.json(comment); } }); }else{ return res.status(500).json({ error: 'Cannot update the comment grade' }); } console.log("updateGrade() : Je suis updaté :D"); };
var tape = require('tape') var queue = require('../') tape('error-promise with error', function (t) { t.plan(2) var q = queue() q.on('error', q.end.bind(q)) q.on('end', function (err) { t.equal(err.message, 'something broke') t.equal(q.length, 0) }) q.push(function (cb) { setTimeout(cb, 10) }) q.push(function () { return new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error('something broke')) }, 20) }) }) q.push(function () { return new Promise(function (resolve, reject) { setTimeout(resolve, 30) }) }) q.start() }) tape('error-promise with empty error', function (t) { t.plan(2) var q = queue() q.on('error', q.end.bind(q)) q.on('end', function (err) { t.equal(err, true) t.equal(q.length, 0) }) q.push(function (cb) { setTimeout(cb, 10) }) q.push(function () { return new Promise(function (resolve, reject) { setTimeout(function () { reject() // eslint-disable-line }, 20) }) }) q.push(function () { return new Promise(function (resolve, reject) { setTimeout(resolve, 30) }) }) q.start() })
// @flow import {connect} from 'react-redux'; import {setIsLoading} from '../actions/api'; import {requestUser} from '../actions/user'; import UserCard from '../components/UserCard'; function mapStateToProps(state: Object): Object { const {user} = state; return {user}; } function mapDispatchToProps(dispatch: Function): Object { return { isLoadingSetter: (val: bool) => dispatch(setIsLoading(val)), fetchUser: () => dispatch(requestUser()), }; } export default connect(mapStateToProps, mapDispatchToProps)(UserCard);
/** * protractor test/ui/conf.js * * Example with command line parameters: * protractor --params.protocol=http --params.server=localhost --params.port=8020 test/ui/conf.js */ exports.config = { specs: [ 'noAngular.js', './../../public/angular/*.spec.js' ], framework: 'mocha', mochaOpts: { timeout: 5000, slow: 3000 }, capabilities: { 'browserName': 'firefox' }, params: { // default values protocol: 'http', server: 'localhost', port: 8020 }, onPrepare: function () { global.serverUrl = browser.params.protocol + '://' + browser.params.server + ':' + browser.params.port; // Protractor can be used on non-angular sites with this function global.isAngularSite = function (flag){ if (typeof flag === 'undefined') { flag = true; } browser.ignoreSynchronization = !flag; }; } };
import Controller from '@ember/controller'; import CourseController from 'ilios-common/mixins/course-controller'; export default Controller.extend(CourseController);
export { default } from 'ember-cli-addon-docs/components/docs-viewer';
class ias_changepassword { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = ias_changepassword;
var ui = require('basis.ui'); module.exports = ui.Node.subclass({ template: resource('./template/index.tmpl'), binding: { name: 'title' } });
var structtesting__1__1internal__1__1__any__of__result3_8js = [ [ "structtesting_1_1internal_1_1_any_of_result3", "structtesting__1__1internal__1__1__any__of__result3_8js.html#ac1e4f74e9301d4f1fdc7c3d2a92d5825", null ] ];
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../../app/controllers/users.server.controller'); // Setting up the users profile api app.route('/users/me').get(users.me); app.route('/users').put(users.update); app.route('/users/accounts').delete(users.removeOAuthProvider); app.route('/user/changeimage').post(users.changeImage); // Setting up the users password api app.route('/users/password').post(users.changePassword); app.route('/auth/forgot').post(users.forgot); app.route('/auth/reset/:token').get(users.validateResetToken); app.route('/auth/reset/:token').post(users.reset); // Setting up the users authentication api app.route('/auth/signup').post(users.signup); app.route('/auth/signin').post(users.signin); app.route('/auth/signout').get(users.signout); // Setting the facebook oauth routes app.route('/auth/facebook').get(passport.authenticate('facebook', { scope: ['email'] })); app.route('/auth/facebook/callback').get(users.oauthCallback('facebook')); // Setting the twitter oauth routes app.route('/auth/twitter').get(passport.authenticate('twitter')); app.route('/auth/twitter/callback').get(users.oauthCallback('twitter')); // Setting the google oauth routes app.route('/auth/google').get(passport.authenticate('google', { scope: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] })); app.route('/auth/google/callback').get(users.oauthCallback('google')); // Setting the linkedin oauth routes app.route('/auth/linkedin').get(passport.authenticate('linkedin')); app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin')); // Setting the github oauth routes app.route('/auth/github').get(passport.authenticate('github')); app.route('/auth/github/callback').get(users.oauthCallback('github')); // Finish by binding the user middleware app.param('userId', users.userByID); };
!function(){"use strict";console.log("woot"),console.log("loot")}(); //# sourceMappingURL=main.js.map
/*globals PI2, Background, LinearGradient, ColorStop, RGBColor, RAD_TO_DEG, DEG_TO_RAD*/ (function() { 'use strict'; var HALF_PI = 0.5 * Math.PI; function normalizeAngle( angle ) { angle = angle % PI2; return angle >= 0 ? angle : angle + PI2; } function quadrantOf( angle ) { if ( angle < HALF_PI) { return 0; } if ( angle < Math.PI ) { return 1; } if ( angle < Math.PI + HALF_PI ) { return 2; } return 3; } /** * Percent or pixels. * * These regexps are very liberal in the values they accept. For example, the * following values are accepted: * * abc10% -> 10% * abc100px -> 100px */ var percentRegex = /(\d+)(\%)/, pixelRegex = /(\d+)(px)/; function unitsOf( string ) { if ( percentRegex.test( string ) ) { return '%'; } if ( pixelRegex.test( string ) ) { return 'px'; } return null; } var mouse = { x: 0, y: 0 }; var editors = []; function Editor( options ) { options = options || {}; this.el = document.querySelector( options.el ); this.canvas = this.el.querySelector( 'canvas' ); this.ctx = this.canvas.getContext( '2d' ); var rect = this.el.getBoundingClientRect(); this.canvas.width = rect.width; this.canvas.height = rect.height; this.x = rect.left + 0.5 * rect.width; this.y = rect.top + 0.5 * rect.height; this.gradientAngle = 0; this.gradient = new LinearGradient(); this.gradient.angle = this.gradientAngle + 'deg'; } Editor.prototype.update = function() { var el = this.el, gradient = this.gradient; var dx = mouse.x - this.x, dy = mouse.y - this.y; this.gradientAngle = Math.round( normalizeAngle( Math.atan2( dy, dx ) ) * RAD_TO_DEG ) % 360; gradient.angle = this.gradientAngle + 'deg'; el.style.background = gradient.css(); // Clean-up. [].forEach.call( el.querySelectorAll( '.colorstop' ), function( child ) { el.removeChild( child ); }); var gradientAngle = this.gradientAngle, quadrant = quadrantOf( gradientAngle * DEG_TO_RAD ), colorStopCount = gradient.colorStops.length - 1; gradient.colorStops.forEach(function( colorStop, index ) { var colorStopEl = document.createElement( 'div' ); colorStopEl.className = 'colorstop'; colorStopEl.id = 'colorstop-' + index; var inPercent, inPixels = false; var pixels, xPixels, yPixels; if ( unitsOf( colorStop.position ) === 'px' ) { inPixels = true; pixels = parseInt( colorStop.position, 10 ); xPixels = Math.round( Math.abs( pixels * Math.sin( gradientAngle * DEG_TO_RAD ) ) ); yPixels = Math.round( Math.abs( pixels * Math.cos( gradientAngle * DEG_TO_RAD ) ) ); } else { inPercent = true; } var top, left; // TODO: Clean this stuff up! // This only handles percentages and pixels right now. if ( quadrant === 0 || quadrant === 1 ) { left = ( index / colorStopCount ) * 100 + '%'; if ( colorStop.position ) { left = colorStop.position; if ( inPixels ) { left = xPixels + 'px'; } } } if ( quadrant === 1 || quadrant === 2 ) { top = ( index / colorStopCount ) * 100 + '%'; if ( colorStop.position ) { top = colorStop.position; if ( inPixels ) { top = yPixels + 'px'; } } } if ( quadrant === 0 || quadrant === 3 ) { top = ( ( colorStopCount - index ) / colorStopCount ) * 100 + '%'; if ( colorStop.position ) { top = ( 100 - parseInt( colorStop.position, 10 ) ) + '%'; if ( inPixels ) { top = 'calc(100% - ' + yPixels + 'px)'; } } } if ( quadrant === 2 || quadrant === 3 ) { left = ( ( colorStopCount - index ) / colorStopCount ) * 100 + '%'; if ( colorStop.position ) { left = ( 100 - parseInt( colorStop.position, 10 ) ) + '%'; if ( inPixels ) { left = 'calc(100% - ' + xPixels + 'px)'; } } } if ( gradient.angle === '0deg' || gradient.angle === '180deg' ) { left = '50%'; } if ( gradient.angle === '90deg' || gradient.angle === '270deg' ) { top = '50%'; } colorStopEl.style.background = colorStop.css(); colorStopEl.style.top = top; colorStopEl.style.left = left; colorStopEl.style.transform = 'rotateZ(' + gradient.angle + ')'; el.appendChild( colorStopEl ); }); this.drawCanvas(); }; Editor.prototype.drawCanvas = function() { var canvas = this.canvas, ctx = this.ctx; ctx.clearRect( 0, 0, canvas.width, canvas.height ); ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; ctx.shadowBlur = 5; ctx.font = '16pt Helvetica, Arial, sans-serif'; ctx.fillStyle = 'white'; ctx.fillText( this.gradientAngle, 20, canvas.height - 20 ); }; function Output( options ) { options = options || {}; this.el = document.querySelector( options.el ); this.background = new Background(); } Output.prototype.update = function() { this.el.style.background = this.background.css(); }; var editor0 = new Editor({ el: '#gradient-canvas-0' }); editors.push( editor0 ); editor0.gradient.colorStops.push( new ColorStop( new RGBColor( 255, 0, 128 ) ) ); editor0.gradient.colorStops.push( new ColorStop( new RGBColor( 0, 255, 255 ), '40%' ) ); editor0.gradient.colorStops.push( new ColorStop( new RGBColor( 255, 128, 255 ), '80%' ) ); editor0.gradient.colorStops.push( new ColorStop( new RGBColor( 0, 0, 255 ) ) ); editor0.update(); var editor1 = new Editor({ el: '#gradient-canvas-1' }); editors.push( editor1 ); editor1.gradient.colorStops.push( new ColorStop( new RGBColor( 0, 0, 128 ) ) ); editor1.gradient.colorStops.push( new ColorStop( new RGBColor( 255, 255, 255 ), '90px' ) ); editor1.gradient.colorStops.push( new ColorStop( new RGBColor( 0, 0, 255 ) ) ); editor1.update(); var output0 = new Output({ el: '#gradient-output' }); output0.background.gradients.push( editor0.gradient ); output0.background.gradients.push( editor1.gradient ); function onMouseMove( event ) { mouse.x = event.pageX; mouse.y = event.pageY; editors.forEach(function( editor ) { editor.update(); }); output0.update(); } window.addEventListener( 'mousemove', onMouseMove ); }) ();
import mag from "../../src/mag" import "../../src/hookins/mag.useState" beforeEach(() => { document.body.innerHTML = "<div id='root'></div>" }) test("camel case", ()=>{ mag.AppCase = mag('<p>', ()=>{}) mag(mag`<AppCase/>`, "root") expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p></p>\n</fragment>") }) test("camel case sub", ()=>{ mag.AppCase = mag('<p>', ()=>{}) mag.AppCase.SubCase = mag('<b>', ()=>{}) mag(mag`<AppCase.SubCase/>`, "root") expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<b></b>\n</fragment>") }) test("camel case sub child", ()=>{ mag.AppCase = mag('<p><children/>', props=>props) mag.AppCase.SubCase = mag('<b>', ()=>{}) mag(mag`<AppCase><AppCase.SubCase></AppCase.SubCase></AppCase>`, "root") expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p><children><b></b></children></p>\n</fragment>") }) test("inner child sub comps", ()=>{ mag.App = mag( `<h1>im in a <type/> component now!</h1>`, props => { // javascript stuff goes here return {type: props.type} }) mag.App.Sub = mag('<b><children/>', props=>props) mag.App.Sub.InnerChild = mag('<i>', ()=>"I'm tiny ...") mag( mag` <App type=fancy/> <App.Sub><App.Sub.InnerChild/></App.Sub> <App/> `, document.getElementById('root') ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<h1>im in a <type>fancy</type> component now!</h1><b><children><i>I'm tiny ...</i></children></b><h1>im in a <type></type> component now!</h1>\n</fragment>") }) test("inner child sub comps", ()=>{ mag.App = mag( `<h1>im in a <type/> component now!</h1><children/>`, props => { // javascript stuff goes here return {...props} }) mag.App.Sub = mag('<b><children/>', props=>props) mag.App.Sub.InnerChild = mag('<i>', ()=>"I'm tiny ...") mag( mag`<App.Sub>Tester</App.Sub>`, document.getElementById('root') ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<b><children>Tester</children></b>\n</fragment>") }) test("inner child sub comps", ()=>{ mag.App = mag( `<h1>im in a <type/> component now!</h1><children/>`, props => { // javascript stuff goes here return {...props} }) mag.App.Sub = mag('<b><children/>', props=>props) mag.App.Sub.InnerChild = mag('<i>', ()=>"I'm tiny ...") mag( mag` <App> <App.Sub>Tester</App.Sub> </App>`, document.getElementById('root') ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<fragment><h1>im in a <type></type> component now!</h1><children><b><children>Tester</children></b></children></fragment>\n</fragment>") }) test("inner child sub comps", ()=>{ mag.App = mag( `<h1>im in a <type/> component now!</h1><children/>`, props => { // javascript stuff goes here return {...props} }) mag.App.Sub = mag('<b><children/>', props=>props) mag.App.Sub.InnerChild = mag('<i>', ()=>"I'm tiny ...") mag( mag` <App> <App.Sub> <App.Sub.InnerChild /> </App.Sub> </App>`, document.getElementById('root') ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<fragment><h1>im in a <type></type> component now!</h1><children><b><children><i>I'm tiny ...</i></children></b></children></fragment>\n</fragment>") }) test("inner child sub comps children", ()=>{ mag.App = mag( `<h1>I'm in a <type/> component now!</h1><children/>`, props => { // javascript stuff goes here return {...props} }) mag.App.Sub = mag('<b>', ({children})=> children) mag.App.Sub.InnerChild = mag('<i>', ()=>"I'm inside ...") mag( mag` <App> <App.Sub> <App.Sub.InnerChild/> </App.Sub> </App> `, document.getElementById('root') ) expect(document.querySelector('#root').innerHTML).toEqual(`<fragment> <fragment><h1>I'm in a <type></type> component now!</h1><children><b><i>I'm inside ...</i></b></children></fragment> </fragment>`) }) test("tagged func with sub prop", ()=>{ mag.App = {} mag.App.Sub = mag('<p><num1></num1><num2/><num3 >', props=>props) mag( mag`<App.Sub num1=${1} num2=2 num3="33.23"/>`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p><num1>1</num1><num2>2</num2><num3>33.23</num3></p>\n</fragment>") }) test("tagged func with sub prop child", ()=>{ mag.Test = mag('<b>', ()=>{}) mag.Test.SubCut = mag('<i>', ()=>{}) mag.App = {} mag.App.Sub = mag('<p><children/><num1></num1><num2/><num3 >', props=>props) mag( mag`<App.Sub num1=${1} num2=2 num3="33.23"><Test.SubCut/></App.Sub>`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p><children><i></i></children><num1>1</num1><num2>2</num2><num3>33.23</num3></p>\n</fragment>") }) test("tagged func with sub prop", ()=>{ mag.App = mag('<p>', ()=>{}) mag.App.Sub = mag('<p><num1></num1><num2/><num3 >', props=>props) mag( mag`<App.Sub num1=${1} num2=2 num3="33.23"/>`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p><num1>1</num1><num2>2</num2><num3>33.23</num3></p>\n</fragment>") }) test("tagged number attr", ()=>{ mag.App = mag('<p><num1></num1><num2/><num3 >', props=>props) mag( mag`<App num1=${1} num2=2 num3="33.23"/>`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<p><num1>1</num1><num2>2</num2><num3>33.23</num3></p>\n</fragment>") }) test("render props", ()=>{ mag.Foo = (props) => { ({ render: mag.View } = props) return mag`<View name="foo" />` }; const Hello = ({ name }) => { return `<div>hello from ${name}</div>` }; mag( mag`<Foo render=${Hello} />`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<fragment>\n<fragment>\n<div>hello from foo</div>\n</fragment>\n</fragment>\n</fragment>") }) test("child as func returns string of html", () =>{ mag.Foo = ({ children }) => { return children('foo') }; var handler = name => `<div>hello from ${name}</div>` mag( mag`<Foo attr="test">${handler}</Foo>`, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<fragment>\n<div>hello from foo</div>\n</fragment>\n</fragment>") }) test("child as func", ()=>{ mag.Sub = mag('<b>', props => { return props.children("test") }) mag( mag` <Sub>${(name) => ` <div>${name}</div> `} </Sub> `, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<b><div>test</div></b>\n</fragment>") }) test("child as func white space", ()=>{ mag.Sub = mag('<b>', props => { return props.children("test") }) mag( mag` <Sub> ${(name) => ` <div>${name}</div> `} </Sub> `, 'root' ) expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<b><div>test</div></b>\n</fragment>") }) test("tagged names case insensitive", () => { mag.sub = mag('<b>', ()=>[]) mag(mag`<SuB/>`, "root") expect(document.querySelector('#root').innerHTML).toEqual("<fragment>\n<b></b>\n</fragment>") }) test("counter function pass as attribute", ()=>{ mag.Counter=mag('<num/><button>couch me', ({num, handler, test})=>{ return { num, onclick:e=> handler(num+ 1) } }) var app=mag('root', props=>{ const [num, setNum] = mag.useState(props.num) function handle(val) { setNum(val) } var obj = [1,2,3] return mag` <Counter handler=${handle} num=${num} test=${obj} /> ` }) app({num: 0}) expect(document.querySelector('#root').innerHTML).toEqual("\n<fragment><num>0</num><button>couch me</button></fragment>\n") document.querySelector('#root button').click() expect(document.querySelector('#root').innerHTML).toEqual("\n<fragment><num>1</num><button>couch me</button></fragment>\n") document.querySelector('#root button').click() expect(document.querySelector('#root').innerHTML).toEqual("\n<fragment><num>2</num><button>couch me</button></fragment>\n") })
// Number -> Number function numberOfPreliminaryTeams(teams) { return (2 * teams) - (2 * Math.pow(2, Math.floor(Math.log2(teams)))); } module.exports = numberOfPreliminaryTeams;
module.exports = { cacheId: 'timer', staticFileGlobs: [ 'dist/*.bundle.js', 'src/**/*.svg', 'index.html', 'src/*.ico', 'jspm_packages/system.js', 'jspm.config.js', 'jspm_packages/npm/systemjs-plugin-babel@0.0.16.json', 'jspm_packages/npm/material-design-icons-iconfont@3.0.2/dist/fonts/MaterialIcons-Regular.woff2' ], maximumFileSizeToCacheInBytes: 10485760, navigateFallback: '/index.html' }
// YouTunes Track Info Element Directive TrackInfo.js JavaScript Document directives.directive('trackInfo', function factory($rootScope) { return { restrict: 'E', replace: true, transclude: true, template: '<div id="trackInfo" ng-transclude></div>', link: function (scope, element, attrs) { var $popup = $('#popup'), isRevealed = false, $playerPane = $('#playerPane'), playerPaneDisplay = $playerPane.css('display'), $track = $('#track'), HOLD_TIME = 3000, scrollWidth = element[0].scrollWidth, width = $track.outerWidth(true), offset = scrollWidth - width, animationName = null, transform = $.keyframe.getVendorPrefix() + 'transform', overflow = function () { offset = scrollWidth - width; animationName = 'scroll-text-' + $rootScope.player.currentTrack.id; $.keyframe.define({ name: animationName, from: { transform: 'translateX(0px)' }, to: { transform: 'translateX(' + (0 - offset) + 'px)' } }); doAnimation(Math.round(offset * 25)); }, doAnimation = function (duration, direction) { direction = (direction === undefined) ? 'normal' : direction; $track.resetKeyframe(function () { $track.playKeyframe({ name: animationName, duration: duration, timingFunction: 'ease-in-out', delay: HOLD_TIME, direction: direction, complete: function () { direction = (direction === 'normal') ? 'reverse' : 'normal'; doAnimation(duration, direction); } }); if (direction === 'reverse') { $track.css(transform, 'translateX(' + (0 - offset) + 'px)'); } else { $track.css(transform, 'none'); } }); }, checkOverflow = function () { var revertPlayerPaneDisplay = false; if ($playerPane.css('display') === 'none') { revertPlayerPaneDisplay = true; $playerPane.css('display', playerPaneDisplay); } setTimeout(function () { //Check for overflow scrollWidth = element[0].scrollWidth; width = $track.outerWidth(true); if (revertPlayerPaneDisplay) { $playerPane.css('display', playerPaneDisplay); } offset = scrollWidth - width; if (offset > 0) { overflow(); // Don't animate if search is revealed if (isRevealed) { $track.pauseKeyframe(); } } else { $track.css(transform, 'none'); } }, 50); }; if ($rootScope.player && $rootScope.player.isReady && $rootScope.player.currentTrack !== null) { checkOverflow(); } $popup.on('webkitTransitionEnd', function (event) { if (event.target === $popup[0]) { isRevealed = !isRevealed; if (isRevealed) { $track.pauseKeyframe(); } else { $track.resumeKeyframe(); } } }); $track.hover(function () { $track.pauseKeyframe(); }, function () { $track.resumeKeyframe(); }) $rootScope.$watch('player.currentTrack', function (newValue, oldValue) { if (newValue !== oldValue) { //Stop and/or delete old animation $track.resetKeyframe(); $('head .keyframe-style').remove(); if ( newValue !== null) { checkOverflow(); } } }); } }; });
$(document).ready(function(){ $("#id_model, #id_board, #id_member").change(function(){ if($("#id_board").val() != ""){ let board_name = $( "#id_board option:selected" ).text() $("#id_name").val("Board "+board_name+" "+$("#id_model").val()+"-based forecaster"); }else if($("#id_member").val() != ""){ let member_name = $( "#id_member option:selected" ).text() $("#id_name").val("Member "+member_name+" "+$("#id_model").val()+"-based forecaster"); }else{ $("#id_name").val("All boards and members "+$("#id_model").val()+"-based forecaster"); } }); $("#id_board").change(function(){ $("#id_member").val(""); }); $("#id_member").change(function(){ $("#id_board").val(""); }); });
app.service('d3Service', d3Service); d3Service.$inject = ['d3Factory']; function d3Service(d3Factory) { var self = this, d3 = d3Factory.d3().then(function (d3f) {setD3(d3f); return d3f;}); self.getD3 = function() { return d3; }; return self; function setD3(d3f) { d3 = d3f; } }
// Code for reading data from command line input and processing it // Start process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', cacheInput).on('end', processData); function cacheInput(data) { input_stdin += data; } function processData() { input_stdin_array = input_stdin.split("\n"); main(); } function readLine() { return input_stdin_array[input_currentline++]; } // End function main(){ var n = parseInt(readLine()); var bin = n.toString(2); // Converting integer into binary number // Method 1 var maxLength = 0; var tempLength = 0; bin = bin.split(''); // Converting binary string into array // Loop for getting maximum consecutive 1's // Looping till bin.length + 1 - if the max consec number is at the end for(var i =0 ;i<bin.length+1;i++){ if(bin[i] === '1'){ tempLength+=1; }else{ if(tempLength>maxLength){ maxLength = tempLength; } tempLength = 0; } } process.stdout.write(maxLength); // Method 2 - for higher performance bin = bin.split(/0+/); // Converting binary string into array of integers with only 1's var maxVal = Math.max.apply(Math,bin); process.stdout.write(maxVal.toString().length); }
export var ribbonTitleDirective = function ($document, ribbonEvents, optimizedResize) { return { scope: { title: '=' }, require: '^ribbon', templateUrl: 'ribbon/templates/ribbon-title-template.html', link: function (scope, element) { var titleElement = element[0].querySelector('.title'); calculatePositionAsync(titleElement); optimizedResize.add(function () { calculatePositionAsync(titleElement); }); ribbonEvents.on('tabActivated', function () { calculatePositionAsync(titleElement); }); } }; function calculatePositionAsync(titleElement) { setTimeout(function () { var left = calculatePosition(titleElement); if (titleElement.style.left !== left) { titleElement.style.left = left; } }, 0); } function calculatePosition(titleElement) { var currentPosition = titleElement.getBoundingClientRect(); var left = $document[0].body.clientWidth / 2 - currentPosition.width / 2; titleElement.style.display = 'none'; var overlap = document.elementFromPoint(left, currentPosition.top); titleElement.style.display = ''; if (overlap && overlap.parentElement.classList.contains('contextual-group')) { var overlapPosition = overlap.getBoundingClientRect(); return (overlapPosition.left + overlapPosition.width + 1) + 'px'; } else { return 'calc(50% - ' + (currentPosition.width / 2) + 'px)'; } } };
var Frex = require('frex.js'); var app = Frex(); app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(Frex.cookieParser()); app.use(Frex.cookieSession({ key: 'stemforge', secret: 'STEMFORGESNOIEW1231298nLakjsdLOIy128947KJDSA' })); app.use(app.router); app.use(Frex.static(__dirname + '/public')); }); app.listen(8000, function() { console.log('website is ready.'); });
var assert = require('assert-plus'); var date = require('../../date'); var logger = require('../../logger/logger').logger; var ChangeOwnerEventBuilder = require('../../model/response/event/changeOwnerEvent').ChangeOwnerEventBuilder; var exports = {}; exports.build = function (event) { logger.debug('build changeOwner event:', event); assert.object(event, 'event'); assert.string(event.type, 'event.type'); assert.string(event.createdAt, 'event.createdAt'); assert.string(event.description, 'event.description'); return new ChangeOwnerEventBuilder() .withType(event.type) .withCreatedAt(event.createdAt) .withDescription(event.description) .withFirstOwner(event.firstOwner) .withOwnerType(event.ownerType) .withLocation(event.location) .build(); }; module.exports = exports;
T.registerModel(function (pane) { T.toolbar.defaults.back = true; this.samples = function() { pane.navigate('samples'); }; this.chat = function () { pane.navigate('chat'); }; });
"use strict"; const ccxt = require ('../../ccxt.js') , asTable = require ('as-table') , log = require ('ololog').configure ({ locate: false }) , fs = require ('fs') , {} = require ('ansicolor').nice , verbose = process.argv.includes ('--verbose') , keysGlobal = 'keys.json' , keysLocal = 'keys.local.json' , keysFile = fs.existsSync (keysLocal) ? keysLocal : (fs.existsSync (keysGlobal) ? keysGlobal : false) , config = keysFile ? require ('../../' + keysFile) : {} let printSupportedExchanges = function () { log ('Supported exchanges:', ccxt.exchanges.join (', ').green) } let printUsage = function () { log ('Usage: node', process.argv[1], 'id1'.green, 'id2'.yellow, 'id3'.blue, '...') printSupportedExchanges () } let printExchangeSymbolsAndMarkets = function (exchange) { log (getExchangeSymbols (exchange)) log (getExchangeMarketsTable (exchange)) } let getExchangeMarketsTable = (exchange) => { return asTable.configure ({ delimiter: ' | ' }) (Object.values (markets)) } let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms)); let proxies = [ '', // no proxy by default 'https://crossorigin.me/', 'https://cors-anywhere.herokuapp.com/', ] ;(async function main () { if (process.argv.length > 3) { let ids = process.argv.slice (2) let exchanges = {} log (ids.join (', ').yellow) // load all markets from all exchanges for (let id of ids) { let settings = config[id] || {} // instantiate the exchange by id let exchange = new ccxt[id] (ccxt.extend ({ // verbose, // 'proxy': 'https://cors-anywhere.herokuapp.com/', }, settings)) // save it in a dictionary under its id for future use exchanges[id] = exchange // load all markets from the exchange let markets = await exchange.loadMarkets () // basic round-robin proxy scheduler let currentProxy = 0 let maxRetries = proxies.length for (let numRetries = 0; numRetries < maxRetries; numRetries++) { try { // try to load exchange markets using current proxy exchange.proxy = proxies[currentProxy] await exchange.loadMarkets () } catch (e) { // rotate proxies in case of connectivity errors, catch all other exceptions // swallow connectivity exceptions only if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) { log.bright.yellow ('[DDoS Protection Error] ' + e.message) } else if (e instanceof ccxt.RequestTimeout) { log.bright.yellow ('[Timeout Error] ' + e.message) } else if (e instanceof ccxt.AuthenticationError) { log.bright.yellow ('[Authentication Error] ' + e.message) } else if (e instanceof ccxt.ExchangeNotAvailable) { log.bright.yellow ('[Exchange Not Available Error] ' + e.message) } else if (e instanceof ccxt.ExchangeError) { log.bright.yellow ('[Exchange Error] ' + e.message) } else { throw e; // rethrow all other exceptions } // retry next proxy in round-robin fashion in case of error currentProxy = ++currentProxy % proxies.length } } log (id.green, 'loaded', exchange.symbols.length.toString ().green, 'markets') } log ('Loaded all markets'.green) // get all unique symbols let uniqueSymbols = ccxt.unique (ccxt.flatten (ids.map (id => exchanges[id].symbols))) // filter out symbols that are not present on at least two exchanges let arbitrableSymbols = uniqueSymbols .filter (symbol => ids.filter (id => (exchanges[id].symbols.indexOf (symbol) >= 0)).length > 1) .sort ((id1, id2) => (id1 > id2) ? 1 : ((id2 > id1) ? -1 : 0)) // print a table of arbitrable symbols let table = arbitrableSymbols.map (symbol => { let row = { symbol } for (let id of ids) if (exchanges[id].symbols.indexOf (symbol) >= 0) row[id] = id return row }) log (asTable.configure ({ delimiter: ' | ' }) (table)) } else { printUsage () } process.exit () }) ()
'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function (global) { 'use strict'; global.console = global.console || {}; var con = global.console; var prop, method; var empty = {}; var dummy = function dummy() {}; var properties = 'memory'.split(','); var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if (!con[prop]) con[prop] = empty; while (method = methods.pop()) if (!con[method]) con[method] = dummy; })(typeof window === 'undefined' ? undefined : window); if (Function.prototype.bind && window.console && typeof console.log == 'object') { ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) { console[method] = this.bind(console[method], console); }, Function.prototype.call); } var ConsoleAppender = (function () { function ConsoleAppender() { _classCallCheck(this, ConsoleAppender); } ConsoleAppender.prototype.debug = function debug(logger, message) { for (var _len = arguments.length, rest = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { rest[_key - 2] = arguments[_key]; } console.debug.apply(console, ['DEBUG [' + logger.id + '] ' + message].concat(rest)); }; ConsoleAppender.prototype.info = function info(logger, message) { for (var _len2 = arguments.length, rest = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { rest[_key2 - 2] = arguments[_key2]; } console.info.apply(console, ['INFO [' + logger.id + '] ' + message].concat(rest)); }; ConsoleAppender.prototype.warn = function warn(logger, message) { for (var _len3 = arguments.length, rest = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { rest[_key3 - 2] = arguments[_key3]; } console.warn.apply(console, ['WARN [' + logger.id + '] ' + message].concat(rest)); }; ConsoleAppender.prototype.error = function error(logger, message) { for (var _len4 = arguments.length, rest = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { rest[_key4 - 2] = arguments[_key4]; } console.error.apply(console, ['ERROR [' + logger.id + '] ' + message].concat(rest)); }; return ConsoleAppender; })(); exports.ConsoleAppender = ConsoleAppender;
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; import _ from 'lodash'; import i18n from 'commons/utils/i18n'; export default React.createClass({ propTypes: { category: PropTypes.object, categories: PropTypes.object.isRequired, genLink: PropTypes.func.isRequired, aggs: PropTypes.object.isRequired, brand: PropTypes.object, query: PropTypes.string, brandId: PropTypes.string, categoryId: PropTypes.string, pageNum: PropTypes.string, }, contextTypes: { activeLocale: PropTypes.string, }, renderCategories() { const { activeLocale } = this.context; const { aggs, category, categories, genLink } = this.props; if (!category || !categories || !aggs) { return undefined; } const tree = categories.tree; const categoryCount = (categoryId) => { if (!aggs || !aggs.categories || !aggs.categories[categoryId]) { return ''; } return `(${aggs.categories[categoryId].doc_count})`; }; const categoryLink = (categoryId) => genLink(Object.assign(_.pick(this.props, ['query', 'sorts']), { categoryId })); const renderTop = (root) => { if (!root.isActive) { return null; } const renderChildOfCategory = (children) => { if (!children) { return null; } return children.filter((child) => child.isActive).map((child) => ( <div key={child.id} className="product-list-category-indent"> <Link className="product-list-category-item sub" to={categoryLink(child.id)}> {child.name[activeLocale]} {categoryCount(child.id)} </Link> </div> )); }; const dfs = (child, parent) => { const renderWithSibling = (elem, category2, siblings, renderSibling) => { const res = []; siblings.forEach((sibling) => { if (!sibling.isActive) { return; } if (sibling.id === category2.id) { res.push(elem); } else { res.push(renderSibling(sibling)); } }); return res; }; if (child.id === category.id) { const elem = ( <div key={child.id} className="product-list-category-indent"> <Link className="product-list-category-item active" to={categoryLink(child.id)}> {child.name[activeLocale]} {categoryCount(child.id)} </Link> {renderChildOfCategory(child.children)} </div> ); if (parent) { return renderWithSibling(elem, child, parent.children, (sibling) => ( <div key={sibling.id} className="product-list-category-indent"> <Link className="product-list-category-item" to={categoryLink(sibling.id)}> {sibling.name[activeLocale]} </Link> </div> )); } return elem; } if (!child.isActive || !child.children || child.children.length < 1) { // if (!child.children || child.children.length < 1) { return null; } let foundElem = null; for (let i = 0; i < child.children.length; i++) { const child2 = child.children[i]; const c = dfs(child2, child); if (c) { foundElem = c; } } if (foundElem) { const currentElem = ( <div key={child.id} className="product-list-category-indent"> <Link className="product-list-category-item active" to={categoryLink(child.id)}> {child.name[activeLocale]} </Link> {foundElem} </div> ); const renderSibling = (sibling) => ( <div key={sibling.id} className="product-list-category-indent"> <Link className="product-list-category-item" to={categoryLink(sibling.id)}> {sibling.name[activeLocale]} </Link> </div> ); return renderWithSibling(currentElem, child, parent.children, renderSibling); } return null; }; const renderChildren = () => { if (root.id === category.id) { return renderChildOfCategory(root.children); } return (root.children || []).map((child) => dfs(child, root)); }; return ( <div key={root.id} className="product-list-top-category"> <Link className={`product-list-category-title ${root.id === category.id ? 'active' : ''}`} to={categoryLink(root.id)}> {root.name[activeLocale]} {`${root.id === category.id ? categoryCount(root.id) : ''}`} </Link> {renderChildren()} </div> ); }; return ( <div> {tree.children.map(renderTop)} </div> ); }, render() { return ( <div className="product-list-left-box"> <Link to="/categories/4" className="title">{i18n.get('word.categories')}</Link> {this.renderCategories()} </div> ); }, });
Package.describe({ name: 'scorpiusjs:attributes', summary: 'Scorpius attributes', version: "0.3.1", git: 'https://github.com/scorpiusjs/scorpius' }); Package.onUse(function(api) { api.versionsFrom('1.4.2.3'); api.use([ 'blaze-html-templates@1.0.5', 'ecmascript', 'check', 'scorpiusjs:base@0.3.1', 'aldeed:collection2@2.10.0', 'aldeed:autoform@5.8.1', 'momentjs:moment@2.17.1' ]); api.imply([ 'aldeed:collection2', 'aldeed:autoform', ]); api.addFiles([ 'attributes.js' ]); // Created by attribute api.addFiles('created-by/created-by.html', 'client'); api.addFiles('created-by/created-by.js'); // Created at attribute api.addFiles('created-at/created-at.html', 'client'); api.addFiles('created-at/created-at.js'); // Updated by attribute api.addFiles('updated-by/updated-by.html', 'client'); api.addFiles('updated-by/updated-by.js'); // Updated at attribute api.addFiles('updated-at/updated-at.html', 'client'); api.addFiles('updated-at/updated-at.js'); api.export('scorpius'); }); Package.onTest(function(api) { api.use('tinytest'); // api.use('scorpiusjs:core'); });
ContactManager.ContactsTableView = Marionette.CompositeView.extend({ tagName: "table", className: "table table-hover", template: JST["app/scripts/templates/contacts/contacts_table.ejs"], childView: ContactManager.ContactView, childViewContainer: "tbody", onShow: function() { this.on("childview:contact:delete", function(view, model) { ContactManager.trigger("contact:delete", model); }); this.on("childview:contact:show", function(view, model) { ContactManager.trigger("contact:show", model.get("id")); }); this.on("childview:contact:edit", function(view, model) { ContactManager.trigger("contact:edit", model.get("id")); }); } });
module.exports = { dist: { expand: true, cwd: 'dist/', src: '**', dest: 'examples/dist', filter: 'isFile' }, bower: { expand: true, cwd: 'bower_components', src: '**', dest: 'examples/bower_components' } }
const expect = require('chai').expect const apiHandler = require('./apiHandler'); const validators = require('./validators'); const sinon = require('sinon'); const chai = require('chai'); describe('apiHandler tests', function () { describe('validateParams tests', function () { it('validateParams should call validateCity and validateEmail', function *() { var validator = sinon.mock(validators); validator.expects('validateCity').withArgs('londyn').returns(true); validator.expects('validateEmail').withArgs('dsa@wp.pl').returns(true); var result = apiHandler.validateParams({city:'londyn',email:'dsa@wp.pl'}); validator.restore(); validator.verify(); expect(result).to.eql(true); }); }); });
'use strict'; // MODULES // var deepSet = require( 'utils-deep-set' ).factory, deepGet = require( 'utils-deep-get' ).factory, partial = require( './partial.js' ); // QUANTILE // /** * FUNCTION: quantile( arr, lambda, k, path[, sep] ) * Evaluates the quantile function for a Weibull distribution with shape parameter `lambda` and scale parameter `k` for each array element and sets the input array. * * @param {Array} arr - input array * @param {Number} lambda - shape parameter * @param {Number} k - scale parameter * @param {String} path - key path used when deep getting and setting * @param {String} [sep] - key path separator * @returns {Array} input array */ function quantile( x, lambda, k, path, sep ) { var len = x.length, opts = {}, dget, dset, fcn, v, i; if ( arguments.length > 4 ) { opts.sep = sep; } if ( len ) { dget = deepGet( path, opts ); dset = deepSet( path, opts ); fcn = partial( lambda, k ); for ( i = 0; i < len; i++ ) { v = dget( x[ i ] ); if ( typeof v === 'number' ) { dset( x[i], fcn( v ) ); } else { dset( x[i], NaN ); } } } return x; } // end FUNCTION quantile() // EXPORTS // module.exports = quantile;
const Hapi = require('hapi') const Inert = require('inert') const Vision = require('vision') const path = require('path') // var Hapi_auth = require('hapi-auth-cookie') // var HapiSwagger = require('hapi-swagger') // var swaggerOptions = { // apiVersion: '1.0.0' // } const server = new Hapi.Server() server.connection({ host: '0.0.0.0', port: 3000 }) // Require the routes and pass the server object. const routes = require('./server/config/routes')(server) global.appRoot = path.resolve(__dirname) // Export the server to be required elsewhere. module.exports = server // Bootstrap Hapi Server Plugins, passes the server object to the plugins // require('./server/config/plugins')(server) server.register([Inert, Vision], (err) => { if (err)console.log(err) server.views({ path: './server/views', engines: { html: require('swig') } }) // server.auth.strategy('session', 'cookie', { // password: 'dancingtomorrow', // cookie: 'sid-indataly', // redirectTo: '/login', // isSecure: false, // ttl: 15 * 60 * 60 * 1000 // }) server.route(routes) server.start(() => { console.log('Server started at: ' + server.info.uri) }) })