code
stringlengths
2
1.05M
$(document).ready(function(){ //Init functions LazyLoad(); ProgressBar(); scrollToTop(); //Lazy Load function LazyLoad() { $("img.lazy").lazyload({ effect : "fadeIn" }); } //Top progress bar function ProgressBar() { //Start loader NProgress.start(); $(window).load(function () { NProgress.done(); }); } //Scroll to Top function scrollToTop() { $(function () { $('#goTop').goTop(); }); } });
/** * Show an account */ var client = require('../../../client'); var async = require('async'); async.waterfall([ function(callback) { // Fetch accounts to get an account ID client.getAccounts({}, function(err, accounts) { if (err) { return console.log(err); } callback(null, accounts[0].id); }); }, function(accountId, callback) { // Optionally, you can manually specify an account ID here if needed // var accountId = ''; client.getAccount(accountId, function(err, account) { if (err) { return console.log(err); } console.log(account); }); } ]);
'use strict'; const BookshelfRepository = require('./bookshelfRepository'); class LoanRepository extends BookshelfRepository { constructor(model) { super(model); this.relationships = {withRelated: ['users','books']}; } getModels() { let promise = this.model.fetchAll(this.relationships); promise.catch(err => console.log(err)); return this.model.fetchAll(this.relationships); } getModelById(id) { let attributes = {}; let model = new this.model(); attributes[model.idAttribute] = +id; return this.model.forge(attributes).fetch(this.relationships); } getBooks() { return this.model.books(); } } module.exports = LoanRepository;
var searchData= [ ['transwarp_20is_20a_20header_2donly_20c_2b_2b_20library_20for_20task_20concurrency_509',['transwarp is a header-only C++ library for task concurrency',['../index.html',1,'']]] ];
import { createBackendModule } from './backendModule' import { SUCCESS_CREATE as JOURNAL_ENTRY_SUCCESS_CREATE } from './journalEntryCreatedEvents' import { BASE_PATH, objectToQueryParams } from 'modules/http' const path = 'journal-entry-proposals' const SUCCESS_FETCH_JEP = '@@' + path + '/SUCCESS_FETCH' const START_FETCH_JEP = '@@' + path + '/START_FETCH' const ERROR_FETCH_JEP = '@@' + path + '/ERROR_FETCH' export const fetchJournalEntryProposals = (params) => { return { types: [START_FETCH_JEP, SUCCESS_FETCH_JEP, ERROR_FETCH_JEP], callAPI: (headers) => fetch(BASE_PATH + path + objectToQueryParams(params), { headers }), payload: { financialFactId: params.financialFactId } } } const module = createBackendModule('inboxFinancialFacts') export const fetchInboxFinancialFacts = module.fetchActionCreator module.ACTION_HANDLERS[JOURNAL_ENTRY_SUCCESS_CREATE] = (state, action) => { const financialFactId = action.json.financialFactId return { ...state, data: state.data.filter(iff => iff.financialFact.id !== financialFactId) } } module.ACTION_HANDLERS[SUCCESS_FETCH_JEP] = (state, action) => { const inboxFinancialFacts = state.data const index = inboxFinancialFacts.findIndex(iff => iff.financialFact.id === action.financialFactId) let inboxFinancialFactToReplace = inboxFinancialFacts[index] const newIffs = [...inboxFinancialFacts.slice(0, index), { ...inboxFinancialFactToReplace, records: action.json._embedded.records }, ...inboxFinancialFacts.slice(index + 1)] return { ...state, data: newIffs } } export default module.reducer
/** * Adds bindings for the keystone routes * * ####Example: * * var app = express(); * app.configure(...); // configuration settings * app.use(...); // middleware, routes, etc. should come before keystone is initialised * keystone.routes(app); * * @param {Express()} app * @api public */ function routes(app) { this.app = app; var keystone = this; // ensure keystone nav has been initialised if (!this.nav) { this.nav = this.initNav(); } // Cache compiled view templates if we are in Production mode this.set('view cache', this.get('env') === 'production'); // Bind auth middleware (generic or custom) to /keystone* routes, allowing // access to the generic signin page if generic auth is used if (this.get('auth') === true) { if (!this.get('signout url')) { this.set('signout url', '/keystone/signout'); } if (!this.get('signin url')) { this.set('signin url', '/keystone/signin'); } if (!this.get('account_manager url')) { this.set('account_manager url', '/keystone/account_manager'); } if (!this.nativeApp || !this.get('session')) { app.all('/keystone*', this.session.persist); } app.all('/keystone/signin', require('../../routes/views/signin')); app.all('/keystone/signout', require('../../routes/views/signout')); app.all('/keystone/account_manager', require('../../routes/views/account_manager')); app.all('/keystone*', this.session.keystoneAuth); } else if ('function' === typeof this.get('auth')) { app.all('/keystone*', this.get('auth')); } var initList = function(protect) { return function(req, res, next) { req.list = keystone.list(req.params.list); if (!req.list || (protect && req.list.get('hidden'))) { req.flash('error', 'List ' + req.params.list + ' could not be found.'); return res.redirect('/keystone'); } next(); }; }; // Keystone Admin Route app.all('/keystone', require('../../routes/views/home')); // Email test routes if (this.get('email tests')) { this.bindEmailTestRoutes(app, this.get('email tests')); } // Cloudinary API for image uploading (only if Cloudinary is configured) if (keystone.get('wysiwyg cloudinary images')) { if (!keystone.get('cloudinary config')) { throw new Error('KeystoneJS Initialisaton Error:\n\nTo use wysiwyg cloudinary images, the \'cloudinary config\' setting must be configured.\n\n'); } app.post('/keystone/api/cloudinary/upload', require('../../routes/api/cloudinary').upload); } // Cloudinary API for selecting an existing image from the cloud if (keystone.get('cloudinary config')) { app.get('/keystone/api/cloudinary/get', require('../../routes/api/cloudinary').get); app.get('/keystone/api/cloudinary/autocomplete', require('../../routes/api/cloudinary').autocomplete); } // Generic Lists API app.all('/keystone/api/:list/:action', initList(), require('../../routes/api/list')); // Generic Lists Download Route app.all('/keystone/download/:list', initList(), require('../../routes/download/list')); // List and Item Details Admin Routes app.all('/keystone/:list/:page([0-9]{1,5})?', initList(true), require('../../routes/views/list')); app.all('/keystone/:list/:item', initList(true), require('../../routes/views/item')); return this; } module.exports = routes;
var seneca = require('seneca')(); seneca.use('../suncalculator'); // Capture the sunrise event seneca.add({role: 'suncalculator', event: 'sunrise'}, function (msg, respond) { console.log('got sunrise event'); respond(null, {answer: 'ok'}) }); // Capture the sunset event seneca.add({role: 'suncalculator', event: 'sunset'}, function (msg, respond) { console.log('got sunset event'); respond(null, {answer: 'ok'}) }); setInterval(function(options) { // Uses today's date for the eventcheck seneca.act({role: 'suncalculator', cmd: 'eventcheck', lat: 35.227085, long: -80.843124}, console.log); }, 500);
import { eventBus } from '../app'; export default { bind: (el, binding, vnode) => { el.addEventListener('click', () => { eventBus.$emit('app:exchange::confirm', binding.value) }); }, unbind: (el) => { el.removeEventListener('click'); } }
/*jshint node:true*/ const ModelBlueprint = require('../engine-model'); const testInfo = require('ember-cli-test-info'); const useTestFrameworkDetector = require('ember-data/blueprints/test-framework-detector'); module.exports = useTestFrameworkDetector({ description: 'Generates a model unit test.', locals: function(options) { let result = ModelBlueprint.locals.apply(this, arguments); result.friendlyDescription = testInfo.description(options.entity.name, "Unit", "Model"); return result; } });
//============================== // (c) 2014 Envisix Labs // // License: MIT // Author: Stuart Malin // stuart [at] envisixlabs [dot] com //============================== "use strict"; var Actimony = require('./Lib/Actimony.js'); var Node = require('./Lib/Node.js'); var TransportWS = require('./lib/TransportWS.js'); var actimony = new Actimony(); var node = new Node(); console.log('node2: nodeID:', node.getNodeID()); node.connectWith(TransportWS, 'ws://localhost:8080');
/* * Includes */ var fs = require('fs'); var colors = require('colors/safe'); /* * Internal functions */ // Returns sections of the comment header grouped by new-lines function makeStringBlocks(string) { let stringBlocks = string.split(/(?:\r\n|\r|\n){3,}/gm); // We don't want the comment notations in the blocks stringBlocks = stringBlocks.map(block => { return block .replace('/*{', '') .replace('}*/', ''); }); // Remove empty blocks stringBlocks = stringBlocks.filter(block => { return block !== ''; }); // Sort into keyed and unkeyed parameters const isExplicit = /^([?@]|#\s)/; const explicit = []; const implicit = stringBlocks.filter(block => { if(isExplicit.test(block)) { explicit.push(block); return false; } return true; }); return { explicit, implicit }; } // Determine the primitive type of a param function getType(string) { const stringLower = string.trim().toLowerCase(); let type = 'string'; if(!isNaN(Number(stringLower))) { type = 'number'; } else if(stringLower === 'true' || stringLower === 'false') { type = 'boolean'; } else if(!!~stringLower.indexOf('#') || !!~stringLower.indexOf('rgb') || !!~stringLower.indexOf('hls')) { type = 'color'; } else if(string.charAt(0) === '[') { type = 'array'; } else if(stringLower.charAt(0) === '{') { type = 'object'; } return type; } // Parse the value out of the string function getValue(string, type) { let value; const stringTrimmed = string.trim(); const stringClean = stringTrimmed.replace(/(^[\[{])|([\]}]$)/, ''); switch(type) { case 'string': return String(stringTrimmed); case 'number': return Number(string); case 'boolean': return string === 'true'; case 'color': return stringTrimmed; case 'array': return stringClean.split('|'); case 'object': return stringClean.reduce((obj, pair) => { pair = pair.split('='); obj[pair[0]] = pair[1]; return obj; }, {}); } return string; } // Extract the key name from the first part of a param string function getKey(string) { return string.replace(/^([?@]+)|(:\s)+$|[?]/g, '').toLowerCase(); } // Default values for types function getDefault(type) { switch(type) { case 'string': return ''; case 'number': return 0; case 'boolean': return false; case 'color': return '#000'; case 'array': return []; case 'object': return {}; } return null; } // Map implicitly defined values to keys function mapImplicit(strings, keys, obj = {}) { strings.forEach((block, i) => { const key = keys[i] || false; if(!key) return; const type = getType(block); const value = getValue(block, type); obj[key] = { type, value, options: false, nullable: false, description: false, }; }); return obj; } // Map explicitly defined values function mapExplicit(strings, obj = {}) { strings.forEach((block, i) => { const params = block.split(/(\r\n|\r|\n)/).filter(p => !(/(\r\n|\r|\n)/).test(p)); const isBlock = !!~block.indexOf('# '); let curObj = false; let groupIsNullable = false; let lineArr = false; let lineKey = ''; params.forEach((param, i) => { // Figure out if we're adding to the root or a block if(!curObj && isBlock) { var blockName = param .toLowerCase() .replace('#', '') .trim() .replace(' ', '_'); curObj = obj[blockName] ? obj[blockName] : obj[blockName] = {}; } else if(!curObj) { curObj = obj; } // Check if multiline and create a new line cache if so const isMultiline = !!~param.slice(0,2).indexOf('@@'); if(isMultiline) { const lineParts = param.split(/\s/); groupIsNullable = !!~lineParts[0].indexOf('?'); groupDescription = lineParts[1] || false; lineKey = getKey(param); lineArr = []; return; } // Check if end of multiline const isEndMultiline = param === '/@'; if(isEndMultiline) { const strValue = lineArr.join(`\n`).trim(); curObj[lineKey] = { type: 'string', value: strValue, options: false, nullable: groupIsNullable, description: groupDescription, }; lineArr = false; return; } // Add to line arr if multiline if(lineArr) { lineArr.push(param); return; } // Return if its a block header if(i === 0 && isBlock) return; // Parse value const parts = param.split(': '); const key = getKey(parts[0]); const rawValue = parts[1].trim(); const groups = rawValue.match(/(<(?:[^>]*)>)+/g); const typeGroup = groups && groups[0]; const optionsGroup = groups && groups[1]; // Type and value let type; let value; if(typeGroup) { typeGroupParts = typeGroup.replace(/[<>]/g, '').split(':'); type = typeGroupParts[0]; value = typeGroupParts[1] ? getValue(typeGroupParts[1], type) : getDefault(type); } else { type = getType(rawValue); value = getValue(rawValue, type); } // Options let options = false; if(optionsGroup) { options = optionsGroup.replace(/[<>]/g, '').split('|'); } // Nullable const nullable = !!~parts[0].indexOf('?'); // Description let description = false; if(groups && groups.length) { let placeholder = rawValue; groups.forEach(g => placeholder = placeholder.replace(g, '')); description = placeholder.trim(); } curObj[key] = { type, value, options, nullable, description, }; }); }); return obj; } // Promise helper function fetchHeader(path, resolve, reject) { fs.readFile(path, 'utf8', (err, data) => { if (err) return reject(err); const headerStart = data.indexOf('/*{'); const headerEnd = data.indexOf('}*/'); if(!~headerStart || !~headerEnd) reject('No header found.'); else { const result = data.slice(headerStart, headerEnd+3); resolve(result); } }); } // Promise helper function writeOutput(path, output, resolve, reject) { fs.writeFile(path, output, (err) => { if(err) reject(err); else resolve(output); }); } // Do the thing function paramify({ input = false, source = false, destination = false, map = false, json = false, pretty = false, }) { return new Promise( function(resolve, reject) { const theThing = function(input) { const output = {}; const stringBlocks = makeStringBlocks(input); mapImplicit(stringBlocks.implicit, map, output); mapExplicit(stringBlocks.explicit, output); const formatted = JSON.stringify(output, null, pretty); const result = json ? formatted : output; resolve(result); }; if(source) { fetchHeader(source, theThing, reject); } else if(input) { theThing(input); } else { reject('No source supplied.'); } } ); } module.exports = paramify; /* * CLI */ if (require.main === module) { const settings = { json: false, pretty: false, }; process.argv.forEach((arg, i) => { const parts = arg.split('='); const key = parts[0]; const value = parts[1]; if(!value) return; const formatted = value.replace(/['"]/g,'').trim(); switch(key) { case 'source': case 'input': case 'destination': settings[key] = formatted; break; case 'map': settings[key] = formatted.split(','); break; case 'json': settings[key] = formatted === 'true'; break; case 'pretty': settings[key] = !isNaN(Number(formatted)) ? Number(formatted) : undefined; break; } }); if(settings.destination) { settings.json = true; } paramify(settings) .then(output => { const d = settings.destination; if(d) { const resolve = () => console.log(colors.cyan(`JSON generated at '${colors.underline(d)}'`)); const reject = err => console.log(colors.red(err)); writeOutput(d, output, resolve, reject); } else console.log(output); }) .catch(err =>{ console.log(colors.red(err)); }); }
// D3 render template Template.d3svgStructure.rendered = function(){ Deps.autorun(function(){ graph = addLinks2structureGraph(structurePeg2graph(qmls.parse( // "w:VLp,qRLw,v;v:VLr,sRLw,u;u:VLp,rRLw" // "w:VLp,qRLw,v;v:VLr,sRL;u:VLp,rRLw" // "w:VLp,qRLw,v,u;v:VLr,sRL;u:VLp,rRLw" // "w:VLp,qRLv;v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" // "w:VLp,qRLvDOa,b,c;v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" "w:VLp,qRLvDOa,b,cMPP{a,b},Q{c};v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" ))) // ************** Generate the tree diagram ***************** var margin = {top: 25, right: 20, bottom: 10, left: 20}, width = 500 - margin.right - margin.left, height = 400 - margin.top - margin.bottom, edgeLenght = 80; var color = function() {return 'LightSteelBlue';}; //DarkSeaGreen Aquamarine d3.scale.category20(); var svg = d3.select("#d3svgStructure").append("svg").attr("height",height).attr("width",width); /* Build the directional arrows for the links/edges */ svg.append("svg:defs").selectAll("marker").data(["end"]) .enter() .append("svg:marker") .attr("id", String) .attr("viewBox", "0 -5 10 10") .attr("refX", 18) .attr("refY", 0) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("svg:path") .attr("d", "M0,-5L10,0L0,5") .style("fill", "#ccc") .style("stroke", "#ccc") // .style("opacity", "0.5") ; /* Establish the dynamic force behavor of the nodes */ var force = d3.layout.force().size([width,height]) .nodes(graph.nodes) .links(graph.links) .linkDistance([120]) .charge([-1000]) .gravity(0.3) .start(); /* Draw the edges/links between the nodes */ var edges = svg.selectAll("line").data(graph.links) .enter() .append("line") .style("stroke", "#ccc") .style("stroke-width", 2) .style("opacity", "0.7") .attr("marker-end", "url(#end)"); /* Draw the nodes themselves */ var nodes = svg.selectAll("circle").data(graph.nodes) .enter() .append("circle") .attr("r", 10) // .attr("opacity", 0.5) .style("fill", function(d,i) { return color(i); }) .call(force.drag); nodes.append("title").text(function(d) { return d.hoverContent; }); var labels = svg.selectAll("nodes").data(graph.nodes) .enter() .append("text") .attr("fill", "SteelBlue") /*PineGreen*/ .attr("font-family", "sans-serif") .attr("font-size", "17px") .attr('x', 7).attr('y', 3) // .attr("x", function(d) { return d.x + 10; }) .style("text-anchor", "start") // .text(function(d) { return d.valuation; }); .text(function(d) { return d.name; }); /* Run the Force effect */ force.on("tick", function() { edges.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); nodes.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); // texts.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); labels.attr("transform", function(d) { return "translate(" + (d.x + 7) + "," + (d.y + 5) + ")"; }); }); // End tick func }); };
import Page from '../classes/Page'; import request from 'request'; function getCompanies() { // not yet associated with user return { method: 'GET', url: `${process.env.CLIENTS_SERVICE_URL}/companies`, headers: { 'content-type': 'application/json', }, body: JSON.stringify(), }; } function getFlarumUser({ forumId, forumToken }) { return { method: 'GET', url: `${process.env.FLARUM_URL}/api/users/${forumId}`, headers: { 'content-type': 'application/json', Authorization: `Token ${forumToken}`, }, body: JSON.stringify({ forumId }), }; } function getFlarumDiscussions(forumToken) { return { method: 'GET', url: `${process.env.FLARUM_URL}/api/discussions`, headers: { 'content-type': 'application/json', Authorization: `Token ${forumToken}`, }, }; } export default (req, res) => { if (!req.session) { res.redirect('/login'); return; } request(getCompanies(), (error, response, body) => { const companies = JSON.parse(body); const user = req.session; const { forumId, forumToken } = req.session; request( getFlarumUser({ forumId, forumToken }), (userError, userResponse, userBody) => { const flarumUser = JSON.parse(userBody); request( getFlarumDiscussions(forumToken), (discussionError, discussionResponce, discussionBody) => { const flarumDiscussions = JSON.parse(discussionBody); const templatePath = '/templates/account.twig'; const page = new Page({ templatePath, templateVariables: { companies, user, flarumUser, flarumDiscussions, flarumURL: process.env.FLARUM_URL, }, }); res.send(page.render()); }); }); }); };
var stemmer = stemmer || null; var wps = function(document) { var self = {}; var privy = {}; self.stem = stemmer || function(word) { return word; }; self.document = document; privy.sln = document.defaultView.getSelection(); self.log = function(msg) { console.log(msg); }; self.indexDocument = function() { if (self.indexed) { return; } try { var rng = self.advanceRange({doc:document,windowSize:50}); var detail = {rng:rng, selection:privy.sln}; var evt = self.document.createEvent("CustomEvent"); evt.initCustomEvent("wps-index-passage", true, false, detail); self.document.dispatchEvent(evt); //privy.sln.removeAllRanges(); //privy.sln.addRange(rng); } catch (ee) { // log ee self.indexed = true; self.log("DONEDONE"); } setTimeout(self.indexDocument, 0); }; privy.rangeSeq = 0; self.nextRangeId = function() { privy.rangeSeq++; return ["RANGE",["00000000",privy.rangeSeq].join("").slice(-8)].join(""); }; self.indexRange = function(rng) { if (! self.index) { self.index = {}; self.index.invList = {}; self.index.N = 0; self.index.ranges = {}; jQuery(self.document).data('index', self.index); } self.index.N++; var rangeID = self.nextRangeId(); var txt = rng.toString(); self.index.ranges[rangeID] = {range:rng,text:txt}; var words = txt.split(/\s+/); words = words.map(function(word) { var out = word.replace(/\W+\s*$/,''); //if (out !== word) { console.log("DELTA: |" + word + "| --> |" + out + "|"); } return out; }).map(String.toLowerCase); var stems = words.map(self.stem); stems.forEach(function(token) { if (! self.index.invList[token]) { self.index.invList[token] = []; } self.index.invList[token].push({rangeid:rangeID}); }); //self.log(JSON.stringify({foo:7,index: Object.keys(self.index).length})); }; self.advanceRange = function(spec) { if (! self.currentRange) { var body = spec.doc.querySelector("body"); self.previousRange = spec.doc.createRange(); self.previousRange.setStart(body,0); self.previousRange.setEnd(body,0); for (var i = 0; i < Math.floor(spec.windowSize / 2); i++) { self.previousRange = self.gobbleWord(self.previousRange); } self.currentRange = self.previousRange.cloneRange(); for (var i = 0; i < Math.ceil(spec.windowSize / 2); i++) { self.currentRange = self.gobbleWord(self.currentRange); } return self.currentRange; } var rng0 = self.previousRange; self.previousRange = self.currentRange.cloneRange(); self.currentRange.setStart(rng0.endContainer, rng0.endOffset); for (var i = 0; i < Math.ceil(spec.windowSize / 2); i++) { self.currentRange = self.gobbleWord(self.currentRange); } return self.currentRange; }; self.gobbleWord = function(rng, spec) { spec = spec || {}; spec.terminator = spec.terminator || /([\s])/; rng = self.fixRange(rng); var txt0 = rng.toString(); var rng2 = rng.cloneRange(); rng2.selectNodeContents(rng.endContainer); rng2.setStart(rng.endContainer,rng.endOffset); var txt = rng2.toString(); if (txt.length === 0) { rng.setEndAfter(rng2.endContainer); return self.gobbleWord(rng, spec); } var tokens0 = txt0.split(spec.terminator); var tokens = txt.split(spec.terminator); //self.log("GOBBLE: " + JSON.stringify({spec:spec,txt0:txt0,txt:txt,tokens0:tokens0,tokens:tokens})); switch (tokens.length) { case 0: //self.log("ZERO: " + JSON.stringify({tokens:tokens})); break; case 1: //self.log("ONE: " + JSON.stringify({tokens:tokens,txt:txt})); rng.setEndAfter(rng2.endContainer); spec.sated = spec.sated || (tokens0.slice(-1)[0] === ''); return spec.sated ? rng : self.gobbleWord(rng, spec); break; case 2: //self.log("TWO: " + JSON.stringify({tokens:tokens})); if (tokens[0].length > 0) { var suffix = tokens[0]; rng.setEnd(rng.endContainer,rng.endOffset + suffix.length); } else { } break; default: //self.log("3+: " + JSON.stringify({tokens:tokens,txt:txt})); if (tokens[0].length > 0) { var suffix = tokens[0]; rng.setEnd(rng.endContainer,rng.endOffset + suffix.length); } else { var suffix = tokens.slice(0,3).join(""); rng.setEnd(rng.endContainer,rng.endOffset + suffix.length); if (tokens[2].length > 0) { } else { var spec2 = Object.create(spec); spec2.sated = true; return self.gobbleWord(rng, spec2); } } } return rng; }; self.fixRange = function(rng) { var ec = rng.endContainer; //self.log(JSON.stringify({fixx:rng.toString(),nodeType: ec.nodeType,ec: ec.outerHTML,off:rng.endOffset})); switch (ec.nodeType) { case ec.ELEMENT_NODE: if (ec.childNodes.length > rng.endOffset) { var kid = ec.childNodes[rng.endOffset]; var rng2 = rng.cloneRange(); rng2.selectNode(kid); //self.log(JSON.stringify({kid:rng2.toString()})); rng.setEnd(kid,0); } else { rng.setEndAfter(ec); } return self.fixRange(rng); } //self.log(JSON.stringify({fixxed:rng.toString()})); return rng; }; self.computeScoreContribution = function(spec) { return spec.tf * spec.idf; }; self.combineScoreContributions = function(contribs) { return contribs.reduce(function(accum, contrib) { return accum + contrib; }, 0.0); }; self.compareScores = function(a,b) { if (Math.abs(a.score - b.score) > 0.0) { return b.score - a.score; } return (b.rangeid < a.rangeid); }; jQuery(self.document).on('query', function(event, detail) { detail = detail || event.detail || (event.originalEvent && event.originalEvent.detail); var words = detail.query.split(/\s+/).map(String.toLowerCase); console.log("QUERYWORDS: " + JSON.stringify({words:words})); var stems = words.map(self.stem); console.log("QUERYSTEMS: " + JSON.stringify({words:words,stems:stems})); var candidates = {}; var results = []; self.index.logN = Math.log(self.index.N); console.log("N: " + JSON.stringify({N:self.index.N,logN:self.index.logN})); stems.forEach(function(stem) { var entries = self.index.invList[stem] || []; var df = entries.length; }); candidates = stems.reduce(function(accum, stem) { var entries = self.index.invList[stem] || []; var idf = self.index.logN - Math.log(1+entries.length); entries.forEach(function(entry) { if (! accum[entry.rangeid]) { accum[entry.rangeid] = []; } accum[entry.rangeid].push(self.computeScoreContribution({stem:stem,idf:idf,tf:1})) }); return accum; }, {}); results = Object.keys(candidates).map(function(rangeid) { return {rangeid:rangeid,score:self.combineScoreContributions(candidates[rangeid])}; }); results.sort(self.compareScores); console.log("QUERYUMMMS: " + JSON.stringify({words:words,stems:stems,results:results //,candidates:candidates })); var index = self.index; //console.log("INDEX: " + JSON.stringify(Object.keys(index), null, 2)); console.log("QUERY ME: " + JSON.stringify({detail:detail,foo:12})); }); jQuery(self.document).on('click', function(event) { console.log("CLICK ME!"); }); jQuery(self.document).on('wps-index-passage', function(event, detail) { var doc = (!! event.target.ownerDocuent) ? event.target.ownerDocument : event.target; detail = detail || event.detail || event.originalEvent.detail; doc.wps.indexRange(detail.rng); }); return self; }; wps.ui = {}; wps.ui.button = new component.buttonComponent({localid:"button"}); wps.ui.pagewatcher = new component.pagewatcherComponent({localid:"pagewatcher"}); jQuery(document).on("wps-pagewatcher-load", function(event) { console.log("WPSLOAD"); var doc = (!! event.target.ownerDocument) ? event.target.ownerDocument : event.target; if (doc.wps) { console.log("NOTFIRST!"); return; } doc.wps = new wps(doc); doc.defaultView.setTimeout(function() { console.log("INDEX!"); doc.wps.indexDocument(); }, 0); }); if (false) { jQuery(document).find("#appcontent").on("DOMContentLoaded.wps load.wps", function(event) { var doc = (!! event.target.ownerDocument) ? event.target.ownerDocument : event.target; doc.wps = new wps(doc); doc.defaultView.setTimeout(function() { doc.wps.indexDocument(); }, 100); }); document.addEventListener('wps-index', function(event) { var doc = (!! event.target.ownerDocuent) ? event.target.ownerDocument : event.target; doc.wps = new wps(doc); doc.defaultView.setTimeout(function() { doc.wps.indexDocument(); }, 100); }, false); var ui = {}; ui.wgcm = window.gContextMenu; ui.gcm = gContextMenu; jQuery(document).on('query.wps', function(event) { console.log("FOOFOO"); }); jQuery(document).on('insert-mozilla-ui.wps', function(event) { console.log("FOO"); var contextMenu = document.querySelector("#contentAreaContextMenu"); ui.fmenuitem = document.createElement("menuitem"); ui.fmenuitem.setAttribute("label", "WPSEARCHTOO"); contextMenu.appendChild(ui.fmenuitem); console.log("BAR"); jQuery(ui.fmenuitem).on('click', function(event) { var gcm = gContextMenu; [gContextMenu, window.gContextMenu, document.defaultView.gContextMenu,ui.wgcm,ui.gcm].forEach(function(gcm) { try { console.log(JSON.stringify({gcm: Object.keys(gcm),nullo:!!gcm,tgt:!!gcm.target})); } catch (ee) { console.log("EE: " + JSON.stringify({ee:ee,msg:ee.message,nullo:[true,!!gcm]})); } }); var query = document.defaultView.prompt("WAS??"); jQuery(gcm.target).trigger('query', {query:query}); jQuery(gcm.target).css({opacity:0.2}); console.log(JSON.stringify({tgt:gcm.target.outerHTML})); }); }); jQuery(document).on('cleanup-mozilla-ui.wps', function(event) { console.log("FOO"); jQuery(ui.fmenuitem).detach(); jQuery(document).off('.wps'); console.log("BAR"); }); } if (true) { jQuery(document).on('wps-index-passage.wps', function(event, detail) { var doc = (!! event.target.ownerDocuent) ? event.target.ownerDocument : event.target; detail = detail || event.detail || event.originalEvent.detail; //console.log("PSG0!"); //console.log("PSG0: " + JSON.stringify(detail)); detail.selection.removeAllRanges(); detail.selection.addRange(detail.rng); }); }
var JS = {}; /* * JS: Core */ JS.core = [ "node_modules/tiny.js/dist/tiny.js", "src/shared/scripts/core.js", "src/shared/scripts/events.js", "src/shared/scripts/factory.js", "src/product-component/scripts/init.js" ]; /* * JS: Abilities */ JS.abilities = [ "src/shared/scripts/Content.js", "src/shared/scripts/Collapsible.js", "src/shared/scripts/Viewport.js", "src/shared/scripts/Positioner.js" ]; /* * JS: Components */ JS.components = [ "src/shared/scripts/Component.js", "src/shared/scripts/Expandable.js", "src/shared/scripts/Menu.js", "src/shared/scripts/Popover.js", "src/shared/scripts/Layer.js", // "src/shared/scripts/Tooltip.js", // "src/shared/scripts/Bubble.js", "src/shared/scripts/Modal.js", "src/shared/scripts/Transition.js", "src/shared/scripts/Dropdown.js", "src/shared/scripts/Form.js", "src/shared/scripts/Condition.js", "src/shared/scripts/Validation.js", "src/shared/scripts/Countdown.js", "src/shared/scripts/Carousel.js", "src/shared/scripts/Calendar.js", "src/product-component/scripts/Product.js", "src/shared/scripts/Autocomplete.js" ]; exports.JS = JS;
import CardParser from './utils/card-parser'; import CardInputParser from './mixins/card-input-parser'; export function isDigit(event) { return String.fromCharCode(event.charCode).match(/\d/); } export { CardParser, CardInputParser };
exports.config = { allScriptsTimeout: 11000, specs: [ 'e2e/*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://127.0.0.1:8000/app/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
define("ace/mode/jack_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(e, t, n) { "use strict"; var r = e("../lib/oop"), i = e("./text_highlight_rules").TextHighlightRules, s = function() { this.$rules = { start: [{ token: "string", regex: '"', next: "string2" }, { token: "string", regex: "'", next: "string1" }, { token: "constant.numeric", regex: "-?0[xX][0-9a-fA-F]+\\b" }, { token: "constant.numeric", regex: "(?:0|[-+]?[1-9][0-9]*)\\b" }, { token: "constant.binary", regex: "<[0-9A-Fa-f][0-9A-Fa-f](\\s+[0-9A-Fa-f][0-9A-Fa-f])*>" }, { token: "constant.language.boolean", regex: "(?:true|false)\\b" }, { token: "constant.language.null", regex: "null\\b" }, { token: "storage.type", regex: "(?:Integer|Boolean|Null|String|Buffer|Tuple|List|Object|Function|Coroutine|Form)\\b" }, { token: "keyword", regex: "(?:return|abort|vars|for|delete|in|is|escape|exec|split|and|if|elif|else|while)\\b" }, { token: "language.builtin", regex: "(?:lines|source|parse|read-stream|interval|substr|parseint|write|print|range|rand|inspect|bind|i-values|i-pairs|i-map|i-filter|i-chunk|i-all\\?|i-any\\?|i-collect|i-zip|i-merge|i-each)\\b" }, { token: "comment", regex: "--.*$" }, { token: "paren.lparen", regex: "[[({]" }, { token: "paren.rparen", regex: "[\\])}]" }, { token: "storage.form", regex: "@[a-z]+" }, { token: "constant.other.symbol", regex: ":+[a-zA-Z_]([-]?[a-zA-Z0-9_])*[?!]?" }, { token: "variable", regex: "[a-zA-Z_]([-]?[a-zA-Z0-9_])*[?!]?" }, { token: "keyword.operator", regex: "\\|\\||\\^\\^|&&|!=|==|<=|<|>=|>|\\+|-|\\*|\\/|\\^|\\%|\\#|\\!" }, { token: "text", regex: "\\s+" }], string1: [{ token: "constant.language.escape", regex: /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|['"\\\/bfnrt])/ }, { token: "string", regex: "[^'\\\\]+" }, { token: "string", regex: "'", next: "start" }, { token: "string", regex: "", next: "start" }], string2: [{ token: "constant.language.escape", regex: /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|['"\\\/bfnrt])/ }, { token: "string", regex: '[^"\\\\]+' }, { token: "string", regex: '"', next: "start" }, { token: "string", regex: "", next: "start" }] } }; r.inherits(s, i), t.JackHighlightRules = s }), define("ace/mode/matching_brace_outdent", ["require", "exports", "module", "ace/range"], function(e, t, n) { "use strict"; var r = e("../range").Range, i = function() {}; (function() { this.checkOutdent = function(e, t) { return /^\s+$/.test(e) ? /^\s*\}/.test(t) : !1 }, this.autoOutdent = function(e, t) { var n = e.getLine(t), i = n.match(/^(\s*\})/); if (!i) return 0; var s = i[1].length, o = e.findMatchingBracket({ row: t, column: s }); if (!o || o.row == t) return 0; var u = this.$getIndent(e.getLine(o.row)); e.replace(new r(t, 0, t, s - 1), u) }, this.$getIndent = function(e) { return e.match(/^\s*/)[0] } }).call(i.prototype), t.MatchingBraceOutdent = i }), define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function(e, t, n) { "use strict"; var r = e("../../lib/oop"), i = e("../../range").Range, s = e("./fold_mode").FoldMode, o = t.FoldMode = function(e) { e && (this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + e.start)), this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + e.end))) }; r.inherits(o, s), function() { this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/, this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/, this.singleLineBlockCommentRe = /^\s*(\/\*).*\*\/\s*$/, this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/, this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/, this._getFoldWidgetBase = this.getFoldWidget, this.getFoldWidget = function(e, t, n) { var r = e.getLine(n); if (this.singleLineBlockCommentRe.test(r) && !this.startRegionRe.test(r) && !this.tripleStarBlockCommentRe.test(r)) return ""; var i = this._getFoldWidgetBase(e, t, n); return !i && this.startRegionRe.test(r) ? "start" : i }, this.getFoldWidgetRange = function(e, t, n, r) { var i = e.getLine(n); if (this.startRegionRe.test(i)) return this.getCommentRegionBlock(e, i, n); var s = i.match(this.foldingStartMarker); if (s) { var o = s.index; if (s[1]) return this.openingBracketBlock(e, s[1], n, o); var u = e.getCommentFoldRange(n, o + s[0].length, 1); return u && !u.isMultiLine() && (r ? u = this.getSectionRange(e, n) : t != "all" && (u = null)), u } if (t === "markbegin") return; var s = i.match(this.foldingStopMarker); if (s) { var o = s.index + s[0].length; return s[1] ? this.closingBracketBlock(e, s[1], n, o) : e.getCommentFoldRange(n, o, -1) } }, this.getSectionRange = function(e, t) { var n = e.getLine(t), r = n.search(/\S/), s = t, o = n.length; t += 1; var u = t, a = e.getLength(); while (++t < a) { n = e.getLine(t); var f = n.search(/\S/); if (f === -1) continue; if (r > f) break; var l = this.getFoldWidgetRange(e, "all", t); if (l) { if (l.start.row <= s) break; if (l.isMultiLine()) t = l.end.row; else if (r == f) break } u = t } return new i(s, o, u, e.getLine(u).length) }, this.getCommentRegionBlock = function(e, t, n) { var r = t.search(/\s*$/), s = e.getLength(), o = n, u = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/, a = 1; while (++n < s) { t = e.getLine(n); var f = u.exec(t); if (!f) continue; f[1] ? a-- : a++; if (!a) break } var l = n; if (l > o) return new i(o, r, l, t.length) } }.call(o.prototype) }), define("ace/mode/jack", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/jack_highlight_rules", "ace/mode/matching_brace_outdent", "ace/mode/behaviour/cstyle", "ace/mode/folding/cstyle"], function(e, t, n) { "use strict"; var r = e("../lib/oop"), i = e("./text").Mode, s = e("./jack_highlight_rules").JackHighlightRules, o = e("./matching_brace_outdent").MatchingBraceOutdent, u = e("./behaviour/cstyle").CstyleBehaviour, a = e("./folding/cstyle").FoldMode, f = function() { this.HighlightRules = s, this.$outdent = new o, this.$behaviour = new u, this.foldingRules = new a }; r.inherits(f, i), function() { this.lineCommentStart = "--", this.getNextLineIndent = function(e, t, n) { var r = this.$getIndent(t); if (e == "start") { var i = t.match(/^.*[\{\(\[]\s*$/); i && (r += n) } return r }, this.checkOutdent = function(e, t, n) { return this.$outdent.checkOutdent(t, n) }, this.autoOutdent = function(e, t, n) { this.$outdent.autoOutdent(t, n) }, this.$id = "ace/mode/jack" }.call(f.prototype), t.Mode = f }); (function() { window.require(["ace/mode/jack"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
/************************************************************* * * MathJax/localization/lt/FontWarnings.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("lt","FontWarnings",{ version: "2.7.0-beta", isLoaded: true, strings: { webFont: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C \u0161iame tinklalapyje vartoja tinkle saugomus \u0161riftus, kuri\u0173 \u012Fk\u0117limas reikalauja laiko. \u017Denkl\u0173 rinkim\u0105 galima greitinti, matematikos \u0161riftus \u012Fdiegus vietiniame sistemos \u0161rift\u0173 aplanke.", imageFonts: "\u201EMathJax\u201C vartoja paveikslinius, o ne vietinius arba tinkle saugomus \u0161riftus. Matematikos \u017Eenklai vaizduojami l\u0117\u010Diau, o spausdinant netenkama rai\u0161kos.", noFonts: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C nepavyksta rasti \u0161rifto arba paveikslini\u0173 \u0161rift\u0173, tod\u0117l vartojami bendrieji unikodo ra\u0161menys, tikintis, kad nar\u0161ykl\u0117 juos rodys taisyklingai. Kai kurie \u017Eenklai gali b\u016Bti rodomi i\u0161darkyti arba visai nerodomi.", webFonts: "Dauguma dabartini\u0173 nar\u0161ykli\u0173 leid\u017Eia gauti \u0161riftus i\u0161 tinklo. Tik\u0117tina, kad atnaujinus nar\u0161ykl\u0117s laid\u0105 arba esam\u0105 nar\u0161ykl\u0119 pakeitus kita, tinklalapyje ger\u0117t\u0173 matematikos \u017Eenkl\u0173 vaizdavimas.", fonts: "\u201EMathJax\u201C gali vartoti [STIX fonts](%1) arba [MathJax TeX fonts](%2). \u012Ediegus vien\u0105 i\u0161 min\u0117t\u0173 alternatyv\u0173, ger\u0117s \u201EMathJax\u201C veikimas.", STIXPage: "Tinklalapyje numatyti [STIX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas.", TeXPage: "Tinklalapyje numatyti [MathJax TeX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas." } }); MathJax.Ajax.loadComplete("[MathJax]/localization/lt/FontWarnings.js");
'use strict'; angular.module('cbt') .directive('flagView', function(){ return { restrict: 'E', template: '{{title}}'+ '<a class="led" ng-repeat="led in values track by $index" ng-class="{\'active\':values[$index]}" title="{{info[title.toLowerCase()][$index]}}"></a>', link: function (scope, elem, attrs) { scope.values = Array(8); scope.$watch('value',function(newValue,oldValue) { for(var i=0; i<8; i++) scope.values[i] = !!(newValue & (0x01 << 7-i)); }); }, controller: function($scope){ // Description Library $scope.info = { error:[ 'RX1OVR: Receive Buffer 1 Overflow Flag bit', 'TXBO: Bus-Off Error Flag bit', 'TXBO: Bus-Off Error Flag bit', 'TXEP: Transmit Error-Passive Flag bit', 'RXEP: Receive Error-Passive Flag bit', 'TXWAR: Transmit Error Warning Flag bit', 'RXWAR: Receive Error Warning Flag bit', 'EWARN: Error Warning Flag bit', ], // Datasheet pg 58 control:[ '', '', '', '', '', '', '', '' ], status:[ 'CANINTF.RX0IF', 'CANINTFL.RX1IF', 'TXB0CNTRL.TXREQ', 'CANINTF.TX0IF', 'TXB1CNTRL.TXREQ', 'CANINTF.TX1IF', 'TXB2CNTRL.TXREQ', 'CANINTF.TX2IF' ] } }, scope: { title: "@", value: "@" } } });
jQuery(document).ready(function(){ var options = jQuery('#neutron-panels').data('options'); console.log(options); jQuery('#neutron-plugin-containers').accordion({ active: false, collapsible: true, autoHeight: false, animated: false }); var dlg = jQuery( "#neutron-panels-dialog" ); dlg.dialog({ autoOpen: false, modal: true, minWidth: 500, close: function(event, ui) { var item = jQuery(this).data('item'); var parent = item.parent(); if(item.find(':hidden').eq(2).val().length == 0){ item.remove(); var widgets = parent.find('.widget'); if(widgets.length == 0){ parent.find('p.desc').show(); } jQuery.each(widgets, function(k,v){ jQuery(this).find(':hidden').eq(5).val(k); }); } jQuery('.dlg-error-msg').hide(); jQuery(this).data('item', null); jQuery('#neutron-widget-reference').html(''); jQuery.uniform.update('#neutron-widget-reference'); } }); jQuery('.widget a.edit-btn').live('click', function(){ dlg.data('item', jQuery(this).parent()); openDialog(dlg, options, jQuery(this).parent().find(':hidden').eq(2).val()); return false; }); jQuery('.widget a.delete-btn').live('click', function(){ var widget = jQuery(this).parent(); var parent = jQuery(this).parent().parent(); widget.fadeOut(function(){ jQuery(this).remove(); var widgets = parent.find('.widget'); if(widgets.length == 0){ parent.find('p.desc').show(); } jQuery.each(widgets, function(k,v){ jQuery(this).find(':hidden').eq(5).val(k); }); }); return false; }); createButtons(); jQuery('#neutron-panels-dialog-save').button().click(function(){ jQuery('.dlg-error-msg').hide(); var item = dlg.data('item'); var widgetIdentifier = item.data('widget').name; var widget_instance_id = jQuery('#neutron-widget-reference').val(); var label = jQuery('#neutron-widget-reference') .find('option[value="'+ widget_instance_id +'"]').text(); if(label.length > 35){ label = label.substr(0, 35); } if(widget_instance_id.length == 0){ jQuery('#dlg-error-msg-blank').fadeIn(); return false; } else if(item.parent().find(':hidden[value="'+ widget_instance_id +'"]').length > 0){ var instanceExists = false var widgetInstances = item.parent().find(':hidden[value="'+ widget_instance_id +'"]'); jQuery.each(widgetInstances, function(){ if(jQuery(this).next().val() == widgetIdentifier){ instanceExists = true; } }); if(instanceExists){ jQuery('#dlg-error-msg-exist').fadeIn(); return false; } } var formElms = item.find(':hidden'); formElms.eq(0).val(options.pluginInstanceId); formElms.eq(1).val(options.pluginIdentifier); formElms.eq(2).val(widget_instance_id); formElms.eq(3).val(widgetIdentifier); formElms.eq(4).val(item.parent().data('panel').name); item.find('.widget-label').text(label); dlg.dialog('close'); return false; }); jQuery( "#widget-list .widget" ).hover( function(){ var widgetOptions = jQuery(this).data('widget'); if(widgetOptions.isPanelAware){ jQuery.each(widgetOptions.allowedPanels, function(index, panel){ jQuery('#' + panel).addClass('accepted'); }); } else { jQuery('#neutron-plugin-containers .neutron-sortable').addClass('accepted'); } }, function(){ var widgetOptions = jQuery(this).data('widget'); if(widgetOptions.isPanelAware){ jQuery('#neutron-plugin-containers .neutron-sortable') .removeClass('accepted'); } } ); jQuery( ".neutron-sortable" ).sortable({ revert: true, items: 'div.widget', placeholder: "ui-state-highlight", forceHelperSize: true, forcePlaceholderSize: true, beforeStop: function(event, ui) { if(ui.item.find('a').length > 0){ return; } ui.item.parent().find('p.desc').hide(); var widgetNum = ui.item.parent().find('.widget').length - 1; var prototype = ui.item.parent().data('prototype'); var widgetHtml = jQuery(prototype).find('div').html().replace(/__name__/g, widgetNum); ui.item.append(widgetHtml); ui.item.append('<a class="delete-btn" href="#" style="float:right"></a>'); ui.item.append('<a href="#" class="edit-btn" style="float:right"></a>'); dlg.data('item', ui.item); createButtons(); openDialog(dlg, options, null); }, update: function(event, ui) { var widgets = ui.item.parent().find('.widget'); if(widgets.length == 0){ ui.item.parent().find('p.desc').show(); } jQuery.each(widgets, function(k,v){ jQuery(this).find(':hidden').eq(5).val(k); }); } }); jQuery( "#widget-list .widget" ).draggable({ connectToSortable: ".neutron-sortable.accepted", helper: "clone", revert: "invalid", stack: '.neutron-sortable', zIndex: 2700, start: function(event, ui){ var widgetOptions = ui.helper.data('widget'); if(widgetOptions.isPanelAware){ jQuery.each(widgetOptions.allowedPanels, function(k,v){ jQuery('#' + v).addClass('ui-state-highlight') .prev().addClass('ui-state-highlight'); }); } }, stop: function(event,ui){ var widgetOptions = ui.helper.data('widget'); if(widgetOptions.isPanelAware){ jQuery('#neutron-plugin-containers .neutron-sortable') .removeClass('ui-state-highlight') .prev().removeClass('ui-state-highlight'); } } }); jQuery('.neutron-sortable').droppable({ drop: function (event, ui) { jQuery(this).sortable("refresh"); }, tolerance: "touch" }); jQuery( ".neutron-sortable" ).disableSelection(); }); function createButtons() { jQuery( ".widget a.edit-btn" ).button({ icons: { primary: "ui-icon-pencil" }, text: false }); jQuery( ".widget a.delete-btn" ).button({ icons: { primary: "ui-icon-trash" }, text: false }); } function openDialog(dlg, options, selectedOption) { var widget = dlg.data('item').data('widget').name; jQuery.ajax({ async : false, type: 'POST', url: options.widget_instance_url, data: { 'name': widget }, success : function(response) { if (response == undefined || response == null){ dlg.data('item').data('widget', null); dlg.dialog('close'); return false; } var html = '<option value="">'+ options.instances_empty_value +'</option>'; jQuery.each(response, function(k,v){ html += '<option value="'+ v.id +'">'+ v.label +'</option>'; }); jQuery('#neutron-widget-reference').html(html); if(selectedOption){ jQuery('#neutron-widget-reference') .find('option[value="'+selectedOption+'"]').attr('selected', true); } jQuery.uniform.update('#neutron-widget-reference'); dlg.dialog('open'); }, error: function(){ dlg.data('item').remove(); } }); }
/* * This file is part of Invenio. * Copyright (C) 2016-2020 CERN. * * Invenio is free software; you can redistribute it and/or modify it * under the terms of the MIT License; see LICENSE file for more details. */ /** * Copyright (c) 2011-2013 Fabien Cazenave, Mozilla. * * 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. */ /* Additional modifications for PDF.js project: - Disables language initialization on page loading; - Removes consoleWarn and consoleLog and use console.log/warn directly. - Removes window._ assignment. - Remove compatibility code for OldIE. */ /*jshint browser: true, devel: true, es5: true, globalstrict: true */ 'use strict'; document.webL10n = (function(window, document, undefined) { var gL10nData = {}; var gTextData = ''; var gTextProp = 'textContent'; var gLanguage = ''; var gMacros = {}; var gReadyState = 'loading'; /** * Synchronously loading l10n resources significantly minimizes flickering * from displaying the app with non-localized strings and then updating the * strings. Although this will block all script execution on this page, we * expect that the l10n resources are available locally on flash-storage. * * As synchronous XHR is generally considered as a bad idea, we're still * loading l10n resources asynchronously -- but we keep this in a setting, * just in case... and applications using this library should hide their * content until the `localized' event happens. */ var gAsyncResourceLoading = true; // read-only /** * DOM helpers for the so-called "HTML API". * * These functions are written for modern browsers. For old versions of IE, * they're overridden in the 'startup' section at the end of this file. */ function getL10nResourceLinks() { return document.querySelectorAll('link[type="application/l10n"]'); } function getL10nDictionary() { var script = document.querySelector('script[type="application/l10n"]'); // TODO: support multiple and external JSON dictionaries return script ? JSON.parse(script.innerHTML) : null; } function getTranslatableChildren(element) { return element ? element.querySelectorAll('*[data-l10n-id]') : []; } function getL10nAttributes(element) { if (!element) return {}; var l10nId = element.getAttribute('data-l10n-id'); var l10nArgs = element.getAttribute('data-l10n-args'); var args = {}; if (l10nArgs) { try { args = JSON.parse(l10nArgs); } catch (e) { console.warn('could not parse arguments for #' + l10nId); } } return { id: l10nId, args: args }; } function fireL10nReadyEvent(lang) { var evtObject = document.createEvent('Event'); evtObject.initEvent('localized', true, false); evtObject.language = lang; document.dispatchEvent(evtObject); } function xhrLoadText(url, onSuccess, onFailure) { onSuccess = onSuccess || function _onSuccess(data) {}; onFailure = onFailure || function _onFailure() { console.warn(url + ' not found.'); }; var xhr = new XMLHttpRequest(); xhr.open('GET', url, gAsyncResourceLoading); if (xhr.overrideMimeType) { xhr.overrideMimeType('text/plain; charset=utf-8'); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { onSuccess(xhr.responseText); } else { onFailure(); } } }; xhr.onerror = onFailure; xhr.ontimeout = onFailure; // in Firefox OS with the app:// protocol, trying to XHR a non-existing // URL will raise an exception here -- hence this ugly try...catch. try { xhr.send(null); } catch (e) { onFailure(); } } /** * l10n resource parser: * - reads (async XHR) the l10n resource matching `lang'; * - imports linked resources (synchronously) when specified; * - parses the text data (fills `gL10nData' and `gTextData'); * - triggers success/failure callbacks when done. * * @param {string} href * URL of the l10n resource to parse. * * @param {string} lang * locale (language) to parse. Must be a lowercase string. * * @param {Function} successCallback * triggered when the l10n resource has been successully parsed. * * @param {Function} failureCallback * triggered when the an error has occured. * * @return {void} * uses the following global variables: gL10nData, gTextData, gTextProp. */ function parseResource(href, lang, successCallback, failureCallback) { var baseURL = href.replace(/[^\/]*$/, '') || './'; // handle escaped characters (backslashes) in a string function evalString(text) { if (text.lastIndexOf('\\') < 0) return text; return text.replace(/\\\\/g, '\\') .replace(/\\n/g, '\n') .replace(/\\r/g, '\r') .replace(/\\t/g, '\t') .replace(/\\b/g, '\b') .replace(/\\f/g, '\f') .replace(/\\{/g, '{') .replace(/\\}/g, '}') .replace(/\\"/g, '"') .replace(/\\'/g, "'"); } // parse *.properties text data into an l10n dictionary // If gAsyncResourceLoading is false, then the callback will be called // synchronously. Otherwise it is called asynchronously. function parseProperties(text, parsedPropertiesCallback) { var dictionary = {}; // token expressions var reBlank = /^\s*|\s*$/; var reComment = /^\s*#|^\s*$/; var reSection = /^\s*\[(.*)\]\s*$/; var reImport = /^\s*@import\s+url\((.*)\)\s*$/i; var reSplit = /^([^=\s]*)\s*=\s*(.+)$/; // TODO: escape EOLs with '\' // parse the *.properties file into an associative array function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) { var entries = rawText.replace(reBlank, '').split(/[\r\n]+/); var currentLang = '*'; var genericLang = lang.split('-', 1)[0]; var skipLang = false; var match = ''; function nextEntry() { // Use infinite loop instead of recursion to avoid reaching the // maximum recursion limit for content with many lines. while (true) { if (!entries.length) { parsedRawLinesCallback(); return; } var line = entries.shift(); // comment or blank line? if (reComment.test(line)) continue; // the extended syntax supports [lang] sections and @import rules if (extendedSyntax) { match = reSection.exec(line); if (match) { // section start? // RFC 4646, section 4.4, "All comparisons MUST be performed // in a case-insensitive manner." currentLang = match[1].toLowerCase(); skipLang = (currentLang !== '*') && (currentLang !== lang) && (currentLang !== genericLang); continue; } else if (skipLang) { continue; } match = reImport.exec(line); if (match) { // @import rule? loadImport(baseURL + match[1], nextEntry); return; } } // key-value pair var tmp = line.match(reSplit); if (tmp && tmp.length === 3) { dictionary[tmp[1]] = evalString(tmp[2]); } } } nextEntry(); } // import another *.properties file function loadImport(url, callback) { xhrLoadText(url, function(content) { parseRawLines(content, false, callback); // don't allow recursive imports }, null); } // fill the dictionary parseRawLines(text, true, function() { parsedPropertiesCallback(dictionary); }); } // load and parse l10n data (warning: global variables are used here) xhrLoadText(href, function(response) { gTextData += response; // mostly for debug // parse *.properties text data into an l10n dictionary parseProperties(response, function(data) { // find attribute descriptions, if any for (var key in data) { var id, prop, index = key.lastIndexOf('.'); if (index > 0) { // an attribute has been specified id = key.substring(0, index); prop = key.substr(index + 1); } else { // no attribute: assuming text content by default id = key; prop = gTextProp; } if (!gL10nData[id]) { gL10nData[id] = {}; } gL10nData[id][prop] = data[key]; } // trigger callback if (successCallback) { successCallback(); } }); }, failureCallback); } // load and parse all resources for the specified locale function loadLocale(lang, callback) { // RFC 4646, section 2.1 states that language tags have to be treated as // case-insensitive. Convert to lowercase for case-insensitive comparisons. if (lang) { lang = lang.toLowerCase(); } callback = callback || function _callback() {}; clear(); gLanguage = lang; // check all <link type="application/l10n" href="..." /> nodes // and load the resource files var langLinks = getL10nResourceLinks(); var langCount = langLinks.length; if (langCount === 0) { // we might have a pre-compiled dictionary instead var dict = getL10nDictionary(); if (dict && dict.locales && dict.default_locale) { console.log('using the embedded JSON directory, early way out'); gL10nData = dict.locales[lang]; if (!gL10nData) { var defaultLocale = dict.default_locale.toLowerCase(); for (var anyCaseLang in dict.locales) { anyCaseLang = anyCaseLang.toLowerCase(); if (anyCaseLang === lang) { gL10nData = dict.locales[lang]; break; } else if (anyCaseLang === defaultLocale) { gL10nData = dict.locales[defaultLocale]; } } } callback(); } else { console.log('no resource to load, early way out'); } // early way out fireL10nReadyEvent(lang); gReadyState = 'complete'; return; } // start the callback when all resources are loaded var onResourceLoaded = null; var gResourceCount = 0; onResourceLoaded = function() { gResourceCount++; if (gResourceCount >= langCount) { callback(); fireL10nReadyEvent(lang); gReadyState = 'complete'; } }; // load all resource files function L10nResourceLink(link) { var href = link.href; // Note: If |gAsyncResourceLoading| is false, then the following callbacks // are synchronously called. this.load = function(lang, callback) { parseResource(href, lang, callback, function() { console.warn(href + ' not found.'); // lang not found, used default resource instead console.warn('"' + lang + '" resource not found'); gLanguage = ''; // Resource not loaded, but we still need to call the callback. callback(); }); }; } for (var i = 0; i < langCount; i++) { var resource = new L10nResourceLink(langLinks[i]); resource.load(lang, onResourceLoaded); } } // clear all l10n data function clear() { gL10nData = {}; gTextData = ''; gLanguage = ''; // TODO: clear all non predefined macros. // There's no such macro /yet/ but we're planning to have some... } /** * Get rules for plural forms (shared with JetPack), see: * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * https://github.com/mozilla/addon-sdk/blob/master/python-lib/plural-rules-generator.p * * @param {string} lang * locale (language) used. * * @return {Function} * returns a function that gives the plural form name for a given integer: * var fun = getPluralRules('en'); * fun(1) -> 'one' * fun(0) -> 'other' * fun(1000) -> 'other'. */ function getPluralRules(lang) { var locales2rules = { 'af': 3, 'ak': 4, 'am': 4, 'ar': 1, 'asa': 3, 'az': 0, 'be': 11, 'bem': 3, 'bez': 3, 'bg': 3, 'bh': 4, 'bm': 0, 'bn': 3, 'bo': 0, 'br': 20, 'brx': 3, 'bs': 11, 'ca': 3, 'cgg': 3, 'chr': 3, 'cs': 12, 'cy': 17, 'da': 3, 'de': 3, 'dv': 3, 'dz': 0, 'ee': 3, 'el': 3, 'en': 3, 'eo': 3, 'es': 3, 'et': 3, 'eu': 3, 'fa': 0, 'ff': 5, 'fi': 3, 'fil': 4, 'fo': 3, 'fr': 5, 'fur': 3, 'fy': 3, 'ga': 8, 'gd': 24, 'gl': 3, 'gsw': 3, 'gu': 3, 'guw': 4, 'gv': 23, 'ha': 3, 'haw': 3, 'he': 2, 'hi': 4, 'hr': 11, 'hu': 0, 'id': 0, 'ig': 0, 'ii': 0, 'is': 3, 'it': 3, 'iu': 7, 'ja': 0, 'jmc': 3, 'jv': 0, 'ka': 0, 'kab': 5, 'kaj': 3, 'kcg': 3, 'kde': 0, 'kea': 0, 'kk': 3, 'kl': 3, 'km': 0, 'kn': 0, 'ko': 0, 'ksb': 3, 'ksh': 21, 'ku': 3, 'kw': 7, 'lag': 18, 'lb': 3, 'lg': 3, 'ln': 4, 'lo': 0, 'lt': 10, 'lv': 6, 'mas': 3, 'mg': 4, 'mk': 16, 'ml': 3, 'mn': 3, 'mo': 9, 'mr': 3, 'ms': 0, 'mt': 15, 'my': 0, 'nah': 3, 'naq': 7, 'nb': 3, 'nd': 3, 'ne': 3, 'nl': 3, 'nn': 3, 'no': 3, 'nr': 3, 'nso': 4, 'ny': 3, 'nyn': 3, 'om': 3, 'or': 3, 'pa': 3, 'pap': 3, 'pl': 13, 'ps': 3, 'pt': 3, 'rm': 3, 'ro': 9, 'rof': 3, 'ru': 11, 'rwk': 3, 'sah': 0, 'saq': 3, 'se': 7, 'seh': 3, 'ses': 0, 'sg': 0, 'sh': 11, 'shi': 19, 'sk': 12, 'sl': 14, 'sma': 7, 'smi': 7, 'smj': 7, 'smn': 7, 'sms': 7, 'sn': 3, 'so': 3, 'sq': 3, 'sr': 11, 'ss': 3, 'ssy': 3, 'st': 3, 'sv': 3, 'sw': 3, 'syr': 3, 'ta': 3, 'te': 3, 'teo': 3, 'th': 0, 'ti': 4, 'tig': 3, 'tk': 3, 'tl': 4, 'tn': 3, 'to': 0, 'tr': 0, 'ts': 3, 'tzm': 22, 'uk': 11, 'ur': 3, 've': 3, 'vi': 0, 'vun': 3, 'wa': 4, 'wae': 3, 'wo': 0, 'xh': 3, 'xog': 3, 'yo': 0, 'zh': 0, 'zu': 3 }; // utility functions for plural rules methods function isIn(n, list) { return list.indexOf(n) !== -1; } function isBetween(n, start, end) { return start <= n && n <= end; } // list of all plural rules methods: // map an integer to the plural form name to use var pluralRules = { '0': function(n) { return 'other'; }, '1': function(n) { if ((isBetween((n % 100), 3, 10))) return 'few'; if (n === 0) return 'zero'; if ((isBetween((n % 100), 11, 99))) return 'many'; if (n === 2) return 'two'; if (n === 1) return 'one'; return 'other'; }, '2': function(n) { if (n !== 0 && (n % 10) === 0) return 'many'; if (n === 2) return 'two'; if (n === 1) return 'one'; return 'other'; }, '3': function(n) { if (n === 1) return 'one'; return 'other'; }, '4': function(n) { if ((isBetween(n, 0, 1))) return 'one'; return 'other'; }, '5': function(n) { if ((isBetween(n, 0, 2)) && n !== 2) return 'one'; return 'other'; }, '6': function(n) { if (n === 0) return 'zero'; if ((n % 10) === 1 && (n % 100) !== 11) return 'one'; return 'other'; }, '7': function(n) { if (n === 2) return 'two'; if (n === 1) return 'one'; return 'other'; }, '8': function(n) { if ((isBetween(n, 3, 6))) return 'few'; if ((isBetween(n, 7, 10))) return 'many'; if (n === 2) return 'two'; if (n === 1) return 'one'; return 'other'; }, '9': function(n) { if (n === 0 || n !== 1 && (isBetween((n % 100), 1, 19))) return 'few'; if (n === 1) return 'one'; return 'other'; }, '10': function(n) { if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19))) return 'few'; if ((n % 10) === 1 && !(isBetween((n % 100), 11, 19))) return 'one'; return 'other'; }, '11': function(n) { if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) return 'few'; if ((n % 10) === 0 || (isBetween((n % 10), 5, 9)) || (isBetween((n % 100), 11, 14))) return 'many'; if ((n % 10) === 1 && (n % 100) !== 11) return 'one'; return 'other'; }, '12': function(n) { if ((isBetween(n, 2, 4))) return 'few'; if (n === 1) return 'one'; return 'other'; }, '13': function(n) { if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) return 'few'; if (n !== 1 && (isBetween((n % 10), 0, 1)) || (isBetween((n % 10), 5, 9)) || (isBetween((n % 100), 12, 14))) return 'many'; if (n === 1) return 'one'; return 'other'; }, '14': function(n) { if ((isBetween((n % 100), 3, 4))) return 'few'; if ((n % 100) === 2) return 'two'; if ((n % 100) === 1) return 'one'; return 'other'; }, '15': function(n) { if (n === 0 || (isBetween((n % 100), 2, 10))) return 'few'; if ((isBetween((n % 100), 11, 19))) return 'many'; if (n === 1) return 'one'; return 'other'; }, '16': function(n) { if ((n % 10) === 1 && n !== 11) return 'one'; return 'other'; }, '17': function(n) { if (n === 3) return 'few'; if (n === 0) return 'zero'; if (n === 6) return 'many'; if (n === 2) return 'two'; if (n === 1) return 'one'; return 'other'; }, '18': function(n) { if (n === 0) return 'zero'; if ((isBetween(n, 0, 2)) && n !== 0 && n !== 2) return 'one'; return 'other'; }, '19': function(n) { if ((isBetween(n, 2, 10))) return 'few'; if ((isBetween(n, 0, 1))) return 'one'; return 'other'; }, '20': function(n) { if ((isBetween((n % 10), 3, 4) || ((n % 10) === 9)) && !( isBetween((n % 100), 10, 19) || isBetween((n % 100), 70, 79) || isBetween((n % 100), 90, 99) )) return 'few'; if ((n % 1000000) === 0 && n !== 0) return 'many'; if ((n % 10) === 2 && !isIn((n % 100), [12, 72, 92])) return 'two'; if ((n % 10) === 1 && !isIn((n % 100), [11, 71, 91])) return 'one'; return 'other'; }, '21': function(n) { if (n === 0) return 'zero'; if (n === 1) return 'one'; return 'other'; }, '22': function(n) { if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99))) return 'one'; return 'other'; }, '23': function(n) { if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0) return 'one'; return 'other'; }, '24': function(n) { if ((isBetween(n, 3, 10) || isBetween(n, 13, 19))) return 'few'; if (isIn(n, [2, 12])) return 'two'; if (isIn(n, [1, 11])) return 'one'; return 'other'; } }; // return a function that gives the plural form name for a given integer var index = locales2rules[lang.replace(/-.*$/, '')]; if (!(index in pluralRules)) { console.warn('plural form unknown for [' + lang + ']'); return function() { return 'other'; }; } return pluralRules[index]; } // pre-defined 'plural' macro gMacros.plural = function(str, param, key, prop) { var n = parseFloat(param); if (isNaN(n)) return str; // TODO: support other properties (l20n still doesn't...) if (prop !== gTextProp) return str; // initialize _pluralRules if (!gMacros._pluralRules) { gMacros._pluralRules = getPluralRules(gLanguage); } var index = '[' + gMacros._pluralRules(n) + ']'; // try to find a [zero|one|two] key if it's defined if (n === 0 && (key + '[zero]') in gL10nData) { str = gL10nData[key + '[zero]'][prop]; } else if (n === 1 && (key + '[one]') in gL10nData) { str = gL10nData[key + '[one]'][prop]; } else if (n === 2 && (key + '[two]') in gL10nData) { str = gL10nData[key + '[two]'][prop]; } else if ((key + index) in gL10nData) { str = gL10nData[key + index][prop]; } else if ((key + '[other]') in gL10nData) { str = gL10nData[key + '[other]'][prop]; } return str; }; /** * l10n dictionary functions */ // fetch an l10n object, warn if not found, apply `args' if possible function getL10nData(key, args, fallback) { var data = gL10nData[key]; if (!data) { console.warn('#' + key + ' is undefined.'); if (!fallback) { return null; } data = fallback; } /** This is where l10n expressions should be processed. * The plan is to support C-style expressions from the l20n project; * until then, only two kinds of simple expressions are supported: * {[ index ]} and {{ arguments }}. */ var rv = {}; for (var prop in data) { var str = data[prop]; str = substIndexes(str, args, key, prop); str = substArguments(str, args, key); rv[prop] = str; } return rv; } // replace {[macros]} with their values function substIndexes(str, args, key, prop) { var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/; var reMatch = reIndex.exec(str); if (!reMatch || !reMatch.length) return str; // an index/macro has been found // Note: at the moment, only one parameter is supported var macroName = reMatch[1]; var paramName = reMatch[2]; var param; if (args && paramName in args) { param = args[paramName]; } else if (paramName in gL10nData) { param = gL10nData[paramName]; } // there's no macro parser yet: it has to be defined in gMacros if (macroName in gMacros) { var macro = gMacros[macroName]; str = macro(str, param, key, prop); } return str; } // replace {{arguments}} with their values function substArguments(str, args, key) { var reArgs = /\{\{\s*(.+?)\s*\}\}/g; return str.replace(reArgs, function(matched_text, arg) { if (args && arg in args) { return args[arg]; } if (arg in gL10nData) { return gL10nData[arg]; } console.log('argument {{' + arg + '}} for #' + key + ' is undefined.'); return matched_text; }); } // translate an HTML element function translateElement(element) { var l10n = getL10nAttributes(element); if (!l10n.id) return; // get the related l10n object var data = getL10nData(l10n.id, l10n.args); if (!data) { console.warn('#' + l10n.id + ' is undefined.'); return; } // translate element (TODO: security checks?) if (data[gTextProp]) { // XXX if (getChildElementCount(element) === 0) { element[gTextProp] = data[gTextProp]; } else { // this element has element children: replace the content of the first // (non-empty) child textNode and clear other child textNodes var children = element.childNodes; var found = false; for (var i = 0, l = children.length; i < l; i++) { if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) { if (found) { children[i].nodeValue = ''; } else { children[i].nodeValue = data[gTextProp]; found = true; } } } // if no (non-empty) textNode is found, insert a textNode before the // first element child. if (!found) { var textNode = document.createTextNode(data[gTextProp]); element.insertBefore(textNode, element.firstChild); } } delete data[gTextProp]; } for (var k in data) { element[k] = data[k]; } } // webkit browsers don't currently support 'children' on SVG elements... function getChildElementCount(element) { if (element.children) { return element.children.length; } if (typeof element.childElementCount !== 'undefined') { return element.childElementCount; } var count = 0; for (var i = 0; i < element.childNodes.length; i++) { count += element.nodeType === 1 ? 1 : 0; } return count; } // translate an HTML subtree function translateFragment(element) { element = element || document.documentElement; // check all translatable children (= w/ a `data-l10n-id' attribute) var children = getTranslatableChildren(element); var elementCount = children.length; for (var i = 0; i < elementCount; i++) { translateElement(children[i]); } // translate element itself if necessary translateElement(element); } return { // get a localized string get: function(key, args, fallbackString) { var index = key.lastIndexOf('.'); var prop = gTextProp; if (index > 0) { // An attribute has been specified prop = key.substr(index + 1); key = key.substring(0, index); } var fallback; if (fallbackString) { fallback = {}; fallback[prop] = fallbackString; } var data = getL10nData(key, args, fallback); if (data && prop in data) { return data[prop]; } return '{{' + key + '}}'; }, // debug getData: function() { return gL10nData; }, getText: function() { return gTextData; }, // get|set the document language getLanguage: function() { return gLanguage; }, setLanguage: function(lang, callback) { loadLocale(lang, function() { if (callback) callback(); translateFragment(); }); }, // get the direction (ltr|rtl) of the current language getDirection: function() { // http://www.w3.org/International/questions/qa-scripts // Arabic, Hebrew, Farsi, Pashto, Urdu var rtlList = ['ar', 'he', 'fa', 'ps', 'ur']; var shortCode = gLanguage.split('-', 1)[0]; return (rtlList.indexOf(shortCode) >= 0) ? 'rtl' : 'ltr'; }, // translate an element or document fragment translate: translateFragment, // this can be used to prevent race conditions getReadyState: function() { return gReadyState; }, ready: function(callback) { if (!callback) { return; } else if (gReadyState === 'complete' || gReadyState === 'interactive') { window.setTimeout(function() { callback(); }); } else if (document.addEventListener) { document.addEventListener('localized', function once() { document.removeEventListener('localized', once); callback(); }); } } }; }) (window, document);
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*! * Next JS * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved. * http://www.xenophy.com */ // {{{ NX.smtp.Smtp NX.define('NX.smtp.Smtp', { }); // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
var http = require('http'); var express = require('express'); var htmlToJson = require('../lib/htmlToJson'); describe('htmlToJson.request', function () { it('should take request library options and a filter, then return parsed results based on the response body', function (done) { var app = express(); var server = http.createServer(app); var port = 19999; app.get('/', function (req, resp) { resp.send('<div id="val">' + req.query.val + '</div>'); }); server.listen(port, function () { var val = 999; htmlToJson.request({ uri: 'http://localhost:' + port, qs: { val: val } }, { 'val': function ($doc) { return +$doc.find('#val').text(); } }, function (err, result) { result.val.should.equal(val); server.close(done); }); }); }); });
"use strict"; var reiny = require('reiny/runtime'); var __runtime = reiny.runtime; var __extend = reiny.xtend; module.exports = function(__props) { if(__props == null) __props = {}; return __runtime(function($){ $('span', {className:['hoge']}, ''aaa'') }); };
/*! * ------------------------------ * jQuery.loadHtmlComponents.js v0.1.0 * http://anasnakawa.github.com/jquery.loadHtmlComponents * license: MIT license (http://opensource.org/licenses/MIT) * ------------------------------ */ // ------------------------------ // table of content // ------------------------------ // a header title // - sub title // a method // ------------------------------ // a header title // -------------- // sub title // a method // describe your method // // * **param:** {type} paramName what to do with this parameter // // e.g: if you want to provide an example, that would be nice // ------------------------------ (function ($) { 'use strict'; var defaults = { attr: 'data-component-url' , extension: 'html' , componentsFolder: '' } , loadHtml = function(options) { options = $.extend(defaults, options); // component url attribute var attr = options.attr // load status attribute , state = attr + '-state' // load done value for status attribute , done = 'ready' // load pending value for status attribute , pending = 'pending' // cache all components , selector = '[' + attr + ']:not([' + state + '])'; // for all elements with component url not in ready state return this.find( selector ).each(function () { // debugger; var $self = $(this) // fetch url , componentUrl = $self.attr(attr) // ability to add component name without extension (.html) , url = ( options.componentsFolder + '/' ) + ( componentUrl.match('.' + options.extension + '$') ? componentUrl : componentUrl + '.' + options.extension ); $self.attr(state, pending); // load content and append $self.load(url, function () { // set state to ready $self.attr(state, done) if( $self.attr(options.attr + '-skip') !== 'true' ) { return $self.loadHtml(options); } }); }); }; $.fn.loadHtml = loadHtml; $.fn.loadHtml.defaults = defaults; })(jQuery);
;(function(window, _, $, undefined){ var Controller = new Class; //Controller.extend({. //Routes: {},. //Hash: window.location.hash,. // /**. // * route(); initiate routing based on what the url is right now. // * route('/path'); take the user to the given route. // */. //Route: function(){. //For(i in this.routes){. // }. // },. //Add_route: function(route, destination){. //This.routes[route] = destination;. // },. // //eg: "users/?id". // //eg: "users/?/edit". //Parse_route: function(route){. //Var segments = route.split('/'), output = [];. //For(var i=0, l=segments.length; i < l; i++){. //Var segment = {};. //If(/^[a-zA-Z_-]+$/.test(segments[i])){. //Segment.type = 'section';. //Segment.name = segments[i];. // }. //Else if(/^\?[a-zA-Z_-]+$/.test(segments[i])){. //Segment.type = 'parameter';. //Segment.name = segments[i].substr(1);. // }. //Else if(/^\?$/.test(segments[i])){. //Segment.type = 'parameter';. //Segment.name = undefined;. // }. //Output.push(segment);. // }. //Return output;. // }. // });. Controller.extend({ subclassed: function(child){ if(child.fn.elements) child.fn.elements = $.extend({}, this.fn.elements, child.fn.elements); if(child.fn.events) child.fn.events = $.extend({}, this.fn.events, child.fn.events); } }); Controller.include({ view: null, namespace: null, eventMatcher: /^(\w+(?:(?: or |\/)\w+)*)\s*(?:on\s+)?(.*)$/, eventSplitter: / or |\//, elements: {}, events: {}, //Default action for activate. activate: function(){ this.view.show(); }, //Default action for deactivate. deactivate: function(){ this.view.hide(); }, //Initiating controllers. init: function(){ if( ! $.domReady) throw('Can not create Controller instances before DOM is ready.'); //Handle arguments. var init, el, namespace, map, args = $.makeArray(arguments); if(args.length == 1){ if( $.isPlainObject(args[0]) ){ map = args[0]; }else if(scalar(args[0])){ el = args[0]; } } else if(args.length == 2){ if( $.isPlainObject(args[1]) ){ el = args[0]; map = args[1]; }else{ el = args[0]; namespace = args[1]; } } else if(args.length == 3){ el = args[0]; namespace = args[1]; map = args[2]; } el = el || (map && map.el) || this.view || false; namespace = namespace || (map && map.namespace) || this.namespace || false; map = map || {}; if(el === false || namespace === false){ throw "Invalid arguments. Element and namespace required."; } //Eof handle arguments. this.view = $(el); this.namespace = namespace; if(map){ for(var i in map){ switch(i){ case 'elements': case 'events': $.extend(this[i], map[i]); break; case 'init': init = map[i]; break; default: //This[i] = map[i];. var obj = {}; obj[i] = map[i]; Class.inherit(this, obj); break; } } map.el && delete map.el; } this.refreshElements(); this.bindEvents(); $.isFunction(init) && init.call(this); }, //Refresh elements. refreshElements: function(){ for(var key in this.elements) this[key] = $(this.elements[key], this.view); }, //Bind events (to a new namespace). bindEvents: function(namespace){ this.view.contents().off('.'+this.namespace); if(namespace) this.namespace = namespace; if(!this.namespace) throw "Namespace required."; for(var key in this.events){ var func, method = this.events[key]; if($.isFunction(method)){ func = this.proxy(method); } else if($.isArray(method)){ method = method.copy(); var methodName = method.shift(); var methodArgs = method; func = this.proxy(function(){ var func = this.proxy(this[methodName]); if( ! $.isFunction(func) ) throw "Function "+methodName+" is not a function."; func.apply(this, methodArgs); }); } else{ func = this.proxy(this[method]); } if( ! $.isFunction(func) ) throw "Function "+method+" is not a function."; var events = key.split(' and '); for(var i = 0; i < events.length; i++){ var match = events[i].match(this.eventMatcher), event = match[1], selector = this.elements[match[2]] || match[2]; event = $.map(event.split(' or '), this.proxy(function(val){ return val + '.' + this.namespace; })).join(' '); if(selector){ this.view.on(event, selector, func); }else{ this.view.on(event, func); } } } return this; }//,. // //bind routes to methods. //BindRoutes: function(){. //For(i in this.routes){. //Controller.addRoute(i, this.routes[i]);. // }. // }. }); exports.Controller = Controller; })(window, _, (jQuery || Zepto || $ || ($={})));
export { default } from 'ember-theater/ember-theater/director/directions/random';
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { toggleCustomInlineStyle, getSelectionCustomInlineStyle, } from 'draftjs-utils'; import LayoutComponent from './Component'; export default class FontSize extends Component { static propTypes = { onChange: PropTypes.func.isRequired, editorState: PropTypes.object, modalHandler: PropTypes.object, config: PropTypes.object, translations: PropTypes.object, }; state: Object = { expanded: undefined, currentFontSize: undefined, }; componentWillMount(): void { const { editorState, modalHandler } = this.props; if (editorState) { this.setState({ currentFontSize: getSelectionCustomInlineStyle(editorState, ['FONTSIZE']).FONTSIZE, }); } modalHandler.registerCallBack(this.expandCollapse); } componentWillReceiveProps(properties: Object): void { if (properties.editorState && this.props.editorState !== properties.editorState) { this.setState({ currentFontSize: getSelectionCustomInlineStyle(properties.editorState, ['FONTSIZE']).FONTSIZE, }); } } componentWillUnmount(): void { const { modalHandler } = this.props; modalHandler.deregisterCallBack(this.expandCollapse); } onExpandEvent: Function = (): void => { this.signalExpanded = !this.state.expanded; }; expandCollapse: Function = (): void => { this.setState({ expanded: this.signalExpanded, }); this.signalExpanded = false; } doExpand: Function = (): void => { this.setState({ expanded: true, }); }; doCollapse: Function = (): void => { this.setState({ expanded: false, }); }; toggleFontSize: Function = (fontSize: number) => { const { editorState, onChange } = this.props; const newState = toggleCustomInlineStyle( editorState, 'fontSize', fontSize, ); if (newState) { onChange(newState); } }; render(): Object { const { config, translations } = this.props; const { expanded, currentFontSize } = this.state; const FontSizeComponent = config.component || LayoutComponent; const fontSize = currentFontSize && Number(currentFontSize.substring(9)); return ( <FontSizeComponent config={config} translations={translations} currentState={{ fontSize }} onChange={this.toggleFontSize} expanded={expanded} onExpandEvent={this.onExpandEvent} doExpand={this.doExpand} doCollapse={this.doCollapse} /> ); } }
import important from "../../plugins/important/index"; describe("Important plugin", () => { it("should add !important to every number and string", () => { const style = { color: "blue", fontSize: 15 }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important" }); }); it("should add !important to every value in an array", () => { const style = { color: "blue", fontSize: 15, display: ["-webkit-flex", "flex"] }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important", display: ["-webkit-flex!important", "flex!important"] }); }); it("should add !important to nested objects", () => { const style = { color: "blue", fontSize: 15, ":hover": {color: "red"} }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important", ":hover": {color: "red!important"} }); }); });
var fs = null; function showWarning(resolution, APISupport) { // set up text according to actual issue if(resolution && APISupport) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to have a resolution of at least 1280x768px</p>\ <p>You also have to use a browser supporting the HTML5 FileSystem & FileWriter API.</p>\ <p>In plain english: Google Chrome (at least version 13.0) </p>'); } else if(resolution) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to have a resolution of at least 1280x768px</p>'); } else if (APISupport) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to use a browser supporting the HTML5 FileSystem & FileWriter API.</p>\ <p>In plain english: Google Chrome (at least version 13.0) </p>'); } // display error message if there's an issue if(resolution || APISupport) { $('section#warning').show(); } } function setupEnvironment() { // check resolution if(screen.width<1280 || screen.height < 768) { showWarning(true, false); } // setup file system try { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder; window.requestFileSystem(window.TEMPORARY, 5*1024*1024 /*5MB*/, // callback if the new filesystem is correctly initiated function(newFS) { fs = newFS; setupPictureUpload(); // locate in settings.js because of asynchronous shit setupRestoreState(); }, // could not initiate the filesystem; no point in going further function(e) { showWarning(false, true); errorHandler(e);}); } catch(err) { showWarning(false, true); } window.onresize = function() { resizeCanvas(); resizeSettings(); refresh(); } } function resizeCanvas() { canvas.width = document.width; canvas.height = document.height; }
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamodel/variant"; import { DataType } from "lib/datamodel/variant"; import { VariantArrayType } from "lib/datamodel/variant"; import { StatusCodes } from "lib/datamodel/opcua_status_code"; import { BrowseDirection } from "lib/services/browse_service"; import UAVariable from "lib/address_space/UAVariable"; import UATwoStateVariable from './UATwoStateVariable'; import util from "util"; function _install_TwoStateVariable_machinery(node,options) { assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.minimumSamplingInterval === 0); assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType"); assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0)); assert(node.hasOwnProperty("id")); options = options || {}; // promote node into a UATwoStateVariable Object.setPrototypeOf(node, UATwoStateVariable.prototype); node.initialize(options); } function install(AddressSpace) { assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery)); AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery; /** * * @method addTwoStateVariable * * @param options * @param options.browseName {String} * @param [options.description {String}] * @param [options.modellingRule {String}] * @param [options.minimumSamplingInterval {Number} =0] * @param options.componentOf {Node|NodeId} * @param options.propertyOf {Node|NodeId} * @param options.trueState {String} * @param options.falseState {String} * @param [options.isTrueSubStateOf {NodeId}] * @param [options.isFalseSubStateOf {NodeId}] * @param [options.modellingRule] * @return {UATwoStateVariable} * * Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime */ AddressSpace.prototype.addTwoStateVariable = function (options) { assert(options.browseName," a browseName is required"); const addressSpace = this; const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType"); options.optionals = options.optionals || []; if (options.trueState) { options.optionals.push("TrueState"); } if (options.falseState) { options.optionals.push("FalseState"); } // we want event based change... options.minimumSamplingInterval = 0; const node = twoStateVariableType.instantiate({ browseName: options.browseName, nodeId: options.nodeId, description: options.description, organizedBy: options.organizedBy, componentOf: options.componentOf, modellingRule: options.modellingRule, minimumSamplingInterval: options.minimumSamplingInterval, optionals: options.optionals }); _install_TwoStateVariable_machinery(node,options); return node; }; } export default install;
/** * ParticlePack2 Shotgunflashyellow Effect. * @method Shotgunflashyellow * @param state {Kiwi.State} Current state * @param x {Number} X position * @param y {Number} Y position * @return Kiwi.Group * @public * @static */ Kiwi.Plugins.ParticlePack2.Shotgunflashyellow = function( state, x, y ) { this.config = { "numParts": 6, "posOffsetX": 0, "posOffsetY": 0, "posRadius": 5, "posRadialStart": 0, "posRadialEnd": 6.283185307179586, "posWidth": 200, "posHeight": 200, "posConstrainRect": true, "posAngle": 0, "posLength": 200, "posRandomLine": true, "posConstrainRadial": true, "posRandomRadial": true, "posShape": "point", "maxVel": 100, "minVel": 70, "velConstrainRect": true, "velConstrainRadial": false, "velRandomRadial": false, "velShape": "point", "velOffsetX": 400, "velOffsetY": 0, "velAngMin": 0, "velAngMax": 0, "velRadius": 144, "velRadialStart": 0, "velRadialEnd": 6.283185307179586, "velWidth": 200, "velHeight": 200, "velAngle": 0, "velLength": 20, "velRandomLine": true, "minStartTime": 0, "maxStartTime": 0, "minLifespan": 0.2, "maxLifespan": 0.4, "gravityX": 0, "gravityY": 0, "startSize": 1, "endSize": 200, "loop": false, "colEnvKeyframes": [ 0.2, 0.3 ], "alpha": 1, "colEnv0": [ 0.9921568627450981, 0.9764705882352941, 0.8313725490196079 ], "colEnv1": [ 0.9921568627450981, 0.9176470588235294, 0.5176470588235295 ], "colEnv2": [ 0.9921568627450981, 0.8588235294117647, 0.2196078431372549 ], "colEnv3": [ 0.996078431372549, 0.8235294117647058, 0.027450980392156862 ], "alphaGradient": [ 1, 1, 0, 0 ], "alphaStops": [ 0.3, 0.5 ], "additive": true, "cells": [ 4, 16, 17 ], "textureID": "_128x128" }; return new Kiwi.GameObjects.StatelessParticles( state, state.textures.particlePack2SpriteSheet, x, y, this.config ); };
$(document).ready(main); function parseDay() { var inputDay = parseInt($("#day").val()); if (inputDay > workout.days || inputDay < 1 || isNaN(inputDay)) { alert("Oops! I don't understand that. Please enter a day number between 1 and 28, inclusive."); $("#day").val(""); } else { showWorkout(inputDay); } } function parseExercise (text, day) { return text.replace(/{\d+, \d+}\w?/g, parseRange(day)); } var parseRange = (day) => (range) => { var totalDays = workout.days; var progress = (day - 1) / (totalDays - 1); let start = parseInt(range.match(/\d+/g)[0]); let end = parseInt(range.match(/\d+/g)[1]); let flags = range.match(/\w*$/g)[0]; if (flags === "i") { return (start + (end - start) * progress).toFixed(0); } else { return (start + (end - start) * progress).toPrecision(2); } }; function showWorkout (day) { $("#workout").empty(); $("#heading").empty(); $("#heading").append("<h1>" + workout.title + ": Day " + day + "</h1>"); for (let section of workout.workout) { $("#workout").append("<h3>" + section.name + "</h3><h4>" + section.fitnessType + "</h4><ol>"); var shuffledList = _.shuffle(section.exercises); for (var i = 0; i < section.count; i++) { $("#workout").append("<li>" + parseExercise(shuffledList[i], day) + "</li>"); } $("#workout").append("</ol>"); } } function main () { /*Add workout info to the main div*/ showWorkout(1); /*Make the input work*/ $("#day").bind("enterKey", parseDay); $("#day").keyup(function(e){ if (e.keyCode == 13) { $(this).trigger("enterKey"); } }); }
$(document).ready(function() { // Toggle Extra Informations for single Topic by Click + $('.toggle-sibling').click(function() { var infoBox = $(this).parent().next('.details-wrapper'); // console.log(infoBox); if (infoBox.hasClass('active')) { // if info box is open, close it and remove status-marker-class infoBox.slideUp('fast').removeClass('active'); } else { // if closed, open amd add status-marker-class infoBox.slideDown('fast').addClass('active'); }; return false; }); // Toggle Info Columns // ========================================================================= $('a.info-trigger').click(function() { // open box on click var objID = this.id; // Get ID of clicked element $('.active-section').removeClass('active-section'); $(this).addClass('active-section'); if (objID == 'info1-trigger') { // open info-box 1 openInfoBox('#col-1'); } else if (objID == 'info2-trigger') { // open info-box 2 openInfoBox('#col-2'); }; return false; }); // Close all open info-boxes and open the requested info-box function openInfoBox (id) { // close all <section> with class "active" $('section.active').slideUp('fast').removeClass('active'); // open the requested info-box and add class "active" $(id).slideDown('fast').addClass('active'); } // Detect Browser Language console.log(window.navigator.language); });
#!/usr/bin/env node var minimist = require('minimist'); var toureiro = require('../lib/toureiro'); var argv = minimist(process.argv.slice(2)); if (argv.h || argv.help) { console.log('Usage: toureiro [port]'); console.log('[port] Port for toureiro to listen to'); console.log('Options:'); console.log('--rh Redis host, default to 127.0.0.1'); console.log('--rp Redis port, default to 6379'); console.log('--rdb Redis database number, default to 0'); console.log('--pass Redis password, default to null'); process.exit(0); } var port = 3000; if (argv._.length > 0 && !isNaN(parseInt(argv._[0]))) { port = parseInt(argv._[0]); } var redisHost = '127.0.0.1'; if (argv.rh) { redisHost = argv.rh; } var redisPort = 6379; if (argv.rp && !isNaN(parseInt(argv.rp))) { redisPort = argv.rp; } var redisDB = 0; if (argv.rdb && !isNaN(parseInt(argv.rdb))) { redisDB = argv.rdb; } var redisPass = null; if (argv.pass) { redisPass = argv.pass; } var app = toureiro({ redis: { host: redisHost, port: redisPort, auth_pass: redisPass, db: redisDB } }); var server = app.listen(port, function () { console.log('Toureiro is now listening at port', port, '...'); });
var fs = require('fs'); var filename = 'data.txt'; fs.unlinkSync(filename); console.log('File Deleted Successfully');
'use strict';var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var dom_adapter_1 = require('angular2/src/core/dom/dom_adapter'); var di_1 = require('angular2/di'); var location_strategy_1 = require('./location_strategy'); var PathLocationStrategy = (function (_super) { __extends(PathLocationStrategy, _super); function PathLocationStrategy() { _super.call(this); this._location = dom_adapter_1.DOM.getLocation(); this._history = dom_adapter_1.DOM.getHistory(); this._baseHref = dom_adapter_1.DOM.getBaseHref(); } PathLocationStrategy.prototype.onPopState = function (fn) { dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false); }; PathLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; }; PathLocationStrategy.prototype.path = function () { return this._location.pathname; }; PathLocationStrategy.prototype.pushState = function (state, title, url) { this._history.pushState(state, title, url); }; PathLocationStrategy.prototype.forward = function () { this._history.forward(); }; PathLocationStrategy.prototype.back = function () { this._history.back(); }; PathLocationStrategy = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', []) ], PathLocationStrategy); return PathLocationStrategy; })(location_strategy_1.LocationStrategy); exports.PathLocationStrategy = PathLocationStrategy; //# sourceMappingURL=path_location_strategy.js.map
(function() { 'use strict'; const Class = require('ee-class') const EventEmitter = require('ee-event-emitter') const type = require('ee-types') const log = require('ee-log') const crypto = require('crypto') const QueryContext = require('related-query-context') const Query = require('./Query') const ModelCloner = require('./ModelCloner') const clone = require('./clone') const RelatedSet = require('./Set') const Lock = require('./Lock'); let ORM; const debugHanging = process.argv.includes('--related-hanging'); const debugDev = process.argv.includes('--related-dev-debug'); let hangingTimeout = 60000; process.argv.forEach((arg) => { const match = /--related-hanging-timeout=([0-9]+)/.exec(arg); if (match) hangingTimeout = parseInt(match[1], 10); }); module.exports = new Class({ inherits: EventEmitter , init: function(options) { //Class.define(this, '_defintion' , Class(options.definition)); Class.define(this, '_orm' , Class(options.orm)); Class.define(this, '_events' , Class(options.events)); Class.define(this, '_values' , Class({})); Class.define(this, '_changedValues' , Class([]).Writable()); Class.define(this, '_mappings' , Class({}).Writable()); Class.define(this, '_belongsTo' , Class({})); Class.define(this, '_references' , Class({})); Class.define(this, '_changedReferences' , Class([])); Class.define(this, '_mappingIds' , Class([])); Class.define(this, '_hasChanges' , Class(false).Writable()); Class.define(this, '_debugMode' , Class(false).Writable()); Class.define(this, '_relatingSets' , Class(options.relatingSets)); Class.define(this, '_getDatabase' , Class(options.getDatabase)); Class.define(this, '_fromDb' , Class(options.isFromDB || false).Writable()); Class.define(this, '_deleted' , Class(false).Writable()); Class.define(this, '_set' , Class(options.set)); // the set this record is contained Class.define(this, '_busy' , Class(false).Writable()); Class.define(this, '_pool' , Class(options.pool || null).Writable().Configurable()); Class.define(this, '_queue' , Class([])); Class.define(this, '_saveLock' , Class(null).Writable().Configurable()); // require the orm if not already set, cannot load at // the begin of the file because the orm includes this file if (!ORM) ORM = require('./ORM'); // we need to clone the json column store Class.define(this, '_jsonColumns', Class(Object.create(this._jsonColumns))); // check for changes //this.on('change', this._setChanged.bind(this)); if (options.parameters) this._setValues(options.parameters, !this._fromDb); } /** * clone the currrent model and all mappings * * @param <function> optional callback. when omitted a promise is returned * @param <boolean> optional. if true the models this model belongs to should point * to the cloned instance * @param <object> * * @returns <Promise> if the callback is omitted */ , clone: function() { // we can clone this model, all the mappings between // this and other models. we first need to load all mappings // else cloning will fail. if this return new ModelCloner(this); } /** * set multiple properties on the model * * @param <Obejct> content * * @returns <Object> model instance */ , setContent: function(content) { if (content && type.object(content)) this._setValues(content, true); return this; } /** * set dirty */ , _setChanged: function() { this._hasChanges = true; } /* * indicates if this record was deleted */ , isDeleted: function() { return !!this._deleted; } /* * inidcates if this model was changed since it was laoded from the database */ , hasChanges: function() { return !!this._changedValues.length || this._hasChanges; } /* * inidcates if this model was changed since it was laoded from the database */ , isDirty: function() { return !!this._changedValues.length || this._hasChanges; } /** * enable the bug mode * * @param <Boolean> optional mode */ , setDebugMode: function(status) { this._debugMode = type.undefined(status) ? true : !!status; return this; } /** * enable the bug mode * * @param <Boolean> optional mode */ , debug: function(status) { this._debugMode = type.undefined(status) ? true : !!status; return this; } /* * returns a complete filter object which lets * you laod exactly this model instance from the db */ , getPrimaryKeyFilter: function() { var filter = {}; this._defintion.primaryKeys.forEach(function(key) { filter[key] = this[key]; }.bind(this)); return filter; } /* * return the models definition object */ , getDefinition: function() { return this._defintion; } /* * return the models primary keys */ , getPrimaryKeys: function() { return this._defintion.primaryKeys; } /* * tell the outside that i'm a model */ , isModel: function() { return true; } /* * return the models name */ , getEntityName: function() { return this._defintion.name; } /* * returns the database name */ , getDatabaseName: function() { this._defintion.getDatabaseName(); } /** * sets the pool for all transactions executed on this model */ , setPool: function(pool) { this._pool = pool; } /* * set values */ , setValues: function(values) { this._setValues(values, true); return this; } /* * set and interprets values on this model * can work with scalar values, queries and model instances */ , _setValues: function(values, isExternalInput) { if (!type.undefined(values) && !type.object(values)) throw new Error('Expected an object contining values for a new model instance, got a «'+type(values)+'»!'); Object.keys(values).forEach(function(property) { var item = values[property] , isJSON = this._jsonColumns[property] || this._jsonColumns[property] === null; if (!isJSON && type.object(item) && this._addQueryObject(property, item)) return; else if (!isJSON && type.array(item)) { item.forEach(function(obj){ if (type.object(obj) && this._addQueryObject(property, obj)) return; else throw new Error('Expected a Query or a Model for the key «'+property+'»!'); }.bind(this)); } else if (property === '____id____') this._mappingIds.push(item); else { // check if we got a vritaul value which is not a normal part of the model // write it directly to the model object if (this._serialize && this._serialize.indexOf(property) !== -1) { // store as serializable value this[property] = item; } else if (!this._defintion.columns[property]) { if (!this._serialize) this._serialize = []; if (this._serialize.indexOf(property) === -1) this._serialize.push(property); this[property] = item; } else { if (isExternalInput) { // need to move it through the setter this[property] = this._prepareTypedInput(property, item); } else { // check if this json type input, if yes, hash it // and store it for later comparison if ((type.object(item) || type.array(item)) && this._jsonColumns[property] === null) { this._jsonColumns[property] = crypto.createHash('md5').update(JSON.stringify(item)).digest('hex') } // convert to date type before sending to the db this._values[property] = this._prepareTypedInput(property, item); } } } }.bind(this)); } /** * prepares the values based on the target type in the db * parses numbers in strings, sets null when required * * @param <Object> columnName * @param <Mixed> value */ , _prepareTypedInput: function(columnName, value) { var column = type.object(columnName) ? columnName : this._columns[columnName]; //if (!column) console.log(columnName, value); // don0t do anything if there isn't enough information on the column if (!column || !column.column) return value; //console.log(column.column, value); // check for valid types, like dates if (value !== undefined && column.column.jsTypeMapping === 'date' && !type.date(value)) { if (type.string(value)) { if (value.length) return new Date(value); else return null; } else if (type.number(value)) return new Date(value); else return value; } // boolean? else if (column.column.jsTypeMapping === 'boolean' && !type.boolean(value)) { if (type.undefined(value) || type.null(value) || (type.string(value) && value === '')) return null; else if (type.string(value) && value.toLowerCase().trim() === 'false') return false; else if (type.string(value) && value.toLowerCase().trim() === 'true') return true; else return !!value; } // handle tinyint as boolean // TODO: make a flag for this later (and don't do it on postgres by default) else if (column.column.nativeType === 'tinyint') { if (type.boolean(value)) return value; else if (type.string(value)) return value == '1' || value == 'true'; else if (type.number(value)) return value == 1; else return null; } // number else if (column.column.jsTypeMapping === 'number' && !type.number(value)) { if (type.string(value) && !isNaN(parseFloat(value))) return parseFloat(value); else if (type.boolean(value)) return value ? 1 : 0; else return null; } // json else if (column.column.jsTypeMapping === 'json' && type.string(value)) { try { value = JSON.parse(value); } catch (e) {}; } return value; } /* * add queries as values of this model */ , _addQueryObject: function(propertyName, item) { var name = propertyName; if (type.object(item) && item instanceof RelatedSet) { // got a set of items item.forEach(function(arrayItem) { this._addQueryObject(propertyName, arrayItem); }.bind(this)); return true; } else if (type.object(item) && ((item.isModel && item.isModel()) || item.isQuery)) { // we got a model // name = item.getEntityName(); // log.wtf(name, this._columns[name].type); if (this._columns[name] && (this._columns[name].type === 'mapping' || this._columns[name].type === 'belongsTo')) this[name].push(item); else if (this._columns[name] && this._columns[name].type === 'reference') this[name] = item; else if (this._genericAccessors[name]) throw new Error('Cannot add «'+name+'» model to «'+this.getEntityName()+'» model! please use the generic accessor!'); else throw new Error('Cannot create a relation between the «'+name+'» and «'+this.getEntityName()+'» models! there is no relation between the two models!'); return true; } return false; } /* * load all fields of this model, if not all were selcted before */ , loadAll: function(callback){ return this.reload(callback); } /* * indicates if this model was loaded from the database */ , isFromDatabase: function(){ return this._fromDb; } /* * tell the entity that isnt from the database */ , isNotFromDatabase: function(){ this._fromDb = false; } /* * indicated if this model was loaded from the database * and if there aren't any changes on it */ , isSaved: function() { this.isFromDatabase() && !this._hasChanges; } /* * reload the current model, so we have the data from the db * * @param <Object> transaction */ , reload: function(...args) { let callback, transaction; args.forEach((arg) => { if (type.function(arg)) callback = arg; else if (type.object(arg)) transaction = arg; }); const promise = Promise.resolve().then(() => { if (!this.isFromDatabase()) return Promise.reject(new Error('Cannot reload model «'+this.getEntityName()+'» without saving it first!')); else { const query = { select : ['*'] , from : this._defintion.getTableName() , database : this._defintion.getDatabaseName() , filter : {} , mode : 'select' }; this._defintion.primaryKeys.forEach((key) => { query.filter[key] = this[key]; }); const context = new QueryContext({ pool: this._pool || 'read' , query: query , debug: this._debugMode }); return (transaction && !transaction.hasEnded() ? transaction : this._getDatabase()).executeQuery(context).then((data) => { if (!data.length) { log(this, context, data); callback(new Error('Reload for model «'+this.getEntityName()+'» failed, record doesn\'t exist!')); } else { this._setValues(data[0]); this._changedValues = []; this._fromDb = true; return this._reloadRelated({transaction}); } }); } }); // if the user passed a callback, use it. // otherwise return the promise if (typeof callback !== 'function') return promise.then(() => Promise.resolve(this)); else promise.then(() => callback(null, this)).catch(callback); } , _reloadRelated: function({transaction}) { return Promise.all(Object.keys(this._mappings).map((keyName) => { return this._mappings[keyName].reload(transaction); })); /* Object.keys(this._belongsTo).forEach(function(keyName){ }.bind(this)); Object.keys(this._references).forEach(function(keyName){ }.bind(this));*/ } /* * returns all values that weer changed since the loading it from the db */ , _getChangedValues: function() { var data = {}; this.getChangedKeys().forEach(function(key){ data[key] = this[key]; }.bind(this)); return data; } /** * returns unique changed keys as array */ , getChangedKeys: function() { return [...new Set(this._changedValues)]; } /** * remove a key from the changed values so it will * not end up in queries */ , removeChangedValueKey: function(keyName) { let index; while(index = this._changedValues.indexOf(keyName) >= 0) { this._changedValues.splice(index, 1); } } /** * remove a value so it wont be stored in the db */ , removeValue: function(keyName) { this.removeChangedValueKey(keyName); if (this._values[keyName]) delete this._values[keyName]; } /** * async event handling. events basically middlewares * that also can halt the process * */ , _emitEvent: function(event, ...args) { // get the listeners placed by extensions on all model // instances and combine them with user placed listeners let listeners = this._extensionEventListeners[event] ? this._extensionEventListeners[event].concat(this.listener(event)) : this.listener(event); // entity events if (this._events && this._events.has(event)) { listeners = listeners.concat(this._events.get(event)); } if (listeners && listeners.length) { // add this model instance as first parameter args.unshift(this); // execute the async listeners one after another return listeners.reduce((promise, currentListener) => { return promise.then((stopExecution) => { // any of the listeners may signal that // the execution should be halted. pass this // to the caller of this class method if (stopExecution) return Promise.resolve(true); else { // we need to wrap the listener because // it may work using callbacks or promises return new Promise((resolve, reject) => { let ignoreCallback = false; // listeners may call the callback or return a promise const mayBePromise = currentListener(...args, (err, stopExecution) => { if (!ignoreCallback) { if (err) reject(err); else resolve(stopExecution); } }); if (type.promise(mayBePromise)) { // make sure the callback is ignored if the promise is used ignoreCallback = true; // pass to upper promise mayBePromise.then(resolve).catch(reject); } }); } }); }, Promise.resolve()); } else return Promise.resolve(); } /* * emits a specifc event when a transaction is commited successfull * * @param <Object> transaction * @param <string> event, event to emit when the transaction was commited */ , _emitOnCommit: function(transaction, event) { transaction.once('commit', function() { this.emit.apply(this, [event, this].concat(Array.prototype.slice.call(arguments, 2))); }.bind(this)); } , delete: function(...args) { let callback, transaction; args.forEach((arg) => { if (type.function(arg)) callback = arg; else if (type.object(arg)) transaction = arg; }); // invoke the saving process const promise = this._prepareDelete({transaction, args}); // there were queries that did not return // this is an attempt to capture those bastards if (debugHanging) { const t = setTimeout(() => { log.error('timeout encountered', 'delete', this.getEntityName(), this); }, 60000); promise.then(() => { clearTimeout(t); return Promise.resolve(); }).catch((err) => { clearTimeout(t); return Promise.reject(err); }); } // if the user passed a callback, use it. // otherwise return the promise if (typeof callback !== 'function') return promise.then(() => Promise.resolve(this)); else promise.then(() => callback(null, this)).catch(callback); } , _prepareDelete: function({transaction, args}) { // there may be problems with locks // and other unexpected behaviors when // executing operations in parallel on the // same record. this makes sure that all // operations on this model instance are // executed one after another return this._enqueue().then((executeNext) => { // check if we got a transaction from the outside // or if the database object we're working on is // a transaction. if (transaction || this._getDatabase().isTransaction()) { if (!transaction) transaction = this._getDatabase().getTransaction(); // make sure the next callback is invoked! return this._delete({transaction}).then(() => { executeNext(); return Promise.resolve(); }).catch((err) => { executeNext(); return Promise.reject(err); }); } else { // we're creating a new transaction for all // operations on this model and all dependencies // that we're going to operate on. ( we pass this // transaction to all other models we're going to save) transaction = this._getDatabase().createTransaction(this._pool || 'write'); // make sure the next callback is invoked! return this._delete({transaction}).then(() => { // auto commit the transaction since we're // the guys that created it! return transaction.commit().then(() => { // set status flags this._deleted = true; this._fromDb = false; this.emit('delete', this); // execute other jobs in the queue executeNext(); return Promise.resolve(); }); }).catch((err) => { // ends the transaction and frees the connection return transaction.rollback().then(() => { // nice, that worked. failing anyway... return Promise.reject(); }).catch(() => { // execute other jobs in the queue executeNext(); // fail using the original error return Promise.reject(err); }); }); } }); } /* * private delete method * * @param <String> the venet to emit */ , _delete: function({transaction}) { try { const query = { from : this._defintion.getTableName() , database : this._defintion.getDatabaseName() , filter : {} , mode : 'delete' }; // cannot delete a model not loaded from the database if (this._fromDb){ if (!query.select) query.select = []; query.limit = 1; this._defintion.primaryKeys.forEach((key) => { query.filter[key] = this[key]; query.select.push(key); }); if (!Object.keys(query.filter).length) { const err = new Error(`Failed to create proper delete query for model '${this.getEntityName()}', no filter was created!`); log(err, this, query); return Promise.reject(err); } else { this._emitOnCommit(transaction, 'afterDeleteCommit'); // lifecycle event for extensions and model implementers return this._emitEvent('beforeDelete', transaction).then((skipDelete) => { if (skipDelete) return this._emitEvent('afterDelete', transaction); else { const context = new QueryContext({ query: query , debug: this._debugMode , pool: this._pool || 'write' }); return transaction.executeQuery(context).then(() => { // lifecycle event for extensions and model implementers return this._emitEvent('afterDelete', transaction); }); } }); } } else return Promise.reject(new Error(`Cannot delete model '${this.getEntityName()}', it wasn't loaded from the database!`)); } catch (err) { return Promise.reject(err); } } /** * upde or insert data. update is executed if all primaries are set, * else an insert is triggered, argumetns a re the same as for save */ , updateOrInsert: function() { var args = new Array(arguments.length) , i, l for (i = 0, l = arguments.length; i < l; i++) args.push(arguments[i]); // if the primaries are set we should try an update, // if that fails we're going to do an insert if (this.getPrimaryKeys().every(function(key) { return !type.undefined(this[key]) && !type.null(this[key]); }.bind(this))) { // update this._fromDb = true; } // invoke save return this.save.appy(this, args); } /** * upde or insert data. update is executed if all primaries are set, * else an insert is triggered, argumetns a re the same as for save * same as updateOrInsert */ , insertOrUpdate: function() { var args = new Array(arguments.length) , i, l for (i = 0, l = arguments.length; i < l; i++) args.push(arguments[i]); // if the primaries are set we should try an update, // if that fails we're going to do an insert if (this.getPrimaryKeys().every(function(key) { return !type.undefined(this[key]) && !type.null(this[key]); }.bind(this))) { // update this._fromDb = true; } // invoke save return this.save.appy(this, args); } /** * checks if a json column has changed, if yes markes the column as dirty */ , _checkJsonColumns: function() { this._jsonColumnsArray.forEach(function(columnName) { if (type.object(this._values[columnName]) || type.array(this._values[columnName])) { if (type.string(this._jsonColumns[columnName])) { // ok, we had a previous value, compute the hash and compare if (crypto.createHash('md5').update(JSON.stringify(this._values[columnName])).digest('hex') !== this._jsonColumns[columnName]) { this._changedValues.push(columnName); this._setChanged(); } } else { // we had no previous value, but we have on now, this has changed this._changedValues.push(columnName); this._setChanged(); } } else if (type.string(this._jsonColumns[columnName])) { // we got a previous value, but no current value this._changedValues.push(columnName); this._setChanged(); } // make strings. the pg driver sucks, it cannot handle json objects if (this._values[columnName] !== null && this._values[columnName] !== undefined) this._values[columnName] = JSON.stringify(this._values[columnName]); }.bind(this)); } /** * public save method, saves all references, this model, all mappings * inverse references (belongs to). will create a transaction when none * is passed to it * * @param <Function> callback -> called after saving finished, optional * @param <Boolean> dontReload -> when the model should not be reloaded after saving it, options, default false * @param <Object> transaction -> the transaction to execute the queries on, optional */ , save: function(...args) { let dontReload = false; let callback, transaction, stack, lock; args.forEach((arg) => { if (arg instanceof Lock) lock = arg; else if (type.function(arg)) callback = arg; else if (type.boolean(arg)) dontReload = arg; else if (type.object(arg)) transaction = arg; else if (type.array(arg)) stack = arg; }); // it's important not to save any model initiated by a users save call // more than once. else we'll may be stuck inside an endless loop when // handling circular data structures :/ // if we're getting a lock from the outside we us it as reference, // else we're going to create our own lock that we can pass to all other // save calls. // resolve, because saving this model is already handled elsewhere! if (this._saveLock) { if (!type.function(callback)) return Promise.resolve(this); else callback(null, this); } else { let localLock; // create a lock if we didn't get one if (!lock) localLock = lock = new Lock(); // lock now! this._saveLock = lock; // make sure to free the lock when the save call is returned lock.once('end', () => { this._saveLock = null; }); if ((debugDev || debugHanging) && !stack) stack = []; // invoke the saving process const promise = this._prepareSave({dontReload, transaction, args, stack, lock}); // there were queries that did not return // this is an attempt to capture those bastards if (debugHanging) { const t = setTimeout(() => { log.error('timeout encountered', 'insert/update', this.getEntityName(), this, stack); }, hangingTimeout); promise.then(() => { clearTimeout(t); return Promise.resolve(this); }).catch((err) => { clearTimeout(t); return Promise.reject(err); }); } // if the user passed a callback, use it. // otherwise return the promise if (typeof callback === 'function') { promise.then(() => { if (localLock) localLock.free(); callback(null, this); }).catch((err) => { if (localLock) localLock.free(); callback(err); }); } else { return promise.then(() => { if (localLock) localLock.free(); return Promise.resolve(this); }).catch((err) => { if (localLock) localLock.free(); return Promise.reject(err); }); } } } /** * can be used to queue async operations * so that they are executed one after another. * this is mainly used because we never should * manipulate the same row in parallel! */ , _enqueue: function(args) { const createCallback = () => { // make sure each callback is invoked exactly one time let invoked = false; return () => { // wait a tick, so that all other stuff // can settle before we continue process.nextTick(() => { if (!invoked && this._queue.length) { invoked = true; // execute the next item in the queue, // pass another instance of the callback // which has its own status this._queue.shift()(createCallback()); } }); }; }; if (!this._queue.length) return Promise.resolve(createCallback()); else { return new Promise((resolve) => { this._queue.push(resolve); }); } } /** * prepare the save operation, creates a transaction if there * isn't already one around and makes sure that all operations * on this model are executed one after another. */ , _prepareSave: function({dontReload, transaction, args, stack, lock}) { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: before queue'}); // there may be problems with locks // and other unexpected behaviors when // executing operations in parallel on the // same record. this makes sure that all // operations on this model instance are // executed one after another return this._enqueue().then((executeNext) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after queue'}); // check if we got a transaction from the outside // or if the database object we're working on is // a transaction. if (transaction || this._getDatabase().isTransaction()) { if (!transaction) transaction = this._getDatabase().getTransaction(); if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: using existing transaction'}); if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: before _save'}); // make sure the next callback is invoked! return this._save({transaction, dontReload, stack, lock}).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after _save -> then'}); executeNext(); return Promise.resolve(); }).catch((err) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after _save -> catch'}); executeNext(); return Promise.reject(err); }); } else { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: creating new transaction'}); // we're creating a new transaction for all // operations on this model and all dependencies // that we're going to operate on. ( we pass this // transaction to all other models we're going to save) transaction = this._getDatabase().createTransaction(this._pool || 'write'); if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: before _save'}); // lock on the transaction, make sure we're // not saving twice on it in order to prevent endless // loops when processing circular data structures this._transactionLock = transaction; // free on transaction end transaction.on('end', () => { this._transactionLock = null; }); // make sure the next callback is invoked! return this._save({transaction, dontReload, stack, lock}).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after _save -> then'}); // auto commit the transaction since we're // the guys that created it! return transaction.commit().then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after transaction.commit -> then'}); // there should not be any changed data anymore this._changedValues = []; if (!dontReload) { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: before reload'}); // reload our data from the db to // get the current clean state return new Promise((resolve, reject) => { this.reload((err) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after reload'}); if (err) reject(err); else resolve(); }); }); } else return Promise.resolve(); }).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after reload'}); // execute other jobs in the queue executeNext(); // we're done return Promise.resolve(); }); }).catch((err) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_prepareSave: after _save -> catch'}); // ends the transaction and frees the connection return transaction.rollback().then(() => { // nice, that worked. failing anyway... return Promise.reject(); }).catch(() => { // execute other jobs in the queue executeNext(); // fail using the original error return Promise.reject(err); }); }); } }); } /* * effective save method, saves all references, this model, all mappings * inverse references (belongs to) * * @param <Object> transaction -> the transaction to execute the queries on * @param <Boolean> dontReload -> when the model should not be reloaded after saving it * @param <Function> callback -> called after saving finished */ , _save: function({transaction, dontReload, stack, lock}) { // properly catch errors try { // make sure the model has a primary key // we cannot reload models which have no primary // key if (!this._defintion.primaryKeys.length) return Promise.reject(new Error(`Cannot save the model '${this.getEntityName()}', no primary key found!`)); // we need to save the state, it has to be re-set after // a rollback let hasChanges = this._hasChanges , isFromDB = this.isFromDatabase(); // we need to change the status if the transaction succeeds transaction.once('commit', () => { this._fromDb = true; this._hasChanges = false; }); // need to reset the source status transaction.once('rollback', () => { // reset to original status this._fromDb = isFromDB; this._hasChanges = hasChanges; }); // its time to check for changes on json type column this._checkJsonColumns(); // make sure to emit this event when the transaction was successful this._emitOnCommit(transaction, 'afterSaveCommit'); if (stack) stack.push({entity: this.getEntityName(), frame: '_save: before _emitEvent: beforeSave'}); // lifecycle event for extensions and model implementers return this._emitEvent('beforeSave', transaction).then((skipSave) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: after _emitEvent: beforeSave', skipSave: !!skipSave}); if (skipSave) return this._emitEvent('afterSave', transaction); else { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: before _saveReferences'}); // first save all references, we need their ids // on our record return this._saveReferences({transaction, dontReload, stack, lock}).then((stopProcess) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: after _saveReferences', stopProcess: !!stopProcess}); if (stopProcess) return Promise.resolve(); else { // decide if we're updating or inserting return (this.isFromDatabase() ? this._update.bind(this) : this._insert.bind(this))({transaction}).then((stopProcess) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: after _update/_insert', stopProcess: !!stopProcess}); if (stopProcess) return Promise.resolve(); else { // save records depending on this one return this._saveDependents({transaction, dontReload, stack, lock}).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: after _saveDependents'}); // lifecycle event for extensions and model implementers return this._emitEvent('afterSave', transaction); }); } }); } }); } }); } catch (err) { if (stack) stack.push({entity: this.getEntityName(), frame: '_save: catch', err: err}); return Promise.reject(err); }; } /** * insert a new record */ , _insert: function({transaction}) { try { const query = { from : this._defintion.getTableName() , database : this._defintion.getDatabaseName() , filter : {} , mode : 'insert' }; // tell the db which keys to return if (this._defintion.primaryKeys.length) query.returning = this._defintion.primaryKeys; // going to emit events on commit this._emitOnCommit(transaction, 'afterInsertCommit', this); // lifecycle event for extensions and model implementers return this._emitEvent('beforeInsert', transaction).then((skipInsert) => { if (skipInsert) return this._emitEvent('afterInsert', transaction); else { // set the query values query.values = this._values; // get a query context that can be sent to // the driver implementation let context = new QueryContext({ query: query , debug: this._debugMode , pool: this._pool || 'write' }); // send the context to the related driver which // prepares it for the actual third party driver return transaction.executeQuery(context).then((result) => { //log(context, result) // the db returned a valid dataset if (result !== undefined) { // mark as from db, this will be reset on rollback this._fromDb = true; // custom data handling for mysql :/ if (!type.object(result)) { // mysql doesn't support compound primaries, check fro that if (result !== null && this._defintion.primaryKeys.length === 1) { this[this._defintion.primaryKeys[0]] = result; } else { // maybe the user did set the primary by himself, this would let us work // on the model if (this._defintion.primaryKeys.some((key) => { return type.undefined(this[key]); })) { return Promise.reject(new Error(`Cannot load data for the model '${this.getEntityName()}' since mysql doesn't support compound primary keys. You need to set the primary key values on the model manually or you have to use a single autoincermenting value as primary instead.`)); } } } else if (type.object(result)) { // assign the values Object.keys(result).forEach(function(key) { this[key] = result[key]; }.bind(this)); } else { const err = new Error(`Insert for the model '${this.getEntityName()}' did not return the requested data! Please file an issue at https://github.com/eventEmitter/related`); log(err, this, context); return Promise.reject(err); } // lifecycle event for extensions and model implementers return this._emitEvent('afterInsert', transaction); } else { const err = new Error(`Unexpected return value while executing an insert query for the model '${this.getEntityName()}'. Please file an issue at https://github.com/eventEmitter/related`); log(err, this, context); return Promise.reject(err); } }); } }); } catch (err) { return Promise.reject(err); } } /** * execute an update on this model */ , _update: function({transaction}) { try { // create the primary key filtler const filter = {}; this._defintion.primaryKeys.forEach((key) => { filter[key] = this[key]; }); // we're going to use the querybuilder to create the update query, // this is mostly used by the extensions so they can set advanced // filters for the update let query = transaction[this.getEntityName()](this._defintion.primaryKeys, filter).limit(1); // set the pool if required if (this._pool) query.pool(this._pool); // going to emit events on commit this._emitOnCommit(transaction, 'afterUpdateCommit', this); // lifecycle event for extensions and model implementers return this._emitEvent('beforeUpdate', transaction, query).then((skipUpdate) => { if (skipUpdate) return this._emitEvent('afterUpdate', transaction); else { // check for changes, skip db update if there aren't any if (!this.hasChanges()) return this._emitEvent('afterUpdate', transaction); else { return new Promise((resolve, reject) => { query.update(this._getChangedValues(), transaction, (err) => { if (err) reject(err); else return this._emitEvent('afterUpdate', transaction).then(resolve).catch(reject); }); }); } } }); } catch (err) { return Promise.reject(err); } } /* * save all dependent records: mappings and items referencing * this model (belongsTo) * * @param <Object> transaction -> execute the wueries on this * @param <Object> dontReload -> indicate wheter to reload the models */ , _saveDependents: function({transaction, dontReload, stack, lock}) { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveDependents: before _emitEvent: beforeSaveDependents'}); // lifecycle event for extensions and model implementers return this._emitEvent('beforeSaveDependents', transaction).then((skipSave) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveDependents: after _emitEvent: beforeSaveDependents', skipSave: skipSave}); if (skipSave) return this._emitEvent('afterSaveDependents', transaction); else { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveDependents: before _saveMappings/_saveBelongsTo'}); // save mappings && belongTos return Promise.all([ this._saveMappings({transaction, dontReload, stack, lock}), this._saveBelongsTo({transaction, dontReload, stack, lock}) ]).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveDependents: after _saveMappings/_saveBelongsTo'}); return this._emitEvent('afterSaveDependents', transaction); }); } }); } /* * save all items referencing this model (belongsTo) * * @param <Object> transaction -> execute the wueries on this * @param <Object> dontReload -> indicate wheter to reload the models */ , _saveBelongsTo: function({transaction, dontReload, stack, lock}) { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveBelongsTo: before _emitEvent: beforeSaveBelongsTo'}); // lifecycle event for extensions and model implementers return this._emitEvent('beforeSaveBelongsTo', transaction).then((skipSave) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveBelongsTo: after _emitEvent: beforeSaveBelongsTo', skipSave: skipSave}); if (skipSave) return this._emitEvent('afterSaveBelongsTo', transaction); else { return Promise.all(Object.keys(this._belongsTo).map((belongsToName) => { this._belongsTo[belongsToName].setDebugMode(this._debugMode); this._belongsTo[belongsToName].setPool(this._pool); if (stack) stack.push({entity: this.getEntityName(), frame: '_saveBelongsTo: before relatingSet.save()', belongsToName: belongsToName}); return this._belongsTo[belongsToName].save(transaction, dontReload, stack, lock); })).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveBelongsTo: after relatingSet.save()'}); return this._emitEvent('afterSaveBelongsTo', transaction); }); } }); } /* * save all mappings * * @param <Object> transaction -> execute the wueries on this * @param <Object> dontReload -> indicate wheter to reload the models */ , _saveMappings: function({transaction, dontReload, stack, lock}) { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveMappings: before _emitEvent: beforeSaveMappings'}); // lifecycle event for extensions and model implementers return this._emitEvent('beforeSaveMappings', transaction).then((skipSave) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveMappings: after _emitEvent: beforeSaveMappings', skipSave: skipSave}); if (skipSave) return this._emitEvent('afterSaveMappings', transaction); else { return Promise.all(Object.keys(this._mappings).map((mappingName) => { this._mappings[mappingName].setDebugMode(this._debugMode); this._mappings[mappingName].setPool(this._pool); if (stack) stack.push({entity: this.getEntityName(), frame: '_saveMappings: before relatingSet.save()', mappingName: mappingName}); return this._mappings[mappingName].save(transaction, dontReload, stack, lock); })).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveMappings: after relatingSet.save()'}); return this._emitEvent('afterSaveMappings', transaction); }); } }); } /* * save all references * * @param <Object> transaction -> execute the wueries on this * @param <Object> dontReload -> indicate wheter to reload the models */ , _saveReferences: function({transaction, dontReload, stack, lock}) { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: before beforeSaveReferences'}); // lifecycle event for extensions and model implementers return this._emitEvent('beforeSaveReferences', transaction).then((skipSave) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: after beforeSaveReferences', skipSave: skipSave}); if (skipSave) return this._emitEvent('afterSaveReferences', transaction); else { return Promise.all(this._changedReferences.map((key) => { const value = this._references[key]; const column = this._columns[key].column; // a query was set as reference if (value === null || value === undefined) { this[column.name] = null; return Promise.resolve(); } else if (value.isQuery) { value.limit(1); value.setDebugMode(this._debugMode); value.pool(this._pool); if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: before value.findOne', reference: key}); return value.findOne(transaction).then((model) => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: after value.findOne', reference: key}); if (!model) { this[column.name] = null; this[column.aliasName || column.referencedModel.name] = null; } else { this[column.name] = model[column.referencedColumn]; this[column.aliasName || column.referencedModel.name] = model; } return Promise.resolve(); }); } else { if (value.isSaved()) { this[column.name] = value[column.referencedColumn]; return Promise.resolve(); } else { value.setDebugMode(this._debugMode); value.setPool(this._pool); if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: before value._save', reference: key}); return value.save(transaction, dontReload, stack, lock).then(() => { if (stack) stack.push({entity: this.getEntityName(), frame: '_saveReferences: after value._save', reference: key}); this[column.name] = value[column.referencedColumn]; return Promise.resolve(); }); } } })).then(() => { return this._emitEvent('afterSaveReferences', transaction); }); } }); } , dir: function(returnResult) { var obj = {}; Object.keys(this._columns).forEach(function(keyName) { var column = this._columns[keyName]; switch (column.type) { case 'mapping': if (this._mappings[keyName]) obj[keyName] = this[keyName].dir(true); break; case 'belongsTo': if (this._belongsTo[keyName]) obj[keyName] = this[keyName].dir(true); break; case 'reference': if (this._references[keyName]) obj[keyName] = (typeof this[keyName] === 'object' && typeof this[keyName].dir === 'function' ? this[keyName].dir(true) : this[keyName]); break; case 'scalar': if (!type.undefined(this[keyName])) obj[keyName] = this[keyName]; break; default: throw new Exception('Column type «'+column.type+'» is not supported!'); } }.bind(this)); if (returnResult) return obj; else log(obj); } , toJSON: function() { var obj = {}; Object.keys(this._columns).forEach(function(keyName) { var column = this._columns[keyName]; switch (column.type) { case 'mapping': if (this._mappings[keyName]) obj[keyName] = this[keyName].toJSON(); break; case 'belongsTo': if (this._belongsTo[keyName]) obj[keyName] = this[keyName].toJSON(); break; case 'reference': if (this._references[keyName] && this[keyName].toJSON) { obj[keyName] = this[keyName].toJSON(); } // hidden ref if (!type.undefined(this._values[column.column.name])) Object.defineProperty(obj, column.column.name, {value: this._values[column.column.name], enumerable: true}); break; case 'scalar': if (!type.undefined(this[keyName])) obj[keyName] = this[keyName]; break; default: throw new Error('Column type «'+column.type+'» is not supported!'); } }.bind(this)); // add data exposed by extensions if (this._serialize) { this._serialize.forEach(function(propertyName) { if (undefined !== this[propertyName]) { obj[propertyName] = this[propertyName]; } }.bind(this)); } return obj; } }); })();
import fetch, { Response } from 'node-fetch'; export default { load() {}, fetch, Response, set Promise(implementation) { if (fetch.Promise === global.Promise) { fetch.Promise = implementation; } } };
Package.describe({ name: 'ndemoreau:azimulti-views-bootstrap', summary: 'Azimuth Multilanguage CMS frontend templates (using Bootstrap 3.x)', version: '0.4.3', git: 'https://github.com/ndemoreau/azimulti-views-bootstrap' }); Package.on_use(function (api) { api.use(['less@1.0.11', 'templating@1.0.9', 'mizzao:bootstrap-3@3.3.0'], 'client'); api.use('ndemoreau:azimulti-core@0.4.3', {unordered: true}); api.add_files('css/style.less', 'client'); api.add_files('blocks/block/block.html', 'client'); api.add_files('blocks/block_with_title/block_with_title.html', 'client'); api.add_files('blocks/block_multi/block_multi.html', 'client'); api.add_files('blocks/block_multi_with_title/block_multi_with_title.html', 'client'); api.add_files('pages/home_page/home_page.html', 'client'); api.add_files('pages/page_default/page_default.html', 'client'); api.add_files('pages/sidebar_left/sidebar_left.html', 'client'); api.add_files('pages/sidebar_left_fixed/sidebar_left_fixed.html', 'client'); api.add_files('pages/sidebar_right/sidebar_right.html', 'client'); api.add_files('views/404.html', 'client'); api.add_files('views/block_display.html', 'client'); api.add_files('views/footer.html', 'client'); api.add_files('views/header.html', 'client'); api.add_files('views/layout.html', 'client'); api.add_files('views/not_authorized.html', 'client'); api.add_files('views/accounts/account_buttons.html', 'client'); api.add_files('views/accounts/error.html', 'client'); api.add_files('views/accounts/forgot_password.html', 'client'); api.add_files('views/accounts/login.html', 'client'); api.add_files('views/accounts/sign_up.html', 'client'); api.add_files('views/accounts/social.html', 'client'); api.add_files('lib/utils.js', 'client'); });
const Nutz = artifacts.require('./satelites/Nutz.sol'); const Storage = artifacts.require('./satelites/Storage.sol'); const PullPayment = artifacts.require('./satelites/PullPayment.sol'); const Market = artifacts.require('./controller/MarketEnabled.sol'); const BigNumber = require('bignumber.js'); const assertJump = require('./helpers/assertJump'); const INFINITY = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; const NTZ_DECIMALS = new BigNumber(10).pow(12); const babz = (ntz) => new BigNumber(NTZ_DECIMALS).mul(ntz); const ntz = (babz) => new BigNumber(babz).div(NTZ_DECIMALS); const ONE_ETH = web3.toWei(1, 'ether'); const eth = (wei) => web3.fromWei(wei, 'ether'); contract('MarketEnabled', (accounts) => { let market; let nutz; let storage; let pull; beforeEach(async () => { nutz = await Nutz.new(); storage = await Storage.new(); pull = await PullPayment.new(); market = await Market.new(pull.address, storage.address, nutz.address); nutz.transferOwnership(market.address); storage.transferOwnership(market.address); pull.transferOwnership(market.address); await market.unpause(); }); async function setSellPrice(newPrice) { await market.moveFloor(newPrice); await market.moveCeiling(newPrice); }; it('#floor should return infinity if no ETH in reserve', async() => { assert.equal((await market.floor()).toNumber(), INFINITY); }); it('#moveCeiling cannot set purchase price larger then sell price', async() => { await market.moveFloor(10); try { await market.moveCeiling(20); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); it('#moveFloor cannot set sell price smaller then purchase price', async() => { await market.moveFloor(10); await market.moveCeiling(9); try { await market.moveFloor(8); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); describe('#purchase', () => { describe(`regular scenario. Purchase NTZ for 30000 NTZ/ETH with 1 ETH`, () => { const sellPrice = 30000; const expectedNumberOfNtz = 30000; beforeEach(async () => { await setSellPrice(sellPrice); }); it('should change active supply', async() => { // purchase some tokens with 1 ether await nutz.purchase(sellPrice, { from: accounts[0], value: ONE_ETH }); const supplyBabz = await nutz.activeSupply.call(); assert.equal(supplyBabz.toNumber(), babz(expectedNumberOfNtz).toNumber(), 'active supply should include newly minted NTZ'); }); it('should not change purchase price', async() => { // purchase some tokens with 1 ether await nutz.purchase(sellPrice, { from: accounts[0], value: ONE_ETH }); // we should be able to buy back issued NTZ by the same price const purchasePrice = await market.floor(); assert.equal(purchasePrice.toNumber(), sellPrice, 'Purchase price should remain unchanged'); }); it('should sent ETH to the contract', async() => { // purchase some tokens with 1 ether await nutz.purchase(sellPrice, { from: accounts[0], value: ONE_ETH }); const reserveWei = web3.eth.getBalance(nutz.address); assert.equal(reserveWei.toNumber(), ONE_ETH, '1 ETH should be sent to contract'); }); it('should add NTZ to the balance', async() => { // purchase tokens with 1 ether await nutz.purchase(sellPrice, { from: accounts[0], value: ONE_ETH }); const balanceBabz = await nutz.balanceOf.call(accounts[0]); assert.equal(balanceBabz.toNumber(), babz(expectedNumberOfNtz).toNumber(), 'Purchased NTZ amount'); }); }); const validScenarios = [ { price: 30000, wei: ONE_ETH, expectedNtz: 30000 }, { price: 5000, wei: ONE_ETH / 2000, expectedNtz: 2.5 }, { price: 1, wei: ONE_ETH / 10 ** 12, expectedNtz: 1 / 10 ** 12 } ]; for (var i = 0; i < validScenarios.length; i++) { let scenarioSpec = validScenarios[i]; it(`should buy ${scenarioSpec.expectedNtz} NTZ for ${eth(scenarioSpec.wei)} ETH at the price ${scenarioSpec.price} NTZ/ETH`, async () => { await setSellPrice(scenarioSpec.price); await nutz.purchase(scenarioSpec.price, { from: accounts[0], value: scenarioSpec.wei }); const balanceBabz = await nutz.balanceOf.call(accounts[0]); assert.equal(ntz(balanceBabz).toNumber(), scenarioSpec.expectedNtz, 'Purchased NTZ amount'); }); } it(`should not allow to buy less then 1 babz`, async () => { // set price to 1 NTZ/ETH, so 1 babz cost 1/10^12 await setSellPrice(1); const babzCostWei = ONE_ETH / 10 ** 12; try { // try to buy tokens with amount of ether one wei short from enough to buy just 1 babz await nutz.purchase(1, { from: accounts[0], value: babzCostWei - 1 }); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); it('should fail if requested price differs from effective purchase price', async() => { await setSellPrice(100); try { await nutz.purchase(99, { from: accounts[0], value: ONE_ETH }); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); }); describe('#sell', () => { it(`should not allow to sell if the price is unreasonably high`, async () => { const bigPrice = new BigNumber(10).pow(50); await market.moveFloor(bigPrice); await market.moveCeiling(3000); await nutz.purchase(3000, { from: accounts[0], value: ONE_ETH }); try { await nutz.sell(bigPrice, 3000, { from: accounts[0] }); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); it('should fail if requested price differs from effective sell price', async() => { const sellPrice = 50; await setSellPrice(sellPrice); await nutz.purchase(50, { from: accounts[0], value: ONE_ETH }); try { await nutz.sell(sellPrice + 1, 50, { from: accounts[0] }); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); }); });
/* * @flow */ import React, { Component } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; // Blocks import Search from '../Search'; import './Chat.css'; class Chat extends Component { constructor(props) { super(props) this.state = { } this.onCreateComment = this.onCreateComment.bind(this); } componentDidMount() { // init scroll and scroll to bottom this._scrolltoBottom(); } _scrolltoBottom() { const { scrollbars } = this.refs; scrollbars.scrollToBottom(); } onCreateComment(value, file, imageBase64) { this.props.onSend(value, file, imageBase64); } render() { return ( <div className="chat"> <div className="chat__list"> <Scrollbars ref="scrollbars" > </Scrollbars> </div> <div className="chat__input"> <Search showTextarea placeholder="Trao đổi công việc" callback={this.onCreateComment} /> </div> </div> ); } } export default Chat;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-1-5 description: Array.prototype.some applied to number primitive includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return obj instanceof Number; } try { Number.prototype[1] = true; Number.prototype.length = 2; return Array.prototype.some.call(5, callbackfn); } finally { delete Number.prototype[1]; delete Number.prototype.length; } } runTestCase(testcase);
module.exports = (opt, columns, moduleCallback) => { const mysql = require('mysql') const readline = require('readline') const mySqlCreds = require(opt.cfg.dirs.creds + opt.destination) let db = mysql.createConnection(mySqlCreds) const async = require('async') let table = opt.source + '.' + opt.table.replace(/\./g, '_') let opfile = opt.opfile let log = opt.log let sqlTable = () => { let cols = [] let ndxs = [] columns.forEach((c) => { cols.push(' ' + c.name + ' ' + c.type + ' NULL') if (c.index) ndxs.push(' INDEX `' + c.name + '` (`' + c.name + '`) ') }) let sql = 'CREATE TABLE ' + table + ' ( ' + cols.join(', ') if (ndxs.length) sql += ', ' + ndxs.join(',') sql += ' )' return sql } async.waterfall([ //create database if not existing (cb) => { db.query('CREATE DATABASE IF NOT EXISTS ' + opt.source, (err) => { if (err) return cb(err) cb(null) }) }, //drop existing table (cb) => { if (opt.update || opt.truncate) return cb(null) db.query('DROP TABLE IF EXISTS ' + table, (err) => { if (err) return cb(err) cb(null) }) }, //create new table (cb) => { if (opt.update || opt.truncate) return cb(null) //don't drop table if update option let sql = sqlTable() db.query(sql, (err) => { if (err) return cb(err) cb(null) }) }, //truncate table if specified (cb) => { if (!opt.truncate) return cb(null) db.query('TRUNCATE TABLE ' + table, (e) => { //if error but it isn't table doesn't exist, throw error at cb if (e instanceof Error && e.toString().indexOf('doesn\'t exist') === -1) return cb('TRUNCATE TABLE error: ' + e) //if error but it's that the table doesn't exist, let's create it if (e instanceof Error && e.toString().indexOf('doesn\'t exist') !== -1) { db.query(sqlTable(), (e) => { if (e) return cb(e) cb(null) }) } else { //otherwise, truncated smoothly cb(null) } }) }, //sql_mode to blank (cb) => { db.query('SET sql_mode = \'\'', (err) => { if (err) return cb('SET sql_mode error: ' + err) cb(null) }) }, //load data into table (cb) => { let sql = 'INSERT INTO ' + table + ' ' let cs = [] let first = true columns.forEach((c) => { cs.push(c.name) }) sql += ' ( ' + cs.join(', ') + ' ) VALUES ' let lineReader = readline.createInterface({ input: opfile.readStream }) lineReader.on('error', (err) => { return cb(err) }) let insertLines = [] lineReader.on('line', (line) => { if (first) { first = false } else { insertLines.push(' ( "' + line.split('\t').join('", "') + '")') } }) lineReader.on('close', () => { sql += insertLines.join(',') cb(null, sql) }) }, (sql, cb) => { db.query(sql, (err) => { if (err) return cb('Insert data error: ' + err) cb(null) }) }, //check table rows (cb) => { db.query('SELECT count(*) as rows FROM ' + table, (err, result) => { if (err) return cb('SELECT COUNT(*) err: ' + err) cb(null, result[0].rows) }) }, (rows, cb) => { //check columns let table_name = table.split('.')[1] let sql = 'SELECT COLUMN_NAME as col FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=\'' + opt.source + '\' AND TABLE_NAME=\'' + table_name + '\'' db.query(sql, (err, result) => { if (err) return cb('SELECT COLUMN_NAME err: ' + err) let cols = [] result.forEach((row) => { cols.push(row.col) }) cb(null, rows, cols) }) } ], (err, rows, columns) => { db.end((err) => { if (err) moduleCallback(err) }) if (err) { log.error(err) return moduleCallback(err) } moduleCallback(null, rows, columns) }) }
export function add(a, b) { return a + b }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const eslintScope = require("eslint-scope"); const { CachedSource, ConcatSource, ReplaceSource } = require("webpack-sources"); const DependencyTemplate = require("../DependencyTemplate"); const Module = require("../Module"); const { UsageState } = require("../ModuleGraph"); const RuntimeGlobals = require("../RuntimeGlobals"); const Template = require("../Template"); const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExportExpressionDependency"); const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); const HarmonyExportInitFragment = require("../dependencies/HarmonyExportInitFragment"); const HarmonyExportSpecifierDependency = require("../dependencies/HarmonyExportSpecifierDependency"); const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); const JavascriptParser = require("../javascript/JavascriptParser"); const LazySet = require("../util/LazySet"); const { concatComparators, keepOriginalOrder } = require("../util/comparators"); const createHash = require("../util/createHash"); const contextify = require("../util/identifier").contextify; const makeSerializable = require("../util/makeSerializable"); const propertyAccess = require("../util/propertyAccess"); /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("../WebpackError")} WebpackError */ /** @typedef {import("../util/Hash")} Hash */ /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** * @typedef {Object} ReexportInfo * @property {Module} module * @property {string[]} exportName * @property {Dependency} dependency */ /** * @typedef {Object} Binding * @property {ModuleInfo} info * @property {string[]} ids * @property {string[]} exportName */ /** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ /** * @typedef {Object} ConcatenatedModuleInfo * @property {"concatenated"} type * @property {Module} module * @property {number} index * @property {Object} ast * @property {Source} internalSource * @property {ReplaceSource} source * @property {Iterable<string>} runtimeRequirements * @property {TODO} globalScope * @property {TODO} moduleScope * @property {Map<string, string>} internalNames * @property {Map<string, string>} exportMap * @property {Map<string, ReexportInfo>} reexportMap * @property {boolean} hasNamespaceObject * @property {string} namespaceObjectName * @property {string} namespaceObjectSource */ /** * @typedef {Object} ExternalModuleInfo * @property {"external"} type * @property {Module} module * @property {number} index * @property {string} name * @property {boolean} interopNamespaceObjectUsed * @property {string} interopNamespaceObjectName * @property {boolean} interopDefaultAccessUsed * @property {string} interopDefaultAccessName */ const RESERVED_NAMES = [ // internal name "__WEBPACK_MODULE_DEFAULT_EXPORT__", // keywords "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", // commonjs "module,__dirname,__filename,exports", // js globals "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf", // browser globals "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", "untaint,window", // window events "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" ] .join(",") .split(","); const bySourceOrder = (a, b) => { const aOrder = a.sourceOrder; const bOrder = b.sourceOrder; if (isNaN(aOrder)) { if (!isNaN(bOrder)) { return 1; } } else { if (isNaN(bOrder)) { return -1; } if (aOrder !== bOrder) { return aOrder < bOrder ? -1 : 1; } } return 0; }; const arrayEquals = (a, b) => { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; }; /** * @typedef {Object} ConcatenationEntry * @property {"concatenated" | "external"} type * @property {Module} module */ /** * @param {ModuleGraph} moduleGraph the module graph * @param {ConcatenatedModuleInfo} info module info * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap * @param {RequestShortener} requestShortener requestShortener * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate * @param {boolean} strictHarmonyModule strictHarmonyModule * @returns {string} the name of the ns obj variable */ const ensureNsObjSource = ( moduleGraph, info, moduleToInfoMap, requestShortener, runtimeTemplate, strictHarmonyModule ) => { const name = info.namespaceObjectName; if (!info.hasNamespaceObject) { info.hasNamespaceObject = true; const nsObj = []; const exportsInfo = moduleGraph.getExportsInfo(info.module); for (const exportInfo of exportsInfo.orderedExports) { const finalName = getFinalName( moduleGraph, info, [exportInfo.name], moduleToInfoMap, requestShortener, runtimeTemplate, false, undefined, strictHarmonyModule, true ); nsObj.push( `\n ${JSON.stringify( exportInfo.getUsedName() )}: ${runtimeTemplate.returningFunction(finalName)}` ); } info.namespaceObjectSource = `var ${name} = {};\n${ RuntimeGlobals.makeNamespaceObject }(${name});\n${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( "," )}\n});\n`; } return name; }; /** * @param {ModuleGraph} moduleGraph the module graph * @param {Module} importedModule module * @param {ExternalModuleInfo} info module info * @param {string[]} exportName exportName * @param {boolean} asCall asCall * @param {boolean} callContext callContext * @param {boolean} strictHarmonyModule strictHarmonyModule * @param {boolean} asiSafe asiSafe * @returns {string} expression to get value of external module */ const getExternalImport = ( moduleGraph, importedModule, info, exportName, asCall, callContext, strictHarmonyModule, asiSafe ) => { const used = exportName.length === 0 || importedModule.getUsedName(moduleGraph, exportName); if (!used) return "/* unused export */undefined"; const comment = arrayEquals(used, exportName) ? "" : Template.toNormalComment(`${exportName.join(".")}`); let exprStart; const exportsType = importedModule.getExportsType(strictHarmonyModule); if (exportName.length === 0) { switch (exportsType) { case "dynamic-default": case "default-only": case "default-with-named": info.interopNamespaceObjectUsed = true; exprStart = info.interopNamespaceObjectName; break; case "namespace": exprStart = info.name; break; case "dynamic": exprStart = info.name; break; default: throw new Error(`Unexpected exportsType ${exportsType}`); } } else { switch (exportsType) { case "default-with-named": case "namespace": break; case "default-only": case "dynamic-default": if (exportName[0] === "default") { exprStart = info.name; } else { exprStart = "/* non-default import from default-exporting module */undefined"; } break; case "dynamic": if (exportName[0] === "default") { info.interopDefaultAccessUsed = true; exprStart = asCall ? `${info.interopDefaultAccessName}()` : asiSafe ? `(${info.interopDefaultAccessName}())` : `${info.interopDefaultAccessName}.a`; } break; default: throw new Error(`Unexpected exportsType ${exportsType}`); } } if (exprStart) { return `${exprStart}${propertyAccess(used, 1)}`; } const reference = `${info.name}${comment}${propertyAccess(used)}`; if (asCall && callContext === false) { return asiSafe ? `(0,${reference})` : `Object(${reference})`; } return reference; }; /** * @param {Set<ReexportInfo>} alreadyVisited alreadyVisited * @param {RequestShortener} requestShortener the request shortener * @param {ReexportInfo} reexport the current reexport * @returns {void | never} throws error when circular */ const checkCircularReexport = (alreadyVisited, requestShortener, reexport) => { if (alreadyVisited.has(reexport)) { throw new Error( `Circular reexports ${Array.from( alreadyVisited, e => `"${e.module.readableIdentifier( requestShortener )}".${e.exportName.join(".")}` ).join(" --> ")} -(circular)-> "${reexport.module.readableIdentifier( requestShortener )}".${reexport.exportName.join(".")}` ); } alreadyVisited.add(reexport); }; /** * @param {ModuleInfo} info module info * @param {string[]} exportName exportName * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap * @param {RequestShortener} requestShortener the request shortener * @param {Set<ReexportInfo>} alreadyVisited alreadyVisited * @returns {Binding} the final variable */ const getFinalBinding = ( info, exportName, moduleToInfoMap, requestShortener, alreadyVisited = new Set() ) => { switch (info.type) { case "concatenated": { if (exportName.length === 0) { return { info, ids: exportName, exportName }; } const exportId = exportName[0]; const directExport = info.exportMap.get(exportId); if (directExport) { return { info, ids: [directExport, ...exportName.slice(1)], exportName }; } const reexport = info.reexportMap.get(exportId); if (reexport) { checkCircularReexport(alreadyVisited, requestShortener, reexport); const refInfo = moduleToInfoMap.get(reexport.module); if (refInfo) { // module is in the concatenation return getFinalBinding( refInfo, [...reexport.exportName, ...exportName.slice(1)], moduleToInfoMap, requestShortener, alreadyVisited ); } } return { info, ids: null, exportName }; } case "external": { return { info, ids: exportName, exportName }; } } }; /** * @param {ModuleGraph} moduleGraph the module graph * @param {ModuleInfo} info module info * @param {string[]} exportName exportName * @param {Map<Module, ModuleInfo>} moduleToInfoMap moduleToInfoMap * @param {RequestShortener} requestShortener the request shortener * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {boolean} asCall asCall * @param {boolean} callContext callContext * @param {boolean} strictHarmonyModule strictHarmonyModule * @param {boolean} asiSafe asiSafe * @returns {string} the final name */ const getFinalName = ( moduleGraph, info, exportName, moduleToInfoMap, requestShortener, runtimeTemplate, asCall, callContext, strictHarmonyModule, asiSafe ) => { const binding = getFinalBinding( info, exportName, moduleToInfoMap, requestShortener ); switch (binding.info.type) { case "concatenated": { const { info, ids, exportName } = binding; if (!ids) { const problem = `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( requestShortener )}"` + ` (known exports: ${Array.from(info.exportMap.keys()).join(" ")}, ` + `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; return `${Template.toNormalComment(problem)} undefined${propertyAccess( exportName, 1 )}`; } if (ids.length === 0) { return ensureNsObjSource( moduleGraph, info, moduleToInfoMap, requestShortener, runtimeTemplate, strictHarmonyModule ); } const exportId = ids[0]; const exportsInfo = moduleGraph.getExportsInfo(info.module); if (exportsInfo.isExportUsed(exportName) === UsageState.Unused) { return `/* unused export */ undefined${propertyAccess(exportName, 1)}`; } const name = info.internalNames.get(exportId); if (!name) { throw new Error( `The export "${exportId}" in "${info.module.readableIdentifier( requestShortener )}" has no internal name` ); } return `${name}${propertyAccess(exportName, 1)}`; } case "external": { const { info, ids } = binding; const importedModule = info.module; return getExternalImport( moduleGraph, importedModule, info, ids, asCall, callContext, strictHarmonyModule, asiSafe ); } } }; const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { let scope = s; while (scope) { if (scopeSet1.has(scope)) break; if (scopeSet2.has(scope)) break; scopeSet1.add(scope); for (const variable of scope.variables) { nameSet.add(variable.name); } scope = scope.upper; } }; const getAllReferences = variable => { let set = variable.references; // Look for inner scope variables too (like in class Foo { t() { Foo } }) const identifiers = new Set(variable.identifiers); for (const scope of variable.scope.childScopes) { for (const innerVar of scope.variables) { if (innerVar.identifiers.some(id => identifiers.has(id))) { set = set.concat(innerVar.references); break; } } } return set; }; const getPathInAst = (ast, node) => { if (ast === node) { return []; } const nr = node.range; const enterNode = n => { if (!n) return undefined; const r = n.range; if (r) { if (r[0] <= nr[0] && r[1] >= nr[1]) { const path = getPathInAst(n, node); if (path) { path.push(n); return path; } } } return undefined; }; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { const enterResult = enterNode(ast[i]); if (enterResult !== undefined) return enterResult; } } else if (ast && typeof ast === "object") { const keys = Object.keys(ast); for (let i = 0; i < keys.length; i++) { const value = ast[keys[i]]; if (Array.isArray(value)) { const pathResult = getPathInAst(value, node); if (pathResult !== undefined) return pathResult; } else if (value && typeof value === "object") { const enterResult = enterNode(value); if (enterResult !== undefined) return enterResult; } } } }; const modulesWithInfoToMap = modulesWithInfo => { const moduleToInfoMap = new Map(); for (const m of modulesWithInfo) { moduleToInfoMap.set(m.module, m); } return moduleToInfoMap; }; const createModuleReference = ({ info, ids = undefined, call = false, directImport = false, strict = false, asiSafe = false }) => { const callFlag = call ? "_call" : ""; const directImportFlag = directImport ? "_directImport" : ""; const strictFlag = strict ? "_strict" : ""; const asiSafeFlag = asiSafe ? "_asiSafe" : ""; const exportData = ids ? Buffer.from(JSON.stringify(ids), "utf-8").toString("hex") : "ns"; return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${strictFlag}${asiSafeFlag}__`; }; const MODULE_REFERENCE_REGEXP = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_strict)?(_asiSafe)?__$/; const isModuleReference = name => { return MODULE_REFERENCE_REGEXP.test(name); }; const matchModuleReference = (name, modulesWithInfo) => { const match = MODULE_REFERENCE_REGEXP.exec(name); if (!match) return null; const index = +match[1]; return { index, info: modulesWithInfo[index], ids: match[2] === "ns" ? [] : JSON.parse(Buffer.from(match[2], "hex").toString("utf-8")), call: !!match[3], directImport: !!match[4], strict: !!match[5], asiSafe: !!match[6] }; }; const TYPES = new Set(["javascript"]); class ConcatenatedModule extends Module { /** * @param {Module} rootModule the root module of the concatenation * @param {Set<Module>} modules all modules in the concantenation (including the root module) * @param {ModuleGraph} moduleGraph the module graph * @param {Object=} associatedObjectForCache object for caching * @returns {ConcatenatedModule} the module */ static createFromModuleGraph( rootModule, modules, moduleGraph, associatedObjectForCache ) { const orderedConcatenationList = ConcatenatedModule._createConcatenationList( rootModule, modules, moduleGraph ); const identifier = ConcatenatedModule._createIdentifier( rootModule, orderedConcatenationList, associatedObjectForCache ); return new ConcatenatedModule({ identifier, rootModule, orderedConcatenationList, modules }); } /** * @param {Object} options options * @param {string} options.identifier the identifier of the module * @param {Module=} options.rootModule the root module of the concatenation * @param {Set<Module>=} options.modules all concatenated modules * @param {TODO=} options.orderedConcatenationList the list of concentated modules and externals */ constructor({ identifier, rootModule, modules, orderedConcatenationList }) { super("javascript/esm", null); // Info from Factory /** @type {string} */ this._identifier = identifier; /** @type {Module} */ this.rootModule = rootModule; /** @type {Set<Module>} */ this._modules = modules; this._orderedConcatenationList = orderedConcatenationList; this.factoryMeta = rootModule && rootModule.factoryMeta; // Caching /** @private @type {string} */ this._cachedCodeGenerationHash = ""; /** @private @type {CodeGenerationResult} */ this._cachedCodeGeneration = undefined; } /** * Assuming this module is in the cache. Update the (cached) module with * the fresh module from the factory. Usually updates internal references * and properties. * @param {Module} module fresh module * @returns {void} */ updateCacheModule(module) { super.updateCacheModule(module); const m = /** @type {ConcatenatedModule} */ (module); this._identifier = m._identifier; this.rootModule = m.rootModule; this._modules = m._modules; this._orderedConcatenationList = m._orderedConcatenationList; } /** * @returns {Set<string>} types availiable (do not mutate) */ getSourceTypes() { return TYPES; } get modules() { return this._orderedConcatenationList .filter(info => info.type === "concatenated") .map(info => info.module); } /** * @returns {string} a unique identifier of the module */ identifier() { return this._identifier; } /** * @param {RequestShortener} requestShortener the request shortener * @returns {string} a user readable identifier of the module */ readableIdentifier(requestShortener) { return ( this.rootModule.readableIdentifier(requestShortener) + ` + ${this._modules.size - 1} modules` ); } /** * @param {LibIdentOptions} options options * @returns {string | null} an identifier for library inclusion */ libIdent(options) { return this.rootModule.libIdent(options); } /** * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) */ nameForCondition() { return this.rootModule.nameForCondition(); } /** * @param {WebpackOptions} options webpack options * @param {Compilation} compilation the compilation * @param {ResolverWithOptions} resolver the resolver * @param {InputFileSystem} fs the file system * @param {function(WebpackError=): void} callback callback function * @returns {void} */ build(options, compilation, resolver, fs, callback) { const { rootModule } = this; this.buildInfo = { strict: true, cacheable: true, moduleArgument: rootModule.buildInfo.moduleArgument, exportsArgument: rootModule.buildInfo.exportsArgument, fileDependencies: new LazySet(), contextDependencies: new LazySet(), missingDependencies: new LazySet(), assets: undefined }; this.buildMeta = rootModule.buildMeta; this.clearDependenciesAndBlocks(); this.clearWarningsAndErrors(); for (const info of this._orderedConcatenationList) { if (info.type === "concatenated") { const m = info.module; // populate cacheable if (!m.buildInfo.cacheable) { this.buildInfo.cacheable = false; } // populate dependencies for (const d of m.dependencies.filter( dep => !(dep instanceof HarmonyImportDependency) || !this._modules.has(compilation.moduleGraph.getModule(dep)) )) { this.dependencies.push(d); } // populate blocks for (const d of m.blocks) { this.blocks.push(d); } // populate file dependencies if (m.buildInfo.fileDependencies) { this.buildInfo.fileDependencies.addAll(m.buildInfo.fileDependencies); } // populate context dependencies if (m.buildInfo.contextDependencies) { this.buildInfo.contextDependencies.addAll( m.buildInfo.contextDependencies ); } // populate missing dependencies if (m.buildInfo.missingDependencies) { this.buildInfo.missingDependencies.addAll( m.buildInfo.missingDependencies ); } // populate warnings const warnings = m.getWarnings(); if (warnings !== undefined) { for (const warning of warnings) { this.addWarning(warning); } } // populate errors const errors = m.getErrors(); if (errors !== undefined) { for (const error of errors) { this.addError(error); } } // populate assets if (m.buildInfo.assets) { if (this.buildInfo.assets === undefined) { this.buildInfo.assets = Object.create(null); } Object.assign(this.buildInfo.assets, m.buildInfo.assets); } if (m.buildInfo.assetsInfo) { if (this.buildInfo.assetsInfo === undefined) { this.buildInfo.assetsInfo = new Map(); } for (const [key, value] of m.buildInfo.assetsInfo) { this.buildInfo.assetsInfo.set(key, value); } } } } callback(); } /** * @param {string=} type the source type for which the size should be estimated * @returns {number} the estimated size of the module (must be non-zero) */ size(type) { // Guess size from embedded modules let size = 0; for (const info of this._orderedConcatenationList) { switch (info.type) { case "concatenated": size += info.module.size(type); break; case "external": size += 5; break; } } return size; } /** * @private * @param {Module} rootModule the root of the concatenation * @param {Set<Module>} modulesSet a set of modules which should be concatenated * @param {ModuleGraph} moduleGraph the module graph * @returns {ConcatenationEntry[]} concatenation list */ static _createConcatenationList(rootModule, modulesSet, moduleGraph) { const list = []; const set = new Set(); /** * @param {Module} module a module * @returns {(function(): Module)[]} imported modules in order */ const getConcatenatedImports = module => { const references = Array.from(moduleGraph.getOutgoingConnections(module)) .filter(connection => { if (!(connection.dependency instanceof HarmonyImportDependency)) return false; return connection && connection.module && connection.active; }) .map(connection => ({ connection, sourceOrder: /** @type {HarmonyImportDependency} */ (connection.dependency) .sourceOrder })); references.sort( concatComparators(bySourceOrder, keepOriginalOrder(references)) ); return references.map(({ connection }) => { return () => connection.module; }); }; const enterModule = getModule => { const module = getModule(); if (!module) return; if (set.has(module)) return; set.add(module); if (modulesSet.has(module)) { const imports = getConcatenatedImports(module); imports.forEach(enterModule); list.push({ type: "concatenated", module }); } else { list.push({ type: "external", get module() { // We need to use a getter here, because the module in the dependency // could be replaced by some other process (i. e. also replaced with a // concatenated module) return getModule(); } }); } }; enterModule(() => rootModule); return list; } static _createIdentifier( rootModule, orderedConcatenationList, associatedObjectForCache ) { const cachedContextify = contextify.bindContextCache( rootModule.context, associatedObjectForCache ); let orderedConcatenationListIdentifiers = ""; for (let i = 0; i < orderedConcatenationList.length; i++) { if (orderedConcatenationList[i].type === "concatenated") { orderedConcatenationListIdentifiers += cachedContextify( orderedConcatenationList[i].module.identifier() ); orderedConcatenationListIdentifiers += " "; } } const hash = createHash("md4"); hash.update(orderedConcatenationListIdentifiers); return rootModule.identifier() + "|" + hash.digest("hex"); } /** * @param {CodeGenerationContext} context context for code generation * @returns {CodeGenerationResult} result */ codeGeneration({ dependencyTemplates, runtimeTemplate, moduleGraph, chunkGraph }) { const hashDigest = this._getHashDigest(chunkGraph, dependencyTemplates); if (this._cachedCodeGenerationHash === hashDigest) { // We can reuse the cached data return this._cachedCodeGeneration; } /** @type {Set<string>} */ const runtimeRequirements = new Set(); const requestShortener = runtimeTemplate.requestShortener; // Metainfo for each module const modulesWithInfo = this._getModulesWithInfo(moduleGraph); // Create mapping from module to info const moduleToInfoMap = modulesWithInfoToMap(modulesWithInfo); // Configure template decorators for dependencies const innerDependencyTemplates = this._getInnerDependencyTemplates( dependencyTemplates, moduleToInfoMap ); // Generate source code and analyse scopes // Prepare a ReplaceSource for the final source for (const info of modulesWithInfo) { this._analyseModule( info, innerDependencyTemplates, runtimeTemplate, moduleGraph, chunkGraph ); } // List of all used names to avoid conflicts const allUsedNames = new Set(RESERVED_NAMES); // List of additional names in scope for module references /** @type {Map<string, { usedNames: Set<string>, alreadyCheckedScopes: Set<TODO> }>} */ const usedNamesInScopeInfo = new Map(); /** * @param {string} module module identifier * @param {string} id export id * @returns {{ usedNames: Set<string>, alreadyCheckedScopes: Set<TODO> }} info */ const getUsedNamesInScopeInfo = (module, id) => { const key = `${module}-${id}`; let info = usedNamesInScopeInfo.get(key); if (info === undefined) { info = { usedNames: new Set(), alreadyCheckedScopes: new Set() }; usedNamesInScopeInfo.set(key, info); } return info; }; // Set of already checked scopes const ignoredScopes = new Set(); // get all global names for (const info of modulesWithInfo) { if (info.type === "concatenated") { const superClassExpressions = []; // ignore symbols from moduleScope if (info.moduleScope) { ignoredScopes.add(info.moduleScope); // The super class expression in class scopes behaves weird // We store ranges of all super class expressions to make // renaming to work correctly for (const childScope of info.moduleScope.childScopes) { if (childScope.type !== "class") continue; if (!childScope.block.superClass) continue; superClassExpressions.push({ range: childScope.block.superClass.range, variables: childScope.variables }); } } // add global symbols if (info.globalScope) { for (const reference of info.globalScope.through) { const name = reference.identifier.name; if (isModuleReference(name)) { const match = matchModuleReference(name, modulesWithInfo); if (!match || match.ids.length < 1) continue; const binding = getFinalBinding( match.info, match.ids, moduleToInfoMap, requestShortener ); if (!binding.ids) continue; const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( binding.info.module.identifier(), binding.info.type === "external" ? "external" : binding.ids.length > 0 ? binding.ids[0] : "" ); for (const expr of superClassExpressions) { if ( expr.range[0] <= reference.identifier.range[0] && expr.range[1] >= reference.identifier.range[1] ) { for (const variable of expr.variables) { usedNames.add(variable.name); } } } addScopeSymbols( reference.from, usedNames, alreadyCheckedScopes, ignoredScopes ); } else { allUsedNames.add(name); } } } } } // generate names for symbols for (const info of modulesWithInfo) { switch (info.type) { case "concatenated": { const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(info.module.identifier(), ""); const namespaceObjectName = this.findNewName( "namespaceObject", allUsedNames, namespaceObjectUsedNames, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(namespaceObjectName); info.namespaceObjectName = namespaceObjectName; for (const variable of info.moduleScope.variables) { const name = variable.name; const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( info.module.identifier(), name ); if (allUsedNames.has(name) || usedNames.has(name)) { const references = getAllReferences(variable); for (const ref of references) { addScopeSymbols( ref.from, usedNames, alreadyCheckedScopes, ignoredScopes ); } const newName = this.findNewName( name, allUsedNames, usedNames, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(newName); info.internalNames.set(name, newName); const source = info.source; const allIdentifiers = new Set( references.map(r => r.identifier).concat(variable.identifiers) ); for (const identifier of allIdentifiers) { const r = identifier.range; const path = getPathInAst(info.ast, identifier); if ( path && path.length > 1 && path[1].type === "Property" && path[1].shorthand ) { source.insert(r[1], `: ${newName}`); } else { source.replace(r[0], r[1] - 1, newName); } } } else { allUsedNames.add(name); info.internalNames.set(name, name); } } break; } case "external": { const { usedNames } = getUsedNamesInScopeInfo( info.module.identifier(), "external" ); const externalName = this.findNewName( "", allUsedNames, usedNames, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalName); info.name = externalName; if ( info.module.buildMeta.exportsType === "default" || info.module.buildMeta.exportsType === "flagged" || !info.module.buildMeta.exportsType ) { const externalNameInterop = this.findNewName( "namespaceObject", allUsedNames, usedNames, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalNameInterop); info.interopNamespaceObjectName = externalNameInterop; } if (!info.module.buildMeta.exportsType) { const externalNameInterop = this.findNewName( "default", allUsedNames, usedNames, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalNameInterop); info.interopDefaultAccessName = externalNameInterop; } break; } } } // Find and replace referenced to modules for (const info of modulesWithInfo) { if (info.type === "concatenated") { for (const reference of info.globalScope.through) { const name = reference.identifier.name; const match = matchModuleReference(name, modulesWithInfo); if (match) { const finalName = getFinalName( moduleGraph, match.info, match.ids, moduleToInfoMap, requestShortener, runtimeTemplate, match.call, !match.directImport, match.strict, match.asiSafe ); const r = reference.identifier.range; const source = info.source; source.replace(r[0], r[1] - 1, finalName); } } } } const result = new ConcatSource(); // add harmony compatibility flag (must be first because of possible circular dependencies) if ( moduleGraph.getExportsInfo(this).otherExportsInfo.used !== UsageState.Unused ) { result.add( runtimeTemplate.defineEsModuleFlagStatement({ exportsArgument: this.exportsArgument, runtimeRequirements }) ); } // define required namespace objects (must be before evaluation modules) for (const info of modulesWithInfo) { if (info.type === "concatenated" && info.namespaceObjectSource) { result.add(info.namespaceObjectSource); runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); } } // evaluate modules in order for (const info of modulesWithInfo) { switch (info.type) { case "concatenated": { result.add( `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( requestShortener )}\n` ); result.add(info.source); if (info.runtimeRequirements) { for (const r of info.runtimeRequirements) { runtimeRequirements.add(r); } } break; } case "external": result.add( `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( requestShortener )}\n` ); runtimeRequirements.add(RuntimeGlobals.require); result.add( `var ${info.name} = __webpack_require__(${JSON.stringify( chunkGraph.getModuleId(info.module) )});\n` ); if (info.interopNamespaceObjectUsed) { if (info.module.buildMeta.exportsType === "default") { runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); result.add( `var ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${info.name}, 2);\n` ); } else if ( info.module.buildMeta.exportsType === "flagged" || !info.module.buildMeta.exportsType ) { runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); result.add( `var ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${info.name});\n` ); } } if (info.interopDefaultAccessUsed) { runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); result.add( `var ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${info.name});\n` ); } break; default: // @ts-ignore never is expected here throw new Error(`Unsupported concatenation entry type ${info.type}`); } } /** @type {CodeGenerationResult} */ const resultEntry = { sources: new Map([["javascript", new CachedSource(result)]]), runtimeRequirements }; this._cachedCodeGeneration = resultEntry; this._cachedCodeGenerationHash = hashDigest; return resultEntry; } _analyseModule( info, innerDependencyTemplates, runtimeTemplate, moduleGraph, chunkGraph ) { if (info.type === "concatenated") { const m = info.module; const codeGenResult = m.codeGeneration({ dependencyTemplates: innerDependencyTemplates, runtimeTemplate, moduleGraph, chunkGraph }); const source = codeGenResult.sources.get("javascript"); const code = source.source(); let ast; try { ast = JavascriptParser.parse(code, { sourceType: "module" }); } catch (err) { if ( err.loc && typeof err.loc === "object" && typeof err.loc.line === "number" ) { const lineNumber = err.loc.line; const lines = code.split("\n"); err.message += "\n| " + lines .slice(Math.max(0, lineNumber - 3), lineNumber + 2) .join("\n| "); } throw err; } const scopeManager = eslintScope.analyze(ast, { ecmaVersion: 6, sourceType: "module", optimistic: true, ignoreEval: true, impliedStrict: true }); const globalScope = scopeManager.acquire(ast); const moduleScope = globalScope.childScopes[0]; const resultSource = new ReplaceSource(source); info.runtimeRequirements = codeGenResult.runtimeRequirements; info.ast = ast; info.internalSource = source; info.source = resultSource; info.globalScope = globalScope; info.moduleScope = moduleScope; } } /** * @param {ChunkGraph} chunkGraph the chunk graph * @param {DependencyTemplates} dependencyTemplates dependency templates * @returns {string} hash */ _getHashDigest(chunkGraph, dependencyTemplates) { const hash = chunkGraph.getModuleHash(this); const dtHash = dependencyTemplates.getHash(); return `${hash}-${dtHash}`; } /** * @param {ModuleGraph} moduleGraph the module graph * @returns {ModuleInfo[]} module info items */ _getModulesWithInfo(moduleGraph) { return this._orderedConcatenationList.map((info, idx) => { /** @type {ModuleInfo} */ let result; switch (info.type) { case "concatenated": { /** @type {Map<string, string>} */ const exportMap = new Map(); /** @type {Map<string, ReexportInfo>} */ const reexportMap = new Map(); for (const dep of info.module.dependencies) { if (dep instanceof HarmonyExportSpecifierDependency) { if (!exportMap.has(dep.name)) { exportMap.set(dep.name, dep.id); } } else if (dep instanceof HarmonyExportExpressionDependency) { if (!exportMap.has("default")) { exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); } } else if ( dep instanceof HarmonyExportImportedSpecifierDependency ) { const exportName = dep.name; const importNames = dep.getIds(moduleGraph); const importedModule = moduleGraph.getModule(dep); if (exportName) { if (!reexportMap.has(exportName)) { reexportMap.set(exportName, { module: importedModule, exportName: importNames, dependency: dep }); } } else if (importedModule) { const providedExports = moduleGraph.getProvidedExports( importedModule ); if (Array.isArray(providedExports)) { for (const name of providedExports) { if (dep.activeExports.has(name) || name === "default") { continue; } if (!reexportMap.has(name)) { reexportMap.set(name, { module: importedModule, exportName: [name], dependency: dep }); } } } } } } result = { type: "concatenated", module: info.module, index: idx, ast: undefined, internalSource: undefined, runtimeRequirements: undefined, source: undefined, globalScope: undefined, moduleScope: undefined, internalNames: new Map(), exportMap, reexportMap, hasNamespaceObject: false, namespaceObjectName: undefined, namespaceObjectSource: null }; break; } case "external": result = { type: "external", module: info.module, index: idx, name: undefined, interopNamespaceObjectUsed: false, interopNamespaceObjectName: undefined, interopDefaultAccessUsed: false, interopDefaultAccessName: undefined }; break; default: throw new Error(`Unsupported concatenation entry type ${info.type}`); } return result; }); } /** * * @param {DependencyTemplates} dependencyTemplates outer dependency templates * @param {Map<Module, ModuleInfo>} moduleToInfoMap map for module info * @returns {DependencyTemplates} inner dependency templates */ _getInnerDependencyTemplates(dependencyTemplates, moduleToInfoMap) { const innerDependencyTemplates = dependencyTemplates.clone(); innerDependencyTemplates.set( HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyImportSpecifierDependency), moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyImportSideEffectDependency, new HarmonyImportSideEffectDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyImportSideEffectDependency), moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportSpecifierDependency), this.rootModule ) ); innerDependencyTemplates.set( HarmonyExportExpressionDependency, new HarmonyExportExpressionDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportExpressionDependency), this.rootModule ) ); innerDependencyTemplates.set( HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportImportedSpecifierDependency), this.rootModule, moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyCompatibilityDependency, new HarmonyCompatibilityDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyCompatibilityDependency), this.rootModule, moduleToInfoMap ) ); // Must use full identifier in our cache here to ensure that the source // is updated should our dependencies list change. // TODO webpack 5 refactor innerDependencyTemplates.updateHash(this.identifier()); return innerDependencyTemplates; } findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { let name = oldName; if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; // Remove uncool stuff extraInfo = extraInfo.replace( /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, "" ); const splittedInfo = extraInfo.split("/"); while (splittedInfo.length) { name = splittedInfo.pop() + (name ? "_" + name : ""); const nameIdent = Template.toIdentifier(name); if ( !usedNamed1.has(nameIdent) && (!usedNamed2 || !usedNamed2.has(nameIdent)) ) return nameIdent; } let i = 0; let nameWithNumber = Template.toIdentifier(`${name}_${i}`); while ( usedNamed1.has(nameWithNumber) || (usedNamed2 && usedNamed2.has(nameWithNumber)) ) { i++; nameWithNumber = Template.toIdentifier(`${name}_${i}`); } return nameWithNumber; } /** * @param {Hash} hash the hash used to track dependencies * @param {ChunkGraph} chunkGraph the chunk graph * @returns {void} */ updateHash(hash, chunkGraph) { for (const info of this._orderedConcatenationList) { switch (info.type) { case "concatenated": info.module.updateHash(hash, chunkGraph); break; case "external": hash.update(`${chunkGraph.getModuleId(info.module)}`); break; } } super.updateHash(hash, chunkGraph); } serialize(context) { const { write } = context; write(this._cachedCodeGenerationHash); write(this._cachedCodeGeneration); super.serialize(context); } static deserialize(context) { const obj = new ConcatenatedModule({ identifier: undefined, rootModule: undefined, orderedConcatenationList: undefined, modules: undefined }); obj.deserialize(context); return obj; } deserialize(context) { const { read } = context; this._cachedCodeGenerationHash = read(); this._cachedCodeGeneration = read(); super.deserialize(context); } } makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); class HarmonyImportSpecifierDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, modulesMap) { super(); this.originalTemplate = originalTemplate; this.modulesMap = modulesMap; } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply(dependency, source, templateContext) { const { moduleGraph, module: parentModule } = templateContext; const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); const module = moduleGraph.getModule(dep); const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.apply(dependency, source, templateContext); return; } let content; const ids = dep.getIds(moduleGraph); if (ids.length === 0) { content = createModuleReference({ info, strict: parentModule.buildMeta.strictHarmonyModule, asiSafe: dep.asiSafe }); } else if (dep.namespaceObjectAsContext && ids.length === 1) { content = createModuleReference({ info, strict: parentModule.buildMeta.strictHarmonyModule, asiSafe: dep.asiSafe }) + propertyAccess(ids); } else { content = createModuleReference({ info, ids, call: dep.call, directImport: dep.directImport, strict: parentModule.buildMeta.strictHarmonyModule, asiSafe: dep.asiSafe }); } if (dep.shorthand) { source.insert(dep.range[1], ": " + content); } else { source.replace(dep.range[0], dep.range[1] - 1, content); } } } class HarmonyImportSideEffectDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, modulesMap) { super(); this.originalTemplate = originalTemplate; this.modulesMap = modulesMap; } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply(dependency, source, templateContext) { const { moduleGraph } = templateContext; const dep = /** @type {HarmonyImportSideEffectDependency} */ (dependency); const module = moduleGraph.getModule(dep); const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.apply(dependency, source, templateContext); return; } } } class HarmonyExportSpecifierDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, rootModule) { super(); this.originalTemplate = originalTemplate; this.rootModule = rootModule; } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply(dependency, source, templateContext) { if (templateContext.module === this.rootModule) { this.originalTemplate.apply(dependency, source, templateContext); } } } class HarmonyExportExpressionDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, rootModule) { super(); this.originalTemplate = originalTemplate; this.rootModule = rootModule; } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply( dependency, source, { module, moduleGraph, runtimeTemplate, initFragments } ) { const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); if (module === this.rootModule) { const used = module.getUsedName(moduleGraph, "default"); if (used) { const map = new Map(); map.set(used, "__WEBPACK_MODULE_DEFAULT_EXPORT__"); initFragments.push( new HarmonyExportInitFragment(module.exportsArgument, map) ); } } const content = `/* harmony default export */ ${ runtimeTemplate.supportsConst() ? "const" : "var" } __WEBPACK_MODULE_DEFAULT_EXPORT__ = `; if (dep.range) { source.replace( dep.rangeStatement[0], dep.range[0] - 1, content + "(" + dep.prefix ); source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); return; } source.replace( dep.rangeStatement[0], dep.rangeStatement[1] - 1, content + dep.prefix ); } } class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, rootModule, modulesMap) { super(); this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } /** * @typedef {Object} GetExportsResultItem * @property {string} name * @property {string[]} ids */ /** * @param {HarmonyExportImportedSpecifierDependency} dep dependency * @param {DependencyTemplateContext} templateContext template context * @returns {GetExportsResultItem[]} exports */ getExports(dep, { moduleGraph }) { const importModule = moduleGraph.getModule(dep); const ids = dep.getIds(moduleGraph); if (ids.length > 0) { // export { named } from "module" return [ { name: dep.name, ids } ]; } if (dep.name) { // export * as abc from "module" return [ { name: dep.name, ids: [] } ]; } // export * from "module" const providedExports = moduleGraph.getProvidedExports(importModule); if (Array.isArray(providedExports)) { return providedExports .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) .map(exp => { return { name: exp, ids: [exp] }; }); } // unknown, should not happen throw new Error("ConcatenatedModule: unknown exports"); } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply(dependency, source, templateContext) { const { module, moduleGraph, initFragments } = templateContext; const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ (dependency); const importedModule = moduleGraph.getModule(dep); const info = this.modulesMap.get(importedModule); if (!info) { this.originalTemplate.apply(dependency, source, templateContext); return; } else if (module === this.rootModule) { const exportDefs = this.getExports(dep, templateContext); for (const def of exportDefs) { const used = module.getUsedName(moduleGraph, def.name); if (!used) { initFragments.push( new HarmonyExportInitFragment( this.rootModule.exportsArgument, undefined, new Set([def.name]) ) ); continue; } let finalName; if (def.ids.length === 0) { finalName = createModuleReference({ info, strict: module.buildMeta.strictHarmonyModule, asiSafe: true }); } else { finalName = createModuleReference({ info, ids: def.ids, strict: module.buildMeta.strictHarmonyModule, asiSafe: true }); } const map = new Map(); map.set(used, `/* concated reexport */ ${finalName}`); initFragments.push( new HarmonyExportInitFragment(this.rootModule.exportsArgument, map) ); } } } } class HarmonyCompatibilityDependencyConcatenatedTemplate extends DependencyTemplate { constructor(originalTemplate, rootModule, modulesMap) { super(); this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply( dependency, source, { runtimeTemplate, dependencyTemplates, moduleGraph } ) { // do nothing } } module.exports = ConcatenatedModule;
const functions = require('firebase-functions'); const Gdax = require('gdax'); const cors = require('cors')({origin: true}); // private endpoints exports.getAccounts = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.AuthenticatedClient(request.query.apikey, request.query.secret, request.query.passphrase, request.query.apiURI) console.log(client) client.getAccounts(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) // public endpoints exports.getProducts = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProducts(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductOrderBook = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductOrderBook({level: request.query.level || 1}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductTicker = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductTicker(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductTrades = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductTrades({after: request.query.after}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) // exports.getProductTradeStream = functions.https.onRequest((request, response) => { // cors(request, response, () => { // var client = new Gdax.PublicClient(request.body.product, request.body.apiURL) // client.getProductTrades(tradesFrom, tradesTo) // }) // }) exports.getProductHistoricRates = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductHistoricRates({granularity: request.query.granularity || 3000}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProduct24HrStats = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProduct24HrStats(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getCurrencies = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getCurrencies(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) })
var CLE_EDITORS; jQuery(document).ready(function() { jQuery.cleditor.defaultOptions.controls = 'bold italic style removeformat | bullets numbering | link unlink | pasteword | source'; jQuery.cleditor.defaultOptions.colors = '387ab6 474747'; jQuery.cleditor.defaultOptions.styles = [["Paragraph", "<p>"], ["Header 2", "<h2>"], ["Header 3", "<h3>"]]; CLE_EDITORS = jQuery("TEXTAREA.editor").cleditor(); }); function refreshCLE() { if (CLE_EDITORS) { CLE_EDITORS.each(function() { this.refresh(); }); } }
const ANCESTRY_FILE = "[\n " + [ '{"name": "Carolus Haverbeke", "sex": "m", "born": 1832, "died": 1905, "father": "Carel Haverbeke", "mother": "Maria van Brussel"}', '{"name": "Emma de Milliano", "sex": "f", "born": 1876, "died": 1956, "father": "Petrus de Milliano", "mother": "Sophia van Damme"}', '{"name": "Maria de Rycke", "sex": "f", "born": 1683, "died": 1724, "father": "Frederik de Rycke", "mother": "Laurentia van Vlaenderen"}', '{"name": "Jan van Brussel", "sex": "m", "born": 1714, "died": 1748, "father": "Jacobus van Brussel", "mother": "Joanna van Rooten"}', '{"name": "Philibert Haverbeke", "sex": "m", "born": 1907, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}', '{"name": "Jan Frans van Brussel", "sex": "m", "born": 1761, "died": 1833, "father": "Jacobus Bernardus van Brussel", "mother":null}', '{"name": "Pauwels van Haverbeke", "sex": "m", "born": 1535, "died": 1582, "father": "N. van Haverbeke", "mother":null}', '{"name": "Clara Aernoudts", "sex": "f", "born": 1918, "died": 2012, "father": "Henry Aernoudts", "mother": "Sidonie Coene"}', '{"name": "Emile Haverbeke", "sex": "m", "born": 1877, "died": 1968, "father": "Carolus Haverbeke", "mother": "Maria Sturm"}', '{"name": "Lieven de Causmaecker", "sex": "m", "born": 1696, "died": 1724, "father": "Carel de Causmaecker", "mother": "Joanna Claes"}', '{"name": "Pieter Haverbeke", "sex": "m", "born": 1602, "died": 1642, "father": "Lieven van Haverbeke", "mother":null}', '{"name": "Livina Haverbeke", "sex": "f", "born": 1692, "died": 1743, "father": "Daniel Haverbeke", "mother": "Joanna de Pape"}', '{"name": "Pieter Bernard Haverbeke", "sex": "m", "born": 1695, "died": 1762, "father": "Willem Haverbeke", "mother": "Petronella Wauters"}', '{"name": "Lieven van Haverbeke", "sex": "m", "born": 1570, "died": 1636, "father": "Pauwels van Haverbeke", "mother": "Lievijne Jans"}', '{"name": "Joanna de Causmaecker", "sex": "f", "born": 1762, "died": 1807, "father": "Bernardus de Causmaecker", "mother":null}', '{"name": "Willem Haverbeke", "sex": "m", "born": 1668, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}', '{"name": "Pieter Antone Haverbeke", "sex": "m", "born": 1753, "died": 1798, "father": "Jan Francies Haverbeke", "mother": "Petronella de Decker"}', '{"name": "Maria van Brussel", "sex": "f", "born": 1801, "died": 1834, "father": "Jan Frans van Brussel", "mother": "Joanna de Causmaecker"}', '{"name": "Angela Haverbeke", "sex": "f", "born": 1728, "died": 1734, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}', '{"name": "Elisabeth Haverbeke", "sex": "f", "born": 1711, "died": 1754, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}', '{"name": "Lievijne Jans", "sex": "f", "born": 1542, "died": 1582, "father":null, "mother":null}', '{"name": "Bernardus de Causmaecker", "sex": "m", "born": 1721, "died": 1789, "father": "Lieven de Causmaecker", "mother": "Livina Haverbeke"}', '{"name": "Jacoba Lammens", "sex": "f", "born": 1699, "died": 1740, "father": "Lieven Lammens", "mother": "Livina de Vrieze"}', '{"name": "Pieter de Decker", "sex": "m", "born": 1705, "died": 1780, "father": "Joos de Decker", "mother": "Petronella van de Steene"}', '{"name": "Joanna de Pape", "sex": "f", "born": 1654, "died": 1723, "father": "Vincent de Pape", "mother": "Petronella Wauters"}', '{"name": "Daniel Haverbeke", "sex": "m", "born": 1652, "died": 1723, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}', '{"name": "Lieven Haverbeke", "sex": "m", "born": 1631, "died": 1676, "father": "Pieter Haverbeke", "mother": "Anna van Hecke"}', '{"name": "Martina de Pape", "sex": "f", "born": 1666, "died": 1727, "father": "Vincent de Pape", "mother": "Petronella Wauters"}', '{"name": "Jan Francies Haverbeke", "sex": "m", "born": 1725, "died": 1779, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}', '{"name": "Maria Haverbeke", "sex": "m", "born": 1905, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}', '{"name": "Petronella de Decker", "sex": "f", "born": 1731, "died": 1781, "father": "Pieter de Decker", "mother": "Livina Haverbeke"}', '{"name": "Livina Sierens", "sex": "f", "born": 1761, "died": 1826, "father": "Jan Sierens", "mother": "Maria van Waes"}', '{"name": "Laurentia Haverbeke", "sex": "f", "born": 1710, "died": 1786, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}', '{"name": "Carel Haverbeke", "sex": "m", "born": 1796, "died": 1837, "father": "Pieter Antone Haverbeke", "mother": "Livina Sierens"}', '{"name": "Elisabeth Hercke", "sex": "f", "born": 1632, "died": 1674, "father": "Willem Hercke", "mother": "Margriet de Brabander"}', '{"name": "Jan Haverbeke", "sex": "m", "born": 1671, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}', '{"name": "Anna van Hecke", "sex": "f", "born": 1607, "died": 1670, "father": "Paschasius van Hecke", "mother": "Martijntken Beelaert"}', '{"name": "Maria Sturm", "sex": "f", "born": 1835, "died": 1917, "father": "Charles Sturm", "mother": "Seraphina Spelier"}', '{"name": "Jacobus Bernardus van Brussel", "sex": "m", "born": 1736, "died": 1809, "father": "Jan van Brussel", "mother": "Elisabeth Haverbeke"}' ].join(",\n ") + "\n]"; export default ANCESTRY_FILE;
'use strict'; // MODULES // var similarity = require( 'compute-cosine-similarity'); // COSINE DISTANCE // /** * FUNCTION: distance( x, y[, accessor] ) * Computes the cosine distance between two arrays. * * @param {Number[]|Array} x - input array * @param {Number[]|Array} y - input array * @param {Function} [accessor] - accessor function for accessing array values * @returns {Number|Null} Cosine distance */ function distance( x, y, clbk ) { var s; if ( arguments.length > 2 ) { s = similarity( x, y, clbk ); } else { s = similarity( x, y ); } return ( s !== null ) ? 1 - s : s; } // end FUNCTION distance() // EXPORTS // module.exports = distance;
/// // Dependencies /// import { fromJS } from 'immutable'; import configureMockStore from 'redux-mock-store'; import { ActionsObservable } from 'redux-observable'; import nock from 'nock'; import url from 'url'; import { baseURL } from '../../app/__mocks__/api'; import epic from '../epics'; import * as actions from '../actions'; import * as formsActions from '../../forms/actions'; /// // Initialization / Configuration /// const userId = 1; const defaultState = fromJS({ user: { accessToken: 'a', id: userId, } }); jest.mock('../../app/api'); const mockStore = configureMockStore([]) let store; const parsedUrl = url.parse(baseURL); const baseHost = parsedUrl.protocol + '//' + parsedUrl.hostname; /// // Tests /// it('[epic] people: ignores invalid actions', () => { store = mockStore(fromJS({})); const action$ = ActionsObservable.of({type: null}); const expected = undefined; return epic(action$, store).toPromise().then(received => { expect(received).toEqual(expected); }); }); pit('[epic] people: correctly processes PEOPLE:GET_LIST_START', () => { const friendsFrom = [ {id: 1}, {id: 2} ]; const friendsTo = [ {id: 3}, {id: 4} ]; nock(baseHost) .get(/^\/people\/1\/friendsFrom.*$/) .reply(200, friendsFrom); nock(baseHost) .get(/^\/people\/1\/friendsTo.*$/) .reply(200, friendsTo); const state = fromJS(defaultState); store = mockStore(state); const action$ = ActionsObservable.of( actions.getListStart() ); const expected = actions.getListDone( friendsFrom.concat(friendsTo) ); return epic(action$, store).toPromise().then(received => { expect(received).toEqual(expected); }); }); pit('[epic] people: correctly processes PEOPLE:SUBMIT_FORM', () => { const item = {a: 'a', b: 'b'}; nock(baseHost) .post(/^\/people\/1\/people.*$/) .reply(200, item); const state = fromJS(defaultState); store = mockStore(state); const action$ = ActionsObservable.of( actions.submitForm(item) ); const expected = [ formsActions.submitFormDone('people'), formsActions.clearFormValues('people'), actions.addItemDone(item), ]; return epic(action$, store).reduce((acc, action) => { return acc.concat([action]); }, []).toPromise().then(received => { expect(received).toEqual(expected); }); });
export class InlineEditing { constructor() { let crudServiceBaseUrl = '//demos.telerik.com/kendo-ui/service'; this.datasource = new kendo.data.DataSource({ transport: { read: { url: crudServiceBaseUrl + '/Products', dataType: 'jsonp' }, update: { url: crudServiceBaseUrl + '/Products/Update', dataType: 'jsonp' }, destroy: { url: crudServiceBaseUrl + '/Products/Destroy', dataType: 'jsonp' }, create: { url: crudServiceBaseUrl + '/Products/Create', dataType: 'jsonp' }, parameterMap: function(options, operation) { if (operation !== 'read' && options.models) { return {models: kendo.stringify(options.models)}; } } }, batch: true, pageSize: 8, schema: { model: { id: 'ProductID', fields: { ProductID: { editable: false, nullable: true }, ProductName: { validation: { required: true } }, UnitPrice: { type: 'number', validation: { required: true, min: 1} }, Discontinued: { type: 'boolean' }, UnitsInStock: { type: 'number', validation: { min: 0, required: true } } } } } }); } }
// Karma configuration // Generated on Mon Jun 22 2015 15:35:14 GMT+0200 (SAST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'requirejs'], // list of files / patterns to load in the browser files: [ 'test-main.js', {pattern: 'src/**/*.js', included: false}, {pattern: 'test/**/*Spec.js', included: false} ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
(function (angular) { "use strict"; angular.module("mfl.downloads", [ "ui.router", "ui.bootstrap", "ui.bootstrap.tpls", "mfl.downloads.controllers", "mfl.downloads.routes", "mfl.facilities.wrapper" ]); })(window.angular);
function f () { try { throw 'a' } catch (err) {} } try { f() } catch (err) {}
"use strict"; angular.module('tcApp').factory('Auth', ['$http', '$q','Identity', 'UserResource',function($http, $q, Identity, UserResource){ return { authenticateUser: function(username, password) { var deferred = $q.defer(); $http.post('/login', {username:username, password:password}).then(function(res) { if(res.data.success){ var user = new UserResource(); angular.extend(user, res.data.user); Identity.currentUser = user; deferred.resolve(true); } else { deferred.resolve(false); } }); return deferred.promise; }, logoutUser: function(){ var deferred = $q.defer(); $http.post('/logout',{logout:true}).then(function() { Identity.currentUser = undefined; deferred.resolve(true); }); return deferred.promise; }, createUser: function(userData) { var newUser = new UserResource(userData); var deferred = $q.defer(); newUser.$save().then(function() { Identity.currentUser = newUser; deferred.resolve(true); }, function(res) { deferred.reject(res.data); }); return deferred.promise; } }; }]);
/* * grunt-phantomcss * https://github.com/micahgodbolt/grunt-phantomcss * * Copyright (c) 2013 Chris Gladd * Copyright (c) since 2014 Anselm Hannemann * Copyright (c) since 2015 Micah Godbolt * * Licensed under the MIT license. */ 'use-strict'; // Get node fileSystem module and define the separator module var fs = require('fs'); var s = fs.separator; var path = require('path'); // Parse arguments passed in from the grunt task var args = JSON.parse(phantom.args[0]); // Get viewport arguments (width | height) var viewportSize = { width: args.viewportSize[0], height: args.viewportSize[1] }; // Messages are sent to the parent by appending them to the tempfile var sendMessage = function() { fs.write(args.tempFile, JSON.stringify(Array.prototype.slice.call(arguments)) + '\n', 'a'); }; // Initialise CasperJs var phantomCSSPath = args.phantomCSSPath; phantom.casperPath = phantomCSSPath + s + 'CasperJs'; phantom.injectJs(phantom.casperPath + s + 'bin' + s + 'bootstrap.js'); var casper = require('casper').create({ viewportSize: viewportSize, logLevel: args.logLevel, verbose: true }); // Require and initialise PhantomCSS module var phantomcss = require(phantomCSSPath + s + 'phantomcss.js'); phantomcss.init({ screenshotRoot: args.screenshots, failedComparisonsRoot: args.failures, libraryRoot: phantomCSSPath, // Give absolute path, otherwise PhantomCSS fails mismatchTolerance: args.mismatchTolerance, // defaults to 0.05 onFail: function(test) { sendMessage('onFail', test); }, onPass: function(test) { sendMessage('onPass', test); }, onTimeout: function(test) { sendMessage('onTimeout', test); }, onComplete: function(allTests, noOfFails, noOfErrors) { sendMessage('onComplete', allTests, noOfFails, noOfErrors); }, fileNameGetter: function(root, filename) { var name = phantomcss.pathToTest + args.baselines + '/' + filename; if (fs.isFile(name + '.png')) { return name + '.diff.png'; } else { return name + '.png'; } }, }); casper.start(); // Run the test scenarios args.test.forEach(function(testSuite) { phantom.casperTest = true; phantom.rootUrl = args.rootUrl; casper.then(function() { phantomcss.pathToTest = path.dirname(testSuite) + '/'; }); require(testSuite); casper.then(function() { phantomcss.compareSession(); }) .then(function() { casper.test.done(); }); }); // End tests casper.run(function() { phantom.exit(); });
/*! * Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg) * * Copyright 2015 Francisco Gonzalez * Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE) */ (function($){ $.fn.easteregg = function(settings) { var _settings = $.extend({}, $.fn.easteregg.default_settings, settings); var _o_easteregg = new EasterEgg(_settings); return _o_easteregg; }; $.fn.easteregg.default_settings = { delay_time : 1000, eggsters : [ { keys : [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 66, 65], callback : null } ] }; function is_same_array(array1, array2) { return array1.lenght == array2.lenght && array1.every(function(element, index) { return element === array2[index]; }); } var EasterEgg = function(settings){ this._settings = settings; this._pressed_keys = []; this._timer; }; EasterEgg.VERSION = '1.0.0'; EasterEgg.prototype = { init : function() { var _self = this; $(document).on('keydown', function(event){ clearInterval(_self._timer); _self._timer = _self.getTimer(); _self._pressed_keys.push(event.keyCode); _self._settings.eggsters.forEach(function(eggster){ if (is_same_array(eggster.keys, _self._pressed_keys)) { _self.clearKeys(); if ($.type(eggster.callback) === 'function') { eggster.callback(); } } }); }); _self._timer = _self.getTimer(); }, setKonami : function(callback) { this._settings.eggsters[0].callback = callback; }, addEgg : function(keys, callback) { if (!($.type(keys) === 'array' || $.type(keys) === 'string') || keys.lenght == 0 || $.type(callback) !== 'function') { return false; } if ($.type(keys) === 'string') { var keys = keys.split(''); keys.forEach(function(element, index, array){ array[index] = element.toUpperCase().charCodeAt(); }); } this._settings.eggsters.push({keys:keys, callback:callback}); }, clearKeys : function() { this._pressed_keys = []; }, getTimer : function() { var _self = this; return setInterval(function(){ _self.clearKeys(); }, _self._settings.delay_time); }, }; })(jQuery);
/* * AppConstants * Each action has a corresponding type, which the reducer knows and picks up on. * To avoid weird typos between the reducer and the actions, we save them as * constants here. We prefix them with 'yourproject/YourComponent' so we avoid * reducers accidentally picking up actions they shouldn't. * * Follow this format: * export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT'; */ export const DEFAULT_LOCALE = 'en' export const SET_LOADING = 'fashion/App/SET_LOADING' export const TOGGLE_MENU = 'fashion/App/TOGGLE_MENU'
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import moment from 'moment'; // import { run } from '@ember/runloop'; module('Integration | Component | time-input', function (hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { this.testDate = moment(); this.timeUpdated = () => { const val = this.testDate; assert.equal( val.format('YYYY-MM-DD HH:mm'), moment().format('YYYY-MM-DD HH:mm') ); }; // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.set('myAction', function(val) { ... }); await render(hbs`<input type="text" id="other"/>`); await render( hbs`<TimeInput @currentDate={{this.testDate}} @onChangedTime={{this.timeUpdated}}/>` ); assert.dom(this.element).hasText(''); // run(() => document.getElementById('timeInput').focus()); // Blur // run(() => document.getElementById('other').focus()); }); });
Package.describe({ name: 'numtel:pg-server', version: '0.0.2', summary: 'Run PostgreSQL server inside your Meteor app', git: 'https://github.com/numtel/meteor-pg-server', documentation: 'README.md' }); function determinePlatformNpmPackage() { switch(process.platform + '_' + process.arch) { case 'linux_x64': return 'pg-server-9.4-linux-x64'; case 'linux_ia32': return 'pg-server-9.4-linux-i386'; case 'darwin_x64': return 'pg-server-9.4-osx-x64'; default: return null; } } // Force Meteor to recognize that this package has binary deps // bcrypt is an npm package that // has different binaries for differnet architectures. Npm.depends({ bcrypt: '0.8.2' }); var npmPkg = determinePlatformNpmPackage(); if(npmPkg === null) { console.error('ERROR: Platform is not supported by numtel:pg-server!'); console.error(' Supports only Linux (32 and 64 bit) and OSX (64 bit)'); } else { var depend = {}; // platform dependent pg-server-xxx package depend[npmPkg] = '9.4.4'; Package.registerBuildPlugin({ name: 'pgServer', use: [ 'underscore@1.0.3' ], sources: [ 'plugin/pgServer.js' ], npmDependencies: depend }); } Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('numtel:pg-server'); api.use('numtel:pg@0.0.3'); api.addFiles('test.pg.json', 'server'); api.addFiles('pg-server-tests.js', 'server'); });
import {NamespaceClass, ResourceClass, Namespace, URI, Class, Property, type, Resource, Vocab, Context, Prefix} from '../src/index' import expect from 'expect' import {Map, Set, List} from 'immutable' describe('URI', () => { it('should be a ResourceClass instance', () => { expect(URI('test')).toBeA(ResourceClass) }) it('should create the correct map', () => { expect( URI('test').toJSON() ).toEqual( { '@id': 'test' } ) }) }) describe('Vocab', () => { it('should be a ResourceClass instance', () => { let ns1 = Namespace( Class('Class1') ) expect(Vocab(ns1)).toBeA(ResourceClass) }) it('should create the correct map', () => { const ns1 = Namespace( Class('Class1'), Property('prop1') ) const ns2 = Namespace( Class('Class2'), Property('prop2') ) expect( Vocab(ns1, ns2).toJSON() ).toEqual( { '@graph': [ { "@id": "Class1", "@type": ["rdfs:Class"] }, { "@id": "prop1", "@type": ["rdfs:Property"] }, { "@id": "Class2", "@type": ["rdfs:Class"] }, { "@id": "prop2", "@type": ["rdfs:Property"] } ] } ) }) it('should support property supclassing', function() { let hydra = Namespace( Class('Link') ) var search = Property('search', hydra.Link()) expect( search.toJSON() ).toEqual( { '@id': 'search', '@type': ['rdfs:Property', 'Link'] } ) }) }) describe('type', () => { it('should be a ResourceClass instance', () => { expect(type('test')).toBeA(ResourceClass) }) it('should create a type set', () => { expect( type('test').toJSON() ).toEqual( { '@type': ['test'] } ) }) }) describe('Class', () => { it('should be a ResourceClass instance', () => { expect(Class('TestClass')).toBeA(ResourceClass) }) it('should create a Class resource', () => { expect( Class('TestClass').toJSON() ).toEqual( { '@id': 'TestClass', '@type': ['rdfs:Class'] } ) }) }) describe('Property', () => { it('should be a ResourceClass instance', () => { expect(Property('testProperty')).toBeA(ResourceClass) }) it('should create a Property resource', () => { expect( Property('testProperty').toJSON() ).toEqual( { '@id': 'testProperty', '@type': ['rdfs:Property'] } ) }) it('should allow additional properties', () => { expect( Property('testProperty').toJSON() ).toEqual( { '@id': 'testProperty', '@type': ['rdfs:Property'], } ) }) }) describe('Resource', () => { it('should be a ResourceClass instance', () => { expect(Resource(URI('/'))).toBeA(ResourceClass) }) it('should generate a resource correctly', () => { let res = Resource( URI('/'), type('Type1'), type('Type2') ) expect(res.toJSON()) .toEqual({ '@id': '/', '@type': ['Type1', 'Type2'] }) }) }) describe('Namespace', () => { it('should be a NamespaceClass instance', () => { expect(Namespace(Class('Class1'))).toBeA(NamespaceClass) }) it('should create a namespace correctly', () => { const ns = Namespace( Class('Class1'), Property('prop1') ) expect( ns.Class1(URI('/')).toJSON() ).toEqual( { '@id': '/', '@type': ['Class1'] } ) expect( ns.prop1('test').toJSON() ).toEqual( { 'prop1': 'test' } ) }) }) describe('Prefix', () => { it('should be a ResourceClass instance', () => { const ns = Namespace( Class('Class1') ) expect(Prefix('ns', 'http://example.com/', ns)).toBeA(ResourceClass) }) it('should generate the context correctly', () => { const ns = Namespace( Class('Class1'), Property('prop1') ) const prefix = Prefix( 'vocab', 'http://example.com/vocab#', ns ) expect( prefix.toJSON() ).toEqual({ '@context': { 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'vocab': 'http://example.com/vocab#', 'Class1': 'vocab:Class1', 'prop1': 'vocab:prop1' } }) }) it('should support context overrides', () => { const ns = Namespace( Property('member'), Property('up') ) const prefix = Prefix( 'vocab', 'http://example.com/vocab#', ns, { 'member': {'@container': '@list'}, 'up': {'@type': '@id'} } ) expect( prefix.toJSON() ).toEqual( { '@context': { 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'vocab': 'http://example.com/vocab#', 'member': {'@id': 'vocab:member', '@container': '@list'}, 'up': {'@id': 'vocab:up', '@type': '@id'} } } ) }) })
// ./models/user.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ userName: String, email:String, passwordHash: String, passwordSalt: String, createdOn : Date, createdBy:{type: Schema.Types.ObjectId, ref: 'user'}, updatedOn:Date, updatedBy:{type: Schema.Types.ObjectId, ref: 'userprofile'}, deletedOn:Boolean, deletedBy:{type: Schema.Types.ObjectId, ref: 'userprofile'} }); var User=mongoose.model('user', UserSchema); module.exports = User; UserSchema.pre('save', function(next) { // get the current date var currentDate = new Date(); // change the updated_at field to current date this.createdOn = currentDate; // if created_at doesn't exist, add to that field if (!this.createdDate) this.createdOn = currentDate; next(); });
/* This module allows to create Cubemaps and store them as resources */ var CubemapTools = { name: "CubemapTools", default_resolution: 256, current_cubemap: null, preview_in_viewport: false, init: function() { LiteGUI.menubar.add("Actions/Cubemap tools", { callback: function() { CubemapTools.showDialog(); }}); }, showDialog: function() { var dialog = null; if(this.dialog) { this.dialog.highlight(); return; } //RenderModule.canvas_manager.addWidget( CubemapTools ); var dialog = new LiteGUI.Dialog( { id: "dialog_cubemap", title:"Cubemap generator", parent:"#visor", close: true, minimize: true, width: 360, min_height: 160, scroll: false, draggable: true}); dialog.show('fade'); dialog.setPosition(100,100); dialog.on_close = function(){ CubemapTools.dialog = null; CubemapTools.preview_in_viewport = false; RenderModule._overwrite_render_callback = null; LS.GlobalScene.requestFrame(); } this.dialog = dialog; LiteGUI.createDropArea( dialog.content, enableDragDropCubemapImages ); var name = "cubemap_" + (Math.random() * 1000).toFixed(0); var resolution = CubemapTools.default_resolution; var loaded_resolution = CubemapTools.default_resolution; var center = "camera eye"; var result = "cubemap"; var cubemap_modes = { "Cross Left": "CUBECROSSL", "Vertical": "CUBEVERT", "Polar":"CUBEPOLAR" }; var mode = "CUBECROSSL"; var layers = 0x3; var export_format = "CUBECROSSL"; var url = ""; var original_file = null; var cubemap_options = { keep_image: true, is_cross: 1 }; var widgets = new LiteGUI.Inspector( { id: "cubemapgen_widgets", name_width: 100 }); dialog.content.appendChild( widgets.root ); widgets.on_refresh = refresh; var info_widget = null; function refresh() { widgets.clear(); //widgets.addTitle("Current Cubemap"); widgets.addString("Name", CubemapTools.current_cubemap ? CubemapTools.current_cubemap.filename : "Not selected", { disabled: true }); if( CubemapTools.current_cubemap ) { widgets.widgets_per_row = 1; widgets.addCombo("Resolution", CubemapTools.current_cubemap.width, { values: [1,2,4,8,16,32,64,128,256,512,1024,2048], callback: function(v) { loaded_resolution = v; }}); widgets.widgets_per_row = 1; widgets.addButtons("Actions", ["Blur","Resize","Clone","Irradiance"], { callback: function(v) { var cubemap = CubemapTools.current_cubemap; if(!cubemap) return; if(v == "Blur") { cubemap.applyBlur( 1,1,1 ); LS.RM.resourceModified( cubemap ); } else if(v == "Resize") { var copy_cubemap = new GL.Texture( loaded_resolution, loaded_resolution, cubemap.getProperties() ); cubemap.copyTo( copy_cubemap ); copy_cubemap.filename = cubemap.filename; copy_cubemap.fullpath = cubemap.fullpath; copy_cubemap.remotepath = cubemap.remotepath; CubemapTools.current_cubemap = copy_cubemap; LS.RM.registerResource( copy_cubemap.fullpath || copy_cubemap.filename, copy_cubemap ); } else if(v == "Clone") { var copy_cubemap = cubemap.clone(); copy_cubemap.filename = "copy_" + LS.RM.getFilename( cubemap.filename ); CubemapTools.current_cubemap = copy_cubemap; LS.RM.registerResource( copy_cubemap.filename, copy_cubemap ); widgets.refresh(); } else if(v == "Irradiance") { var fullpath = cubemap.fullpath || cubemap.filename; var extension = LS.RM.getExtension( fullpath ); var basename = LS.RM.getBasename( fullpath ); var folder = LS.RM.getFolder( fullpath ); cubemap = CubemapTools.generateIrradianceFromCubemap( cubemap ); cubemap.filename = "IR_" + basename + "." + extension; //cubemap.fullpath = folder + "/" + fullpath; CubemapTools.current_cubemap = cubemap; LS.RM.registerResource( cubemap.filename, cubemap ); widgets.refresh(); } LS.GlobalScene.refresh(); }}); widgets.addButton("Helper", "Set as Environment", { callback: function(v) { var cubemap = CubemapTools.current_cubemap; if(!cubemap) return; if(!LS.GlobalScene.info) LS.GlobalScene.root.addComponent( LS.Components.GlobalInfo() ); LS.GlobalScene.info.textures.environment = cubemap.fullpath || cubemap.filename; if( !LS.GlobalScene.root.getComponent( LS.Components.Skybox ) ) LS.GlobalScene.root.addComponent( new LS.Components.Skybox() ); LS.GlobalScene.refresh(); EditorModule.refreshAttributes(); }}); widgets.addCheckbox("Preview in viewport", CubemapTools.preview_in_viewport, function(v){ CubemapTools.preview_in_viewport = v; RenderModule._overwrite_render_callback = v ? CubemapTools.render.bind(CubemapTools) : null; LS.GlobalScene.requestFrame(); }); } else { CubemapTools.preview_in_viewport = false; RenderModule._overwrite_render_callback = null; } widgets.addSection("Generate from Scene"); widgets.addString("Name", name, { callback: function(v) { name = v; }}); widgets.addCombo("Resolution", CubemapTools.default_resolution, { values: [32,64,128,256,512,1024], callback: function(v) { resolution = v; }}); widgets.addCombo("Center", center , { values: ["camera eye","camera target","node","mesh"], callback: function(v) { center = v; }}); widgets.addLayers("Layers", layers , { callback: function(v) { layers = v; }}); widgets.addCombo("Mode", mode , { values: cubemap_modes, callback: function(v) { mode = v; }}); widgets.addButton("Preview", "Open Window", { callback: function(v) { var position = computePosition(); var image = CubemapTools.generateCubemapFromScene( position, { layers: layers, size: resolution, mode: mode } ); if(!image) return; var new_window = window.open("","Visualizer","width="+(image.width + 20)+", height="+(image.height)); new_window.document.body.style.margin = 0; new_window.document.body.style.padding = 0; new_window.document.body.style.backgroundColor = "black"; new_window.document.body.appendChild( image ); LS.GlobalScene.refresh(); }}); /* widgets.addCombo("Result", "cubemap", { values: ["cubemap","spherical","image x6"], callback: function(v) { result = v; }}); */ widgets.addSeparator(); widgets.addButton(null, "Create cubemap", { callback: function() { var position = computePosition(); var image = CubemapTools.generateCubemapFromScene( position, { layers: layers, size: resolution, mode: mode } ); if(!image) return; /* if(keep) { image.link = image.toDataURL('image/jpg'); LS.ResourcesManager.registerResource( name + "_intermediate.png", image ); } */ var texture = GL.Texture.cubemapFromImage( image, mode == "CUBECROSSL" ? { is_cross: 1 } : null ); texture.image = image; LS.ResourcesManager.registerResource( name + "_" + mode + ".png", texture ); LiteGUI.alert("Cubemap created with name: " + name + ".png"); CubemapTools.current_cubemap = texture; widgets.refresh(); }}); widgets.addSection("Load", { collapsed: false }); widgets.addCombo("Input Mode",mode, { values: cubemap_modes, callback: function(v){ mode = v; if(v == "CUBECROSSL") cubemap_options = { keep_image: true, is_cross: 1 }; else if(v == "CUBEPOLAR") cubemap_options = { keep_image: true, is_polar: 1 }; else cubemap_options = { keep_image: true }; }}); widgets.addString("URL","", { callback: function(v){ url = v; original_file = null; }}); widgets.addFile("From File", null, { generate_url: true, callback: function(file_info){ if(!file_info) { url = original_file = null; return; } url = file_info.url; original_file = file_info.file; }}); widgets.addTexture("From Memory/Server","", { skip_load: true, callback: function(name){ url = name; original_file = null; loadCubemap(); }}); info_widget = widgets.addInfo(null, "" ); widgets.addButton( null, "Load cubemap", { callback: loadCubemap }); widgets.addSeparator(); widgets.addInfo(null,"You can also drag a set of six images containing every side of a cubemap where the files contains the string posx,posy,posz,negx,negy,negz depending on the side"); widgets.addString("Ouput name", name, { callback: function(v) { dialog.cubemap_name = v; }}); widgets.addCombo("Output size", CubemapTools.default_resolution, { values: [0,32,64,128,256,512,1024], callback: function(v) { dialog.cubemap_resolution = v; }}); widgets.addSection("Export", { collapsed: false }); widgets.addCombo("Format", export_format, { values: cubemap_modes, callback: function(v) { export_format = v; }}); widgets.addButton( null, "Download cubemap", { callback: downloadCubemap }); }//refresh widgets.refresh(); function loadCubemap() { if(!name) { LiteGUI.alert("No Cubemap name specified"); return; } if(!url) { LiteGUI.alert("No Cubemap url specified"); return; } //is a texture in memory var res = LS.ResourcesManager.getResource( url ); if(res) { if( res.texture_type == gl.TEXTURE_CUBE_MAP ) { CubemapTools.current_cubemap = res; widgets.refresh(); return; } if(!res.img) return console.log("Texture doesnt have the original image attached"); var texture = GL.Texture.cubemapFromImage( res.img, cubemap_options ); processResult( texture ); } //is an external filename info_widget.setValue("Loading..."); var texture = GL.Texture.cubemapFromURL( LS.ResourcesManager.getFullURL( url ), cubemap_options , function(tex){ if(!tex) return LiteGUI.alert("Error creating the cubemap, check the size. Only 1x6 (vertical) or 6x3 (cross) formats supported."); processResult( tex ); CubemapTools.current_cubemap = tex; widgets.refresh(); }); } function processResult( texture ) { if(!texture) { LiteGUI.alert("Texture is not CUBEMAP, check that the name has CUBECROSSL in it to specify the cubemap type."); return; } var fullname = name + "_" + mode + ".png"; if(texture.fullpath) { name = fullname = texture.fullpath; } else LS.ResourcesManager.registerResource( fullname, texture ); if(original_file) texture._original_file = original_file; else LS.ResourcesManager.getURLasFile( url, function(file) { texture._original_file = file; }); //keep the original file in case we want to save it info_widget.setValue("Cubemap created with name: " + fullname); } function computePosition() { var camera = RenderModule.selected_camera; var position = vec3.create(); var node = SelectionModule.getSelectedNode(); if(center == "camera eye") position = camera.getEye(); else if(center == "camera target") position = camera.getCenter(); else if(center == "node" && node && node.transform ) position = node.transform.getGlobalPosition(); else if(center == "mesh" && node && node._instances && node._instances.length ) { var ri = node._instances[0]; position = BBox.getCenter( ri.aabb ); } return position; } function enableDragDropCubemapImages( e, dialog ) { console.log(e.dataTransfer); var path = e.dataTransfer.getData("res-fullpath"); if( path ) { var res = LS.RM.getResource(path); } else if( e.dataTransfer.files.length ) { if(e.dataTransfer.files.length != 6) { LiteGUI.alert("You need six images to create a cubemap"); return; } var name = dialog.cubemap_name; var size = dialog.cubemap_resolution; that.generateCubemapFromFiles( e.dataTransfer.files, null, { name: name, size: size } ); } e.preventDefault(); e.stopPropagation(); } function downloadCubemap() { var cubemap = CubemapTools.current_cubemap; if(!cubemap) return; var data = null; if(export_format == "CUBEPOLAR") { var polar_texture = CubemapTools.convertCubemapToPolar(cubemap); data = polar_texture.toBinary(); } else if(export_format == "CUBEVERT") { var image = CubemapTools.convertCubemapToVerticalImage(cubemap); data = image.toBlob(function(v){ LiteGUI.downloadFile("cubemap.png", v ); }); } else //if(export_format == "CUBECROSSL") { data = cubemap.toBinary(); } if(data) LiteGUI.downloadFile("cubemap.png", data ); } }, //generate cubemap from current view generateCubemapFromScene: function( position, options ) { options = options || {}; var size = options.size || 256; var mode = options.mode || "vertical"; var position = position || RenderModule.selected_camera.getEye(); var canvas = null; if(mode == "CUBEVERT") canvas = createCanvas( size, size * 6 ); else if(mode == "CUBECROSSL") canvas = createCanvas( size * 4, size * 3 ); else { console.error("Unknown mode: " + mode); return; } var ctx = canvas.getContext("2d"); var cams = LS.Camera.cubemap_camera_parameters; var render_settings = RenderModule.render_settings; render_settings.skip_viewport = true; //avoids overwriting the viewport and aspect render_settings.layers = options.layers !== undefined ? options.layers : 0xFF; var bg_color = LS.GlobalScene.root.camera ? LS.GlobalScene.root.camera.background_color : [0,0,0,1]; var near = RenderModule.selected_camera.near; var far = RenderModule.selected_camera.far; gl.viewport( 0, 0, size, size ); for(var i = 0; i < 6; ++i) { //gl.clearColor( Math.abs(cams[i].dir[0]), Math.abs(cams[i].dir[1]), Math.abs(cams[i].dir[2]), 1.0); gl.clearColor( bg_color[0], bg_color[1], bg_color[2], bg_color[3]); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var face = cams[i]; var cam_info = { layers: 0xFF, eye: position, center: [ position[0] + face.dir[0], position[1] + face.dir[1], position[2] + face.dir[2]], up: face.up, fov: 90, aspect: 1.0, near: near, far: far }; var camera = new LS.Camera( cam_info ); //LS.Renderer.renderFrame( camera, render_settings ); LS.Renderer.enableCamera( camera, render_settings, true ); LS.Renderer.renderInstances( render_settings ); var frame = gl.snapshot( 0, 0, size, size, true ); //ctx.drawImage( frame, 0, gl.canvas.height - resolution, resolution, resolution, 0,resolution*i, resolution, resolution ); var face = cams[i]; if(mode == "CUBEVERT") ctx.drawImage( frame, 0, 0, size, size, 0, size*i, size, size ); else if(mode == "CUBECROSSL") ctx.drawImage( frame, 0, 0, size, size, face.crossx * size, face.crossy * size, size, size ); else console.log("Unknown mode: " + mode ); } render_settings.skip_viewport = false; return canvas; }, generateIrradianceFromCubemap: function( cubemap ) { //downscale var copy_cubemap = new GL.Texture( 64, 64, cubemap.getProperties() ); cubemap.copyTo( copy_cubemap ); cubemap = copy_cubemap; //blur for(var i = 0; i < 8; ++i) cubemap.applyBlur( i,i,1 ); //downscale again var copy_cubemap = new GL.Texture( 8, 8, cubemap.getProperties() ); cubemap.copyTo( copy_cubemap ); cubemap = copy_cubemap; //blur again for(var i = 0; i < 6; ++i) cubemap.applyBlur( i, i, 1 ); return cubemap; }, convertCubemapToPolar: function( cubemap_texture, size, target_texture, keep_type ) { return GL.Texture.cubemapToTexture2D( cubemap_texture, size, target_texture, keep_type, 0 ); }, convertCubemapToVerticalImage: function( cubemap_texture ) { var pixels = cubemap_texture.getCubemapPixels(); var final_pixels = new Uint8Array( cubemap_texture.width * cubemap_texture.height * 6 * 4 ); var pos = 0; for(var i = 0; i < 6; ++i) { final_pixels.set(pixels[i],pos); pos += pixels[i].length; } var canvas = createCanvas(cubemap_texture.width, cubemap_texture.height*6 ); var ctx = canvas.getContext("2d"); var data = ctx.getImageData(0,0,canvas.width,canvas.height); data.data.set(final_pixels); ctx.putImageData(data,0,0); return canvas; }, generateCubemapFromFiles: function( files, callback, options ) { options = options || {}; var face_names = ["posx","posy","posz","negx","negy","negz"]; var faces = {}; var imgs = {}; var size = 0; var num_images_loaded = 0; var imgs_urls = {}; var alert_dialog = LiteGUI.alert("Generating cubemap..."); //read files for(var i = 0; i < files.length; i++) { var file = files[i]; var name = file.name.toLowerCase(); var found = false; for(var j in face_names) { var face_name = face_names[j]; if( name.indexOf(face_name) == -1 ) continue; found = true; faces[ face_name ] = file; face_names.splice(j,1); console.log( "Reading " + face_name + " " + file.size ); var objectURL = URL.createObjectURL( file ); imgs_urls[ face_name ] = objectURL; num_images_loaded++; if(num_images_loaded == 6) inner_load(); } if(!found) { alert_dialog.close(); LiteGUI.alert("Error: Cubemap image doesnt have a valid name: " + name); return; } } if(face_names.length) { alert_dialog.close(); LiteGUI.alert("Files must have names as posx,negx, etc to specify the face"); return; } //load images function inner_load() { var face_name = null; var img_url = null; for(var i in imgs_urls) { img_url = imgs_urls[i]; face_name = i; URL.revokeObjectURL( imgs_urls ); delete imgs_urls[i]; break; } if(!face_name) { //we have all the images console.log("Compositing images"); inner_create(); return; } console.log("Loading " + face_name); var img = new Image(); img.face_name = face_name; img.src = img_url; img.onload = function() { console.log("Loaded " + this.face_name); if(!size) size = img.width; if(img.width != img.height || size != img.width) { alert_dialog.close(); LiteGUI.alert("Error: Cubemap images must be square and have the same resolution"); return; } imgs[ this.face_name ] = img; inner_load(); } img.onerror = function(err){ console.error(err); } } //generate the cross image function inner_create() { var size = options.size || 512; //create canvas var canvas = createCanvas(size*4,size*3); var ctx = canvas.getContext("2d"); ctx.fillStyle = "black"; ctx.fillRect(0,0, canvas.width, canvas.height); ctx.drawImage( imgs["negx"], 0, size, size,size ); ctx.drawImage( imgs["posz"], size, size, size,size ); ctx.drawImage( imgs["posx"], size*2, size, size,size ); ctx.drawImage( imgs["negz"], size*3, size, size,size ); ctx.drawImage( imgs["posy"], size, 0, size,size ); ctx.drawImage( imgs["negy"], size, size*2, size,size ); console.log("Converting to dataURL..."); var img_data = canvas.toDataURL("image/png", 0.9); console.log("Generating file from dataURL..."); var cubemap_file = dataURItoBlob(img_data); var objectURL = URL.createObjectURL( cubemap_file ); var img = new Image(); img.src = objectURL; img.filename = (options.name || ("cubemap_"+ (Math.floor(Math.random()*1000))) ) + "_CUBECROSSL.png"; img.onload = function(){ //document.body.appendChild(img); //debug console.log("Cubemap registered"); var texture = new GL.Texture.cubemapFromImage(this, { is_cross: 1 } ); texture._original_file = cubemap_file; LS.ResourcesManager.registerResource( this.filename, texture ); } alert_dialog.close(); LiteGUI.alert("Cubemap created!"); if(callback) callback(texture); } }, render: function( camera ) { //disabled if(!this.dialog || !this.current_cubemap || !this.preview_in_viewport) return false; if(!RenderModule.frame_updated || this.inplayer ) return false; var scene = this._preview_scene; if(!this._preview_scene) { scene = this._preview_scene = new LS.Scene(); scene.root.addComponent( new LS.Components.Skybox() ); scene.info.ambient_color = [1,1,1]; scene._sphere = new LS.SceneNode(); scene._sphere.addComponent( new LS.Components.GeometricPrimitive({ geometry: LS.Components.GeometricPrimitive.SPHERE, subdivisions: 20 }) ); scene.root.addChild( scene._sphere ); scene._sphere.material = new LS.StandardMaterial(); scene._sphere.material.reflection_factor = 1; scene._sphere.material.reflection_fresnel = 0; var render_settings = new LS.RenderSettings(); //render_settings.lights_disabled = true; this.preview_render_settings = render_settings; } scene.root.camera.configure( camera.serialize() ); LS.RM.textures[ ":cubemap" ] = this.current_cubemap; scene.info.textures.environment = ":cubemap"; scene.info.textures.irradiance = ":cubemap"; scene._sphere.transform.position = camera.getCenter(); LS.Renderer.render( scene, this.preview_render_settings ); return true; } } CORE.registerModule( CubemapTools );
/*! * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file. */ import {WebexPlugin} from '@webex/webex-core'; const Calendar = WebexPlugin.extend({ namespace: 'Calendar', /** * Decrypts an encrypted incoming calendar event * @param {Object} event * @returns {Promise} Resolves with a decrypted calendar event */ processMeetingEvent(event) { return this.webex.transform('inbound', event) .then(() => event); }, /** * Retrieves a collection of meetings based on the request parameters * @param {Object} options * @param {Date} options.fromDate the start of the time range * @param {Date} options.toDate the end of the time range * @returns {Promise} Resolves with an array of meetings */ list(options) { options = options || {}; return this.webex.request({ method: 'GET', service: 'calendar', resource: 'calendarEvents', qs: options }) .then((res) => res.body.items); } }); export default Calendar;
var fs = require('fs') net = require('net') child = require('child_process') spawn = child.spawn exec = child.exec var robot_ip = '20.10.10.115', robot_name = 'raspberry pi', robot_port = 5002 var server_ip = '192.168.2.2', server_name = 'drewpi', server_port = 5001 var cmd_path = __dirname + '/commands.txt' var motorPath = __dirname + '/text_test_1.py' fs.watch(cmd_path, {persistent:true}, function(event,fn) { if(event=='change') { var instance = spawn('python', [motorPath]) } }) var server = net.createServer(function(socket) { console.log('A client has connected.\n') socket.on('data', function(data) { console.log('I am receiving data\n') fs.writeFile(cmd_path, data.toString(), function(err) { if(err) { console.log(err) } }) }) socket.on('end', function() { console.log('disconnected') }) }); server.listen(robot_port, robot_ip, function(){ address = server.address() console.log('Server open at: %j\n', address) })
$( document ).ready(function() { "use strict"; firebase.auth().onAuthStateChanged(firebaseUser =>{ if (firebaseUser){ var rootRef = firebase.database().ref().child("users").child(firebaseUser.uid).child("movies").child("seen"); rootRef.on("child_added", snap =>{ var movieId = snap.child("movieId").val(); var moviename = snap.child("moviename").val(); var poster = snap.child("poster").val(); var posterPre = "https://image.tmdb.org/t/p/w500"; $("#seenList").append("<div class='col-md-2 col-xs-6'><div class='movieVast'><a href='detail'><img class='posterSize movieId' alt='"+movieId+"' src='"+poster + "'/><p class='textVast'>"+ moviename +"</p></a></div></div>"); $(".col-md-2:has(img[alt=null])").remove(); //wanneer er geklikt wordt op een .movieId --> sessionstorage van alt-waarde $(".movieId").on("click", function(){ var movieId = $(this).attr("alt"); sessionStorage.setItem("movieId", movieId); }); }); } }); });
'use strict'; /* * Defining the Package */ var Module = require('meanio').Module; var Players = new Module('players'); /* * All MEAN packages require registration * Dependency injection is used to define required modules */ Players.register(function(app, auth, database) { //We enable routing. By default the Package Object is passed to the routes Players.routes(app, auth, database); Players.menus.add({ title: 'Players', link: 'players page', menu: 'main' }); Players.aggregateAsset('css', 'players.css'); /** //Uncomment to use. Requires meanio@0.3.7 or above // Save settings with callback // Use this for saving data from administration pages Players.settings({ 'someSetting': 'some value' }, function(err, settings) { //you now have the settings object }); // Another save settings example this time with no callback // This writes over the last settings. Players.settings({ 'anotherSettings': 'some value' }); // Get settings. Retrieves latest saved settigns Players.settings(function(err, settings) { //you now have the settings object }); */ return Players; });
require("coffee-script"); require("hubiquitus").start("topology.json");
/** * @author mr.doob / http://mrdoob.com/ */ THREE.DirectionalLight = function ( hex, intensity ) { THREE.Light.call( this, hex ); this.position = new THREE.Vector3( 0, 1, 0 ); this.intensity = intensity || 1; }; THREE.DirectionalLight.prototype = new THREE.Light(); THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
var querstring = require('querystring'); var obj = querstring.parse('username=stark&age=18&hobby=lanqiu'); console.log(obj); // { username: 'stark', age: '18', hobby: 'lanqiu' }
import { withRouter } from 'react-router'; import Component from './ndc-overview-component'; export default withRouter(Component);
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colordialog', 'tt', { clear: 'Бушату', highlight: 'Билгеләү', options: 'Төс көйләүләре', selected: 'Сайланган төсләр', title: 'Төс сайлау' } );
/*! * DevExtreme Web * Version: 15.1.7 * Build date: Sep 22, 2015 * * Copyright (c) 2012 - 2015 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ Globalize.addCultureInfo("ru", {messages: { Yes: "Да", No: "Нет", Cancel: "Отмена", Clear: "Очистить", Done: "Готово", Loading: "Загрузка...", Select: "Выбрать...", Search: "Поиск", Back: "Назад", OK: "OK", "dxCollectionWidget-noDataText": "Нет данных для отображения", "validation-required": "Поле необходимо заполнить", "validation-required-formatted": "Необходимо заполнить: {0}", "validation-numeric": "Значение должно быть числом", "validation-numeric-formatted": "Значение поля {0} должно быть числом", "validation-range": "Значение поля не входит в диапазон", "validation-range-formatted": "Значение поля {0} не входит в диапазон", "validation-stringLength": "Неверная длина значения в поле", "validation-stringLength-formatted": "Неверная длина значения в поле {0}", "validation-custom": "Недопустимое значение", "validation-custom-formatted": "Недопустимое значение: {0}", "validation-compare": "Значения полей не соответствуют друг другу.", "validation-compare-formatted": "Значение поля {0} не соответствует", "validation-pattern": "Значение не соответствует шаблону", "validation-pattern-formatted": "Значение поля {0} не соответствует шаблону", "validation-email": "Недопустимое значение email", "validation-email-formatted": "Недопустимое значениe {0}", "validation-mask": "Недопустимое значение" }}); Globalize.addCultureInfo("ru", {messages: { "dxLookup-searchPlaceholder": "Минимальное количество символов: {0}", "dxList-pullingDownText": "Потяните, чтобы обновить...", "dxList-pulledDownText": "Отпустите, чтобы обновить...", "dxList-refreshingText": "Обновление...", "dxList-pageLoadingText": "Загрузка...", "dxList-nextButtonText": "Далее", "dxList-selectAll": "Выбрать все", "dxListEditDecorator-delete": "Удалить", "dxListEditDecorator-more": "Еще", "dxScrollView-pullingDownText": "Потяните, чтобы обновить...", "dxScrollView-pulledDownText": "Отпустите, чтобы обновить...", "dxScrollView-refreshingText": "Обновление...", "dxScrollView-reachBottomText": "Загрузка...", "dxDateBox-simulatedDataPickerTitleTime": "Выберите время", "dxDateBox-simulatedDataPickerTitleDate": "Выберите дату", "dxDateBox-simulatedDataPickerTitleDateTime": "Выберите дату и время", "dxDateBox-validation-datetime": "Значение должно быть датой/временем", "dxFileUploader-selectFile": "Выберите файл", "dxFileUploader-dropFile": "или Перетащите файл сюда", "dxFileUploader-bytes": "байт", "dxFileUploader-kb": "кБ", "dxFileUploader-Mb": "МБ", "dxFileUploader-Gb": "ГБ", "dxFileUploader-upload": "Загрузить", "dxFileUploader-uploaded": "Загружено", "dxFileUploader-readyToUpload": "Готово к загрузке", "dxFileUploader-uploadFailedMessage": "Загрузка не удалась", "dxRangeSlider-ariaFrom": "От {0}", "dxRangeSlider-ariaTill": "До {0}", "dxSwitch-onText": "ВКЛ", "dxSwitch-offText": "ВЫКЛ" }}); Globalize.addCultureInfo("ru", {messages: { "dxDataGrid-columnChooserTitle": "Выбор столбцов", "dxDataGrid-columnChooserEmptyText": "Перетащите столбец сюда, чтобы скрыть его", "dxDataGrid-groupContinuesMessage": "Продолжение на следующей странице", "dxDataGrid-groupContinuedMessage": "Продолжение с предыдущей страницы", "dxDataGrid-editingEditRow": "Редактировать", "dxDataGrid-editingSaveRowChanges": "Сохранить", "dxDataGrid-editingCancelRowChanges": "Отменить", "dxDataGrid-editingDeleteRow": "Удалить", "dxDataGrid-editingUndeleteRow": "Восстановить", "dxDataGrid-editingConfirmDeleteMessage": "Вы уверены, что хотите удалить эту запись?", "dxDataGrid-validationCancelChanges": "Отменить изменения", "dxDataGrid-editingConfirmDeleteTitle": "", "dxDataGrid-groupPanelEmptyText": "Перетащите столбец сюда, чтобы сгруппировать по нему", "dxDataGrid-noDataText": "Нет данных", "dxDataGrid-searchPanelPlaceholder": "Искать...", "dxDataGrid-filterRowShowAllText": "(Все)", "dxDataGrid-filterRowResetOperationText": "Сбросить", "dxDataGrid-filterRowOperationEquals": "Равно", "dxDataGrid-filterRowOperationNotEquals": "Не равно", "dxDataGrid-filterRowOperationLess": "Меньше", "dxDataGrid-filterRowOperationLessOrEquals": "Меньше или равно", "dxDataGrid-filterRowOperationGreater": "Больше", "dxDataGrid-filterRowOperationGreaterOrEquals": "Больше или равно", "dxDataGrid-filterRowOperationStartsWith": "Начинается с", "dxDataGrid-filterRowOperationContains": "Содержит", "dxDataGrid-filterRowOperationNotContains": "Не содержит", "dxDataGrid-filterRowOperationEndsWith": "Заканчивается на", "dxDataGrid-applyFilterText": "Применить фильтр", "dxDataGrid-trueText": "Да", "dxDataGrid-falseText": "Нет", "dxDataGrid-sortingAscendingText": "Сортировать по возрастанию", "dxDataGrid-sortingDescendingText": "Сортировать по убыванию", "dxDataGrid-sortingClearText": "Сбросить сортировку", "dxDataGrid-editingSaveAllChanges": "Сохранить изменения", "dxDataGrid-editingCancelAllChanges": "Отменить изменения", "dxDataGrid-editingAddRow": "Добавить строку", "dxDataGrid-summaryMin": "Мин: {0}", "dxDataGrid-summaryMinOtherColumn": "Мин по {1} : {0}", "dxDataGrid-summaryMax": "Макс: {0}", "dxDataGrid-summaryMaxOtherColumn": "Макс по {1} : {0}", "dxDataGrid-summaryAvg": "Срзнач: {0}", "dxDataGrid-summaryAvgOtherColumn": "Срзнач по {1} : {0}", "dxDataGrid-summarySum": "Сумм: {0}", "dxDataGrid-summarySumOtherColumn": "Сумм по {1} : {0}", "dxDataGrid-summaryCount": "Кол-во: {0}", "dxDataGrid-columnFixingFix": "Закрепить", "dxDataGrid-columnFixingUnfix": "Открепить", "dxDataGrid-columnFixingLeftPosition": "Налево", "dxDataGrid-columnFixingRightPosition": "Направо", "dxDataGrid-exportTo": "Экспортировать", "dxDataGrid-exportToExcel": "Экспортировать в Excel файл", "dxDataGrid-excelFormat": "Excel файл", "dxDataGrid-selectedRows": "Выбранные строки", "dxDataGrid-headerFilterEmptyValue": "(Пустое)", "dxDataGrid-headerFilterOK": "ОК", "dxDataGrid-headerFilterCancel": "Отменить", "dxDataGrid-ariaColumn": "Столбец", "dxDataGrid-ariaValue": "Значение", "dxDataGrid-ariaFilterCell": "Фильтр", "dxDataGrid-ariaCollapse": "Свернуть", "dxDataGrid-ariaExpand": "Развернуть", "dxDataGrid-ariaDataGrid": "Таблица данных", "dxDataGrid-ariaSearchInGrid": "Искать в таблице данных", "dxDataGrid-ariaSelectAll": "Выбрать всё", "dxDataGrid-ariaSelectRow": "Выбрать строку", "dxPager-infoText": "Страница {0} из {1}", "dxPivotGrid-grandTotal": "Итого", "dxPivotGrid-total": "{0} Всего", "dxPivotGrid-fieldChooserTitle": "Выбор полей", "dxPivotGrid-showFieldChooser": "Показать выбор полей", "dxPivotGrid-expandAll": "Раскрыть все", "dxPivotGrid-collapseAll": "Свернуть все", "dxPivotGrid-sortColumnBySummary": "Сортировать \"{0}\" по этой колонке", "dxPivotGrid-sortRowBySummary": "Сортировать \"{0}\" по этой строке", "dxPivotGrid-removeAllSorting": "Сбросить все сортировки", "dxPivotGrid-rowFields": "Поля строк", "dxPivotGrid-columnFields": "Поля столбцов", "dxPivotGrid-dataFields": "Поля данных", "dxPivotGrid-filterFields": "Поля фильтров", "dxPivotGrid-allFields": "Все поля", "dxScheduler-editorLabelTitle": "Название", "dxScheduler-editorLabelStartDate": "Дата начала", "dxScheduler-editorLabelEndDate": "Дата завершения", "dxScheduler-editorLabelDescription": "Описание", "dxScheduler-editorLabelRecurrence": "Повторение", "dxScheduler-openAppointment": "Открыть задачу", "dxScheduler-recurrenceNever": "Никогда", "dxScheduler-recurrenceDaily": "Ежедневно", "dxScheduler-recurrenceWeekly": "Еженедельно", "dxScheduler-recurrenceMonthly": "Ежемесячно", "dxScheduler-recurrenceYearly": "Ежегодно", "dxScheduler-recurrenceEvery": "Интервал", "dxScheduler-recurrenceEnd": "Завершить повторение", "dxScheduler-recurrenceAfter": "Количество повторений", "dxScheduler-recurrenceOn": "Повторять до", "dxScheduler-recurrenceRepeatDaily": "дней(дня)", "dxScheduler-recurrenceRepeatWeekly": "недели(недель)", "dxScheduler-recurrenceRepeatMonthly": "месяца(месяцев)", "dxScheduler-recurrenceRepeatYearly": "года(лет)", "dxScheduler-recurrenceRepeatOnDate": "до даты", "dxScheduler-recurrenceRepeatCount": "повторений", "dxScheduler-switcherDay": "День", "dxScheduler-switcherWeek": "Неделя", "dxScheduler-switcherWorkWeek": "Рабочая неделя", "dxScheduler-switcherMonth": "Месяц", "dxScheduler-allDay": "Весь день", "dxCalendar-todayButtonText": "Сегодня", "dxCalendar-ariaWidgetName": "Календарь", "dxColorView-ariaRed": "Красный", "dxColorView-ariaGreen": "Зеленый", "dxColorView-ariaBlue": "Синий", "dxColorView-ariaAlpha": "Прозрачность", "dxColorView-ariaHex": "Код цвета" }});
import React from 'react'; import HashtagList from './HashtagList'; export default class FollowList extends React.Component{ componentWillMount(){ } render(){ let heartIcon = <i className="glyphicon glyphicon-heart"/>; let heading = <div>{heartIcon} Follow <span className="pull-right"> <a onClick={this.props.doGetFollowHashtags}> <i className="glyphicon glyphicon-refresh"/> </a> </span> </div>; let itemArray = this.props.followHashtags.map((item) => { return { name: item.hashtag, number: item.follows, policyId: item.policyId } }); return( <HashtagList heading={heading} hashtags={itemArray} glyphicon={heartIcon} addHandler={this.props.doAddFollowHashtag} deleteHandler={this.props.doRemoveFollowHashtag}/> ); } }
/* 實作 ck.Express 物件 for API Server */ class ApiServer extends ck.Express { static _addSlash (url) { return url.indexOf(`/`) === 0 ? url : `/${url}` } static _genRouteFn (genFn) { return async (req, res, next) => { try { await genFn(req, res, next) } catch (e) { next(e) } } } getGroupPath (group, version = require(`package.json`).version) { return `/api/v${version}/${group}` } createRouter (path = ``) { const router = super.createRouter(path) const methods = [`get`, `post`, `put`, `delete`] for (const method of methods) { const originalFn = router[method] router[method] = (...args) => { const lastArgIndex = args.length - 1 args[0] = ApiServer._addSlash(args[0]) args[lastArgIndex] = ApiServer._genRouteFn(args[lastArgIndex]) originalFn.apply(router, args) } } return router } } module.exports = new ApiServer()
/** * 用户业务操作 */ const validator = require('validator') const userModel = require('./../models/user-info') const userCode = require('./../codes/user') const user = { /** * 创建用户 * @param {object} user 用户信息 * @return {object} 创建结果 */ async create( user ) { let result = await userModel.create(user) return result }, /** * 查找存在用户信息 * @param {object} formData 查找的表单数据 * @return {object|null} 查找结果 */ async getExistOne( formData ) { let resultData = await userModel.getExistOne({ 'email': formData.email, 'name': formData.userName }) return resultData }, /** * 登录业务操作 * @param {object} formData 登录表单信息 * @return {object} 登录业务操作结果 */ async signIn( formData ) { let resultData = await userModel.getOneByUserNameAndPassword({ 'password': formData.password, 'name': formData.userName}) return resultData }, /** * 根据用户名查找用户业务操作 * @param {string} userName 用户名 * @return {object|null} 查找结果 */ async getUserInfoByUserName( userName ) { let resultData = await userModel.getUserInfoByUserName( userName ) || {} let userInfo = { // id: resultData.id, email: resultData.email, userName: resultData.name, detailInfo: resultData.detail_info, createTime: resultData.create_time } return userInfo }, /** * 检验用户注册数据 * @param {object} userInfo 用户注册数据 * @return {object} 校验结果 */ validatorSignUp( userInfo ) { let result = { success: false, message: '', } if ( /[a-z0-9\_\-]{6,16}/.test(userInfo.userName) === false ) { result.message = userCode.ERROR_USER_NAME return result } if ( !validator.isEmail( userInfo.email ) ) { result.message = userCode.ERROR_EMAIL return result } if ( !/[\w+]{6,16}/.test( userInfo.password ) ) { result.message = userCode.ERROR_PASSWORD return result } if ( userInfo.password !== userInfo.confirmPassword ) { result.message = userCode.ERROR_PASSWORD_CONFORM return result } result.success = true return result } } module.exports = user
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { Card, CardTitle, CardActions } from 'material-ui/Card'; import compose from 'recompose/compose'; import inflection from 'inflection'; import ViewTitle from '../layout/ViewTitle'; import Title from '../layout/Title'; import { DeleteButton, EditButton, ListButton } from '../button'; import { crudGetOne as crudGetOneAction } from '../../actions/dataActions'; import DefaultActions from './ShowActions'; import translate from '../../i18n/translate'; /** * Turns a children data structure (either single child or array of children) into an array. * We can't use React.Children.toArray as it loses references. */ const arrayizeChildren = children => (Array.isArray(children) ? children : [children]); export class Show extends Component { componentDidMount() { this.props.crudGetOne(this.props.resource, this.props.id, this.getBasePath()); } componentWillReceiveProps(nextProps) { if (this.props.id !== nextProps.id) { this.props.crudGetOne(nextProps.resource, nextProps.id, this.getBasePath()); } } // FIXME Seems that the cloneElement in CrudRoute slices the children array, which makes this necessary to avoid rerenders shouldComponentUpdate(nextProps) { if (nextProps.isLoading !== this.props.isLoading) { return true; } const currentChildren = arrayizeChildren(this.props.children); const newChildren = arrayizeChildren(nextProps.children); return newChildren.every((child, index) => child === currentChildren[index]); } getBasePath() { const { location } = this.props; return location.pathname.split('/').slice(0, -2).join('/'); } render() { const { actions = <DefaultActions />, title, children, id, data, isLoading, resource, hasDelete, hasEdit, translate } = this.props; const basePath = this.getBasePath(); const resourceName = translate(`resources.${resource}.name`, { smart_count: 1, _: inflection.humanize(inflection.singularize(resource)), }); const defaultTitle = translate('aor.page.show', { name: `${resourceName}`, id, data, }); const titleElement = data ? <Title title={title} record={data} defaultTitle={defaultTitle} /> : ''; return ( <div> <Card style={{ opacity: isLoading ? 0.8 : 1 }}> {actions && React.cloneElement(actions, { basePath, data, hasDelete, hasEdit, refresh: this.refresh, resource, })} <ViewTitle title={titleElement} /> {data && React.cloneElement(children, { resource, basePath, record: data, })} </Card> </div> ); } } Show.propTypes = { actions: PropTypes.element, children: PropTypes.element, crudGetOne: PropTypes.func.isRequired, data: PropTypes.object, hasDelete: PropTypes.bool, hasEdit: PropTypes.bool, id: PropTypes.string.isRequired, isLoading: PropTypes.bool.isRequired, location: PropTypes.object.isRequired, params: PropTypes.object.isRequired, resource: PropTypes.string.isRequired, title: PropTypes.any, translate: PropTypes.func, }; function mapStateToProps(state, props) { return { id: props.params.id, data: state.admin[props.resource].data[props.params.id], isLoading: state.admin.loading > 0, }; } const enhance = compose( connect( mapStateToProps, { crudGetOne: crudGetOneAction }, ), translate, ); export default enhance(Show);
function spyProperties(a,b){Object.keys(b).forEach(function(d){var e="__"+d;try{b[e]=b[d];b[d]=undefined;Object.defineProperty(b,d,{get:function(){console.debug("[Property Usage] %debugNamespace.%property".replace("%debugNamespace",a).replace("%property",d));return b[e]}})}catch(c){if(b[e]){b[d]=b[e];b[e]=undefined}}})};
module.exports = function(grunt) { // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { options: { style: 'compressed', noCache: true }, files: { 'css/style.css': 'scss/style.scss', 'css/ie.css': 'scss/ie.scss' } } }, watch: { css: { files: 'scss/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };
var vertx = require('vertx'); vertx.createHttpServer().requestHandler(function(req) { req.response.end('Hello World\n'); }).listen(8080)
Template['signup'].helpers({ }); Template['signup'].events({ });
$ = jQuery = require('jquery'); require('./picker.js'); require('./picker.date.js'); require('./picker.time.js'); require('./legacy.js');
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; export default function(babel, opts = {}) { if (typeof babel.env === 'function') { // Only available in Babel 7. const env = babel.env(); if (env !== 'development' && !opts.skipEnvCheck) { throw new Error( 'React Refresh Babel transform should only be enabled in development environment. ' + 'Instead, the environment is: "' + env + '". If you want to override this check, pass {skipEnvCheck: true} as plugin options.', ); } } const {types: t} = babel; const refreshReg = t.identifier(opts.refreshReg || '$RefreshReg$'); const refreshSig = t.identifier(opts.refreshSig || '$RefreshSig$'); const registrationsByProgramPath = new Map(); function createRegistration(programPath, persistentID) { const handle = programPath.scope.generateUidIdentifier('c'); if (!registrationsByProgramPath.has(programPath)) { registrationsByProgramPath.set(programPath, []); } const registrations = registrationsByProgramPath.get(programPath); registrations.push({ handle, persistentID, }); return handle; } function isComponentishName(name) { return typeof name === 'string' && name[0] >= 'A' && name[0] <= 'Z'; } function findInnerComponents(inferredName, path, callback) { const node = path.node; switch (node.type) { case 'Identifier': { if (!isComponentishName(node.name)) { return false; } // export default hoc(Foo) // const X = hoc(Foo) callback(inferredName, node, null); return true; } case 'FunctionDeclaration': { // function Foo() {} // export function Foo() {} // export default function Foo() {} callback(inferredName, node.id, null); return true; } case 'ArrowFunctionExpression': { if (node.body.type === 'ArrowFunctionExpression') { return false; } // let Foo = () => {} // export default hoc1(hoc2(() => {})) callback(inferredName, node, path); return true; } case 'FunctionExpression': { // let Foo = function() {} // const Foo = hoc1(forwardRef(function renderFoo() {})) // export default memo(function() {}) callback(inferredName, node, path); return true; } case 'CallExpression': { const argsPath = path.get('arguments'); if (argsPath === undefined || argsPath.length === 0) { return false; } const calleePath = path.get('callee'); switch (calleePath.node.type) { case 'MemberExpression': case 'Identifier': { const calleeSource = calleePath.getSource(); const firstArgPath = argsPath[0]; const innerName = inferredName + '$' + calleeSource; const foundInside = findInnerComponents( innerName, firstArgPath, callback, ); if (!foundInside) { return false; } // const Foo = hoc1(hoc2(() => {})) // export default memo(React.forwardRef(function() {})) callback(inferredName, node, path); return true; } default: { return false; } } } case 'VariableDeclarator': { const init = node.init; if (init === null) { return false; } const name = node.id.name; if (!isComponentishName(name)) { return false; } switch (init.type) { case 'ArrowFunctionExpression': case 'FunctionExpression': // Likely component definitions. break; case 'CallExpression': { // Maybe a HOC. // Try to determine if this is some form of import. const callee = init.callee; const calleeType = callee.type; if (calleeType === 'Import') { return false; } else if (calleeType === 'Identifier') { if (callee.name.indexOf('require') === 0) { return false; } else if (callee.name.indexOf('import') === 0) { return false; } // Neither require nor import. Might be a HOC. // Pass through. } else if (calleeType === 'MemberExpression') { // Could be something like React.forwardRef(...) // Pass through. } break; } case 'TaggedTemplateExpression': // Maybe something like styled.div`...` break; default: return false; } const initPath = path.get('init'); const foundInside = findInnerComponents( inferredName, initPath, callback, ); if (foundInside) { return true; } // See if this identifier is used in JSX. Then it's a component. const binding = path.scope.getBinding(name); if (binding === undefined) { return; } let isLikelyUsedAsType = false; const referencePaths = binding.referencePaths; for (let i = 0; i < referencePaths.length; i++) { const ref = referencePaths[i]; if ( ref.node && ref.node.type !== 'JSXIdentifier' && ref.node.type !== 'Identifier' ) { continue; } const refParent = ref.parent; if (refParent.type === 'JSXOpeningElement') { isLikelyUsedAsType = true; } else if (refParent.type === 'CallExpression') { const callee = refParent.callee; let fnName; switch (callee.type) { case 'Identifier': fnName = callee.name; break; case 'MemberExpression': fnName = callee.property.name; break; } switch (fnName) { case 'createElement': case 'jsx': case 'jsxDEV': case 'jsxs': isLikelyUsedAsType = true; break; } } if (isLikelyUsedAsType) { // const X = ... + later <X /> callback(inferredName, init, initPath); return true; } } } } return false; } function isBuiltinHook(hookName) { switch (hookName) { case 'useState': case 'React.useState': case 'useReducer': case 'React.useReducer': case 'useEffect': case 'React.useEffect': case 'useLayoutEffect': case 'React.useLayoutEffect': case 'useMemo': case 'React.useMemo': case 'useCallback': case 'React.useCallback': case 'useRef': case 'React.useRef': case 'useContext': case 'React.useContext': case 'useImperativeMethods': case 'React.useImperativeMethods': case 'useDebugValue': case 'React.useDebugValue': return true; default: return false; } } function getHookCallsSignature(functionNode) { const fnHookCalls = hookCalls.get(functionNode); if (fnHookCalls === undefined) { return null; } return { key: fnHookCalls.map(call => call.name + '{' + call.key + '}').join('\n'), customHooks: fnHookCalls .filter(call => !isBuiltinHook(call.name)) .map(call => t.cloneDeep(call.callee)), }; } const hasForceResetCommentByFile = new WeakMap(); // We let user do /* @refresh reset */ to reset state in the whole file. function hasForceResetComment(path) { const file = path.hub.file; let hasForceReset = hasForceResetCommentByFile.get(file); if (hasForceReset !== undefined) { return hasForceReset; } hasForceReset = false; const comments = file.ast.comments; for (let i = 0; i < comments.length; i++) { const cmt = comments[i]; if (cmt.value.indexOf('@refresh reset') !== -1) { hasForceReset = true; break; } } hasForceResetCommentByFile.set(file, hasForceReset); return hasForceReset; } function createArgumentsForSignature(node, signature, scope) { const {key, customHooks} = signature; let forceReset = hasForceResetComment(scope.path); const customHooksInScope = []; customHooks.forEach(callee => { // Check if a corresponding binding exists where we emit the signature. let bindingName; switch (callee.type) { case 'MemberExpression': if (callee.object.type === 'Identifier') { bindingName = callee.object.name; } break; case 'Identifier': bindingName = callee.name; break; } if (scope.hasBinding(bindingName)) { customHooksInScope.push(callee); } else { // We don't have anything to put in the array because Hook is out of scope. // Since it could potentially have been edited, remount the component. forceReset = true; } }); let finalKey = key; if (typeof require === 'function' && !opts.emitFullSignatures) { // Prefer to hash when we can (e.g. outside of ASTExplorer). // This makes it deterministically compact, even if there's // e.g. a useState initializer with some code inside. // We also need it for www that has transforms like cx() // that don't understand if something is part of a string. finalKey = require('crypto') .createHash('sha1') .update(key) .digest('base64'); } const args = [node, t.stringLiteral(finalKey)]; if (forceReset || customHooksInScope.length > 0) { args.push(t.booleanLiteral(forceReset)); } if (customHooksInScope.length > 0) { args.push( // TODO: We could use an arrow here to be more compact. // However, don't do it until AMA can run them natively. t.functionExpression( null, [], t.blockStatement([ t.returnStatement(t.arrayExpression(customHooksInScope)), ]), ), ); } return args; } const seenForRegistration = new WeakSet(); const seenForSignature = new WeakSet(); const seenForOutro = new WeakSet(); const hookCalls = new WeakMap(); const HookCallsVisitor = { CallExpression(path) { const node = path.node; const callee = node.callee; // Note: this visitor MUST NOT mutate the tree in any way. // It runs early in a separate traversal and should be very fast. let name = null; switch (callee.type) { case 'Identifier': name = callee.name; break; case 'MemberExpression': name = callee.property.name; break; } if (name === null || !/^use[A-Z]/.test(name)) { return; } const fnScope = path.scope.getFunctionParent(); if (fnScope === null) { return; } // This is a Hook call. Record it. const fnNode = fnScope.block; if (!hookCalls.has(fnNode)) { hookCalls.set(fnNode, []); } const hookCallsForFn = hookCalls.get(fnNode); let key = ''; if (path.parent.type === 'VariableDeclarator') { // TODO: if there is no LHS, consider some other heuristic. key = path.parentPath.get('id').getSource(); } // Some built-in Hooks reset on edits to arguments. const args = path.get('arguments'); if (name === 'useState' && args.length > 0) { // useState second argument is initial state. key += '(' + args[0].getSource() + ')'; } else if (name === 'useReducer' && args.length > 1) { // useReducer second argument is initial state. key += '(' + args[1].getSource() + ')'; } hookCallsForFn.push({ callee: path.node.callee, name, key, }); }, }; return { visitor: { ExportDefaultDeclaration(path) { const node = path.node; const decl = node.declaration; const declPath = path.get('declaration'); if (decl.type !== 'CallExpression') { // For now, we only support possible HOC calls here. // Named function declarations are handled in FunctionDeclaration. // Anonymous direct exports like export default function() {} // are currently ignored. return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. if (seenForRegistration.has(node)) { return; } seenForRegistration.add(node); // Don't mutate the tree above this point. // This code path handles nested cases like: // export default memo(() => {}) // In those cases it is more plausible people will omit names // so they're worth handling despite possible false positives. // More importantly, it handles the named case: // export default memo(function Named() {}) const inferredName = '%default%'; const programPath = path.parentPath; findInnerComponents( inferredName, declPath, (persistentID, targetExpr, targetPath) => { if (targetPath === null) { // For case like: // export default hoc(Foo) // we don't want to wrap Foo inside the call. // Instead we assume it's registered at definition. return; } const handle = createRegistration(programPath, persistentID); targetPath.replaceWith( t.assignmentExpression('=', handle, targetExpr), ); }, ); }, FunctionDeclaration: { enter(path) { const node = path.node; let programPath; let insertAfterPath; switch (path.parent.type) { case 'Program': insertAfterPath = path; programPath = path.parentPath; break; case 'ExportNamedDeclaration': insertAfterPath = path.parentPath; programPath = insertAfterPath.parentPath; break; case 'ExportDefaultDeclaration': insertAfterPath = path.parentPath; programPath = insertAfterPath.parentPath; break; default: return; } const id = node.id; if (id === null) { // We don't currently handle anonymous default exports. return; } const inferredName = id.name; if (!isComponentishName(inferredName)) { return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. if (seenForRegistration.has(node)) { return; } seenForRegistration.add(node); // Don't mutate the tree above this point. // export function Named() {} // function Named() {} findInnerComponents( inferredName, path, (persistentID, targetExpr) => { const handle = createRegistration(programPath, persistentID); insertAfterPath.insertAfter( t.expressionStatement( t.assignmentExpression('=', handle, targetExpr), ), ); }, ); }, exit(path) { const node = path.node; const id = node.id; if (id === null) { return; } const signature = getHookCallsSignature(node); if (signature === null) { return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. if (seenForSignature.has(node)) { return; } seenForSignature.add(node); // Don't mutate the tree above this point. const sigCallID = path.scope.generateUidIdentifier('_s'); path.scope.parent.push({ id: sigCallID, init: t.callExpression(refreshSig, []), }); // The signature call is split in two parts. One part is called inside the function. // This is used to signal when first render happens. path .get('body') .unshiftContainer( 'body', t.expressionStatement(t.callExpression(sigCallID, [])), ); // The second call is around the function itself. // This is used to associate a type with a signature. // Unlike with $RefreshReg$, this needs to work for nested // declarations too. So we need to search for a path where // we can insert a statement rather than hard coding it. let insertAfterPath = null; path.find(p => { if (p.parentPath.isBlock()) { insertAfterPath = p; return true; } }); if (insertAfterPath === null) { return; } insertAfterPath.insertAfter( t.expressionStatement( t.callExpression( sigCallID, createArgumentsForSignature( id, signature, insertAfterPath.scope, ), ), ), ); }, }, 'ArrowFunctionExpression|FunctionExpression': { exit(path) { const node = path.node; const signature = getHookCallsSignature(node); if (signature === null) { return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. if (seenForSignature.has(node)) { return; } seenForSignature.add(node); // Don't mutate the tree above this point. const sigCallID = path.scope.generateUidIdentifier('_s'); path.scope.parent.push({ id: sigCallID, init: t.callExpression(refreshSig, []), }); // The signature call is split in two parts. One part is called inside the function. // This is used to signal when first render happens. if (path.node.body.type !== 'BlockStatement') { path.node.body = t.blockStatement([ t.returnStatement(path.node.body), ]); } path .get('body') .unshiftContainer( 'body', t.expressionStatement(t.callExpression(sigCallID, [])), ); // The second call is around the function itself. // This is used to associate a type with a signature. if (path.parent.type === 'VariableDeclarator') { let insertAfterPath = null; path.find(p => { if (p.parentPath.isBlock()) { insertAfterPath = p; return true; } }); if (insertAfterPath === null) { return; } // Special case when a function would get an inferred name: // let Foo = () => {} // let Foo = function() {} // We'll add signature it on next line so that // we don't mess up the inferred 'Foo' function name. insertAfterPath.insertAfter( t.expressionStatement( t.callExpression( sigCallID, createArgumentsForSignature( path.parent.id, signature, insertAfterPath.scope, ), ), ), ); // Result: let Foo = () => {}; __signature(Foo, ...); } else { // let Foo = hoc(() => {}) path.replaceWith( t.callExpression( sigCallID, createArgumentsForSignature(node, signature, path.scope), ), ); // Result: let Foo = hoc(__signature(() => {}, ...)) } }, }, VariableDeclaration(path) { const node = path.node; let programPath; let insertAfterPath; switch (path.parent.type) { case 'Program': insertAfterPath = path; programPath = path.parentPath; break; case 'ExportNamedDeclaration': insertAfterPath = path.parentPath; programPath = insertAfterPath.parentPath; break; case 'ExportDefaultDeclaration': insertAfterPath = path.parentPath; programPath = insertAfterPath.parentPath; break; default: return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. if (seenForRegistration.has(node)) { return; } seenForRegistration.add(node); // Don't mutate the tree above this point. const declPaths = path.get('declarations'); if (declPaths.length !== 1) { return; } const declPath = declPaths[0]; const inferredName = declPath.node.id.name; findInnerComponents( inferredName, declPath, (persistentID, targetExpr, targetPath) => { if (targetPath === null) { // For case like: // export const Something = hoc(Foo) // we don't want to wrap Foo inside the call. // Instead we assume it's registered at definition. return; } const handle = createRegistration(programPath, persistentID); if (targetPath.parent.type === 'VariableDeclarator') { // Special case when a variable would get an inferred name: // let Foo = () => {} // let Foo = function() {} // let Foo = styled.div``; // We'll register it on next line so that // we don't mess up the inferred 'Foo' function name. // (eg: with @babel/plugin-transform-react-display-name or // babel-plugin-styled-components) insertAfterPath.insertAfter( t.expressionStatement( t.assignmentExpression('=', handle, declPath.node.id), ), ); // Result: let Foo = () => {}; _c1 = Foo; } else { // let Foo = hoc(() => {}) targetPath.replaceWith( t.assignmentExpression('=', handle, targetExpr), ); // Result: let Foo = hoc(_c1 = () => {}) } }, ); }, Program: { enter(path) { // This is a separate early visitor because we need to collect Hook calls // and "const [foo, setFoo] = ..." signatures before the destructuring // transform mangles them. This extra traversal is not ideal for perf, // but it's the best we can do until we stop transpiling destructuring. path.traverse(HookCallsVisitor); }, exit(path) { const registrations = registrationsByProgramPath.get(path); if (registrations === undefined) { return; } // Make sure we're not mutating the same tree twice. // This can happen if another Babel plugin replaces parents. const node = path.node; if (seenForOutro.has(node)) { return; } seenForOutro.add(node); // Don't mutate the tree above this point. registrationsByProgramPath.delete(path); const declarators = []; path.pushContainer('body', t.variableDeclaration('var', declarators)); registrations.forEach(({handle, persistentID}) => { path.pushContainer( 'body', t.expressionStatement( t.callExpression(refreshReg, [ handle, t.stringLiteral(persistentID), ]), ), ); declarators.push(t.variableDeclarator(handle)); }); }, }, }, }; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _ = require('lodash'); var async = require('async'); /** * Helper class that triggers execution for components */ var Executor = /** @class */ (function () { function Executor() { } /** * Triggers execution for component that implement IExecutable and IParamExecutable interfaces * and passes to IParamExecutable them set of parameters. * @param correlationId a unique transaction id to trace calls across components * @param component a components to be executed * @param args a set of parameters to pass to executed components * @param callback a function to call back with results when execution is complete */ Executor.executeOne = function (correlationId, component, args, callback) { if (_.isFunction(component.execute)) { try { return component.execute(correlationId, args, callback); } catch (err) { callback(err, null); } } else callback(null, null); }; /** * Triggers execution for components that implement IExecutable and IParamExecutable interfaces * and passes to IParamExecutable them set of parameters. * @param correlationId a unique transaction id to trace calls across components * @param components a list of components to be executed * @param args a set of parameters to pass to executed components * @param callback a function to call back with results when execution is complete */ Executor.execute = function (correlationId, components, args, callback) { var results = []; async.eachSeries(components, function (component, callback) { Executor.executeOne(correlationId, component, args, function (err, result) { results.push(result); callback(err); }); }, function (err) { callback(err, results); }); }; return Executor; }()); exports.Executor = Executor; //# sourceMappingURL=Executor.js.map
// ==UserScript== // @name Kingsage Enhancement Suite // @version 1.3.1.0 // @author grafilicious // @include http://*.kingsage.*game.php* // @include http://*.kingsage.*redir.php* // @include https://*.kingsage.*game.php* // @include https://*.kingsage.*redir.php* // @exclude http://support.*/* // @grant none // ==/UserScript==
import React, { Component, PropTypes } from 'react'; import { TextInput, ScrollView, Text, View, TouchableHighlight } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import DropdownAlert from 'react-native-dropdownalert'; import Swipeout from 'react-native-swipe-out'; import Modal from 'react-native-root-modal'; import Button from 'react-native-button'; import { Actions } from 'react-native-router-flux'; import styles from '../styles/styles.js'; export default class Tasks extends Component { static propTypes = { addTask: PropTypes.func.isRequired, removeTask: PropTypes.func.isRequired, tasks: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { formOpen: false, formTaskTitle: '', } } componentDidMount() { Actions.refresh({ renderRightButton: this.renderRightButton }); } renderRightButton = () => { return ( <TouchableHighlight onPress={() => this.openForm()}> <Text style={styles.navbarRightButton}>+</Text> </TouchableHighlight> ); } tasksDone() { return [].concat(this.props.tasks.tasks.filter((ele) => ele.status == 'done')); } tasksOpen() { return [].concat(this.props.tasks.tasks.filter((ele) => ele.status == 'open')); } listDoneTasks() { if(this.props.showtabs == 'open') { return; } const list = this.tasksDone(); return list.map((task) => { const swipeButtons = [ { text: 'Delete', backgroundColor: 'red', color: 'white', onPress: () => this.deleteTask(task), }, { text: 'Undone', type: 'primary', onPress: () => this.undoTask(task), } ]; return ( <View key={task.id} style={styles.taskrow}> <Swipeout left={swipeButtons} style={styles.taskswipe}> <View style={styles.taskdescription}> <Text>{task.title}</Text> </View> </Swipeout> </View> ) }); } listOpenTasks() { if(this.props.showtabs == 'done') { return; } const list = this.tasksOpen(); return list.map((task) => { const swipeButtons = [ { text: 'Delete', backgroundColor: 'red', color: 'white', onPress: () => this.deleteTask(task), }, { text: 'Done', type: 'primary', onPress: () => this.completeTask(task), } ]; return ( <View key={task.id} style={styles.taskrow}> <Swipeout left={swipeButtons} style={styles.taskswipe}> <View style={styles.taskdescription}> <Text>{task.title}</Text> </View> </Swipeout> </View> ) }); } deleteTask(task) { this.props.removeTask(task); } completeTask(task) { this.props.markTaskComplete(task); } undoTask(task) { this.props.markTaskIncomplete(task); } saveTask() { const taskTitle = this.state.formTaskTitle; this.setState({formTaskTitle: ''}); this.props.addTask(taskTitle); this.closeForm(); } _titleOnChange(text) { this.setState({formTaskTitle: text}); } openForm() { this.setState({formOpen: true}); } closeForm() { this.setState({formOpen: false}); } formTask() { return ( <Modal visible={this.state.formOpen}> <View style={styles.inputmodalroot} onPress={() => this.closeForm()}> <View style={styles.inputmodalrow}> <Text style={styles.inputmodalhead}>New Task</Text> </View> <View style={styles.inputmodalrow}> <TextInput style={styles.inputmodalinput} placeholder="Task Description" onChangeText={(text) => this._titleOnChange(text)} onSubmitEditing={() => {this.saveTask()}} autoCorrect={false} value={this.state.formName} /> </View> <View style={styles.inputmodalrow}> <TouchableHighlight style={styles.inputmodalcancel} onPress={() => this.closeForm()}> <View> <Text>Cancel</Text> </View> </TouchableHighlight> <TouchableHighlight style={styles.inputmodalsave} onPress={() => this.saveTask()}> <View> <Text>Save</Text> </View> </TouchableHighlight> </View> </View> </Modal> ); } titleStats() { const open = this.props.tasks.tasks.filter((el) => el.status == 'open').length; const done = this.props.tasks.tasks.length - open; return ( <View style={styles.header}> <Text style={styles.headertext}>Open: {open}</Text> <Text style={styles.headertext}>Done: {done}</Text> </View> ) } render() { return ( <ScrollView style={styles.tasksscrollview}> {this.formTask()} {this.titleStats()} {this.listOpenTasks()} {this.listDoneTasks()} <DropdownAlert ref={(ref) => this.dropdown = ref} /> </ScrollView> ); } } /* */
module.exports = [ { output: { filename: "commonjs.js", libraryTarget: "commonjs-module" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd.js", libraryTarget: "umd" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd-default.js", libraryTarget: "umd", libraryExport: "default" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "this.js", libraryTarget: "this" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "global.js", library: "globalName" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "commonjs2-external.js", libraryTarget: "commonjs2" }, externals: ["external"] } ];
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the CustomParameterGroup class. * @constructor * Additional parameters for a set of operations, such as: * Paging_getMultiplePagesFragmentWithGroupingNextLink, * Paging_nextFragmentWithGrouping. * * @member {string} apiVersion Sets the api version to use. * * @member {string} tenant Sets the tenant to use. * */ function CustomParameterGroup() { } /** * Defines the metadata of CustomParameterGroup * * @returns {object} metadata of CustomParameterGroup * */ CustomParameterGroup.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'CustomParameterGroup', modelProperties: { apiVersion: { required: true, type: { name: 'String' } }, tenant: { required: true, type: { name: 'String' } } } } }; }; module.exports = CustomParameterGroup;
import * as ModelUtils from './model-utils'; import * as IdentUtils from './identifier-utils'; import * as FieldUtils from './field-utils'; /** * Builds a map of foreign key to primary key columns between the supplied child * model and its parent model. The map is keyed by the child foreign key * columns. * * @param {Model} child - The child to find join columns for * @param {String} [childAlias] - The alias that refers to the child entity in * the query this is to be used for * @param {String} [parentAlias] - The alias that refers to the parent entity in * the query this is to be used for * @returns {Object} - The map of child foreign key columns to parent primary * key columns */ export function getJoinColumnsFromChildToParent(child, childAlias, parentAlias) { let childPrimaries = ModelUtils.getPrimaryFields(child); const parentPrimaries = ModelUtils.getPrimaryFields(ModelUtils.getParent(child)); // If the child hasn't specified any primary keys, we inherit the identifier // definition from the parent if (childPrimaries.length === 0) { childPrimaries = parentPrimaries.slice(); } if (childPrimaries.length !== parentPrimaries.length) { throw new Error('Primary key count mismatch between ' + ModelUtils.getName(child) + ' and parent ' + ModelUtils.getName(ModelUtils.getParent(child))); } if (childPrimaries.length === 1) { const childName = IdentUtils.prefixAlias(childPrimaries[0].name, childAlias); const parentName = IdentUtils.prefixAlias(parentPrimaries[0].name, parentAlias); return { [childName]: parentName }; } } /** * Builds a map of foreign key to primary key columns between the supplied model * and the model indicated by the given field. * * @param {Object} field - The field action as the source of the join * @param {String} [sourceAlias] - The alias of the source entity * @param {String} [targetAlias] - The alias of the target entity * @returns {Object} - An object map keyed by source columns, pointing to target * columns */ export function getJoinColumns(field, sourceAlias, targetAlias) { // TODO Composite key support if (!field.ref) { throw new Error('Cannot join on a field that does not refer to another model'); } const target = FieldUtils.getRef(field); if (field.relation === 'one-to-one' || field.relation === 'many-to-one') { // Get the primary key of the target entity const targetPrimaryFields = ModelUtils.getPrimaryFields(target); if (targetPrimaryFields.length > 1) { throw new Error('Composite keys are not yet supported'); } return { [IdentUtils.prefixAlias(field.column, sourceAlias)]: IdentUtils.prefixAlias(targetPrimaryFields[0].column, targetAlias) }; } if (field.relation === 'one-to-many') { const targetField = ModelUtils.getField(target, field.mappedBy); const ownerPrimaryFields = ModelUtils.getPrimaryFields(field.owningModel); if (ownerPrimaryFields.length > 1) { throw new Error('Composite keys are not yet supported'); } return { [IdentUtils.prefixAlias(ownerPrimaryFields[0].column, sourceAlias)]: IdentUtils.prefixAlias(targetField.column, targetAlias) }; } throw new Error('Invalid relation type: ' + field.relation); } /** * Given a field that represents a relationship, retrieves the field that * represents the owning side of the relationship. As the field given may in * fact be the owning side of the relationship, this may return the original * field given. * * @param {Object} field - The field from which we find ownership * @returns {Object} - The field that owns the relationship */ export function getOwningField(field) { if (!field.mappedBy) { return field; } return ModelUtils.getField(field.ref, field.mappedBy); } /** * Given a field that represents a relationship, retrieves the field that * represents the non-owning side of the relationship, usually indicated by * * @param {Object} field - The field from which we find the non-owner * @returns {Object} - The non-owning field in the relationship */ export function getNonOwningField(field) { if (field.mappedBy) { return field; } const ref = FieldUtils.getRef(field); if (!ref) { return null; } const fields = ModelUtils.getFields(ref); return fields.find((_field) => { return _field.owningModel === field.ref && _field.mappedBy === field.name; }); } /** * Given a field that represents a many-to-many relationship, retrieves the * field on the association table that references the owner of the given field. * In reality, many-to-many relationships are actually just a pair of * many-to-one relationships, where the actual owner of both is the association * table. This function returns the many-to-one owner that refers to the given * field. * * @param {Object} field - The field to find the association table field for * @returns {Object} - The field of the association table */ export function getAssociationEntityField(field) { if (!field.through) { return null; } } /** * Builds the entity that represents an association table for a many-to-many * relationship. * * @param {Object} field - The field which represents one half of the * relationship for which the association table will be built * @param {Model} Model - The base Model class. Passed in rather than included * @returns {undefined} - Nothing */ export function buildAssociationEntity(field, Model) { if (field.relation !== 'many-to-many' || field.through) { return; } let startField = getOwningField(field); if (!startField) { return; } let endField = getNonOwningField(field); if (!endField) { return; } if (startField.mappedBy) { const tmp = startField; startField = endField; endField = tmp; if (!startField) { return; } if (startField.through || endField.through) { startField.through = startField.through || endField.through; endField.through = startField.through || endField.through; return; } } const fields = {}; fields[startField.name || startField.owningModel.name] = { 'ref': startField.ref, 'relation': 'many-to-one', 'primary': true, 'column': startField.joinColumns ? startField.joinColumns[0].name : undefined }; fields[endField.name || endField.owningModel.name] = { 'ref': endField.ref, 'relation': 'many-to-one', 'primary': true, 'column': startField.inverseJoinColumns ? startField.inverseJoinColumns[0].name : undefined }; const AssociationEntity = Model.extend( startField.owningModel.name + endField.owningModel.name, fields, { 'table': startField.joinTable || (startField.owningModel.name + '_' + endField.owningModel.name) } ); startField.through = AssociationEntity; endField.through = AssociationEntity; } /** * Retrieves the first field found on the owner that refers to the target. This * is not always the most desirable function to use, as in the example of a * self-referencing many-to-many relationship where the association table would * have two fields which both refer to the same target. * * @param {Object} owner - The owning entity to find a field on * @param {Object} target - The entity the matching field must reference * @returns {Object} - The field on the owner that refers to the target */ export function getFieldReferringTo(owner, target) { const fields = Object.values(ModelUtils.getFields(owner)); return fields.find((field) => { return FieldUtils.getRef(field) === target; }); } /** * Given a field that represents one side of a relationship, retrieves the field * that represents the other side of the relationship. If the field given is * the non-owning field in the relationship, there should always be a * corresponding field to return. If the field is the owning side, then it is * possible that there will not be a corresponding field if the developer didn't * create one when mapping their domain. * * @param {Object} field - The field find the other side for * @returns {Object} - The field representing the other side of the relationship */ export function getOtherSide(field) { if (!field || !field.ref) { return null; } if (field.mappedBy) { return ModelUtils.getField(field.ref, field.mappedBy); } return ModelUtils.getFields(field.ref).find((_field) => { return _field.ref === field.owningModel && _field.mappedBy === field.name; }); }
var app = app || {} app.TaskCollection = Backbone.Collection.extend({ model: app.SharedTaskModel, url: "/tasks", // will be overwritten to be `tasks-unassigned`, `task-user/<username>`, or `tasks-completed` collectionKind: null, initialize: function(models, options) { this.masterTaskCollection = app.allTasks; this.collectionKind = options.collectionKind; this.url = options.url; this.listenTo(this.masterTaskCollection, "add", this.taskAdded); this.listenTo(this.masterTaskCollection, "change", this.taskChanged); this.listenTo(this.masterTaskCollection, "remove", this.taskRemoved); this.fetch(); // returns and array of object. each obj is passed to new SharedTaskModel(obj) }, taskAdded: function(e) { console.log(Date.now() + " : " + this.collectionKind + " added ", e); var status = e.get("status"); var creator = e.get("creator"); var assignee = e.get("assignee"); var currentUser = app.currentUser.get("username"); switch (this.collectionKind) { case "unassigned": if (status === "unassigned") { this.add(e); } break; case "user": if (creator === currentUser || assignee === currentUser) { this.add(e); } break; case "completed": if (status === "completed") { this.add(e); } break; } }, taskChanged: function(e) { console.log(Date.now() + " : " + this.collectionKind + " changed ", e); var status = e.get("status"); var creator = e.get("creator"); var assignee = e.get("assignee"); var currentUser = app.currentUser.get("username"); switch (this.collectionKind) { case "unassigned": if (status !== "unassigned") { this.remove(e); } else if (status === "unassigned") { this.add(e); } break; case "user": if ((creator === currentUser || assignee === currentUser) && status !== "completed") { this.add(e); } else { this.remove(e); } break; case "completed": if (status === "completed") { this.add(e); } break; } }, taskRemoved: function(e) { this.remove(e); } })
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Croatian language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang['hr'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbars : 'Editor toolbars', // MISSING editor : 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source : 'Kôd', newPage : 'Nova stranica', save : 'Snimi', preview : 'Pregledaj', cut : 'Izreži', copy : 'Kopiraj', paste : 'Zalijepi', print : 'Ispiši', underline : 'Potcrtano', bold : 'Podebljaj', italic : 'Ukosi', selectAll : 'Odaberi sve', removeFormat : 'Ukloni formatiranje', strike : 'Precrtano', subscript : 'Subscript', superscript : 'Superscript', horizontalrule : 'Ubaci vodoravnu liniju', pagebreak : 'Ubaci prijelom stranice', pagebreakAlt : 'Page Break', // MISSING unlink : 'Ukloni link', undo : 'Poništi', redo : 'Ponovi', // Common messages and labels. common : { browseServer : 'Pretraži server', url : 'URL', protocol : 'Protokol', upload : 'Pošalji', uploadSubmit : 'Pošalji na server', image : 'Slika', flash : 'Flash', form : 'Form', checkbox : 'Checkbox', radio : 'Radio Button', textField : 'Text Field', textarea : 'Textarea', hiddenField : 'Hidden Field', button : 'Button', select : 'Selection Field', imageButton : 'Image Button', notSet : '<nije postavljeno>', id : 'Id', name : 'Naziv', langDir : 'Smjer jezika', langDirLtr : 'S lijeva na desno (LTR)', langDirRtl : 'S desna na lijevo (RTL)', langCode : 'Kôd jezika', longDescr : 'Dugački opis URL', cssClass : 'Stylesheet klase', advisoryTitle : 'Advisory naslov', cssStyle : 'Stil', ok : 'OK', cancel : 'Poništi', close : 'Close', // MISSING preview : 'Preview', // MISSING generalTab : 'Općenito', advancedTab : 'Napredno', validateNumberFailed : 'Ova vrijednost nije broj.', confirmNewPage : 'Sve napravljene promjene će biti izgubljene ukoliko ih niste snimili. Sigurno želite učitati novu stranicu?', confirmCancel : 'Neke od opcija su promjenjene. Sigurno želite zatvoriti ovaj prozor?', options : 'Options', // MISSING target : 'Target', // MISSING targetNew : 'New Window (_blank)', // MISSING targetTop : 'Topmost Window (_top)', // MISSING targetSelf : 'Same Window (_self)', // MISSING targetParent : 'Parent Window (_parent)', // MISSING langDirLTR : 'Left to Right (LTR)', // MISSING langDirRTL : 'Right to Left (RTL)', // MISSING styles : 'Style', // MISSING cssClasses : 'Stylesheet Classes', // MISSING width : 'Širina', height : 'Visina', align : 'Poravnaj', alignLeft : 'Lijevo', alignRight : 'Desno', alignCenter : 'Središnje', alignTop : 'Vrh', alignMiddle : 'Sredina', alignBottom : 'Dolje', invalidHeight : 'Visina mora biti broj.', invalidWidth : 'Širina mora biti broj.', invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING invalidInlineStyle : 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', // MISSING cssLengthTooltip : 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nedostupno</span>' }, contextmenu : { options : 'Context Menu Options' // MISSING }, // Special char dialog. specialChar : { toolbar : 'Ubaci posebne znakove', title : 'Odaberite posebni karakter', options : 'Special Character Options' // MISSING }, // Link dialog. link : { toolbar : 'Ubaci/promijeni link', other : '<drugi>', menu : 'Promijeni link', title : 'Link', info : 'Link Info', target : 'Meta', upload : 'Pošalji', advanced : 'Napredno', type : 'Link vrsta', toUrl : 'URL', // MISSING toAnchor : 'Sidro na ovoj stranici', toEmail : 'E-Mail', targetFrame : '<okvir>', targetPopup : '<popup prozor>', targetFrameName : 'Ime ciljnog okvira', targetPopupName : 'Naziv popup prozora', popupFeatures : 'Mogućnosti popup prozora', popupResizable : 'Promjenjiva veličina', popupStatusBar : 'Statusna traka', popupLocationBar: 'Traka za lokaciju', popupToolbar : 'Traka s alatima', popupMenuBar : 'Izborna traka', popupFullScreen : 'Cijeli ekran (IE)', popupScrollBars : 'Scroll traka', popupDependent : 'Ovisno (Netscape)', popupLeft : 'Lijeva pozicija', popupTop : 'Gornja pozicija', id : 'Id', langDir : 'Smjer jezika', langDirLTR : 'S lijeva na desno (LTR)', langDirRTL : 'S desna na lijevo (RTL)', acccessKey : 'Pristupna tipka', name : 'Naziv', langCode : 'Smjer jezika', tabIndex : 'Tab Indeks', advisoryTitle : 'Advisory naslov', advisoryContentType : 'Advisory vrsta sadržaja', cssClasses : 'Stylesheet klase', charset : 'Kodna stranica povezanih resursa', styles : 'Stil', rel : 'Relationship', // MISSING selectAnchor : 'Odaberi sidro', anchorName : 'Po nazivu sidra', anchorId : 'Po Id elementa', emailAddress : 'E-Mail adresa', emailSubject : 'Naslov', emailBody : 'Sadržaj poruke', noAnchors : '(Nema dostupnih sidra)', noUrl : 'Molimo upišite URL link', noEmail : 'Molimo upišite e-mail adresu' }, // Anchor dialog anchor : { toolbar : 'Ubaci/promijeni sidro', menu : 'Svojstva sidra', title : 'Svojstva sidra', name : 'Ime sidra', errorName : 'Molimo unesite ime sidra', remove : 'Remove Anchor' // MISSING }, // List style dialog list: { numberedTitle : 'Numbered List Properties', // MISSING bulletedTitle : 'Bulleted List Properties', // MISSING type : 'Type', // MISSING start : 'Start', // MISSING validateStartNumber :'List start number must be a whole number.', // MISSING circle : 'Circle', // MISSING disc : 'Disc', // MISSING square : 'Square', // MISSING none : 'None', // MISSING notset : '<not set>', // MISSING armenian : 'Armenian numbering', // MISSING georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal : 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace : { title : 'Pronađi i zamijeni', find : 'Pronađi', replace : 'Zamijeni', findWhat : 'Pronađi:', replaceWith : 'Zamijeni s:', notFoundMsg : 'Traženi tekst nije pronađen.', findOptions : 'Find Options', // MISSING matchCase : 'Usporedi mala/velika slova', matchWord : 'Usporedi cijele riječi', matchCyclic : 'Usporedi kružno', replaceAll : 'Zamijeni sve', replaceSuccessMsg : 'Zamijenjeno %1 pojmova.' }, // Table Dialog table : { toolbar : 'Tablica', title : 'Svojstva tablice', menu : 'Svojstva tablice', deleteTable : 'Izbriši tablicu', rows : 'Redova', columns : 'Kolona', border : 'Veličina okvira', widthPx : 'piksela', widthPc : 'postotaka', widthUnit : 'width unit', // MISSING cellSpace : 'Prostornost ćelija', cellPad : 'Razmak ćelija', caption : 'Naslov', summary : 'Sažetak', headers : 'Zaglavlje', headersNone : 'Ništa', headersColumn : 'Prva kolona', headersRow : 'Prvi red', headersBoth : 'Oba', invalidRows : 'Broj redova mora biti broj veći od 0.', invalidCols : 'Broj kolona mora biti broj veći od 0.', invalidBorder : 'Debljina ruba mora biti broj.', invalidWidth : 'Širina tablice mora biti broj.', invalidHeight : 'Visina tablice mora biti broj.', invalidCellSpacing : 'Prostornost ćelija mora biti broj.', invalidCellPadding : 'Razmak ćelija mora biti broj.', cell : { menu : 'Ćelija', insertBefore : 'Ubaci ćeliju prije', insertAfter : 'Ubaci ćeliju poslije', deleteCell : 'Izbriši ćelije', merge : 'Spoji ćelije', mergeRight : 'Spoji desno', mergeDown : 'Spoji dolje', splitHorizontal : 'Podijeli ćeliju vodoravno', splitVertical : 'Podijeli ćeliju okomito', title : 'Svojstva ćelije', cellType : 'Vrsta ćelije', rowSpan : 'Rows Span', colSpan : 'Columns Span', wordWrap : 'Prelazak u novi red', hAlign : 'Vodoravno poravnanje', vAlign : 'Okomito poravnanje', alignBaseline : 'Osnovna linija', bgColor : 'Boja pozadine', borderColor : 'Boja ruba', data : 'Podatak', header : 'Zaglavlje', yes : 'Da', no : 'ne', invalidWidth : 'Širina ćelije mora biti broj.', invalidHeight : 'Visina ćelije mora biti broj.', invalidRowSpan : 'Rows span mora biti cijeli broj.', invalidColSpan : 'Columns span mora biti cijeli broj.', chooseColor : 'Choose' // MISSING }, row : { menu : 'Red', insertBefore : 'Ubaci red prije', insertAfter : 'Ubaci red poslije', deleteRow : 'Izbriši redove' }, column : { menu : 'Kolona', insertBefore : 'Ubaci kolonu prije', insertAfter : 'Ubaci kolonu poslije', deleteColumn : 'Izbriši kolone' } }, // Button Dialog. button : { title : 'Image Button svojstva', text : 'Tekst (vrijednost)', type : 'Vrsta', typeBtn : 'Gumb', typeSbm : 'Pošalji', typeRst : 'Poništi' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Checkbox svojstva', radioTitle : 'Radio Button svojstva', value : 'Vrijednost', selected : 'Odabrano' }, // Form Dialog. form : { title : 'Form svojstva', menu : 'Form svojstva', action : 'Akcija', method : 'Metoda', encoding : 'Encoding' }, // Select Field Dialog. select : { title : 'Selection svojstva', selectInfo : 'Info', opAvail : 'Dostupne opcije', value : 'Vrijednost', size : 'Veličina', lines : 'linija', chkMulti : 'Dozvoli višestruki odabir', opText : 'Tekst', opValue : 'Vrijednost', btnAdd : 'Dodaj', btnModify : 'Promijeni', btnUp : 'Gore', btnDown : 'Dolje', btnSetValue : 'Postavi kao odabranu vrijednost', btnDelete : 'Obriši' }, // Textarea Dialog. textarea : { title : 'Textarea svojstva', cols : 'Kolona', rows : 'Redova' }, // Text Field Dialog. textfield : { title : 'Text Field svojstva', name : 'Ime', value : 'Vrijednost', charWidth : 'Širina', maxChars : 'Najviše karaktera', type : 'Vrsta', typeText : 'Tekst', typePass : 'Šifra' }, // Hidden Field Dialog. hidden : { title : 'Hidden Field svojstva', name : 'Ime', value : 'Vrijednost' }, // Image Dialog. image : { title : 'Svojstva slika', titleButton : 'Image Button svojstva', menu : 'Svojstva slika', infoTab : 'Info slike', btnUpload : 'Pošalji na server', upload : 'Pošalji', alt : 'Alternativni tekst', lockRatio : 'Zaključaj odnos', resetSize : 'Obriši veličinu', border : 'Okvir', hSpace : 'HSpace', vSpace : 'VSpace', alertUrl : 'Unesite URL slike', linkTab : 'Link', button2Img : 'Želite li promijeniti odabrani gumb u jednostavnu sliku?', img2Button : 'Želite li promijeniti odabranu sliku u gumb?', urlMissing : 'Image source URL is missing.', // MISSING validateBorder : 'Border must be a whole number.', // MISSING validateHSpace : 'HSpace must be a whole number.', // MISSING validateVSpace : 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash : { properties : 'Flash svojstva', propertiesTab : 'Svojstva', title : 'Flash svojstva', chkPlay : 'Auto Play', chkLoop : 'Ponavljaj', chkMenu : 'Omogući Flash izbornik', chkFull : 'Omogući Fullscreen', scale : 'Omjer', scaleAll : 'Prikaži sve', scaleNoBorder : 'Bez okvira', scaleFit : 'Točna veličina', access : 'Script Access', accessAlways : 'Uvijek', accessSameDomain: 'Ista domena', accessNever : 'Nikad', alignAbsBottom : 'Abs dolje', alignAbsMiddle : 'Abs sredina', alignBaseline : 'Bazno', alignTextTop : 'Vrh teksta', quality : 'Kvaliteta', qualityBest : 'Best', qualityHigh : 'High', qualityAutoHigh : 'Auto High', qualityMedium : 'Medium', qualityAutoLow : 'Auto Low', qualityLow : 'Low', windowModeWindow: 'Window', windowModeOpaque: 'Opaque', windowModeTransparent : 'Transparent', windowMode : 'Vrsta prozora', flashvars : 'Varijable za Flash', bgcolor : 'Boja pozadine', hSpace : 'HSpace', vSpace : 'VSpace', validateSrc : 'Molimo upišite URL link', validateHSpace : 'HSpace mora biti broj.', validateVSpace : 'VSpace mora biti broj.' }, // Speller Pages Dialog spellCheck : { toolbar : 'Provjeri pravopis', title : 'Provjera pravopisa', notAvailable : 'Žao nam je, ali usluga trenutno nije dostupna.', errorLoading : 'Greška učitavanja aplikacije: %s.', notInDic : 'Nije u rječniku', changeTo : 'Promijeni u', btnIgnore : 'Zanemari', btnIgnoreAll : 'Zanemari sve', btnReplace : 'Zamijeni', btnReplaceAll : 'Zamijeni sve', btnUndo : 'Vrati', noSuggestions : '-Nema preporuke-', progress : 'Provjera u tijeku...', noMispell : 'Provjera završena: Nema grešaka', noChanges : 'Provjera završena: Nije napravljena promjena', oneChange : 'Provjera završena: Jedna riječ promjenjena', manyChanges : 'Provjera završena: Promijenjeno %1 riječi', ieSpellDownload : 'Provjera pravopisa nije instalirana. Želite li skinuti provjeru pravopisa?' }, smiley : { toolbar : 'Smješko', title : 'Ubaci smješka', options : 'Smiley Options' // MISSING }, elementsPath : { eleLabel : 'Elements path', // MISSING eleTitle : '%1 element' }, numberedlist : 'Brojčana lista', bulletedlist : 'Obična lista', indent : 'Pomakni udesno', outdent : 'Pomakni ulijevo', justify : { left : 'Lijevo poravnanje', center : 'Središnje poravnanje', right : 'Desno poravnanje', block : 'Blok poravnanje' }, blockquote : 'Blockquote', clipboard : { title : 'Zalijepi', cutError : 'Sigurnosne postavke Vašeg pretraživača ne dozvoljavaju operacije automatskog izrezivanja. Molimo koristite kraticu na tipkovnici (Ctrl/Cmd+X).', copyError : 'Sigurnosne postavke Vašeg pretraživača ne dozvoljavaju operacije automatskog kopiranja. Molimo koristite kraticu na tipkovnici (Ctrl/Cmd+C).', pasteMsg : 'Molimo zaljepite unutar doljnjeg okvira koristeći tipkovnicu (<STRONG>Ctrl/Cmd+V</STRONG>) i kliknite <STRONG>OK</STRONG>.', securityMsg : 'Zbog sigurnosnih postavki Vašeg pretraživača, editor nema direktan pristup Vašem međuspremniku. Potrebno je ponovno zalijepiti tekst u ovaj prozor.', pasteArea : 'Paste Area' // MISSING }, pastefromword : { confirmCleanup : 'Tekst koji želite zalijepiti čini se da je kopiran iz Worda. Želite li prije očistiti tekst?', toolbar : 'Zalijepi iz Worda', title : 'Zalijepi iz Worda', error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText : { button : 'Zalijepi kao čisti tekst', title : 'Zalijepi kao čisti tekst' }, templates : { button : 'Predlošci', title : 'Predlošci sadržaja', options : 'Template Options', // MISSING insertOption : 'Zamijeni trenutne sadržaje', selectPromptMsg : 'Molimo odaberite predložak koji želite otvoriti<br>(stvarni sadržaj će biti izgubljen):', emptyListMsg : '(Nema definiranih predložaka)' }, showBlocks : 'Prikaži blokove', stylesCombo : { label : 'Stil', panelTitle : 'Formatting Styles', // MISSING panelTitle1 : 'Block stilovi', panelTitle2 : 'Inline stilovi', panelTitle3 : 'Object stilovi' }, format : { label : 'Format', panelTitle : 'Format', tag_p : 'Normal', tag_pre : 'Formatirano', tag_address : 'Address', tag_h1 : 'Heading 1', tag_h2 : 'Heading 2', tag_h3 : 'Heading 3', tag_h4 : 'Heading 4', tag_h5 : 'Heading 5', tag_h6 : 'Heading 6', tag_div : 'Normal (DIV)' }, div : { title : 'Create Div Container', // MISSING toolbar : 'Create Div Container', // MISSING cssClassInputLabel : 'Stylesheet Classes', // MISSING styleSelectLabel : 'Style', // MISSING IdInputLabel : 'Id', // MISSING languageCodeInputLabel : ' Language Code', // MISSING inlineStyleInputLabel : 'Inline Style', // MISSING advisoryTitleInputLabel : 'Advisory Title', // MISSING langDirLabel : 'Language Direction', // MISSING langDirLTRLabel : 'Left to Right (LTR)', // MISSING langDirRTLLabel : 'Right to Left (RTL)', // MISSING edit : 'Edit Div', // MISSING remove : 'Remove Div' // MISSING }, iframe : { title : 'IFrame Properties', // MISSING toolbar : 'IFrame', // MISSING noUrl : 'Please type the iframe URL', // MISSING scrolling : 'Enable scrollbars', // MISSING border : 'Show frame border' // MISSING }, font : { label : 'Font', voiceLabel : 'Font', panelTitle : 'Font' }, fontSize : { label : 'Veličina', voiceLabel : 'Veličina slova', panelTitle : 'Veličina' }, colorButton : { textColorTitle : 'Boja teksta', bgColorTitle : 'Boja pozadine', panelTitle : 'Colors', // MISSING auto : 'Automatski', more : 'Više boja...' }, colors : { '000' : 'Black', // MISSING '800000' : 'Maroon', // MISSING '8B4513' : 'Saddle Brown', // MISSING '2F4F4F' : 'Dark Slate Gray', // MISSING '008080' : 'Teal', // MISSING '000080' : 'Navy', // MISSING '4B0082' : 'Indigo', // MISSING '696969' : 'Dark Gray', // MISSING 'B22222' : 'Fire Brick', // MISSING 'A52A2A' : 'Brown', // MISSING 'DAA520' : 'Golden Rod', // MISSING '006400' : 'Dark Green', // MISSING '40E0D0' : 'Turquoise', // MISSING '0000CD' : 'Medium Blue', // MISSING '800080' : 'Purple', // MISSING '808080' : 'Gray', // MISSING 'F00' : 'Red', // MISSING 'FF8C00' : 'Dark Orange', // MISSING 'FFD700' : 'Gold', // MISSING '008000' : 'Green', // MISSING '0FF' : 'Cyan', // MISSING '00F' : 'Blue', // MISSING 'EE82EE' : 'Violet', // MISSING 'A9A9A9' : 'Dim Gray', // MISSING 'FFA07A' : 'Light Salmon', // MISSING 'FFA500' : 'Orange', // MISSING 'FFFF00' : 'Yellow', // MISSING '00FF00' : 'Lime', // MISSING 'AFEEEE' : 'Pale Turquoise', // MISSING 'ADD8E6' : 'Light Blue', // MISSING 'DDA0DD' : 'Plum', // MISSING 'D3D3D3' : 'Light Grey', // MISSING 'FFF0F5' : 'Lavender Blush', // MISSING 'FAEBD7' : 'Antique White', // MISSING 'FFFFE0' : 'Light Yellow', // MISSING 'F0FFF0' : 'Honeydew', // MISSING 'F0FFFF' : 'Azure', // MISSING 'F0F8FF' : 'Alice Blue', // MISSING 'E6E6FA' : 'Lavender', // MISSING 'FFF' : 'White' // MISSING }, scayt : { title : 'Provjeri pravopis tijekom tipkanja (SCAYT)', opera_title : 'Not supported by Opera', // MISSING enable : 'Omogući SCAYT', disable : 'Onemogući SCAYT', about : 'O SCAYT', toggle : 'Omoguću/Onemogući SCAYT', options : 'Opcije', langs : 'Jezici', moreSuggestions : 'Više prijedloga', ignore : 'Zanemari', ignoreAll : 'Zanemari sve', addWord : 'Dodaj riječ', emptyDic : 'Naziv rječnika ne smije biti prazno.', optionsTab : 'Opcije', allCaps : 'Ignore All-Caps Words', // MISSING ignoreDomainNames : 'Ignore Domain Names', // MISSING mixedCase : 'Ignore Words with Mixed Case', // MISSING mixedWithDigits : 'Ignore Words with Numbers', // MISSING languagesTab : 'Jezici', dictionariesTab : 'Rječnici', dic_field_name : 'Dictionary name', // MISSING dic_create : 'Create', // MISSING dic_restore : 'Restore', // MISSING dic_delete : 'Delete', // MISSING dic_rename : 'Rename', // MISSING dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab : 'O SCAYT' }, about : { title : 'O CKEditoru', dlgTitle : 'O CKEditoru', help : 'Check $1 for help.', // MISSING userGuide : 'CKEditor User\'s Guide', // MISSING moreInfo : 'Za informacije o licencama posjetite našu web stranicu:', copy : 'Copyright &copy; $1. All rights reserved.' }, maximize : 'Povećaj', minimize : 'Minimize', // MISSING fakeobjects : { anchor : 'Sidro', flash : 'Flash animacija', iframe : 'IFrame', // MISSING hiddenfield : 'Hidden Field', // MISSING unknown : 'Nepoznati objekt' }, resize : 'Povuci za promjenu veličine', colordialog : { title : 'Select color', // MISSING options : 'Color Options', // MISSING highlight : 'Highlight', // MISSING selected : 'Selected Color', // MISSING clear : 'Clear' // MISSING }, toolbarCollapse : 'Collapse Toolbar', // MISSING toolbarExpand : 'Expand Toolbar', // MISSING toolbarGroups : { document : 'Document', // MISSING clipboard : 'Clipboard/Undo', // MISSING editing : 'Editing', // MISSING forms : 'Forms', // MISSING basicstyles : 'Basic Styles', // MISSING paragraph : 'Paragraph', // MISSING links : 'Links', // MISSING insert : 'Insert', // MISSING styles : 'Styles', // MISSING colors : 'Colors', // MISSING tools : 'Tools' // MISSING }, bidi : { ltr : 'Text direction from left to right', // MISSING rtl : 'Text direction from right to left' // MISSING }, docprops : { label : 'Svojstva dokumenta', title : 'Svojstva dokumenta', design : 'Design', // MISSING meta : 'Meta Data', chooseColor : 'Choose', // MISSING other : '<drugi>', docTitle : 'Naslov stranice', charset : 'Enkodiranje znakova', charsetOther : 'Ostalo enkodiranje znakova', charsetASCII : 'ASCII', // MISSING charsetCE : 'Središnja Europa', charsetCT : 'Tradicionalna kineska (Big5)', charsetCR : 'Ćirilica', charsetGR : 'Grčka', charsetJP : 'Japanska', charsetKR : 'Koreanska', charsetTR : 'Turska', charsetUN : 'Unicode (UTF-8)', // MISSING charsetWE : 'Zapadna Europa', docType : 'Zaglavlje vrste dokumenta', docTypeOther : 'Ostalo zaglavlje vrste dokumenta', xhtmlDec : 'Ubaci XHTML deklaracije', bgColor : 'Boja pozadine', bgImage : 'URL slike pozadine', bgFixed : 'Pozadine se ne pomiče', txtColor : 'Boja teksta', margin : 'Margine stranice', marginTop : 'Vrh', marginLeft : 'Lijevo', marginRight : 'Desno', marginBottom : 'Dolje', metaKeywords : 'Ključne riječi dokumenta (odvojene zarezom)', metaDescription : 'Opis dokumenta', metaAuthor : 'Autor', metaCopyright : 'Autorska prava', previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING } };
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.3-3-1 description: Object.getOwnPropertyDescriptor - 'P' is own data property includes: [runTestCase.js] ---*/ function testcase() { var obj = { property: "ownDataProperty" }; var desc = Object.getOwnPropertyDescriptor(obj, "property"); return desc.value === "ownDataProperty"; } runTestCase(testcase);
var path = require('path'); var gulp = require('gulp'); var args = require('yargs').argv; var colors = require('colors'); var spawn = require('child_process').spawn; var fs = require('fs'); const mappings = require('./api-specs.json'); const defaultSpecRoot = "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master"; gulp.task('default', function () { console.log("Usage: gulp codegen " + "[--spec-root <swagger specs root>] " + "[--projects <project names>] " + "[--autorest <autorest info>] " + "[--autorest-csharp <autorest.csharp info>] " + "[--debug] " + "[--autorest-args <AutoRest arguments>]\n"); console.log("--spec-root"); console.log(`\tRoot location of Swagger API specs, default value is "${defaultSpecRoot}"`); console.log("--projects"); console.log("\tComma separated projects to regenerate, default is all. List of available project names:"); Object.keys(mappings).forEach(function(i) { console.log('\t' + i.magenta); }); console.log("--autorest"); console.log("\tThe version of AutoRest. E.g. 2.0.9, or the location of AutoRest repo, e.g. E:\\repo\\autorest"); console.log("--autorest-csharp"); console.log("\tThe NPM version number for the autorest.csharp generator, e.g. @2.1.28 or @preview, or a file path to a local autorest.csharp generator."); console.log("\tUsually you'll only need to provide this and not a --autorest argument in order to work on C# code generation."); console.log("\tSee https://github.com/Azure/autorest/blob/master/docs/developer/autorest-extension.md"); console.log("--debug"); console.log("\tFlag that allows you to attach a debugger to the autorest.csharp generator."); console.log("--autorest-args"); console.log("\tPasses additional argument to AutoRest generator"); }); var specRoot = args['spec-root'] || defaultSpecRoot; var projects = args['projects']; var autoRestVersion = 'latest'; // default if (args['autorest'] !== undefined) { autoRestVersion = args['autorest']; } var debug = args['debug']; var autoRestArgs = args['autorest-args'] || ''; var autoRestExe; gulp.task('codegen', function (cb) { if (autoRestVersion.match(/[0-9]+\.[0-9]+\.[0-9]+.*/) || autoRestVersion == 'latest' || autoRestVersion == 'preview') { autoRestExe = 'autorest ---version=' + autoRestVersion; handleInput(projects, cb); } else { autoRestExe = "node " + path.join(autoRestVersion, "src/autorest-core/dist/app.js"); handleInput(projects, cb); } }); var handleInput = function (projects, cb) { if (projects === undefined) { Object.keys(mappings).forEach(function (proj) { codegen(proj, cb); }); } else { projects.split(",").forEach(function (proj) { proj = proj.replace(/\ /g, ''); if (mappings[proj] === undefined) { console.error('Invalid project name "' + proj + '"!'); process.exit(1); } codegen(proj, cb); }); } } var codegen = function (project, cb) { const regenManager = args['regenerate-manager'] ? ' --regenerate-manager=true ' : ''; var outputDir = path.resolve(mappings[project].dir); if (!args['preserve']) { deleteFolderRecursive(outputDir); } console.log('Generating "' + project + '" from spec file ' + specRoot + '/' + mappings[project].source); var generator = '--fluent'; if (mappings[project].fluent !== null && mappings[project].fluent === false) { generator = ''; } const autorestCSArg = args['autorest-csharp'] || "@latest"; const generatorPath = autorestCSArg.startsWith("@") ? "@microsoft.azure/autorest.csharp" + autorestCSArg : path.resolve(autorestCSArg); const autorestUseArg = `--use=${generatorPath}`; cmd = autoRestExe + ' ' + specRoot + "/" + mappings[project].source + ' --csharp ' + ' --azure-arm ' + generator + ' --csharp.sync-methods=none ' + ` --csharp.namespace=${mappings[project].package} ` + ` --csharp.output-folder=${outputDir} ` + ` --csharp.license-header=MICROSOFT_MIT_NO_CODEGEN ` + ` --csharp.clear-output-folder=false ` + autorestUseArg + regenManager + ' --use=@microsoft.azure/autorest.csharp@preview' + ' --package-version=1.3.0 ' + ' --runtime-version=3.3.10 ' + autoRestArgs; if (mappings[project].args !== undefined) { cmd = cmd + ' ' + mappings[project].args; } if (debug) { cmd += ' --csharp.debugger'; } console.log('Command: ' + cmd); spawn(cmd, [], { shell: true, stdio: "inherit" }); }; var deleteFolderRecursive = function(path) { var header = "Code generated by Microsoft (R) AutoRest Code Generator"; if(fs.existsSync(path)) { fs.readdirSync(path).forEach(function(file, index) { var curPath = path + "/" + file; if(fs.lstatSync(curPath).isDirectory()) { // recurse deleteFolderRecursive(curPath); } else { // delete file var content = fs.readFileSync(curPath).toString('utf8'); if (content.indexOf(header) > -1) { fs.unlinkSync(curPath); } } }); } };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require react //= require react_ujs //= require components //= require_tree . //= require bootstrap-sprockets //= require bootstrap //= require tether
/* * Report container widget * * Data attributes: * - data-control="report-container" - enables the report container plugin * * JavaScript API: * $('#container').reportContainer() * * Dependancies: * - Isotope (isotope.js) */ +function ($) { "use strict"; // REPORTCONTAINER CLASS DEFINITION // ============================ var ReportContainer = function(element, options) { this.options = options this.$el= $(element) this.$form = this.$el.closest('form') this.$toolbar = $('[data-container-toolbar]', this.$form) this.alias = $('[data-container-alias]', this.$form).val() this.init(); } ReportContainer.DEFAULTS = { breakpoint: 768, columns: 10 } ReportContainer.prototype.init = function (){ var self = this this.$el.isotope({ itemSelector: '.item', resizable: false }) $(window).resize($.proxy(this.updateWidth, this)) this.updateWidth() if (!Modernizr.touch) { this.$el.sortable({ vertical: false, handle: '.drag-handle', onDrop: function($item, container, _super) { $item.removeClass("dragged") $("body").removeClass("dragging") self.updateSeparators() self.redraw() self.postSortOrders() } }) } this.$el.on('hidden.oc.inspector', '[data-inspectable]', function() { var values = $('[data-inspector-values]', this).val(), parsedValues = $.parseJSON(values), li = $(this).closest('li').get(0) self.$form.request(self.alias + '::onUpdateWidget', { data: { 'fields': values, 'alias': $('[data-widget-alias]', $(this).closest('div.content')).val() }, success: function(data) { this.success(data).done(function(){ li.className = li.className.replace(/width\-[0-9]+/g, '') $(li).addClass('width-'+parsedValues['ocWidgetWidth']) $(li).toggleClass('new-line', parsedValues['ocWidgetNewRow'] == 1) self.updateSeparators() self.redraw() }) } }) }) this.$el.on('click', '.content > button.close', function() { var $btn = $(this) $.oc.confirm('Remove this widget?', function() { self.$form.request(self.alias + '::onRemoveWidget', { data: { 'alias': $('[data-widget-alias]', $btn.closest('div.content')).val() } }) $btn.closest('li').remove() self.redraw() self.setSortOrders() }) }) $(window).on('oc.reportWidgetAdded', function(){ self.redraw() self.setSortOrders() }) $(window).on('oc.reportWidgetRefresh', function(){ self.redraw() }) window.setTimeout(function(){ self.updateWidth() self.redraw() }, 200) this.setSortOrders() } ReportContainer.prototype.updateWidth = function(){ var width = this.$el.width(), wrapped = width <= this.options.breakpoint, columnWidth = wrapped ? width : width / this.options.columns this.$el.isotope({ masonry: { columnWidth: columnWidth } }) this.$el.toggleClass('wrapped', wrapped) } ReportContainer.prototype.redraw = function() { this.$el .isotope('reloadItems') .isotope({ sortBy: 'original-order' }) var $items = $('li.item', this.$el) $items.css({'width': '', 'height': ''}) $('> .dropdown', this.$toolbar).toggleClass('dropup', !!$items.length) } ReportContainer.prototype.setSortOrders = function() { this.sortOrders = [] var self = this $('[data-widget-order]', this.$el).each(function(){ self.sortOrders.push($(this).val()) }) } ReportContainer.prototype.postSortOrders = function() { var aliases = [], self = this $('[data-widget-alias]', this.$el).each(function(){ aliases.push($(this).val()) }) this.$form.request(self.alias + '::onSetWidgetOrders', { data: { 'aliases': aliases.join(','), 'orders': self.sortOrders.join(',') } }) } ReportContainer.prototype.updateSeparators = function() { $('li.item.separator', this.$el).remove() $('li.item.new-line', this.$el).each(function(){ $(this).before('<li class="item separator"></li>') }) } // REPORTCONTAINER PLUGIN DEFINITION // ============================ var old = $.fn.reportContainer $.fn.reportContainer = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('oc.reportContainer') var options = $.extend({}, ReportContainer.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('oc.reportContainer', (data = new ReportContainer(this, options))) if (typeof option == 'string') data[option].call($this) }) } $.fn.reportContainer.Constructor = ReportContainer // REPORTCONTAINER NO CONFLICT // ================= $.fn.reportContainer.noConflict = function () { $.fn.reportContainer = old return this } // REPORTCONTAINER DATA-API // =============== $(document).render(function () { $('[data-control="report-container"]').reportContainer() }) }(window.jQuery);
import React, {Component} from 'react'; import SelectField from 'material-ui/SelectField'; class TeamMatch extends Component { render() { const style = { h1: { fontFamily: "Roboto", fontSize: 22, fontWeight: 500, marginTop: 15, marginBottom: 0, }, matchContainer: { width: "80%", margin: "auto", }, }; return ( <div style={style.matchContainer}> <h1 style={style.h1}> Match {this.props.matchNumber} </h1> <SelectField value={this.props.player1} fullWidth={true} onChange={this.props.selectPlayer1} maxHeight={200} > {this.props.players} </SelectField> <div> <span>and</span> </div> <SelectField value={this.props.player2} fullWidth={true} onChange={this.props.selectPlayer2} maxHeight={200} > {this.props.players} </SelectField> </div> ) } } export default TeamMatch;
AwsApplicationModel = AwsDeploy.Model.extend({ idAttribute: "application_name" }); AwsApplicationCollection = AwsDeploy.Collection.extend({ model: AwsApplicationModel, url: "/aws/apps" }); AwsEnvironmentModel = AwsDeploy.Model.extend({ idAttribute: "environment_id" }); AwsEnvironmentCollection = AwsDeploy.Collection.extend({ model: AwsEnvironmentModel, url: function () { return "/aws/apps/" + this.application_name + "/environments"; } }); AwsApplicationVersionModel = AwsDeploy.Model.extend({ idAttribute: "version_label" }); AwsApplicationVersionCollection = AwsDeploy.Collection.extend({ model: AwsApplicationVersionModel, url: function () { return "/aws/apps/" + this.application_name + "/versions"; } }); AwsS3BucketModel = AwsDeploy.Model.extend({ idAttribute: "bucket_name" }); AwsS3BucketCollection = AwsDeploy.Collection.extend({ model: AwsS3BucketModel, url: function () { return "/aws/s3/buckets"; } });
version https://git-lfs.github.com/spec/v1 oid sha256:4cf204823e3498eff3398eefe0ba3895ba2ec12a24deeb0ff1ae3f01c5ce5f2d size 129