code
stringlengths
2
1.05M
/** * Created by kobi on 5/15/14. */ exports.welcome = function(req,res){ res.json({message:'welcome to Money Map API'}); }
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard = require('./scoreboard'), ParticleEmitter = require('./particle-emitter'), CharacterParticleEmitter = require('./character-particle-emitter'); const eventBus = require('./event-bus'), screenShake = require('./screen-shake'); class Level { /** * @param number Level number * @param input * @param stage */ constructor(number, input, stage, levelEnding, mazeNumber) { this.number = number; this._input = input; this._stage = stage; this._gfx = new PIXI.Container(); this._gfx.z = 1; // custom property this._gfx.x = 32; this._gfx.y = 32; this._stage.addChild(this._gfx); this._board = new Board(this._gfx, mazeNumber); this._longTasksManager = new LongTasks.Manager(); this._characters = new Characters(this._board, this._gfx, this._longTasksManager); this._currentGhostSubModeIndex = 0; this._ghostSubModeElapsed = 0; this._frightTimeLeft = null; this._lvlSpec = null; this._pause = new Pause(stage, input); this._scoreboard = new Scoreboard(stage); levelEnding.scoreboard = this._scoreboard; this._particleEmitter = new ParticleEmitter(this._gfx); this._characterParticleEmitter = new CharacterParticleEmitter(this._gfx); } start() { this._lvlSpec = config.levelSpecifications[this.number]; this._characters.start(this._lvlSpec); this._pause.start(); this._scoreboard.start(); this._particleEmitter.start(); this._characterParticleEmitter.start(); screenShake.start(this._gfx); eventBus.fire({ name: 'event.level.start', args: { levelNumber: this.number } }); } stop() { this._characters.stop(); this._pause.stop(); this._scoreboard.stop(); this._particleEmitter.stop(); this._characterParticleEmitter.stop(); screenShake.stop(); // TODO: In next game, make this more encapsulated let idx = this._stage.getChildIndex(this._gfx); this._stage.removeChildAt(idx); this._gfx.destroy(true); } step(elapsed) { if (this._pause.active) { // TODO: Count how long paused } else { this._handleLongTasks(elapsed); this._handleSubMode(elapsed); this._handleCollisionsAndSteps(elapsed); screenShake.step(elapsed); this._particleEmitter.step(elapsed); this._characterParticleEmitter.step(elapsed); } this._stepPaused(elapsed); } checkForEndLevelCondition() { return this._board.dotsLeft() == false; } _stepPaused(elapsed) { this._pause.step(elapsed); } _handleLongTasks(elapsed) { this._longTasksManager.step(elapsed); } _handleSubMode(elapsed) { if (this._frightTimeLeft !== null) { this._handleFrightLeft(elapsed); return; // fright essentially pauses the sub-mode timer. } this._ghostSubModeElapsed += elapsed; let currentSubModeTotalTime = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].time; if (this._ghostSubModeElapsed >= currentSubModeTotalTime) { this._currentGhostSubModeIndex += 1; this._ghostSubModeElapsed = 0; let mode = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].mode; this._characters.switchMode(mode); } } _handleFrightLeft(elapsed) { this._frightTimeLeft -= elapsed; if (this._frightTimeLeft <= 0) { this._characters.removeRemainingFright(); this._frightTimeLeft = null; } else { // TODO: Here check if flashing should start } } _handleCollisionsAndSteps(elapsed) { let result = this._characters.checkCollisions(); let requestedDirection = this._determineRequestedDirection(); if (result.collision) { this._characters.stepPacman(0, requestedDirection); // 0 means stopped one frame } else { this._characters.stepPacman(elapsed, requestedDirection); } this._characters.stepGhosts(elapsed); if (result.energizer) { this._characters.signalFright(); this._frightTimeLeft = this._lvlSpec.frightTime; eventBus.fire({ name: 'event.action.energizer' }); } if (result.dot) { eventBus.fire({ name: 'event.action.eatdot', args: { x: result.x, y: result.y, direction: this._determineCurrentDirection() } }); } } _determineRequestedDirection() { if (this._input.isDown('up')) { return 'up'; } else if (this._input.isDown('down')) { return 'down'; } else if (this._input.isDown('left')) { return 'left'; } else if (this._input.isDown('right')) { return 'right'; } else { // null means no new requested direction; stay the course return null; } } _determineCurrentDirection() { return this._characters.determineCurrentDirection(); } } module.exports = Level;
/* this file is autogenerated*/
/* globals options */ /* eslint-disable comma-dangle */ var opt = options; var socket = new WebSocket('ws://localhost:' + opt.port); socket.addEventListener('message', function(event) { var ngHotReloadCore = (opt.root || window)[opt.ns].ngHotReloadCore; var data = event.data ? JSON.parse(event.data) : {}; if (data.message !== 'reload') { return; } if (data.fileType === 'script') { // If this is a js file, update by creating a script tag // and loading the updated file from the ng-hot-reload server. var script = document.createElement('script'); // Prevent browser from using a cached version of the file. var query = '?t=' + Date.now(); script.src = 'http://localhost:' + opt.port + '/' + data.src + query; document.body.appendChild(script); } else if (data.fileType === 'template') { ngHotReloadCore.template.update(data.filePath, data.file); } else { var errorMsg = 'Unknown file type ' + data.filePath; ngHotReloadCore.manualReload(errorMsg); } });
//repl read eval print loop console.log('start');
"use strict"; class FeatsPage extends ListPage { constructor () { const pageFilter = new PageFilterFeats(); super({ dataSource: "data/feats.json", pageFilter, listClass: "feats", sublistClass: "subfeats", dataProps: ["feat"], isPreviewable: true, }); } getListItem (feat, ftI, isExcluded) { this._pageFilter.mutateAndAddToFilters(feat, isExcluded); const eleLi = document.createElement("div"); eleLi.className = `lst__row flex-col ${isExcluded ? "lst__row--blacklisted" : ""}`; const source = Parser.sourceJsonToAbv(feat.source); const hash = UrlUtil.autoEncodeHash(feat); eleLi.innerHTML = `<a href="#${hash}" class="lst--border lst__row-inner"> <span class="col-0-3 px-0 flex-vh-center lst__btn-toggle-expand self-flex-stretch">[+]</span> <span class="bold col-3-5 px-1">${feat.name}</span> <span class="col-3-5 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slAbility}</span> <span class="col-3 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slPrereq}</span> <span class="source col-1-7 text-center ${Parser.sourceJsonToColor(feat.source)} pr-0" title="${Parser.sourceJsonToFull(feat.source)}" ${BrewUtil.sourceJsonToStyle(feat.source)}>${source}</span> </a> <div class="flex ve-hidden relative lst__wrp-preview"> <div class="vr-0 absolute lst__vr-preview"></div> <div class="flex-col py-3 ml-4 lst__wrp-preview-inner"></div> </div>`; const listItem = new ListItem( ftI, eleLi, feat.name, { hash, source, ability: feat._slAbility, prerequisite: feat._slPrereq, }, { uniqueId: feat.uniqueId ? feat.uniqueId : ftI, isExcluded, }, ); eleLi.addEventListener("click", (evt) => this._list.doSelect(listItem, evt)); eleLi.addEventListener("contextmenu", (evt) => ListUtil.openContextMenu(evt, this._list, listItem)); return listItem; } handleFilterChange () { const f = this._filterBox.getValues(); this._list.filter(item => this._pageFilter.toDisplay(f, this._dataList[item.ix])); FilterBox.selectFirstVisible(this._dataList); } getSublistItem (feat, pinId) { const hash = UrlUtil.autoEncodeHash(feat); const $ele = $(`<div class="lst__row lst__row--sublist flex-col"> <a href="#${hash}" class="lst--border lst__row-inner"> <span class="bold col-4 pl-0">${feat.name}</span> <span class="col-4 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none" : ""}">${feat._slAbility}</span> <span class="col-4 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none" : ""} pr-0">${feat._slPrereq}</span> </a> </div>`) .contextmenu(evt => ListUtil.openSubContextMenu(evt, listItem)) .click(evt => ListUtil.sublist.doSelect(listItem, evt)); const listItem = new ListItem( pinId, $ele, feat.name, { hash, ability: feat._slAbility, prerequisite: feat._slPrereq, }, ); return listItem; } doLoadHash (id) { const feat = this._dataList[id]; $("#pagecontent").empty().append(RenderFeats.$getRenderedFeat(feat)); ListUtil.updateSelected(); } async pDoLoadSubHash (sub) { sub = this._filterBox.setFromSubHashes(sub); await ListUtil.pSetFromSubHashes(sub); } } const featsPage = new FeatsPage(); window.addEventListener("load", () => featsPage.pOnLoad());
jQuery(document).ready(function($){ var nameDefault = 'Your name...'; var emailDefault = 'Your email...'; var messageDefault = 'Your message...'; // Setting up existing forms setupforms(); function setupforms() { // Applying default values setupDefaultText('#name',nameDefault); setupDefaultText('#email',emailDefault); setupDefaultText('#message',messageDefault); // Focus / Blur check against defaults focusField('#name'); focusField('#email'); focusField('#message'); } function setupDefaultText(fieldID,fieldDefault) { $(fieldID).val(fieldDefault); $(fieldID).attr('data-default', fieldDefault); } function evalDefault(fieldID) { if($(fieldID).val() != $(fieldID).attr('data-default')) { return false; } else { return true; } } function hasDefaults(formType) { switch (formType) { case "contact" : if(evalDefault('#name') && evalDefault('#email') && evalDefault('#message')) { return true; } else { return false; } default : return false; } } function focusField(fieldID) { $(fieldID).focus(function(evaluation) { if(evalDefault(fieldID)) { $(fieldID).val(''); } }).blur(function(evaluation) { if(evalDefault(fieldID) || $(fieldID).val() === '') { $(fieldID).val($(fieldID).attr('data-default')); } }); } $('.button-submit').click(function(event) { event.preventDefault(); }); $('#submit-contact').bind('click', function(){ if(!hasDefaults('contact')) { $('#form-contact').submit(); } }); $("#form-contact").validate({ rules: { name: { required: true, minlength: 3 }, email: { required: true, email: true }, message: { required: true, minlength: 10 } }, messages: { name: { required: "Please enter your name.", minlength: "Name must have at least 3 characters." }, email: { required: "Please enter your email address.", email: "This is not a valid email address format." }, message: { required: "Please enter a message.", minlength: "Message must have at least 10 characters." } } }); function validateContact() { if(!$('#form-contact').valid()) { return false; } else { return true; } } $("#form-contact").ajaxForm({ beforeSubmit: validateContact, type: "POST", url: "assets/php/contact-form-process.php", data: $("#form-contact").serialize(), success: function(msg){ $("#form-message").ajaxComplete(function(event, request, settings){ if(msg == 'OK') // Message Sent? Show the 'Thank You' message { result = '<span class="form-message-success"><i class="icon-thumbs-up"></i> Your message was sent. Thank you!</span>'; clear = true; } else { result = '<span class="form-message-error"><i class="icon-thumbs-down"></i> ' + msg +'</span>'; clear = false; } $(this).html(result); if(clear == true) { $('#name').val(''); $('#email').val(''); $('#message').val(''); } }); } }); });
$(document).ready(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()), // use the element's text as the event title className: $.trim($(this).attr("class").split(' ')[1]) // get the class name color[x] }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'agendaWeek,agendaDay' }, defaultView: 'agendaDay', timeFormat: 'H:mm{ - H:mm}', axisFormat: 'H:mm', minTime: '8:00', maxTime: '22:00', allDaySlot: false, monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'], dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], titleFormat: { month: 'yyyy MMMM', week: "yyyy'年' MMM d'日'{ '&#8212;'[ MMM] d'日' }", day: "dddd, yyyy'年' MMM d'日'" }, /*defaultEventMinutes: 120, */ selectable: true, selectHelper: true, select: function(start, end, allDay) { var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); calendar.fullCalendar('renderEvent', { title: type, start: start, end: end, allDay: allDay, className: color }, true // make the event "stick" ); calendar.fullCalendar('unselect'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }, editable: true, eventMouseover: function(event, domEvent) { /* for(var key in event){ $("<p>").text(key + ':' + event[key]).appendTo($("body")); }; */ var layer = '<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100"><a><img src="images/icon_edit.gif" title="edit" width="14" id="edbut'+event._id+'" border="0" style="padding-right:3px; padding-top:2px;" /></a><a><img src="images/icon_delete.png" title="delete" width="14" id="delbut'+event._id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a></div>'; $(this).append(layer); $("#delbut"+event._id).hide(); $("#delbut"+event._id).fadeIn(300); $("#delbut"+event._id).click(function() { calendar.fullCalendar('removeEvents', event._id); //$.post("delete.php", {eventId: event._id}); calendar.fullCalendar('refetchEvents'); }); $("#edbut"+event._id).hide(); $("#edbut"+event._id).fadeIn(300); $("#edbut"+event._id).click(function() { //var title = prompt('Current Event Title: ' + event.title + '\n\nNew Event Title: '); /* if(title){ $.post("update_title.php", {eventId: event.id, eventTitle: title}); calendar.fullCalendar('refetchEvents'); } */ var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); event.title = type; event.className = color; calendar.fullCalendar('updateEvent', event); calendar.fullCalendar('refetchEvents'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }); }, eventMouseout: function(calEvent, domEvent) { $("#events-layer").remove(); }, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.end = (date.getTime() + 7200000)/1000; copiedEventObject.allDay = false; // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); } }); });
#!/usr/bin/env node var app = require('./app'), config = require('./config'); app.set('port', process.env.PORT || config.app.port); var server = app.listen(app.get('port'), function() { "use strict"; console.log('Express server listening on port ' + server.address().port); });
"use strict"; /** * Storing multiple constant values inside of an object * Keep in mind the values in the object mean they can be modified * Which makes no sense for a constant, use wisely if you do this */ app.service('$api', ['$http', '$token', '$rootScope', '$sweetAlert', '$msg', 'SERVER_URL', function ($http, $token, $rootScope, $sweetAlert, $msg, SERVER_URL) { const SERVER_URI = SERVER_URL + 'api/'; var config = { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()} }; /* Authentication Service ----------------------------------------------*/ this.isAuthorized = function (module_name) { return $http.get(SERVER_URI + 'check_auth', { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()}, params: {'module_name': module_name} }); }; this.authenticate = function (data) { return $http.post(SERVER_URI + 'login', data); }; this.resetPassword = function (email) { return $http.post(SERVER_URI + 'reset_password', email); }; this.exit = function () { $token.deleteFromAllStorage(); return $http.get(SERVER_URI + 'logout', {params: {user: $rootScope.user} }) }; /* User Service ----------------------------------------------*/ this.findMember = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'all_users', params.search, config); } return $http.get(SERVER_URI + 'all_users', config); }; this.removeMember = function (data) { return $http.delete(SERVER_URI + 'remove_profile/' + data, config); }; this.updateUserProfile = function (data) { return $http.put(SERVER_URI + 'update_profile', data, config); }; this.usersCount = function () { return $http.get(SERVER_URI + 'users_count', config); }; /* Shop Service ----------------------------------------------*/ this.makePayment = function (params) { config.params = params; return $http.get(SERVER_URI + 'execute_payment', config); }; /* Chat Service ----------------------------------------------*/ this.getChatList = function (params) { return $http.get(SERVER_URI+'chat_list', config); }; this.saveMessage = function(data) { return $http.post(SERVER_URI + 'save_message', data, config); }; this.getConversation = function () { }; /* Product Service ----------------------------------------------*/ this.products = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'product_list', params.search, config); } return $http.get(SERVER_URI + 'product_list', config); }; this.productDetail = function (id) { config.params = {id: id}; return $http.get(SERVER_URI + 'product_detail', config); }; this.buyProduct = function (params) { config.params = params; return $http.get(SERVER_URI + 'buy_product', config); }; this.handleError = function (res) { switch (res.status) { case 400: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 403: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 500: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; case 503: $sweetAlert.error(res.statusText, $msg.SERVICE_UNAVAILABLE); break; case 404: $sweetAlert.error(res.statusText, $msg.NOT_FOUND_ERROR); break; default: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; } }; }]);
/** * @file Link files. * @function filelink * @param {string} src - Source file (actual file) path. * @param {string} dest - Destination file (link) path. * @param {object} [options] - Optional settings. * @param {string} [options.type='symlink'] - Link type * @param {boolean} [options.mkdirp] - Make parent directories. * @param {boolean} [options.force] - Force to symlink or not. * @param {function} callback - Callback when done. */ 'use strict' const fs = require('fs') const argx = require('argx') const path = require('path') const {mkdirpAsync, existsAsync, statAsync} = require('asfs') const _cleanDest = require('./_clean_dest') const _followSymlink = require('./_follow_symlink') /** @lends filelink */ async function filelink (src, dest, options) { let args = argx(arguments) if (args.pop('function')) { throw new Error('Callback is no more supported. Use promise interface instead') } options = args.pop('object') || {} const cwd = options.cwd || process.cwd() src = path.resolve(cwd, args.shift('string')) dest = path.resolve(cwd, args.shift('string')) const type = options.type || 'symlink' const force = !!options.force const destDir = path.dirname(dest) src = await _followSymlink(src) if (options.mkdirp) { await mkdirpAsync(destDir) } else { let exists = await existsAsync(destDir) if (!exists) { throw new Error(`Directory not exists: ${destDir}`) } } let srcName = path.relative(destDir, src) let destName = path.relative(destDir, dest) let before = (await existsAsync(dest)) && (await statAsync(dest)) if (force) { await _cleanDest(dest) } process.chdir(destDir) _doLinkSync(srcName, destName, type) process.chdir(cwd) let after = (await existsAsync(dest)) && (await statAsync(dest)) await new Promise((resolve) => process.nextTick(() => resolve())) let unchanged = (before && before.size) === (after && after.size) return !unchanged } module.exports = filelink function _doLinkSync (src, dest, type) { switch (type) { case 'link': fs.linkSync(src, dest) break case 'symlink': fs.symlinkSync(src, dest) break default: throw new Error('Unknown type:' + type) } }
// EXPRESS SERVER HERE // // BASE SETUP var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), methodOverride = require('method-override'), // routes = require('./routes/routes'), morgan = require('morgan'), serveStatic = require('serve-static'), errorHandler = require('errorhandler'); // =========================CONFIGURATION===========================// // =================================================================// app.set('port', process.env.PORT || 9001); /* * Set to 9001 to not interfere with Gulp 9000. * If you're using Cloud9, or an IDE that uses a different port, process.env.PORT will * take care of your problems. You don't need to set a new port. */ app.use(serveStatic('app', {'index': 'true'})); // Set to True or False if you want to start on Index or not app.use('/bower_components', express.static(__dirname + '/bower_components')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(morgan('dev')); app.use(cookieParser('secret')); app.use(session({secret: 'evernote now', resave: true, saveUninitialized: true})); app.use(function(req, res, next) { res.locals.session = req.session; next(); }); if (process.env.NODE_ENV === 'development') { app.use(errorHandler()); } // ==========================ROUTER=================================// // =================================================================// // ROUTES FOR THE API - RUN IN THE ORDER LISTED var router = express.Router(); // ------------- ROUTES ---------------- // // REGISTERING THE ROUTES app.use('/', router); // STARTING THE SERVER console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!'); app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed exports = module.exports = app; // This is needed otherwise the index.js for routes will not work
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var json=JSON.parse(data); //Importar mòdul theThingsCoAP var theThingsCoAP = require('../../') //Crear client theThingsCoAP var client = theThingsCoAP.createClient() client.on('ready', function () { read(json.endDate) }) //Funció per llegir dades de la plataforma thethings.iO function read(endDate){ client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) { if (typeof data!=='undefined' && data!==null){ if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].value+coma+data[i].datetime.split('T')[1]+coma } socket.write(dataSend); read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replace(/:/g, '').replace('T', '')) }else{ socket.write("</FINAL>"); } } }) } }); //Configuració del port en el servidor TCP }).listen(port);
import { GET_WAREHOUSES_FULL_LIST, GET_WAREHOUSE, GET_COMPANIES, GET_SUPERVISORS } from '../actions/warehouses'; import humanize from 'humanize'; import Moment from 'moment'; const INITIAL_STATE = { warehousesList: [], warehouseDetail: {}, warehouseId: 0, companiesList: [], supervisorsList: [] }; export default function(state = INITIAL_STATE, action) { switch(action.type) { case GET_WAREHOUSES_FULL_LIST: return { ...state, warehousesList: action.payload.data.map(function(warehouse) { return { company: warehouse.company, supervisor: warehouse.supervisor, email: warehouse.email, telephone: warehouse.telephone, address: warehouse.address, contact_name: warehouse.contact_name, action: warehouse.id }; }) }; case GET_WAREHOUSE: return { ...state, warehouseDetail: { company: action.payload.data[0].company_id, supervisor: action.payload.data[0].supervisor_id, name: action.payload.data[0].name, email: action.payload.data[0].email, telephone: action.payload.data[0].telephone, address: action.payload.data[0].address, tax: action.payload.data[0].tax, contact_name: action.payload.data[0].contact_name }, warehouseId: action.payload.data[0].id } case GET_COMPANIES: return { ...state, companiesList: action.payload.data.map(function(company) { return { value: company.id, label: company.name } }) } case GET_SUPERVISORS: return { ...state, supervisorsList: action.payload.data.map(function(supervisor) { return { value: supervisor.id, label: supervisor.name } }) } default: return state; } }
dhtmlXForm.prototype.items.calendar = { render: function(item, data) { var t = this; item._type = "calendar"; item._enabled = true; this.doAddLabel(item, data); this.doAddInput(item, data, "INPUT", "TEXT", true, true, "dhxform_textarea"); item.childNodes[item._ll?1:0].childNodes[0]._idd = item._idd; item._f = (data.dateFormat||"%d-%m-%Y"); // formats item._f0 = (data.serverDateFormat||item._f); // formats for save-load, if set - use them for saving and loading only item._c = new dhtmlXCalendarObject(item.childNodes[item._ll?1:0].childNodes[0], data.skin||item.getForm().skin||"dhx_skyblue"); item._c._nullInInput = true; // allow null value from input item._c.enableListener(item.childNodes[item._ll?1:0].childNodes[0]); item._c.setDateFormat(item._f); if (!data.enableTime) item._c.hideTime(); if (!isNaN(data.weekStart)) item._c.setWeekStartDay(data.weekStart); if (typeof(data.calendarPosition) != "undefined") item._c.setPosition(data.calendarPosition); item._c._itemIdd = item._idd; item._c.attachEvent("onBeforeChange", function(d) { if (item._value != d) { // call some events if (item.checkEvent("onBeforeChange")) { if (item.callEvent("onBeforeChange",[item._idd, item._value, d]) !== true) { return false; } } // accepted item._value = d; t.setValue(item, d); item.callEvent("onChange", [this._itemIdd, item._value]); } return true; }); this.setValue(item, data.value); return this; }, getCalendar: function(item) { return item._c; }, setSkin: function(item, skin) { item._c.setSkin(skin); }, setValue: function(item, value) { if (!value || value == null || typeof(value) == "undefined" || value == "") { item._value = null; item.childNodes[item._ll?1:0].childNodes[0].value = ""; } else { item._value = (value instanceof Date ? value : item._c._strToDate(value, item._f0)); item.childNodes[item._ll?1:0].childNodes[0].value = item._c._dateToStr(item._value, item._f); } item._c.setDate(item._value); window.dhtmlXFormLs[item.getForm()._rId].vals[item._idd] = item.childNodes[item._ll?1:0].childNodes[0].value; }, getValue: function(item, asString) { var d = item._c.getDate(); if (asString===true && d == null) return ""; return (asString===true?item._c._dateToStr(d,item._f0):d); }, destruct: function(item) { // unload calendar instance item._c.unload(); item._c = null; try {delete item._c;} catch(e){} item._f = null; try {delete item._f;} catch(e){} item._f0 = null; try {delete item._f0;} catch(e){} // remove custom events/objects item.childNodes[item._ll?1:0].childNodes[0]._idd = null; // unload item this.d2(item); item = null; } }; (function(){ for (var a in {doAddLabel:1,doAddInput:1,doUnloadNestedLists:1,setText:1,getText:1,enable:1,disable:1,isEnabled:1,setWidth:1,setReadonly:1,isReadonly:1,setFocus:1,getInput:1}) dhtmlXForm.prototype.items.calendar[a] = dhtmlXForm.prototype.items.input[a]; })(); dhtmlXForm.prototype.items.calendar.d2 = dhtmlXForm.prototype.items.input.destruct; dhtmlXForm.prototype.getCalendar = function(name) { return this.doWithItem(name, "getCalendar"); };
let charLS; function jpegLSDecode (data, isSigned) { // prepare input parameters const dataPtr = charLS._malloc(data.length); charLS.writeArrayToMemory(data, dataPtr); // prepare output parameters const imagePtrPtr = charLS._malloc(4); const imageSizePtr = charLS._malloc(4); const widthPtr = charLS._malloc(4); const heightPtr = charLS._malloc(4); const bitsPerSamplePtr = charLS._malloc(4); const stridePtr = charLS._malloc(4); const allowedLossyErrorPtr = charLS._malloc(4); const componentsPtr = charLS._malloc(4); const interleaveModePtr = charLS._malloc(4); // Decode the image const result = charLS.ccall( 'jpegls_decode', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number'], [dataPtr, data.length, imagePtrPtr, imageSizePtr, widthPtr, heightPtr, bitsPerSamplePtr, stridePtr, componentsPtr, allowedLossyErrorPtr, interleaveModePtr] ); // Extract result values into object const image = { result, width: charLS.getValue(widthPtr, 'i32'), height: charLS.getValue(heightPtr, 'i32'), bitsPerSample: charLS.getValue(bitsPerSamplePtr, 'i32'), stride: charLS.getValue(stridePtr, 'i32'), components: charLS.getValue(componentsPtr, 'i32'), allowedLossyError: charLS.getValue(allowedLossyErrorPtr, 'i32'), interleaveMode: charLS.getValue(interleaveModePtr, 'i32'), pixelData: undefined }; // Copy image from emscripten heap into appropriate array buffer type const imagePtr = charLS.getValue(imagePtrPtr, '*'); if (image.bitsPerSample <= 8) { image.pixelData = new Uint8Array(image.width * image.height * image.components); image.pixelData.set(new Uint8Array(charLS.HEAP8.buffer, imagePtr, image.pixelData.length)); } else if (isSigned) { image.pixelData = new Int16Array(image.width * image.height * image.components); image.pixelData.set(new Int16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } else { image.pixelData = new Uint16Array(image.width * image.height * image.components); image.pixelData.set(new Uint16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } // free memory and return image object charLS._free(dataPtr); charLS._free(imagePtr); charLS._free(imagePtrPtr); charLS._free(imageSizePtr); charLS._free(widthPtr); charLS._free(heightPtr); charLS._free(bitsPerSamplePtr); charLS._free(stridePtr); charLS._free(componentsPtr); charLS._free(interleaveModePtr); return image; } function initializeJPEGLS () { // check to make sure codec is loaded if (typeof CharLS === 'undefined') { throw new Error('No JPEG-LS decoder loaded'); } // Try to initialize CharLS // CharLS https://github.com/cornerstonejs/charls if (!charLS) { charLS = CharLS(); if (!charLS || !charLS._jpegls_decode) { throw new Error('JPEG-LS failed to initialize'); } } } function decodeJPEGLS (imageFrame, pixelData) { initializeJPEGLS(); const image = jpegLSDecode(pixelData, imageFrame.pixelRepresentation === 1); // throw error if not success or too much data if (image.result !== 0 && image.result !== 6) { throw new Error(`JPEG-LS decoder failed to decode frame (error code ${image.result})`); } imageFrame.columns = image.width; imageFrame.rows = image.height; imageFrame.pixelData = image.pixelData; return imageFrame; } export default decodeJPEGLS; export { initializeJPEGLS };
//= require ./ace/ace //= require ./ace/mode-ruby //= require ./ace/theme-tomorrow //= require ./ace/ext-whitespace $(function() { var editor = ace.edit("editor"); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setMode("ace/mode/ruby"); editor.getSession().setTabSize(2); editor.getSession().setUseSoftTabs(true); $("form").submit(function() { $("#content").val(editor.getValue()); }); });
// =================================================================== // // Mixology example: SENDER // Gearcloud Labs, 2014 // // Main parts // mNode code (ie, WebRTC setup via Mixology) // // Video effects // Photo booth - Colors and reflections; see effects.js // Pause/resume video // // To run // localhost:9090/controls/sender.html // // =================================================================== // === Video inits =================================================== var video = document.createElement('video'); var feed = document.createElement('canvas'); var display = document.createElement('canvas'); video.style.display = 'none'; feed.style.display = 'none'; feed.width = 640; feed.height = 480; display.width = 640; display.height = 480; document.body.appendChild(video); document.body.appendChild(feed); document.body.appendChild(display); var options = []; // array for visual effect options // === Mixology initialization ======================================== var CONFIG = { 'iceServers': [ {'url': 'stun:stun.l.google.com:19302' } ] }; var RTC_OPTIONS = { optional:[{RtpDataChannels: true}] }; var SDP_CONSTRAINTS = {'mandatory': { 'OfferToReceiveAudio':true, 'OfferToReceiveVideo':true }}; var VIDEO_CONSTRAINTS = { mandatory: { maxWidth:640, maxHeight:480 }, optional:[] }; signaller = document.URL.split('/').slice(0,3).join('/'); var stream; // my camera stream var m = new Mixology(signaller); var myPeerId; m.onRegistered = function(peer) { console.log("onRegistered:"+ JSON.stringify(peer,null,2)); myPeerId = peer.fqmNodeName; for (var pid in m.inputs) { // receiveRtcStream starts dance immediately // to throttle we'd need a handshake before this // DATA CHANNEL: onMessage enables data channel m.receiveRtcStream(pid, CONFIG, onAddStream, onRtcMessage, onRtcDataUp); } for (var pid in m.outputs) { // sendRtcStream starts dance immediately // to throttle we'd need a handshake before this m.sendRtcStream(pid, stream, CONFIG, onRtcMessage, onRtcDataUp, RTC_OPTIONS); // m.sendRtcStream(pid, stream, CONFIG); } }; m.onPeerRegistered = function(peer) { console.log("onPeerRegistered:"+JSON.stringify(peer,null,2)); if (peer.direction == "out") { if (stream) { // sendRtcStream starts dance immediately // to throttle we'd need a handshake before this m.sendRtcStream(peer.peer, stream, CONFIG, onRtcMessage, onRtcDataUp); } } if (peer.direction == "in") { // receiveRtcStream starts dance immediately // to throttle we'd need a handshake before this // DATA CHANNEL: onMessage enables data channel m.receiveRtcStream(peer.peer, CONFIG, onAddStream, onRtcMessage, onRtcDataUp); } }; m.onPeerUnRegistered = function(peer) { console.log("onPeerUnRegistered:"+JSON.stringify(peer,null,2)); m.closeRtcStream(peer.peer); }; m.onMessage = function(d) { console.log("onMessage:"+JSON.stringify(d,null,2)); if (d.data.rtcEvent) { m.processRtcEvent(d.data, SDP_CONSTRAINTS); } }; function onAddStream(stream, peerId) { console.log("onAddStream called for "+peerId); } function onRtcDataUp(peerId) { console.log("RtcData connection up. Peer:"+peerId); // m.sendRtcMessage(peerId, "Hello from "+m.fqmNodeName); } function onRtcMessage(from, msg) { console.log("Got RTC Message from:"+from+":"+msg.data); } // === Sender code =================================================================== function getLocalCam() { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; window.URL = window.URL || window.webkitURL; if (!navigator.getUserMedia) { console.log("navigator.getUserMedia() is not available"); // to do: tell user too } else { navigator.getUserMedia({audio: false, video: VIDEO_CONSTRAINTS}, function(strm) { stream = strm; // save stream because other peers will use it too // initialize some stuff, only if user accepts use of webcam document.getElementById("controls").style.visibility = "visible"; // mark camera ready, and check model + audio console.log("Camera ready"); // Register with Mixology server m.register([], ['out']); // sender, out video.src = window.URL.createObjectURL(strm); // Chrome and Firefox // video.src = stream; // Opera, not tested video.autoplay = true; // probably not needed streamFeed(); // start video }, function(err) { console.log("GetUserMedia error:"+JSON.stringify(err,null,2)); }); } } function streamFeed() { requestAnimationFrame(streamFeed); var feedContext = feed.getContext('2d'); var displayContext = display.getContext('2d'); var imageData; feedContext.drawImage(video, 0, 0, display.width, display.height); imageData = feedContext.getImageData(0, 0, display.width, display.height); // add effects imageData = addEffects(imageData, feed.width, feed.height); displayContext.putImageData(imageData, 0, 0); } // // BROWSER & WEBGL DETECTION // var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); var isFirefox = /Firefox/.test(navigator.userAgent); var isMac = /Mac OS/.test(navigator.userAgent); var supportsWebGL = function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } }; if (isChrome) { console.log("Detected Chrome browser"); if (!supportsWebGL()) { window.location = "error.html?no-webgl"; } } else if (isFirefox) { console.log("Detected Firefox browser"); if (!supportsWebGL()) { window.location = "error.html?no-webgl"; } } else { window.location = "error.html?not-chrome"; } // === Initialize ===================================================== // Ask user to allow use of their webcam function initSender() { console.log("initSender()"); getLocalCam(); // in turn, registers with Mixology server } initSender();
// @flow /* global document */ export default function injectStyles(styles: any) { const stylesElement = document.createElement('style'); stylesElement.innerText = styles.toString(); return stylesElement; }
import { test , moduleFor } from 'appkit/tests/helpers/module_for'; import Index from 'appkit/routes/index'; moduleFor('route:index', "Unit - IndexRoute"); test("it exists", function(){ ok(this.subject() instanceof Index); });
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); const Tapable = require("tapable").Tapable; const AsyncSeriesWaterfallHook = require("tapable").AsyncSeriesWaterfallHook; const SyncWaterfallHook = require("tapable").SyncWaterfallHook; const SyncBailHook = require("tapable").SyncBailHook; const SyncHook = require("tapable").SyncHook; const HookMap = require("tapable").HookMap; const NormalModule = require("./NormalModule"); const RawModule = require("./RawModule"); const RuleSet = require("./RuleSet"); const cachedMerge = require("./util/cachedMerge"); const EMPTY_RESOLVE_OPTIONS = {}; const loaderToIdent = data => { if (!data.options) return data.loader; if (typeof data.options === "string") return data.loader + "?" + data.options; if (typeof data.options !== "object") throw new Error("loader options must be string or object"); if (data.ident) return data.loader + "??" + data.ident; return data.loader + "?" + JSON.stringify(data.options); }; const identToLoaderRequest = resultString => { const idx = resultString.indexOf("?"); let options; if (idx >= 0) { options = resultString.substr(idx + 1); resultString = resultString.substr(0, idx); return { loader: resultString, options }; } else { return { loader: resultString }; } }; class NormalModuleFactory extends Tapable { constructor(context, resolverFactory, options) { super(); this.hooks = { resolver: new SyncWaterfallHook(["resolver"]), factory: new SyncWaterfallHook(["factory"]), beforeResolve: new AsyncSeriesWaterfallHook(["data"]), afterResolve: new AsyncSeriesWaterfallHook(["data"]), createModule: new SyncBailHook(["data"]), module: new SyncWaterfallHook(["module", "data"]), createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), createGenerator: new HookMap( () => new SyncBailHook(["generatorOptions"]) ), generator: new HookMap( () => new SyncHook(["generator", "generatorOptions"]) ) }; this._pluginCompat.tap("NormalModuleFactory", options => { switch (options.name) { case "before-resolve": case "after-resolve": options.async = true; break; case "parser": this.hooks.parser .for("javascript/auto") .tap(options.fn.name || "unnamed compat plugin", options.fn); return true; } let match; match = /^parser (.+)$/.exec(options.name); if (match) { this.hooks.parser .for(match[1]) .tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); return true; } match = /^create-parser (.+)$/.exec(options.name); if (match) { this.hooks.createParser .for(match[1]) .tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); return true; } }); this.resolverFactory = resolverFactory; this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); this.cachePredicate = typeof options.unsafeCache === "function" ? options.unsafeCache : Boolean.bind(null, options.unsafeCache); this.context = context || ""; this.parserCache = Object.create(null); this.generatorCache = Object.create(null); this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { let resolver = this.hooks.resolver.call(null); // Ignored if (!resolver) return callback(); resolver(result, (err, data) => { if (err) return callback(err); // Ignored if (!data) return callback(); // direct module if (typeof data.source === "function") return callback(null, data); this.hooks.afterResolve.callAsync(data, (err, result) => { if (err) return callback(err); // Ignored if (!result) return callback(); let createdModule = this.hooks.createModule.call(result); if (!createdModule) { if (!result.request) { return callback(new Error("Empty dependency (no request)")); } createdModule = new NormalModule(result); } createdModule = this.hooks.module.call(createdModule, result); return callback(null, createdModule); }); }); }); this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { const contextInfo = data.contextInfo; const context = data.context; const request = data.request; const noPreAutoLoaders = request.startsWith("-!"); const noAutoLoaders = noPreAutoLoaders || request.startsWith("!"); const noPrePostAutoLoaders = request.startsWith("!!"); let elements = request .replace(/^-?!+/, "") .replace(/!!+/g, "!") .split("!"); let resource = elements.pop(); elements = elements.map(identToLoaderRequest); const loaderResolver = this.getResolver("loader"); const normalResolver = this.getResolver("normal", data.resolveOptions); asyncLib.parallel( [ callback => this.resolveRequestArray( contextInfo, context, elements, loaderResolver, callback ), callback => { if (resource === "" || resource[0] === "?") { return callback(null, { resource }); } normalResolver.resolve( contextInfo, context, resource, {}, (err, resource, resourceResolveData) => { if (err) return callback(err); callback(null, { resourceResolveData, resource }); } ); } ], (err, results) => { if (err) return callback(err); let loaders = results[0]; const resourceResolveData = results[1].resourceResolveData; resource = results[1].resource; // translate option idents try { for (const item of loaders) { if (typeof item.options === "string" && item.options[0] === "?") { const ident = item.options.substr(1); item.options = this.ruleSet.findOptionsByIdent(ident); item.ident = ident; } } } catch (e) { return callback(e); } if (resource === false) { // ignored return callback( null, new RawModule( "/* (ignored) */", `ignored ${context} ${request}`, `${request} (ignored)` ) ); } const userRequest = loaders .map(loaderToIdent) .concat([resource]) .join("!"); let resourcePath = resource; let resourceQuery = ""; const queryIndex = resourcePath.indexOf("?"); if (queryIndex >= 0) { resourceQuery = resourcePath.substr(queryIndex); resourcePath = resourcePath.substr(0, queryIndex); } const result = this.ruleSet.exec({ resource: resourcePath, resourceQuery, issuer: contextInfo.issuer, compiler: contextInfo.compiler }); const settings = {}; const useLoadersPost = []; const useLoaders = []; const useLoadersPre = []; for (const r of result) { if (r.type === "use") { if (r.enforce === "post" && !noPrePostAutoLoaders) useLoadersPost.push(r.value); else if ( r.enforce === "pre" && !noPreAutoLoaders && !noPrePostAutoLoaders ) useLoadersPre.push(r.value); else if (!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders) useLoaders.push(r.value); } else if ( typeof r.value === "object" && r.value !== null && typeof settings[r.type] === "object" && settings[r.type] !== null ) { settings[r.type] = cachedMerge(settings[r.type], r.value); } else { settings[r.type] = r.value; } } asyncLib.parallel( [ this.resolveRequestArray.bind( this, contextInfo, this.context, useLoadersPost, loaderResolver ), this.resolveRequestArray.bind( this, contextInfo, this.context, useLoaders, loaderResolver ), this.resolveRequestArray.bind( this, contextInfo, this.context, useLoadersPre, loaderResolver ) ], (err, results) => { if (err) return callback(err); loaders = results[0].concat(loaders, results[1], results[2]); process.nextTick(() => { const type = settings.type; const resolveOptions = settings.resolve; callback(null, { context: context, request: loaders .map(loaderToIdent) .concat([resource]) .join("!"), dependencies: data.dependencies, userRequest, rawRequest: request, loaders, resource, resourceResolveData, settings, type, parser: this.getParser(type, settings.parser), generator: this.getGenerator(type, settings.generator), resolveOptions }); }); } ); } ); }); } create(data, callback) { const dependencies = data.dependencies; const cacheEntry = dependencies[0].__NormalModuleFactoryCache; if (cacheEntry) return callback(null, cacheEntry); const context = data.context || this.context; const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; const request = dependencies[0].request; const contextInfo = data.contextInfo || {}; this.hooks.beforeResolve.callAsync( { contextInfo, resolveOptions, context, request, dependencies }, (err, result) => { if (err) return callback(err); // Ignored if (!result) return callback(); const factory = this.hooks.factory.call(null); // Ignored if (!factory) return callback(); factory(result, (err, module) => { if (err) return callback(err); if (module && this.cachePredicate(module)) { for (const d of dependencies) { d.__NormalModuleFactoryCache = module; } } callback(null, module); }); } ); } resolveRequestArray(contextInfo, context, array, resolver, callback) { if (array.length === 0) return callback(null, []); asyncLib.map( array, (item, callback) => { resolver.resolve( contextInfo, context, item.loader, {}, (err, result) => { if ( err && /^[^/]*$/.test(item.loader) && !/-loader$/.test(item.loader) ) { return resolver.resolve( contextInfo, context, item.loader + "-loader", {}, err2 => { if (!err2) { err.message = err.message + "\n" + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + ` You need to specify '${ item.loader }-loader' instead of '${item.loader}',\n` + " see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed"; } callback(err); } ); } if (err) return callback(err); const optionsOnly = item.options ? { options: item.options } : undefined; return callback( null, Object.assign({}, item, identToLoaderRequest(result), optionsOnly) ); } ); }, callback ); } getParser(type, parserOptions) { let ident = type; if (parserOptions) { if (parserOptions.ident) ident = `${type}|${parserOptions.ident}`; else ident = JSON.stringify([type, parserOptions]); } if (ident in this.parserCache) { return this.parserCache[ident]; } return (this.parserCache[ident] = this.createParser(type, parserOptions)); } createParser(type, parserOptions = {}) { const parser = this.hooks.createParser.for(type).call(parserOptions); if (!parser) { throw new Error(`No parser registered for ${type}`); } this.hooks.parser.for(type).call(parser, parserOptions); return parser; } getGenerator(type, generatorOptions) { let ident = type; if (generatorOptions) { if (generatorOptions.ident) ident = `${type}|${generatorOptions.ident}`; else ident = JSON.stringify([type, generatorOptions]); } if (ident in this.generatorCache) { return this.generatorCache[ident]; } return (this.generatorCache[ident] = this.createGenerator( type, generatorOptions )); } createGenerator(type, generatorOptions = {}) { const generator = this.hooks.createGenerator .for(type) .call(generatorOptions); if (!generator) { throw new Error(`No generator registered for ${type}`); } this.hooks.generator.for(type).call(generator, generatorOptions); return generator; } getResolver(type, resolveOptions) { return this.resolverFactory.get( type, resolveOptions || EMPTY_RESOLVE_OPTIONS ); } } module.exports = NormalModuleFactory;
// ==UserScript== // @name Youtube BPM Meter // @version 1.3 // @updateURL https://raw.githubusercontent.com/Greeniac916/YoutubeBPM/master/youtube-bpm.js // @description Plugin adding beat counter to Youtube // @author Greeniac916 // @match https://www.youtube.com/* // @grant none // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== var playButton = $(".ytp-play-button"); var bpmDelay = 0; var beats = 0; var interval, loadInt; function setup() { //Create HTML String Elements var card = "<div id='bpm-header' class='yt-card yt-card-has-padding'></div>"; var input = "<input id='bpm-input' placeholder='Enter BPM' type='number' style='vertical-align: middle'>"; var submit = "<input id='bpm-btn' type='button' value='Submit' style='vertical-align: middle'>"; var reset = "<input id='rst-btn' type='button' value='Reset' style='vertical-align: middle'>"; var output = "<span id='span-beats-text' style='float: right; vertical-align: middle;'>Beats: 0</span>"; //Insert Card Div $("#watch7-content").prepend(card); //Insert HTML elements to card $("#bpm-header").append(input); $("#bpm-header").append(submit); $("#bpm-header").append(reset); $("#bpm-header").append(output); //Bind Buttons $("#bpm-btn").bind("click", function() { var bpm = $("#bpm-input")[0].value; bpmDelay = 60000 / bpm; //Converts BPM to milisecond intervals clearInterval(interval); counter(); }); $("#rst-btn").bind("click", function() { beats = 0; display(0); }); } function display(value) { $("#span-beats-text")[0].textContent = "Beats: " + value; } function counter() { interval = setInterval(function() { display(beats); if (playButton.attr("aria-label") == "Pause") { //If youtube paying video beats++; } }, bpmDelay); } function waitForElement(elementPath, callBack){ window.setTimeout(function(){ if($(elementPath).length){ callBack(elementPath, $(elementPath)); }else{ waitForElement(elementPath, callBack); } },500); } function load() { console.log("Loading plugin."); playButton.click(); setup(); $(".video-list-item").bind("click", function() { waitForElement("#progress", function() { waitForElement("#eow-title", load); }); }); $(".yt-lockup").bind("click", function() { waitForElement("#progress", function() { waitForElement("#eow-title", load); }); }); } (function() { 'use strict'; load(); })();
/** * Copyright (c) 2015-present, Pavel Aksonov * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component, PropTypes, } from 'react'; import NavigationExperimental from 'react-native-experimental-navigation'; import Actions, { ActionMap } from './Actions'; import getInitialState from './State'; import Reducer, { findElement } from './Reducer'; import DefaultRenderer from './DefaultRenderer'; import Scene from './Scene'; import * as ActionConst from './ActionConst'; const { RootContainer: NavigationRootContainer, } = NavigationExperimental; const propTypes = { dispatch: PropTypes.func, }; class Router extends Component { constructor(props) { super(props); this.state = {}; this.renderNavigation = this.renderNavigation.bind(this); this.handleProps = this.handleProps.bind(this); } componentDidMount() { this.handleProps(this.props); } componentWillReceiveProps(props) { this.handleProps(props); } handleProps(props) { let scenesMap; if (props.scenes) { scenesMap = props.scenes; } else { let scenes = props.children; if (Array.isArray(props.children) || props.children.props.component) { scenes = ( <Scene key="__root" hideNav {...this.props} > {props.children} </Scene> ); } scenesMap = Actions.create(scenes, props.wrapBy); } // eslint-disable-next-line no-unused-vars const { children, styles, scenes, reducer, createReducer, ...parentProps } = props; scenesMap.rootProps = parentProps; const initialState = getInitialState(scenesMap); const reducerCreator = props.createReducer || Reducer; const routerReducer = props.reducer || ( reducerCreator({ initialState, scenes: scenesMap, })); this.setState({ reducer: routerReducer }); } renderNavigation(navigationState, onNavigate) { if (!navigationState) { return null; } Actions.get = key => findElement(navigationState, key, ActionConst.REFRESH); Actions.callback = props => { const constAction = (props.type && ActionMap[props.type] ? ActionMap[props.type] : null); if (this.props.dispatch) { if (constAction) { this.props.dispatch({ ...props, type: constAction }); } else { this.props.dispatch(props); } } return (constAction ? onNavigate({ ...props, type: constAction }) : onNavigate(props)); }; return <DefaultRenderer onNavigate={onNavigate} navigationState={navigationState} />; } render() { if (!this.state.reducer) return null; return ( <NavigationRootContainer reducer={this.state.reducer} renderNavigation={this.renderNavigation} /> ); } } Router.propTypes = propTypes; export default Router;
var helper = require(__dirname + '/../test-helper'); var CopyFromStream = require(__dirname + '/../../../lib/copystream').CopyFromStream; var ConnectionImitation = function () { this.send = 0; this.hasToBeSend = 0; this.finished = 0; }; ConnectionImitation.prototype = { endCopyFrom: function () { assert.ok(this.finished++ === 0, "end shoud be called only once"); assert.equal(this.send, this.hasToBeSend, "at the moment of the end all data has to be sent"); }, sendCopyFromChunk: function (chunk) { this.send += chunk.length; return true; }, updateHasToBeSend: function (chunk) { this.hasToBeSend += chunk.length; return chunk; } }; var buf1 = new Buffer("asdfasd"), buf2 = new Buffer("q03r90arf0aospd;"), buf3 = new Buffer(542), buf4 = new Buffer("93jfemialfjkasjlfas"); test('CopyFromStream, start streaming before data, end after data. no drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation(); stream.on('drain', function () { assert.ok(false, "there has not be drain event"); }); stream.startStreamingToConnection(conn); assert.ok(stream.write(conn.updateHasToBeSend(buf1))); assert.ok(stream.write(conn.updateHasToBeSend(buf2))); assert.ok(stream.write(conn.updateHasToBeSend(buf3))); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); assert.equal(conn.hasToBeSend, conn.send); }); test('CopyFromStream, start streaming after end, end after data. drain event', function () { var stream = new CopyFromStream(); assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); var conn = new ConnectionImitation() assert.ok(!stream.write(conn.updateHasToBeSend(buf1))); assert.ok(!stream.write(conn.updateHasToBeSend(buf2))); assert.ok(!stream.write(conn.updateHasToBeSend(buf3))); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); stream.startStreamingToConnection(conn); assert.equal(conn.hasToBeSend, conn.send); }); test('CopyFromStream, start streaming between data chunks. end after data. drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.startStreamingToConnection(conn); stream.write(conn.updateHasToBeSend(buf3)); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); }); test('CopyFromStream, start sreaming before end. end stream with data. drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.write(conn.updateHasToBeSend(buf3)); stream.startStreamingToConnection(conn); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); }); test('CopyFromStream, start streaming after end. end with data. drain event', function(){ var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.write(conn.updateHasToBeSend(buf3)); stream.startStreamingToConnection(conn); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); stream.startStreamingToConnection(conn); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); });
function main () { const ad_el = document.getElementById('bsa-cpc') if (!ad_el || innerWidth < 800) { // if no ad element or element hidden, don't load buysellads return } const script = document.createElement('script') script.onload = () => { if (_bsa.isMobile()) { // bsa doesn't show ads on mobile, hide th box ad_el.remove() return } _bsa.init('default', 'CK7ITKJU', 'placement:pydantic-docshelpmanualio', { target: '#bsa-cpc', align: 'horizontal', }) ad_el.classList.add('loaded') } script.src = 'https://m.servedby-buysellads.com/monetization.js' document.head.appendChild(script) } main()
var g_data; var margin = {top: 40, right: 45, bottom: 60, left: 60}, width = 460 - margin.left - margin.right, height = 436 - margin.top - margin.bottom; var xValue = function(d) { return d.condition;}; var x = d3.scalePoint().range([20, width-20]) var xAxis = d3.axisBottom() .scale(x); x.domain(["control","GI.1_12hpi","GI.1_24hpi","GI.2_12hpi","GI.2_24hpi"]); var y = d3.scaleLinear().range([height, 0]); var yAxis = d3.axisLeft() .scale(y) .ticks(10); var tool = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); var svg = d3.select("div#rab_gene_scatter").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // add the x axis svg.append("g") .attr("class", "x_axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("font-size", "12px") .style("font-family", "sans-serif") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-45)"); // add the y axis svg.append("g") .attr("class", "y_axis") .call(yAxis); // y axis text label svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 0 - margin.left) .attr("x",0 - (height / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Reads per Kilobase per Million (rpkm)"); // draw legend var legend = svg.selectAll(".legend") .data(["adult", "kitten"]) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); // draw legend colored circles legend.append("circle") .attr("cx", width) .attr("cy", 6) .attr("r", 5) .style("fill", function(d) { if (d == "kitten") { return "steelblue"; } else { return "red"; }}); // draw legend text legend.append("text") .attr("x", width + 8) .attr("y", 6) .attr("dy", ".35em") .style("text-anchor", "start") .text(function(d) { return d;}) // read in data // global variable to check if datafile is already loaded // if its already loaded don't want to waste time re-loading // also includes a boolean if a gene should be plotted following data load var loaded_data = "not_loaded"; function load_scatter_data(data_file, plot_gene, new_gene){ if(loaded_data != data_file){ console.log("loading new file"); $('#current_gene_name').text("LOADING..."); d3.tsv(data_file, function(data) { data.forEach(function(d) { d.rpkm = +d.rpkm; }); g_data = data; loaded_data = data_file; $('#current_gene_name').text("Expression scatter plot"); if(plot_gene == true){ update_plot(new_gene); return; } }); }; if(plot_gene == true){ update_plot(new_gene); return; } }; function update_plot(gene_name){ // filter the data for this particular gene var filt_data = g_data.filter(function(d) { return d.gene == gene_name}); y.domain([0, d3.max(filt_data, function(d) { return d.rpkm; })]); // Select what we want to change var scatter_points = svg.selectAll(".matts_bar") .data(filt_data) // Make the update changes //UPDATE scatter_points.transition().duration(1000) .attr("cy", function(d) { return y(d.rpkm); }); // add new spots from the enter selection // note this will only happen once in this case // ENTER scatter_points.enter() .append("circle") .style("fill", function(d) { if (d.age == "kitten") { return "steelblue"; } else { return "red"; }}) .attr("class", "matts_bar") .attr("cx", function(d) { return x(d.condition); }) .attr("r", 5) .on("mouseover", function(d) { d3.select(this).classed("hover", true); tool.transition() .duration(0) .style("opacity", .9); tool .html(d.sample) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px"); }) .on("mouseout", function(d) { d3.select(this).classed("hover", false); tool.transition() .duration(0) .style("opacity", 0); }) .transition().duration(1000).attr("cy", function(d) { return y(d.rpkm); }); // no need for an EXIT section // update the y axis info svg.select(".y_axis") .transition() .duration(1000) .call(yAxis); // update gene name in window $('#current_gene_name').text(gene_name); }
import React from 'react'; import ReactDOM from 'react-dom'; import ReactDOMServer from 'react-dom/server'; import { Router, RouterContext, match, browserHistory, createMemoryHistory } from 'react-router'; import HtmlBase from './pages/html-base'; import routes from './routes'; if (typeof document !== 'undefined') { const outlet = document.getElementById('outlet'); ReactDOM.render(<Router history={browserHistory} routes={routes} />, outlet); } // This is our 'server' rendering export default (locals, callback) => { const history = createMemoryHistory(); const location = history.createLocation(locals.path); // This is from the webpack plugin match({ routes, location }, (error, redirectLocation, renderProps) => { // entire page rendering let html = ReactDOMServer.renderToStaticMarkup(<HtmlBase><RouterContext {...renderProps} /></HtmlBase>) callback(null, '<!DOCTYPE html>' + html); }); };
/** * Template literals are a way to more easily achieve string concatenation. * Template literals are defined using back ticks (``). * Placeholders are indicated by using a ${variable} * Function tags are used to reference functions. Tags are a very handy featurs as they can * be used to protect against cross-site scripting by html encoding, tags to support localization, etc */ describe('template literals', function() { it('can use placeholders', function() { let a = 'hello'; let b = 'world'; let result = `${a} ${b}`; console.log(result); expect(result).toBe('hello world'); }); it('can use function tags', function() { function doStuff(...words) { let text = ''; words.forEach(function(word) { text += `${word} `; }); return text.toUpperCase(); } let result = doStuff('hello', 'world'); console.log(result); expect(result).toBe('HELLO WORLD '); }); }); // describe('spread operator', function() { // it('', function() { // }); // it('', function() { // }); // });
export function up(queryInterface, Sequelize) { return Promise.all([ queryInterface.changeColumn('memberships', 'approved', { type: Sequelize.BOOLEAN, defaultValue: null, }), queryInterface.changeColumn('quotes', 'approved', { type: Sequelize.BOOLEAN, defaultValue: null, }), ]); } export function down(queryInterface, Sequelize) { return Promise.all([ queryInterface.changeColumn('memberships', 'approved', { type: Sequelize.BOOLEAN, defaultValue: false, }), queryInterface.changeColumn('quotes', 'approved', { type: Sequelize.BOOLEAN, defaultValue: false, }), ]); }
import express from 'express'; import path from 'path'; let app = express(); /*** Webpack imports ***/ import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import config from './webpack.config.js'; const webpackOptions = { publicPath: config.output.publicPath, // needed so that when going to the localhost:3000 it will load the contents // from this directory contentBase: config.devServer.contentBase, quiet: false, // hides all the bundling file names noInfo: true, // adds color to the terminal stats: { colors: true } }; const isDevelopment = process.env.NODE_ENV !== 'production'; const port = isDevelopment ? 3003 : process.env.PORT; const public_path = path.join(__dirname, 'public'); app.use(express.static(public_path)) // .get('/', function(req, res) { // res.sendFile('index.html', {root: public_path}) // }); /*** during development I am using a webpack-dev-server ***/ if(isDevelopment) { new WebpackDevServer(webpack(config), webpackOptions) .listen(port, 'localhost', function(err) { if (err) { console.log(err); } console.log(`Listening on port: ${port}`); }); } module.exports = app;
///@INFO: UNCOMMON // This Component shows the possibility of using another Render Engine within WebGLStudio. // The idea here is to create a component that calls the other render engine renderer during my rendering method function ThreeJS( o ) { this.enabled = true; this.autoclear = true; //clears the scene on start this._code = ThreeJS.default_code; if(global.gl) { if( typeof(THREE) == "undefined") this.loadLibrary( function() { this.setupContext(); } ); else this.setupContext(); } this._script = new LScript(); //maybe add function to retrieve texture this._script.catch_exceptions = false; if(o) this.configure(o); } ThreeJS.prototype.setupContext = function() { if(this._engine) return; if( typeof(THREE) == "undefined") { console.error("ThreeJS library not loaded"); return; } if( !THREE.Scene ) { console.error("ThreeJS error parsing library"); return; //this could happen if there was an error parsing THREE.JS } //GLOBAL VARS this._engine = { component: this, node: this._root, scene: new THREE.Scene(), camera: new THREE.PerspectiveCamera( 70, gl.canvas.width / gl.canvas.height, 1, 1000 ), renderer: new THREE.WebGLRenderer( { canvas: gl.canvas, context: gl } ), root: new THREE.Object3D(), ThreeJS: this.constructor }; this._engine.scene.add( this._engine.root ); } ThreeJS.default_code = "//renderer, camera, scene, already created, they are globals.\n//use root as your base Object3D node if you want to use the scene manipulators.\n\nthis.start = function() {\n}\n\nthis.render = function(){\n}\n\nthis.update = function(dt){\n}\n"; ThreeJS.library_url = "http://threejs.org/build/three.js"; Object.defineProperty( ThreeJS.prototype, "code", { set: function(v) { this._code = v; this.processCode(); }, get: function() { return this._code; }, enumerable: true }); ThreeJS["@code"] = { widget: "code", allow_inline: false }; ThreeJS.prototype.onAddedToScene = function( scene ) { LEvent.bind( ONE.Renderer, "renderInstances", this.onEvent, this ); LEvent.bind( scene, "start", this.onEvent, this ); LEvent.bind( scene, "update", this.onEvent, this ); LEvent.bind( scene, "finish", this.onEvent, this ); this.processCode(); } ThreeJS.prototype.clearScene = function() { if(!this._engine) return; //remove inside root var root = this._engine.root; for( var i = root.children.length - 1; i >= 0; i--) root.remove( root.children[i] ); //remove inside scene but not root root = this._engine.scene; for( var i = root.children.length - 1; i >= 0; i--) if( root.children[i] != this._engine.root ) root.remove( root.children[i] ); } ThreeJS.prototype.onRemovedFromScene = function( scene ) { LEvent.unbind( ONE.Renderer, "renderInstances", this.onEvent, this ); LEvent.unbindAll( scene, this ); //clear scene if(this.autoclear) this.clearScene(); } ThreeJS.prototype.onEvent = function( e, param ) { if( !this.enabled || !this._engine ) return; var engine = this._engine; if(e == "start") { //clear scene? if(this.autoclear) this.clearScene(); if(this._script) this._script.callMethod( "start" ); } else if(e == "renderInstances") { //copy camera info so both cameras matches var current_camera = ONE.Renderer._current_camera; engine.camera.fov = current_camera.fov; engine.camera.aspect = current_camera._final_aspect; engine.camera.near = current_camera.near; engine.camera.far = current_camera.far; engine.camera.updateProjectionMatrix() engine.camera.position.fromArray( current_camera._global_eye ); engine.camera.lookAt( new THREE.Vector3( current_camera._global_center[0], current_camera._global_center[1], current_camera._global_center[2] ) ); //copy the root info ThreeJS.copyTransform( this._root, engine.root ); //render using ThreeJS engine.renderer.setSize( gl.viewport_data[2], gl.viewport_data[3] ); if( engine.renderer.resetGLState ) engine.renderer.resetGLState(); else if( engine.renderer.state.reset ) engine.renderer.state.reset(); if(this._script) this._script.callMethod( "render" ); else engine.renderer.render( engine.scene, engine.camera ); //render the scene //reset GL here? //read the root position and update the node? } else if(e == "update") { if(this._script) this._script.callMethod( "update", param ); else engine.scene.update( param ); } else if(e == "finish") { if(this._script) this._script.callMethod( "finish" ); } } /* ThreeJS.prototype.getCode = function() { return this.code; } ThreeJS.prototype.setCode = function( code, skip_events ) { this.code = code; this.processCode( skip_events ); } */ ThreeJS.copyTransform = function( a, b ) { //litescene to threejs if( a.constructor === ONE.SceneNode ) { var global_position = vec3.create(); if(a.transform) a.transform.getGlobalPosition( global_position ); b.position.set( global_position[0], global_position[1], global_position[2] ); //rotation var global_rotation = quat.create(); if(a.transform) a.transform.getGlobalRotation( global_rotation ); b.quaternion.set( global_rotation[0], global_rotation[1], global_rotation[2], global_rotation[3] ); //scale var global_scale = vec3.fromValues(1,1,1); if(a.transform) a.transform.getGlobalScale( global_scale ); b.scale.set( global_scale[0], global_scale[1], global_scale[2] ); } if( a.constructor === ONE.Transform ) { var global_position = vec3.create(); a.getGlobalPosition( global_position ); b.position.set( global_position[0], global_position[1], global_position[2] ); //rotation var global_rotation = quat.create(); a.getGlobalRotation( global_rotation ); b.quaternion.set( global_rotation[0], global_rotation[1], global_rotation[2], global_rotation[3] ); //scale var global_scale = vec3.fromValues(1,1,1); a.getGlobalScale( global_scale ); b.scale.set( global_scale[0], global_scale[1], global_scale[2] ); } else //threejs to litescene { if( b.constructor == ONE.Transform ) b.fromMatrix( a.matrixWorld ); else if( b.constructor == ONE.SceneNode && b.transform ) b.transform.fromMatrix( a.matrixWorld ); } } ThreeJS.prototype.loadLibrary = function( on_complete ) { if( typeof(THREE) !== "undefined" ) { if(on_complete) on_complete.call(this); return; } if( this._loading ) { LEvent.bind( this, "threejs_loaded", on_complete, this ); return; } if(this._loaded) { if(on_complete) on_complete.call(this); return; } this._loading = true; var that = this; ONE.Network.requestScript( ThreeJS.library_url, function(){ console.log("ThreeJS library loaded"); that._loading = false; that._loaded = true; LEvent.trigger( that, "threejs_loaded" ); LEvent.unbindAllEvent( that, "threejs_loaded" ); if(!that._engine) that.setupContext(); }); } ThreeJS.prototype.processCode = function( skip_events ) { if(!this._script || !this._root || !this._root.scene ) return; this._script.code = this.code; //force threejs inclusion if( typeof(THREE) == "undefined") { this.loadLibrary( function() { this.processCode(); }); return; } if(!this._engine) this.setupContext(); if(this._root && !ONE.Script.block_execution ) { //compiles and executes the context return this._script.compile( this._engine, true ); } return true; } ONE.registerComponent( ThreeJS );
'use strict'; var path = require('path') , chai = require('chai') , expect = chai.expect , sumChildren = require(path.join(__dirname, '..', 'lib', 'util', 'sum-children')) ; describe("simplifying timings lists", function () { it("should correctly reduce a simple list", function () { expect(sumChildren([[22, 42]])).equal(20); }); it("should accurately sum overlapping child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add another interval completely encompassed by the first intervals.push([ 5, 10]); // add another that starts within the first range but extends beyond intervals.push([11, 33]); // add a final interval that's entirely disjoint intervals.push([35, 39]); expect(sumChildren(intervals)).equal(37); }); it("should accurately sum partially overlapping child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add another interval completely encompassed by the first intervals.push([ 5, 10]); // add another that starts simultaneously with the first range but that extends beyond intervals.push([ 0, 33]); expect(sumChildren(intervals)).equal(33); }); it("should accurately sum partially overlapping, open-ranged child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add a range that starts at the exact end of the first intervals.push([22, 33]); expect(sumChildren(intervals)).equal(33); }); });
import $ from 'jquery'; let hoverChildDirective = { bind: (el, binding) => { $(el) .on('mouseenter', function(event) { $(el).children('.icon').addClass(binding.value); }) .on('mouseleave', function(event) { $(el).children('.icon').removeClass(binding.value); }); } }; export { hoverChildDirective };
var searchData= [ ['size_0',['size',['../struct_vma_allocation_info.html#aac76d113a6a5ccbb09fea00fb25fd18f',1,'VmaAllocationInfo::size()'],['../struct_vma_virtual_block_create_info.html#a670ab8c6a6e822f3c36781d79e8824e9',1,'VmaVirtualBlockCreateInfo::size()'],['../struct_vma_virtual_allocation_create_info.html#aae08752b86817abd0d944c6025dc603e',1,'VmaVirtualAllocationCreateInfo::size()'],['../struct_vma_virtual_allocation_info.html#afb6d6bd0a6813869ea0842048d40aa2b',1,'VmaVirtualAllocationInfo::size()']]], ['srcallocation_1',['srcAllocation',['../struct_vma_defragmentation_move.html#a25aa1bb64efc507a49c6cbc50689f862',1,'VmaDefragmentationMove']]], ['statistics_2',['statistics',['../struct_vma_detailed_statistics.html#a13efbdb35bd1291191d275f43e96d360',1,'VmaDetailedStatistics::statistics()'],['../struct_vma_budget.html#a6d15ab3a798fd62d9efa3a1e1f83bf54',1,'VmaBudget::statistics()']]] ];
var theServersDao = require('../daos/ServersDao'); var ServerMatcherMiddleware = function (pReq, pRes, pNext) { 'use strict'; var ip = pReq.headers['x-forwarded-for'] || pReq.connection.remoteAddress; theServersDao.getServerIdByIp(ip, function (pData) { if (pData.error) { var server = { ip: ip }; theServersDao.createServer(server, function (pData) { pReq.body.server_id = pData.id; pNext(); }); } else { pReq.body.server_id = pData.id; pNext(); } }); }; module.exports = ServerMatcherMiddleware;
!(function() { 'use strict'; function ComponentLoader($window, $q) { var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component)) { component = resolveComponent(component) } if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function loadItem(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component); }); newScriptTag.addEventListener('error', function(ev) { d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } } ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
var url = require('url') , path = require('path') , fs = require('fs') , utils = require('./utils') , EventEmitter = require('events').EventEmitter exports = module.exports = Context function Context(app, req, res) { var self = this this.app = app this.req = req this.res = res this.done = this.done.bind(this) EventEmitter.call(this) var socket = res.socket res.on('finish', done) socket.on('error', done) socket.on('close', done) function done(err) { res.removeListener('finish', done) socket.removeListener('error', done) socket.removeListener('close', done) self.done(err) } } Context.prototype = { done: function(err) { if (this._notifiedDone === true) return if (err) { if (this.writable) { this.resHeaders = {} this.type = 'text/plain' this.status = err.code === 'ENOENT' ? 404 : (err.status || 500) this.length = Buffer.byteLength(err.message) this.res.end(err.message) } this.app.emit('error', err) } this._notifiedDone = true this.emit('done', err) }, throw: function(status, err) { status = status || 500 err = err || {} err.status = status err.message = err.message || status.toString() this.done(err) }, render: function *(view, locals) { var app = this.app , viewPath = path.join(app.viewRoot, view) , ext = path.extname(viewPath) , exts, engine, content, testPath, i, j if (!ext || (yield utils.fileExists(viewPath))) { for (i = 0; app.viewEngines[i]; i++) { exts = (app.viewEngines[i].exts || ['.' + app.viewEngines[i].name.toLowerCase()]) if (ext) { if (~exts.indexOf(ext)) { engine = app.viewEngines[i] break } continue } for (j = 0; exts[j]; j++) { testPath = viewPath + exts[j] if (yield utils.fileExists(testPath)) { viewPath = testPath engine = app.viewEngines[i] break } } } } if (!engine) return this.throw(500, new Error('View does not exist')) return yield engine.render(viewPath, locals) }, /* * opts: { path: ..., domain: ..., expires: ..., maxAge: ..., httpOnly: ..., secure: ..., sign: ... } */ cookie: function(name, val, opts) { if (!opts) opts = {} if (typeof val == 'object') val = JSON.stringify(val) if (this.secret && opts.sign) { val = this.app.cookies.prefix + this.app.cookies.sign(val, this.secret) } var headerVal = name + '=' + val + '; Path=' + (opts.path || '/') if (opts.domain) headerVal += '; Domain=' + opts.domain if (opts.expires) { if (typeof opts.expires === 'number') opts.expires = new Date(opts.expires) if (opts.expires instanceof Date) opts.expires = opts.expires.toUTCString() headerVal += '; Expires=' + opts.expires } if (opts.maxAge) headerVal += '; Max-Age=' + opts.maxAge if (opts.httpOnly) headerVal += '; HttpOnly' if (opts.secure) headerVal += '; Secure' this.setResHeader('Set-Cookie', headerVal) }, get writable() { var socket = this.res.socket return socket && socket.writable && !this.res.headersSent }, get path() { return url.parse(this.url).pathname }, set path(val) { var obj = url.parse(this.url) obj.pathname = val this.url = url.format(obj) }, get status() { return this._status }, set status(code) { this._status = this.res.statusCode = code }, get type() { return this.getResHeader('Content-Type') }, set type(val) { if (val == null) return this.removeResHeader('Content-Type') this.setResHeader('Content-Type', val) }, get length() { return this.getResHeader('Content-Length') }, set length(val) { if (val == null) return this.removeResHeader('Content-Length') this.setResHeader('Content-Length', val) }, get body() { return this._body }, set body(val) { this._body = val } } utils.extend(Context.prototype, EventEmitter.prototype) utils.proxy(Context.prototype, { req: { method : 'access', url : 'access', secure : 'getter', headers : ['getter', 'reqHeaders'], }, res: { _headers : ['access', 'resHeaders'], getHeader : ['invoke', 'getResHeader'], setHeader : ['invoke', 'setResHeader'], removeHeader : ['invoke', 'removeResHeader'] } })
var express = require('express'); var soapSave = require('../utils/soa_save_esig')('http://192.168.0.6:8001/soa-infra/services/default/SignatureService/SignatureService_ep?WSDL'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { var sig = req.query; console.log(sig); if(!sig.userRoleType){ res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "need to supply userRoleType" }); return; } if (sig.req_type && sig.req_type == 'r'){ var inputData = { applicantId: sig.applicantId, formId: sig.formId, userRoleType: sig.userRoleType }; soapSave.retrieve(inputData,function (result ){ var b64string = result.signatureImage; if(b64string == null){ res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" }); } else{ var buf = new Buffer(b64string, 'base64'); var cacObj =JSON.parse( buf.toString('ascii') ); res.render('response', { title: 'MPSTD CAC Signature response', cacContent: JSON.stringify(cacObj.subject), cacSignature: JSON.stringify(cacObj.fingerprint), timeStamp: JSON.stringify(result.signatureDateTime) }); // console.log("base64 buffer length = " +buf.length); } } ); } else{//default Esing sign pad res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" }); } }); module.exports = router;
// Underscore.js 1.4.3 // http://underscorejs.org // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.4.3'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); return _.map(obj, function(value) { return (_.isFunction(method) ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // with specific `key:value` pairs. _.where = function(obj, attrs) { if (_.isEmpty(attrs)) return []; return _.filter(obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See: https://bugs.webkit.org/show_bug.cgi?id=80797 _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value : value, index : index, criteria : iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index < right.index ? -1 : 1; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(obj, value, context, behavior) { var result = {}; var iterator = lookupIterator(value || _.identity); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = function(obj, value, context) { return group(obj, value, context, function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(value); }); }; // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = function(obj, value, context) { return group(obj, value, context, function(result, key) { if (!_.has(result, key)) result[key] = 0; result[key]++; }); }; // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n != null) && !guard) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { each(input, function(value) { if (_.isArray(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(concat.apply(ArrayProto, arguments)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(args, "" + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, l = list.length; i < l; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, l = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < l; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Binding with arguments is also known as `curry`. // Delegates to **ECMAScript 5**'s native `Function.bind` if available. // We check for `func.bind` first, to fail fast when `func` is undefined. _.bind = function(func, context) { var args, bound; if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length == 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.throttle = function(func, wait) { var context, args, timeout, result; var previous = 0; var later = function() { previous = new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) result = func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var values = []; for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var pairs = []; for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(n); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + (0 | Math.random() * (max - min + 1)); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named property is a function then invoke it; // otherwise, return it. _.result = function(object, property) { if (object == null) return null; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name){ var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = '' + ++idCounter; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); }).call(this);
// Regular expression that matches all symbols in the Linear B Syllabary block as per Unicode v5.1.0: /\uD800[\uDC00-\uDC7F]/;
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var Session = require('express-session'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // create session middleware var session = Session({ resave: true, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'love' // ??? }); var dashboard_routes = require('./routes/dashboard'); var test_routes = require('./routes/test'); var users_routes = require('./routes/users'); var regions_routes = require('./routes/regions'); var informations_routes = require('./routes/informations'); var commands_routes = require('./routes/commands'); var document_routes = require('./routes/documents'); var images_routes = require('./routes/images'); var authentications_routes = require('./routes/authentications'); var auth = require('./routes/auth'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.png'))); app.use(logger('dev')); /* Automatically parse json object in request, and store the parsing * result in `req.body`. If request is not json type (i.e., "Content-Type" * is not "application/json", it won't be parsed. */ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use('/public', express.static(path.join(__dirname, 'public'))); // for logging // Each time a request reaches, log the verb, url, body of request. app.use(function(req, res, next) { console.log('===================================================='); console.log('Request:'); console.log(req.method, req.originalUrl); console.log(req.body); console.log('----------------------------------------------------'); next(); }); /* * Session control: * * Session only applies for /login, /login.do, /logout, and url starting with * /dashboard. * * 1. Add `session` middleware for these routes, which can automatically set * session information in `req.session` * 2. When a user log in through /login.do, store login information in session, * specifically, `req.session.user` * 3. Every time a request ask for /dashboard/*, check whether `req.session.user` * is set. If `req.session.user` is undefined, redirect to login page. * 4. When logging out, delete `req.session.user`. * */ app.get('/login', session, function(req, res, next) { res.render('login'); }); app.post('/login.do', session, function (req, res, next) { var username = req.body.username; var password = req.body.password; console.log('username =', username, 'password =', password); if (username == "admin" && password == "admin") { // store login information in session req.session.user = { username: 'admin', password: 'admin' }; res.redirect('/dashboard'); } else { res.redirect('/login'); } }); app.get('/logout', session, function(req, res, next) { // delete login information in session req.session.user = null; res.redirect('/login'); }); // routes, see routes/*.js app.use('/dashboard', session, function (req, res, next) { /* * If `req.session.user` exists, it means that user is already logged in. * Otherwise, we should redirect to login page. */ console.log('req.session = ', req.session); if (req.session.user || /^\/login/.test(req.url)) { console.log('next'); next(); } else { res.redirect('/login'); console.log('redirect'); } }, dashboard_routes); // routes for RESTful APIs app.use('/test', auth.forAllUsers, test_routes); app.use('/authentications', auth.forAllUsers, authentications_routes); app.use('/users', auth.forAllUsers, users_routes); app.use('/regions', auth.forAllUsers, regions_routes); app.use('/information', auth.forAllUsers, informations_routes); app.use('/commands', auth.forAllUsers, commands_routes); app.use('/documents', auth.forAllUsers, document_routes); app.use('/images', images_routes); // catch 404 and forward to error handler app.use(function (req, res, next) { res.status(404).send({ status: 404, message: req.url + ' Not Found' }); }); // error handlers /* development error handler, will print stacktrace * * this error handler can be triggered by `next(error)`, * where error is an `Error` object created by `new Error(message)` * * Example: * * function do_get(req, res, next) { * if (something_wrong) { * var error = new Error('some message'); * error.status = 503; * } else { * do_something(); * } * */ if (app.get('env') === 'development') { app.use(function (err, req, res, next) { console.log('caused development error handler'); if (err.status != 404) { console.log(err.message); console.log(err.stack); } var status = err.status || 500; res.status(status); res.send({ status: status, message: err.message, stack: err.stack, }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { console.log('caused production error handler'); res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
require.config( { //By default load any module IDs from js/lib baseUrl: "app/", //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { lib: "../lib", } } ); requirejs( ["lib/angular/angular"], function() { require( ["app"], function() { angular.element( document ).ready( function() { angular.bootstrap( document, ['dotaApp'] ); } ); } ); } );
import Ember from 'ember'; import ApplicationSerializer from 'ghost-admin/serializers/application'; import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin'; const {String: {pluralize}} = Ember; export default ApplicationSerializer.extend(EmbeddedRecordsMixin, { attrs: { roles: {embedded: 'always'}, lastLoginUTC: {key: 'last_login'}, createdAtUTC: {key: 'created_at'}, updatedAtUTC: {key: 'updated_at'} }, extractSingle(store, primaryType, payload) { let root = this.keyForAttribute(primaryType.modelName); let pluralizedRoot = pluralize(primaryType.modelName); payload[root] = payload[pluralizedRoot][0]; delete payload[pluralizedRoot]; return this._super(...arguments); }, normalizeSingleResponse(store, primaryModelClass, payload) { let root = this.keyForAttribute(primaryModelClass.modelName); let pluralizedRoot = pluralize(primaryModelClass.modelName); if (payload[pluralizedRoot]) { payload[root] = payload[pluralizedRoot][0]; delete payload[pluralizedRoot]; } return this._super(...arguments); } });
const type = { name: "array", structure: [ { name: "type", match: "^array$" }, { name: "content" }, ], child: "content", identify, validate, next, execute, }; module.exports = type; function identify({ current }) { const regexp = new RegExp("^array$"); if (current.content && current.type && Object.keys(current).length === 2 && Array.isArray(current.content) === false && typeof current.content === "object" && regexp.test(current.type)) { return true; } return false; } function validate({ current, ruleConfig, parents, processor }) { const type = processor.identify({ current: current.content, ruleConfig, parents }); type.validate({ current: current.content, ruleConfig, parents: [...parents, type.child], processor }); return true; } function next(current) { return current.content ? current.content : null; } function execute({ target, source, rule, processor }) { return new Promise(async (resolve, reject) => { try { if (Array.isArray(source.current)) { for (const key in source.current) { const value = source.current[key]; target.current[key] = await processor.executeNext({ // eslint-disable-line no-await-in-loop rule: { ...rule, current: rule.current.content }, source: { ...source, current: value }, target: { ...target, current: target.current[key] }, }); } } resolve(target.current); } catch (error) { reject(error); } }); }
import React, { Component } from 'react'; import InputBar from "../containers/input_bar"; import PriceList from "../containers/price_list"; import StateTax from "../containers/state_tax"; import TipPercent from "../containers/tip_percent"; import FinalAmount from "../containers/final_amount"; export default class App extends Component { render() { return ( <div> <InputBar /> <div className="container middle-area"> <div className="row"> <PriceList /> <StateTax /> <TipPercent /> </div> </div> <FinalAmount /> </div> ); } }
import { createVue, destroyVM } from '../util'; describe('Tabs', () => { let vm; afterEach(() => { destroyVM(vm); }); it('create', done => { vm = createVue({ template: ` <el-tabs ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理" ref="pane-click">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); let paneList = vm.$el.querySelector('.el-tabs__content').children; let spy = sinon.spy(); vm.$refs.tabs.$on('tab-click', spy); setTimeout(_ => { const tabList = vm.$refs.tabs.$refs.tabs; expect(tabList[0].classList.contains('is-active')).to.be.true; expect(paneList[0].style.display).to.not.ok; tabList[2].click(); vm.$nextTick(_ => { expect(spy.withArgs(vm.$refs['pane-click']).calledOnce).to.true; expect(tabList[2].classList.contains('is-active')).to.be.true; expect(paneList[2].style.display).to.not.ok; done(); }); }, 100); }); it('active-name', done => { vm = createVue({ template: ` <el-tabs ref="tabs" :active-name="activeName" @click="handleClick"> <el-tab-pane name="tab-A" label="用户管理">A</el-tab-pane> <el-tab-pane name="tab-B" label="配置管理">B</el-tab-pane> <el-tab-pane name="tab-C" label="角色管理">C</el-tab-pane> <el-tab-pane name="tab-D" label="定时任务补偿">D</el-tab-pane> </el-tabs> `, data() { return { activeName: 'tab-B' }; }, methods: { handleClick(tab) { this.activeName = tab.name; } } }, true); setTimeout(_ => { const paneList = vm.$el.querySelector('.el-tabs__content').children; const tabList = vm.$refs.tabs.$refs.tabs; expect(tabList[1].classList.contains('is-active')).to.be.true; expect(paneList[1].style.display).to.not.ok; tabList[3].click(); vm.$nextTick(_ => { expect(tabList[3].classList.contains('is-active')).to.be.true; expect(paneList[3].style.display).to.not.ok; expect(vm.activeName === 'tab-D'); done(); }); }, 100); }); it('card', () => { vm = createVue({ template: ` <el-tabs type="card"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); expect(vm.$el.classList.contains('el-tabs--card')).to.be.true; }); it('border card', () => { vm = createVue({ template: ` <el-tabs type="border-card"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); expect(vm.$el.classList.contains('el-tabs--border-card')).to.be.true; }); it('dynamic', (done) => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane :label="tab.label" :name="tab.name" v-for="tab in tabs">Test Content</el-tab-pane> </el-tabs> `, data() { return { tabs: [{ label: 'tab1', name: 'tab1' }, { label: 'tab2', name: 'tab2' }, { label: 'tab3', name: 'tab3' }, { label: 'tab4', name: 'tab4' }] }; } }, true); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-tab-pane').length).to.equal(4); vm.tabs.push({ label: 'tab5', name: 'tab5' }); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-tab-pane').length).to.equal(5); done(); }); }, 100); }); it('closable', done => { vm = createVue({ template: ` <el-tabs type="card" :closable="true" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); let spy = sinon.spy(); vm.$refs.tabs.$on('tab-remove', spy); setTimeout(_ => { const tabList = vm.$refs.tabs.$refs.tabs; const paneList = vm.$el.querySelector('.el-tabs__content').children; tabList[1].querySelector('.el-icon-close').click(); vm.$nextTick(_ => { expect(tabList.length).to.be.equal(3); expect(paneList.length).to.be.equal(3); expect(spy.calledOnce).to.true; expect(tabList[1].innerText.trim()).to.be.equal('角色管理'); expect(paneList[0].innerText.trim()).to.be.equal('A'); done(); }); }, 100); }); it('closable in tab-pane', (done) => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane label="用户管理" closable>A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理" closable>C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-icon-close').length).to.equal(2); done(); }, 100); }); it('closable edge', done => { vm = createVue({ template: ` <el-tabs type="card" :closable="true" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); vm.$nextTick(_ => { const paneList = vm.$el.querySelector('.el-tabs__content').children; const tabList = vm.$refs.tabs.$refs.tabs; tabList[0].querySelector('.el-icon-close').click(); vm.$nextTick(_ => { expect(tabList.length).to.be.equal(3); expect(paneList.length).to.be.equal(3); expect(tabList[0].innerText.trim()).to.be.equal('配置管理'); expect(paneList[0].innerText.trim()).to.be.equal('B'); tabList[2].click(); tabList[2].querySelector('.el-icon-close').click(); setTimeout(_ => { expect(tabList.length).to.be.equal(2); expect(paneList.length).to.be.equal(2); expect(tabList[1].classList.contains('is-active')).to.be.true; expect(tabList[1].innerText.trim()).to.be.equal('角色管理'); expect(paneList[1].innerText.trim()).to.be.equal('C'); done(); }, 100); }); }); }); it('disabled', done => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane disabled label="配置管理" ref="disabled">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); vm.$nextTick(_ => { const tabList = vm.$refs.tabs.$refs.tabs; tabList[1].click(); vm.$nextTick(_ => { expect(tabList[1].classList.contains('is-active')).to.not.true; done(); }); }); }); });
/*jshint node:true */ "use strict"; var extend = require('util')._extend; module.exports = function (task, args, done) { var that = this, params, finish, cb, isDone = false, start, r, streamReturn = []; finish = function (err, results, runMethod) { var hrDuration = process.hrtime(start); if (isDone) { return; } isDone = true; var duration = hrDuration[0] + (hrDuration[1] / 1e9); // seconds done.call(that, err, results, { duration: duration, // seconds hrDuration: hrDuration, // [seconds,nanoseconds] runMethod: runMethod }); }; cb = function (err, results) { finish(err, results, 'callback'); }; params = extend([], args); params.push(cb); try { start = process.hrtime(); r = task.apply(this, params); } catch (err) { finish(err, null, 'catch'); } if (r && typeof r.done === 'function') { // wait for promise to resolve // FRAGILE: ASSUME: Promises/A+, see http://promises-aplus.github.io/promises-spec/ r.done(function (results) { finish(null, results, 'promise'); }, function(err) { finish(err, null, 'promise'); }); } else if (r && typeof r.on === 'function' && typeof r.once === 'function' && typeof r.end === 'function' && r.pipe) { // wait for stream to end r.on('data', function (results) { // return an array of results because we must listen to all the traffic through the stream if (typeof results !== 'undefined') { streamReturn.push(results); } }); r.once('error', function (err) { finish(err, null, 'stream'); }); r.once('end', function () { finish(null, streamReturn, 'stream'); }); // start stream if (typeof args !== 'undefined' && args !== null) { r.write.apply(that, args); } } else if (task.length < params.length) { // synchronous, function took in args.length parameters, and the callback was extra finish(null, r, 'sync'); //} else { // FRAGILE: ASSUME: callback } };
import path from 'node:path'; import test from 'ava'; import slash from 'slash'; import { isIgnoredByIgnoreFiles, isIgnoredByIgnoreFilesSync, isGitIgnored, isGitIgnoredSync, } from '../ignore.js'; import { PROJECT_ROOT, getPathValues, } from './utilities.js'; const runIsIgnoredByIgnoreFiles = async (t, patterns, options, fn) => { const promisePredicate = await isIgnoredByIgnoreFiles(patterns, options); const syncPredicate = isIgnoredByIgnoreFilesSync(patterns, options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isIgnoredByIgnoreFilesSync() result is different than isIgnoredByIgnoreFiles()', ); return promiseResult; }; const runIsGitIgnored = async (t, options, fn) => { const promisePredicate = await isGitIgnored(options); const syncPredicate = isGitIgnoredSync(options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isGitIgnoredSync() result is different than isGitIgnored()', ); return promiseResult; }; test('ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/gitignore'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['bar.js']; t.deepEqual(actual, expected); } }); test('ignore - mixed path styles', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(slash(path.resolve(directory, 'foo.js'))), ), ); } }); test('ignore - os paths', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(path.resolve(directory, 'foo.js')), ), ); } }); test('negative ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/negative'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['foo.js']; t.deepEqual(actual, expected); } }); test('multiple negation', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/multiple-negation'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => [ '!!!unicorn.js', '!!unicorn.js', '!unicorn.js', 'unicorn.js', ].filter(file => !isIgnored(file)), ); const expected = ['!!unicorn.js', '!unicorn.js']; t.deepEqual(actual, expected); } }); test('check file', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const ignoredFile of getPathValues(path.join(directory, 'foo.js'))) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(ignoredFile), ), ); } for (const notIgnoredFile of getPathValues(path.join(directory, 'bar.js'))) { t.false( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(notIgnoredFile), ), ); } }); test('custom ignore files', async t => { const cwd = path.join(PROJECT_ROOT, 'fixtures/ignore-files'); const files = [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', 'not-ignored.js', ]; t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.eslintignore', {cwd}, isEslintIgnored => files.filter(file => isEslintIgnored(file)), ), [ 'ignored-by-eslint.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.prettierignore', {cwd}, isPrettierIgnored => files.filter(file => isPrettierIgnored(file)), ), [ 'ignored-by-prettier.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.{prettier,eslint}ignore', {cwd}, isEslintOrPrettierIgnored => files.filter(file => isEslintOrPrettierIgnored(file)), ), [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', ], ); });
/* jshint expr:true */ import Ember from 'ember'; const { run } = Ember; import { expect } from 'chai'; import { describeModel, it } from 'ember-mocha'; import { beforeEach } from 'mocha'; let store; let m; describeModel( 'parent', 'Unit | Model | foo', { // Specify the other units that are required for this test. needs: ['model:child', 'model:pet'], }, function() { beforeEach( function () { store = this.store(); return run(() => { store.pushPayload({ data: null, included: [ { id: '1', type: 'parents', relationships: { children: { data: [ {id: '1', type: 'children'} ] } } }, { id: '1', type: 'children' }, { id: '2', type: 'children' }, { id: '1', type: 'pets' }, { id: '2', type: 'pets' } ] }); }); }); // Replace this with your real tests. it('parent stains itself', function() { const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.set('name', 'asdf'); }); m = "Parent should be dirty after updating an attribute on itself"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('dirty child stains parent', function() { const child = store.peekRecord('child', '1'); const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { child.set('name', 'foo'); }); m = "Parent should be dirty after updating an attribute on child"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('parent stains when children relationship is updated', function() { const parent = store.peekRecord('parent', '1'); const child2 = store.peekRecord('child', '2'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.get('children').pushObject(child2); }); m = "Parent should be dirty after adding another child"; expect(parent.get('hasDirtyAttributes'), m).true; }); } );
import { mediaPreview } from 'mtt-blog/helpers/media-preview'; import { module, test } from 'qunit'; module('Unit | Helper | media preview'); // Replace this with your real tests. test('it works', function(assert) { let result = mediaPreview([42]); assert.ok(result); });
/*============================= = Views = =============================*/ App.Views.UserInfo = Backbone.View.extend({ el: $('#user-info'), events: { "click #settings" : "clickSettings", "click #logout" : "clickLogout" }, clickLogout: function(event) { $.ajax({ url: 'auth/logout', type: 'get', dataType: 'json', success: function(data) { if (data.result == 'Success') { window.location = '/'; //Reload index page } else { alert('Logout failed'); //Alert on fail } }, error: function (xhr, ajaxOptions, thrownError) { console.log('Logout failed (hard)'); } }); }, clickSettings: function(event) { console.log('Settings clicked'); } });
// Generated by CoffeeScript 1.10.0 var AppController, MainController, ModalNewDeckController, NavController; AppController = (function() { function AppController($scope) { this.scope = $scope; this.scope.$on('search', function(term) { return console.log(term); }); $scope.$on('deckHasBeenSelected', function(deck) { $scope.currentDeck = deck.targetScope.currentDeck; return $scope.$broadcast('currentDeckHasChanged'); }); } return AppController; })(); NavController = (function() { function NavController($scope, $uibModal, $localStorage) { if (!$localStorage.decks) { $localStorage.decks = []; } $scope.decks = $localStorage.decks; $scope.selectDeck = function(deck) { $scope.currentDeck = deck; return $scope.$emit('deckHasBeenSelected', $scope.currentDeck); }; $scope.selectDeck($scope.decks[0]); $scope.addDeck = function($scope) { var modal; modal = $uibModal.open({ templateUrl: "template/modalNewDeck.html", controller: "modalNewDeckController" }); return modal.result.then(function(deckName) { return $localStorage.decks.push(new Deck(deckName)); }); }; } return NavController; })(); ModalNewDeckController = (function() { function ModalNewDeckController($scope, $uibModalInstance) { $scope.cancel = function() { return $uibModalInstance.dismiss("cancel"); }; $scope.submit = function() { return $uibModalInstance.close($scope.name); }; } return ModalNewDeckController; })(); MainController = (function() { function MainController($scope, $localStorage, $http) { $scope.cards = []; $scope.$on("currentDeckHasChanged", function(e) { $scope.currentDeck = e.targetScope.currentDeck; return $scope.load(); }); $scope.load = function() { return $scope.cards = $scope.currentDeck.cards; }; $scope.addNewCard = function() { $scope.cards.push(new Card($scope.title, $scope.description)); $scope.title = ""; return $scope.description = ""; }; } return MainController; })(); myApp.controller('appController', AppController); myApp.controller('navController', NavController); myApp.controller('mainController', MainController); myApp.controller('modalNewDeckController', ModalNewDeckController);
/* vim: set expandtab sw=4 ts=4 sts=4: */ /** * @fileoverview functions used for visualizing GIS data * * @requires jquery * @requires vendor/jquery/jquery.svg.js * @requires vendor/jquery/jquery.mousewheel.js * @requires vendor/jquery/jquery.event.drag-2.2.js */ /* global drawOpenLayers */ // templates/table/gis_visualization/gis_visualization.twig // Constants var zoomFactor = 1.5; var defaultX = 0; var defaultY = 0; // Variables var x = 0; var y = 0; var scale = 1; var svg; /** * Zooms and pans the visualization. */ function zoomAndPan () { var g = svg.getElementById('groupPanel'); if (!g) { return; } g.setAttribute('transform', 'translate(' + x + ', ' + y + ') scale(' + scale + ')'); var id; var circle; $('circle.vector').each(function () { id = $(this).attr('id'); circle = svg.getElementById(id); $(svg).on('change', circle, { r : (3 / scale), 'stroke-width' : (2 / scale) }); }); var line; $('polyline.vector').each(function () { id = $(this).attr('id'); line = svg.getElementById(id); $(svg).on('change', line, { 'stroke-width' : (2 / scale) }); }); var polygon; $('path.vector').each(function () { id = $(this).attr('id'); polygon = svg.getElementById(id); $(svg).on('change', polygon, { 'stroke-width' : (0.5 / scale) }); }); } /** * Initially loads either SVG or OSM visualization based on the choice. */ function selectVisualization () { if ($('#choice').prop('checked') !== true) { $('#openlayersmap').hide(); } else { $('#placeholder').hide(); } } /** * Adds necessary styles to the div that coontains the openStreetMap. */ function styleOSM () { var $placeholder = $('#placeholder'); var cssObj = { 'border' : '1px solid #aaa', 'width' : $placeholder.width(), 'height' : $placeholder.height(), 'float' : 'right' }; $('#openlayersmap').css(cssObj); } /** * Loads the SVG element and make a reference to it. */ function loadSVG () { var $placeholder = $('#placeholder'); $placeholder.svg({ onLoad: function (svgRef) { svg = svgRef; } }); // Removes the second SVG element unnecessarily added due to the above command $placeholder.find('svg:nth-child(2)').remove(); } /** * Adds controllers for zooming and panning. */ function addZoomPanControllers () { var $placeholder = $('#placeholder'); if ($('#placeholder').find('svg').length > 0) { var pmaThemeImage = $('#pmaThemeImage').val(); // add panning arrows $('<img class="button" id="left_arrow" src="' + pmaThemeImage + 'west-mini.png">').appendTo($placeholder); $('<img class="button" id="right_arrow" src="' + pmaThemeImage + 'east-mini.png">').appendTo($placeholder); $('<img class="button" id="up_arrow" src="' + pmaThemeImage + 'north-mini.png">').appendTo($placeholder); $('<img class="button" id="down_arrow" src="' + pmaThemeImage + 'south-mini.png">').appendTo($placeholder); // add zooming controls $('<img class="button" id="zoom_in" src="' + pmaThemeImage + 'zoom-plus-mini.png">').appendTo($placeholder); $('<img class="button" id="zoom_world" src="' + pmaThemeImage + 'zoom-world-mini.png">').appendTo($placeholder); $('<img class="button" id="zoom_out" src="' + pmaThemeImage + 'zoom-minus-mini.png">').appendTo($placeholder); } } /** * Resizes the GIS visualization to fit into the space available. */ function resizeGISVisualization () { var $placeholder = $('#placeholder'); var oldWidth = $placeholder.width(); var visWidth = $('#div_view_options').width() - 48; // Assign new value for width $placeholder.width(visWidth); $('svg').attr('width', visWidth); // Assign the offset created due to resizing to defaultX and center the svg. defaultX = (visWidth - oldWidth) / 2; x = defaultX; y = 0; scale = 1; } /** * Initialize the GIS visualization. */ function initGISVisualization () { // Loads either SVG or OSM visualization based on the choice selectVisualization(); // Resizes the GIS visualization to fit into the space available resizeGISVisualization(); if (typeof OpenLayers !== 'undefined') { // Configure OpenLayers // eslint-disable-next-line no-underscore-dangle OpenLayers._getScriptLocation = function () { return './js/vendor/openlayers/'; }; // Adds necessary styles to the div that coontains the openStreetMap styleOSM(); // Draws openStreetMap with openLayers drawOpenLayers(); } // Loads the SVG element and make a reference to it loadSVG(); // Adds controllers for zooming and panning addZoomPanControllers(); zoomAndPan(); } function getRelativeCoords (e) { var position = $('#placeholder').offset(); return { x : e.pageX - position.left, y : e.pageY - position.top }; } /** * Ajax handlers for GIS visualization page * * Actions Ajaxified here: * * Zooming in and zooming out on mousewheel movement. * Panning the visualization on dragging. * Zooming in on double clicking. * Zooming out on clicking the zoom out button. * Panning on clicking the arrow buttons. * Displaying tooltips for GIS objects. */ /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('table/gis_visualization.js', function () { $(document).off('click', '#choice'); $(document).off('mousewheel', '#placeholder'); $(document).off('dragstart', 'svg'); $(document).off('mouseup', 'svg'); $(document).off('drag', 'svg'); $(document).off('dblclick', '#placeholder'); $(document).off('click', '#zoom_in'); $(document).off('click', '#zoom_world'); $(document).off('click', '#zoom_out'); $(document).off('click', '#left_arrow'); $(document).off('click', '#right_arrow'); $(document).off('click', '#up_arrow'); $(document).off('click', '#down_arrow'); $('.vector').off('mousemove').off('mouseout'); }); AJAX.registerOnload('table/gis_visualization.js', function () { // If we are in GIS visualization, initialize it if ($('#gis_div').length > 0) { initGISVisualization(); } if (typeof OpenLayers === 'undefined') { $('#choice, #labelChoice').hide(); } $(document).on('click', '#choice', function () { if ($(this).prop('checked') === false) { $('#placeholder').show(); $('#openlayersmap').hide(); } else { $('#placeholder').hide(); $('#openlayersmap').show(); } }); $(document).on('mousewheel', '#placeholder', function (event, delta) { event.preventDefault(); var relCoords = getRelativeCoords(event); if (delta > 0) { // zoom in scale *= zoomFactor; // zooming in keeping the position under mouse pointer unmoved. x = relCoords.x - (relCoords.x - x) * zoomFactor; y = relCoords.y - (relCoords.y - y) * zoomFactor; zoomAndPan(); } else { // zoom out scale /= zoomFactor; // zooming out keeping the position under mouse pointer unmoved. x = relCoords.x - (relCoords.x - x) / zoomFactor; y = relCoords.y - (relCoords.y - y) / zoomFactor; zoomAndPan(); } return true; }); var dragX = 0; var dragY = 0; $(document).on('dragstart', 'svg', function (event, dd) { $('#placeholder').addClass('placeholderDrag'); dragX = Math.round(dd.offsetX); dragY = Math.round(dd.offsetY); }); $(document).on('mouseup', 'svg', function () { $('#placeholder').removeClass('placeholderDrag'); }); $(document).on('drag', 'svg', function (event, dd) { var newX = Math.round(dd.offsetX); x += newX - dragX; dragX = newX; var newY = Math.round(dd.offsetY); y += newY - dragY; dragY = newY; zoomAndPan(); }); $(document).on('dblclick', '#placeholder', function (event) { scale *= zoomFactor; // zooming in keeping the position under mouse pointer unmoved. var relCoords = getRelativeCoords(event); x = relCoords.x - (relCoords.x - x) * zoomFactor; y = relCoords.y - (relCoords.y - y) * zoomFactor; zoomAndPan(); }); $(document).on('click', '#zoom_in', function (e) { e.preventDefault(); // zoom in scale *= zoomFactor; var $placeholder = $('#placeholder').find('svg'); var width = $placeholder.attr('width'); var height = $placeholder.attr('height'); // zooming in keeping the center unmoved. x = width / 2 - (width / 2 - x) * zoomFactor; y = height / 2 - (height / 2 - y) * zoomFactor; zoomAndPan(); }); $(document).on('click', '#zoom_world', function (e) { e.preventDefault(); scale = 1; x = defaultX; y = defaultY; zoomAndPan(); }); $(document).on('click', '#zoom_out', function (e) { e.preventDefault(); // zoom out scale /= zoomFactor; var $placeholder = $('#placeholder').find('svg'); var width = $placeholder.attr('width'); var height = $placeholder.attr('height'); // zooming out keeping the center unmoved. x = width / 2 - (width / 2 - x) / zoomFactor; y = height / 2 - (height / 2 - y) / zoomFactor; zoomAndPan(); }); $(document).on('click', '#left_arrow', function (e) { e.preventDefault(); x += 100; zoomAndPan(); }); $(document).on('click', '#right_arrow', function (e) { e.preventDefault(); x -= 100; zoomAndPan(); }); $(document).on('click', '#up_arrow', function (e) { e.preventDefault(); y += 100; zoomAndPan(); }); $(document).on('click', '#down_arrow', function (e) { e.preventDefault(); y -= 100; zoomAndPan(); }); /** * Detect the mousemove event and show tooltips. */ $('.vector').on('mousemove', function (event) { var contents = $.trim(Functions.escapeHtml($(this).attr('name'))); $('#tooltip').remove(); if (contents !== '') { $('<div id="tooltip">' + contents + '</div>').css({ position : 'absolute', top : event.pageY + 10, left : event.pageX + 10, border : '1px solid #fdd', padding : '2px', 'background-color' : '#fee', opacity : 0.90 }).appendTo('body').fadeIn(200); } }); /** * Detect the mouseout event and hide tooltips. */ $('.vector').on('mouseout', function () { $('#tooltip').remove(); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var logLevels = { TRACE: 'TRACE', INFO: 'INFO', WARN: 'WARN', ERROR: 'ERROR' }; function _log(category, level) { var _console2; var now = (0, _moment2.default)().format(); for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (level === logLevels.ERROR) { var _console; return (_console = console).error.apply(_console, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } return (_console2 = console).log.apply(_console2, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } function Logger(category, requestId) { this.category = category; this.requestId = requestId; } function createLogLevel(level) { return function logWithLevel() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (this.requestId) { _log.apply(undefined, [this.category, level, 'RequestId: ' + this.requestId].concat(args)); } _log.apply(undefined, [this.category, level].concat(args)); }; } Logger.prototype.trace = createLogLevel(logLevels.TRACE); Logger.prototype.info = createLogLevel(logLevels.INFO); Logger.prototype.warn = createLogLevel(logLevels.WARN); Logger.prototype.error = createLogLevel(logLevels.ERROR); Logger.prototype.log = function log(level) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } if ((0, _lodash.size)(args) === 1 && (0, _lodash.isObject)(args[0])) { _log(this.category, (0, _lodash.toUpper)(level), JSON.stringify(args[0])); return; } _log.apply(undefined, [this.category, (0, _lodash.toUpper)(level)].concat(args)); };
import { expect } from "chai"; import { createStore, applyMiddleware } from 'redux'; import Immutable from 'immutable'; import reducers from '../src/lib/reducers'; import * as Utils from '../src/lib/utils'; describe('utils', function () { beforeEach(function () { this.state = Immutable.fromJS([ {title: "alpha"}, {title: "beta", children: [ {title: "foo"}, {title: "bar", children: [ {title: "quux"}, {title: "xyzzy"} ]}, {title: "baz"} ]}, {title: "gamma"}, {title: "level1", children: [ {title: 'level2', children: [ {title: 'level3', children: [ {title: 'level4'} ]} ]} ]}, {title: 'thud'} ]); this.store = createStore(reducers, { nodes: this.state }); this.expectedSeries = [ '0', '1', '1.children.0', '1.children.1', '1.children.1.children.0', '1.children.1.children.1', '1.children.2', '2', '3', '3.children.0', '3.children.0.children.0', '3.children.0.children.0.children.0', '4' ]; this.expectedSiblings = [ ['0', '1', '2', '3', '4'], ['1.children.0', '1.children.1', '1.children.2'], ['1.children.1.children.0', '1.children.1.children.1'], ['3.children.0'] ['3.children.0.children.0'], ['3.children.0.children.0.children.0'], ]; }); describe('splitPath', function () { it('should split a dot-delimited path into a key array', function () { expect(Utils.splitPath('1.children.1.children.2')) .to.deep.equal(['1', 'children', '1', 'children', '2']); }) }) describe('getNodeContext', function () { it('should construct contextual information for a node path', function () { var path = '1.children.1.children.0'; var expected = { key: ['1', 'children', '1', 'children', '0'], parentKey: ['1', 'children', '1'], index: 0, value: this.state.getIn(['1', 'children', '1', 'children', '0']), siblings: this.state.getIn(['1', 'children', '1', 'children']) }; var result = Utils.getNodeContext(this.state, path); expect(result).to.deep.equal(expected); }) }); function commonSiblingPathTest (inReverse, state, expectedSiblings) { var traversal = inReverse ? Utils.getPreviousSiblingPath : Utils.getNextSiblingPath; var siblingList; while (siblingList = expectedSiblings.shift()) { if (inReverse) { siblingList.reverse(); } var current, expected, result; current = siblingList.shift(); while (siblingList.length) { expected = siblingList.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } result = traversal(state, current); expect(result).to.equal(null); } } describe('getNextSiblingPath', function () { it('should find the path to the next sibling', function () { commonSiblingPathTest(false, this.state, this.expectedSiblings); }); }); describe('getPreviousSiblingPath', function () { it('should find the path to the previous sibling', function () { commonSiblingPathTest(true, this.state, this.expectedSiblings); }); }); function commonNodePathTest (inReverse, state, expectedSeries) { var current, expected, result; var traversal = (inReverse) ? Utils.getPreviousNodePath : Utils.getNextNodePath; if (inReverse) { expectedSeries.reverse(); } current = expectedSeries.shift(); while (expectedSeries.length) { expected = expectedSeries.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } } describe('getNextNodePath', function () { it('should find the path to the next node', function () { commonNodePathTest(false, this.state, this.expectedSeries); }) it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(false, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); describe('getPreviousNodePath', function () { it('should find the path to the previous node', function () { commonNodePathTest(true, this.state, this.expectedSeries); }); it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(true, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); });
function child() { alert('child'); } function parent() { alert('parent'); } function grandParent() { alert('grand parent'); }
/** * Created by ko on 2016-07-15. */ $(document).ready(function () { var pageNo= 1; // webtoon $("#recipe").on("click", function () { $("#travel_content").html(""); $("#youtube_content").html(""); $("#honbap_content").html(""); $("#game_content").html(""); $("#parcelArea").css("display","none"); $("#resultArea").html(""); $("#prodInfo_content").css("display", "none"); pageNo=1; $("#cvs_content").css("display", "none"); common_module.moveYoutubeMenu(); recipe_module.recipeTitle(); recipe_module.showRecipe(1); $(window).unbind('scroll'); $(window).scroll(function(){ if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) { pageNo +=1; recipe_module.showRecipe(pageNo); $(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">'); } }); $("#webtoon_content").css("display", "none"); }); });
/*! * inferno-component v1.2.2 * (c) 2017 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('inferno')) : typeof define === 'function' && define.amd ? define(['inferno'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Component = factory(global.Inferno)); }(this, (function (inferno) { 'use strict'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; var isBrowser = typeof window !== 'undefined' && window.document; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isStringOrNumber(obj) { var type = typeof obj; return type === 'string' || type === 'number'; } function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isInvalid(obj) { return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isNull(obj) { return obj === null; } function isTrue(obj) { return obj === true; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var Lifecycle = function Lifecycle() { this.listeners = []; this.fastUnmount = true; }; Lifecycle.prototype.addListener = function addListener (callback) { this.listeners.push(callback); }; Lifecycle.prototype.trigger = function trigger () { var this$1 = this; for (var i = 0; i < this.listeners.length; i++) { this$1.listeners[i](); } }; var noOp = ERROR_MSG; if (process.env.NODE_ENV !== 'production') { noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'; } var componentCallbackQueue = new Map(); // when a components root VNode is also a component, we can run into issues // this will recursively look for vNode.parentNode if the VNode is a component function updateParentComponentVNodes(vNode, dom) { if (vNode.flags & 28 /* Component */) { var parentVNode = vNode.parentVNode; if (parentVNode) { parentVNode.dom = dom; updateParentComponentVNodes(parentVNode, dom); } } } // this is in shapes too, but we don't want to import from shapes as it will pull in a duplicate of createVNode function createVoidVNode() { return inferno.createVNode(4096 /* Void */); } function createTextVNode(text) { return inferno.createVNode(1 /* Text */, null, null, text); } function addToQueue(component, force, callback) { // TODO this function needs to be revised and improved on var queue = componentCallbackQueue.get(component); if (!queue) { queue = []; componentCallbackQueue.set(component, queue); Promise.resolve().then(function () { componentCallbackQueue.delete(component); applyState(component, force, function () { for (var i = 0; i < queue.length; i++) { queue[i](); } }); }); } if (callback) { queue.push(callback); } } function queueStateChanges(component, newState, callback, sync) { if (isFunction(newState)) { newState = newState(component.state, component.props, component.context); } for (var stateKey in newState) { component._pendingState[stateKey] = newState[stateKey]; } if (!component._pendingSetState && isBrowser) { if (sync || component._blockRender) { component._pendingSetState = true; applyState(component, false, callback); } else { addToQueue(component, false, callback); } } else { component.state = Object.assign({}, component.state, component._pendingState); component._pendingState = {}; } } function applyState(component, force, callback) { if ((!component._deferSetState || force) && !component._blockRender && !component._unmounted) { component._pendingSetState = false; var pendingState = component._pendingState; var prevState = component.state; var nextState = Object.assign({}, prevState, pendingState); var props = component.props; var context = component.context; component._pendingState = {}; var nextInput = component._updateComponent(prevState, nextState, props, props, context, force, true); var didUpdate = true; if (isInvalid(nextInput)) { nextInput = createVoidVNode(); } else if (nextInput === inferno.NO_OP) { nextInput = component._lastInput; didUpdate = false; } else if (isStringOrNumber(nextInput)) { nextInput = createTextVNode(nextInput); } else if (isArray(nextInput)) { if (process.env.NODE_ENV !== 'production') { throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.'); } throwError(); } var lastInput = component._lastInput; var vNode = component._vNode; var parentDom = (lastInput.dom && lastInput.dom.parentNode) || (lastInput.dom = vNode.dom); component._lastInput = nextInput; if (didUpdate) { var subLifecycle = component._lifecycle; if (!subLifecycle) { subLifecycle = new Lifecycle(); } else { subLifecycle.listeners = []; } component._lifecycle = subLifecycle; var childContext = component.getChildContext(); if (!isNullOrUndef(childContext)) { childContext = Object.assign({}, context, component._childContext, childContext); } else { childContext = Object.assign({}, context, component._childContext); } component._patch(lastInput, nextInput, parentDom, subLifecycle, childContext, component._isSVG, false); subLifecycle.trigger(); component.componentDidUpdate(props, prevState); inferno.options.afterUpdate && inferno.options.afterUpdate(vNode); } var dom = vNode.dom = nextInput.dom; var componentToDOMNodeMap = component._componentToDOMNodeMap; componentToDOMNodeMap && componentToDOMNodeMap.set(component, nextInput.dom); updateParentComponentVNodes(vNode, dom); if (!isNullOrUndef(callback)) { callback(); } } else if (!isNullOrUndef(callback)) { callback(); } } var Component$1 = function Component(props, context) { this.state = {}; this.refs = {}; this._blockRender = false; this._ignoreSetState = false; this._blockSetState = false; this._deferSetState = false; this._pendingSetState = false; this._pendingState = {}; this._lastInput = null; this._vNode = null; this._unmounted = true; this._lifecycle = null; this._childContext = null; this._patch = null; this._isSVG = false; this._componentToDOMNodeMap = null; /** @type {object} */ this.props = props || inferno.EMPTY_OBJ; /** @type {object} */ this.context = context || {}; }; Component$1.prototype.render = function render (nextProps, nextState, nextContext) { }; Component$1.prototype.forceUpdate = function forceUpdate (callback) { if (this._unmounted) { return; } isBrowser && applyState(this, true, callback); }; Component$1.prototype.setState = function setState (newState, callback) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, callback, false); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.setStateSync = function setStateSync (newState) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, null, true); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.componentWillMount = function componentWillMount () { }; Component$1.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState, prevContext) { }; Component$1.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps, nextState, context) { return true; }; Component$1.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps, context) { }; Component$1.prototype.componentWillUpdate = function componentWillUpdate (nextProps, nextState, nextContext) { }; Component$1.prototype.getChildContext = function getChildContext () { }; Component$1.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force, fromSetState) { if (this._unmounted === true) { if (process.env.NODE_ENV !== 'production') { throwError(noOp); } throwError(); } if ((prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) || prevState !== nextState || force) { if (prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) { if (!fromSetState) { this._blockRender = true; this.componentWillReceiveProps(nextProps, context); this._blockRender = false; } if (this._pendingSetState) { nextState = Object.assign({}, nextState, this._pendingState); this._pendingSetState = false; this._pendingState = {}; } } var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState, context); if (shouldUpdate !== false || force) { this._blockSetState = true; this.componentWillUpdate(nextProps, nextState, context); this._blockSetState = false; this.props = nextProps; var state = this.state = nextState; this.context = context; inferno.options.beforeRender && inferno.options.beforeRender(this); var render = this.render(nextProps, state, context); inferno.options.afterRender && inferno.options.afterRender(this); return render; } } return inferno.NO_OP; }; return Component$1; })));
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule getDOMNodeID * @typechecks */ "use strict"; /** * Accessing "id" or calling getAttribute('id') on a form element can return its * control whose name or ID is "id". All DOM nodes support `getAttributeNode` * but this can also get called on other objects so just return '' if we're * given something other than a DOM node (such as window). * * @param {DOMElement|DOMWindow|DOMDocument} domNode DOM node. * @returns {string} ID of the supplied `domNode`. */ function getDOMNodeID(domNode) { if (domNode.getAttributeNode) { var attributeNode = domNode.getAttributeNode('id'); return attributeNode && attributeNode.value || ''; } else { return ''; } } module.exports = getDOMNodeID;
/** * @jsx React.DOM * @copyright Prometheus Research, LLC 2014 */ "use strict"; var React = require('react/addons'); var PropTypes = React.PropTypes; var Header = require('./Header'); var Viewport = require('./Viewport'); var ColumnMetrics = require('./ColumnMetrics'); var DOMMetrics = require('./DOMMetrics'); var GridScrollMixin = { componentDidMount() { this._scrollLeft = this.refs.viewport.getScroll().scrollLeft; this._onScroll(); }, componentDidUpdate() { this._onScroll(); }, componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount() { this._scrollLeft = undefined; }, onScroll({scrollLeft}) { if (this._scrollLeft !== scrollLeft) { this._scrollLeft = scrollLeft; this._onScroll(); } }, _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); this.refs.viewport.setScrollLeft(this._scrollLeft); } } }; var Grid = React.createClass({ mixins: [ GridScrollMixin, ColumnMetrics.Mixin, DOMMetrics.MetricsComputatorMixin ], propTypes: { rows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.array.isRequired }, getStyle: function(){ return{ overflowX: 'scroll', overflowY: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight } }, render() { var headerRows = this.props.headerRows || [{ref : 'row'}]; return ( <div {...this.props} style={this.getStyle()} className="react-grid-Grid"> <Header ref="header" columns={this.state.columns} onColumnResize={this.onColumnResize} height={this.props.rowHeight} totalWidth={this.DOMMetrics.gridWidth()} headerRows={headerRows} /> <Viewport ref="viewport" width={this.state.columns.width} rowHeight={this.props.rowHeight} rowRenderer={this.props.rowRenderer} cellRenderer={this.props.cellRenderer} rows={this.props.rows} selectedRows={this.props.selectedRows} expandedRows={this.props.expandedRows} length={this.props.length} columns={this.state.columns} totalWidth={this.DOMMetrics.gridWidth()} onScroll={this.onScroll} onRows={this.props.onRows} rowOffsetHeight={this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length} /> </div> ); }, getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, }); module.exports = Grid;
import './turn-order-a2314c0f.js'; import 'redux'; import 'immer'; import './reducer-4d135cbd.js'; import './Debug-1ad6801e.js'; import 'flatted'; import './ai-ce6b7ece.js'; import './initialize-ec2b5846.js'; export { C as Client } from './client-abd9e531.js';
'use strict'; angular.module('shoprApp') .controller('BookrCtrl', function ($scope, localStorageService, Auth, $http, $routeParams, $location) { $scope.Auth = Auth; //$scope.books = Auth.getCurrentUser().books; $scope.mySubs = Auth.getCurrentUser().books; function getById(books, id) { for(var b in books) { if(books[b]._id === id) return books[b]; } } function loadMore(book) { var page = book.recent[book.recent.length-book.pageIndex-1]; if(page && !page.src) { $http.get('/api/pages/'+book._id+'/'+page.issue).success(function(fullPage) { for(var k in fullPage[0]) page[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var forward = book.recent[book.recent.length-book.pageIndex]; if(forward && !forward.src) { $http.get('/api/pages/'+book._id+'/'+forward.issue).success(function(fullPage) { for(var k in fullPage[0]) forward[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var back = book.recent[book.recent.length-book.pageIndex-2]; if(back && !back.src) { $http.get('/api/pages/'+book._id+'/'+back.issue).success(function(fullPage) { for(var k in fullPage[0]) back[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } } function init(book, pageIndex) { book.pageIndex = pageIndex; $scope.$watch(function(){ return this.pageIndex; }.bind(book), function(newValue, oldValue){ console.log(this); loadMore(this); // $location.path('/bookr/'+this._id+'/'+this.pageIndex, false); var elm = $('book[ng-id="'+this._id+'"]')[0]; elm && $('html, body').animate({ scrollTop: elm.offsetTop }, 450); }.bind(book)); $scope.books.push(book); } function pad(books) { for(var b in books) { var book = books[b]; console.log(book); var recentLength = book.recent.length; for(var i = 0; i < book.count-recentLength; i++) book.recent.push({_id:book._id+'_'+(book.count-(recentLength+1)-i), issue:book.count-(recentLength+1)-i}); console.log(book); } } var books = [$routeParams]; $scope.books = []; for(var b in books) { var book = getById($scope.mySubs, books[b].book); if(!book) { var page = books[b].page; $http.get('/api/books/'+books[b].book).success(function(book){ pad([book]); console.log(book); $scope.mySubs.push(book); init(book, page); console.log('wtf?'); }); continue; } init(book, parseInt(books[b].page)); } });
'use strict'; var express = require("express"); var http = require("http"); var app = express(); var httpServer = http.Server(app); var io = require('socket.io')(httpServer); // Users array. var users = []; // Channels pre-defined array. var channels = [ 'Angular', 'React', 'Laravel', 'Symfony' ]; // Start http server. httpServer.listen(3000, function () { }); // Use static files 'app' folder for '/' path. app.use(express.static(__dirname + '/app/')); // Channels endpoint. app.get('/channels', function (req, res) { res.send(channels); }); // On connection event. io.on('connection', function (socket) { // Join event. socket.on('join', function (data) { // Join socket to channel. socket.join(data.channel); // Add user to users lists. users.push({id: socket.id, name: data.user}); // Bind username to socket object. socket.username = data.user; // If socket already exists in a channel, leave. if (typeof socket.channel != 'undefined') { socket.leave(socket.channel); } // Bind channel to socket. socket.channel = data.channel; }); // Message event. socket.on('message', function (data) { // Send to selected channel user's message. io.sockets.in(data.channel).emit('message', {message: data.message, user: data.username}); }); // Private message event. socket.on('private', function (data) { // Split message to take receiver name. var message = data.message.split(" "); // Get username from message array. var to_user = message[0].slice(1); // Filter users to find user's socket id and send message. users.filter(function (user) { if (user.name == to_user) { // Format message. var private_message = "(private) " + data.message.slice(to_user.length + 2); // Send message to user who sent the message. io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user}); // Send message to receiver. io.sockets.connected[user.id].emit('message', {message: private_message, user: data.username}); } }); }); // Disconnect event. socket.on('disconnect', function () { // Check if user joined any room and clean users array. users = users.filter(function (user) { if (user.id == socket.id) { return false; } return true }); }); });
import globalize from 'globalize'; import configure from '../src/configure'; export default function testLocalizer() { function getCulture(culture){ return culture ? globalize.findClosestCulture(culture) : globalize.culture() } function shortDay(dayOfTheWeek, culture) { let names = getCulture(culture).calendar.days.namesShort; return names[dayOfTheWeek.getDay()]; } var date = { formats: { date: 'd', time: 't', default: 'f', header: 'MMMM yyyy', footer: 'D', weekday: shortDay, dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: 'yyyy', century: 'yyyy', }, firstOfWeek(culture) { culture = getCulture(culture) return (culture && culture.calendar.firstDay) || 0 }, parse(value, format, culture){ return globalize.parseDate(value, format, culture) }, format(value, format, culture){ return globalize.format(value, format, culture) } } function formatData(format, _culture){ var culture = getCulture(_culture) , numFormat = culture.numberFormat if (typeof format === 'string') { if (format.indexOf('p') !== -1) numFormat = numFormat.percent if (format.indexOf('c') !== -1) numFormat = numFormat.curency } return numFormat } var number = { formats: { default: 'D' }, parse(value, culture) { return globalize.parseFloat(value, 10, culture) }, format(value, format, culture){ return globalize.format(value, format, culture) }, decimalChar(format, culture){ var data = formatData(format, culture) return data['.'] || '.' }, precision(format, _culture){ var data = formatData(format, _culture) if (typeof format === 'string' && format.length > 1) return parseFloat(format.substr(1)) return data ? data.decimals : null } } configure.setLocalizers({ date, number }) }
var instance = null; OptionSelect = function OptionSelect(optionSelectFunction, id, options) { this.optionSelect = optionSelectFunction; this.containerId = id; this.options = options; instance.instanceData.set(this); } OptionSelect.prototype.open = function() { $(this.containerId).show(); }; Template.optionSelect.onCreated(function() { this.instanceData = new ReactiveVar({}); instance = this; }); Template.optionSelect.helpers({ options: function() { return instance.instanceData.get().options; } }); Template.optionSelect.events({ 'click .option-select__selection': function() { var obj = instance.instanceData.get(); obj.optionSelect(this); $(obj.containerId).hide(); }, 'click #option-select-close': function() { $(instance.instanceData.get().containerId).hide(); } });
// Ember.merge only supports 2 arguments // Ember.assign isn't available in older Embers // Ember.$.extend isn't available in Fastboot import Ember from 'ember'; export default function(...objects) { let merged = {}; objects.forEach(obj => { merged = Ember.merge(merged, obj); }); return merged; }
var fs = require('fs'); var dot = require('dot'); var defaults = require('defaults'); var Block = require('glint-block'); var Style = require('glint-plugin-block-style-editable'); var TextBlock = require('glint-block-text'); var MDBlock = require('glint-block-markdown'); var MetaBlock = require('glint-block-meta'); var CKEditorBlock = require('glint-block-ckeditor'); var Adapter = require('glint-adapter'); var PageAdapter = require('page-adapter'); var Container = require('glint-container'); var Wrap = require('glint-wrap'); var Widget = require('glint-widget'); var LayoutWrap = require('wrap-layout'); var template = fs.readFileSync(__dirname + '/index.dot', 'utf-8'); var compiled = dot.template(template); function text() { return Block(TextBlock()).use(Style()); } function markdown() { return Block(MDBlock()).use(Style()); } function editor() { return Block(CKEditorBlock()).use(Style()); } exports = module.exports = function wrap(o) { o = o || {}; var wrap = Wrap(); var blocks = { 'home-title': text().selector('[data-id=home-title]'), 'home-teaser': editor().selector('[data-id=home-teaser]'), 'home-subtitle': markdown().selector('[data-id=home-subtitle]'), 'home-box-1': markdown().selector('[data-id=home-box-1]'), 'home-box-2': markdown().selector('[data-id=home-box-2]'), 'home-box-3': markdown().selector('[data-id=home-box-3]'), 'home-box-4': markdown().selector('[data-id=home-box-4]'), 'home-box-5': markdown().selector('[data-id=home-box-5]'), 'home-box-6': markdown().selector('[data-id=home-box-6]'), 'www-title': text().selector('[data-id=www-title]'), 'www-content': editor().selector('[data-id=www-content]'), 'bb-title': text().selector('[data-id=bb-title]'), 'bb-content': markdown().selector('[data-id=bb-content]'), 'doc-title': text().selector('[data-id=doc-title]'), 'doc-content': markdown().selector('[data-id=doc-content]'), 'img-title': text().selector('[data-id=img-title]'), 'img-content': editor().selector('[data-id=img-content]'), 'contact-title': text().selector('[data-id=contact-title]'), 'contact-content': markdown().selector('[data-id=doc-content]'), meta: Block(MetaBlock()) }; var adapter = o.adapter || PageAdapter(o); var db = o.db || 'glint'; var type = o.type || 'main'; var id = o.id || 'main'; var templateData = o.templateData || '__template__'; var homeAdapter = Adapter(adapter) .db(db) .type(type) var container = Container(blocks, homeAdapter) .id(id) .template(templateData); wrap .parallel(container) .series('content', Widget(function(options) { return compiled(options) }).place('force:server')) .series(LayoutWrap(o.layout).place('force:server')) wrap.routes = adapter.routes; return wrap; };
var Logger = require("./Logger.js"); var Level = require("./Level.js"); var PrintPattern = require("./PrintPattern.js"); module.exports = (function() { /* STATE VARIABLES */ // OUT configuration var OUT_INTERVAL = undefined; // 1sec var OUT_INTERVAL_TIMEOUT = 1000; // 1sec var OUT_SIZE = 1000; // logger objects var loggers = {}; // appender list var appenders = {}; appenders[Level.trace] = {}; appenders[Level.log] = {}; appenders[Level.info] = {}; appenders[Level.warn] = {}; appenders[Level.error] = {}; // information to log var records = new Array(); // -------------------------------------------------------------------------- /* METHODS */ // add a logger to the map // logger_name should be something like group.subgroup.name var createLogger = function(logger_name) { if (loggers[logger_name] == undefined) { loggers[logger_name] = new Logger(logger_name, function(record) { records.push(record); writeLog(); }); } return loggers[logger_name]; } // create the appender objects // the appender_config should be something like // [{ // "name": "appender name", // "type": "appender implementation", // "level": "level that appender listens", // "loggers": ["logger1", "logger2", "group.logger3"], // Follows the optional attributes // -------------------------------------------------- // "print_pattern": "[{y}/{M}/{d} {w} {h}:{m}:{s}.{ms}] [{lvl}] [{lg}] // {out}", // "config": {...[appender exclusive configuration]} // }, ...] var loadAppenderConfig = function(appender_configs) { realeaseAppenders(); for ( var i in appender_configs) { // get an appender config var appender_config = appender_configs[i]; // create appender object var AppenderType = require("./appender/" + appender_config.type + "Appender.js"); var appender_object = new AppenderType(appender_config.name, new PrintPattern(appender_config.print_pattern), appender_config.config); for ( var l in appender_config.loggers) { var listened_logger = appender_config.loggers[l]; // initialize listened logger appender list if (appenders[Level[appender_config.level]][listened_logger] == undefined) { appenders[Level[appender_config.level]][listened_logger] = new Array(); } appenders[Level[appender_config.level]][listened_logger] .push(appender_object); } } } // realease appenders internal resources; var realeaseAppenders = function() { for (lv in appenders) { var level_appender = appenders[lv]; for (lg in level_appender) { var logger_appender = level_appender[lg]; if (logger_appender.length > 0) { for (i in logger_appender) { var appender = logger_appender[i]; appender.release(); } } delete level_appender[lg]; } } }; // Wrapper that decides when the app will log without hold the process var writeLog = function() { if (OUT_INTERVAL == undefined) { OUT_INTERVAL = setTimeout(writeLogImpl, OUT_INTERVAL_TIMEOUT); } }; // real log process var writeLogImpl = function() { for (var i = 0; i < OUT_SIZE; i++) { // getting message record var record = records[i]; // stop the loop when ther record list is empty; if (record == undefined) { break; } // the record should be logged on all appender that listen the same // level or the appenders that listen lower levels for (var level = record.level; level >= 1; level--) { // getting appender list by level var level_appenders = appenders[level]; // try to catch all appenders as possible var logger_composition = record.logger.split("."); var logger_name = undefined; for (var lc = 0; lc < logger_composition.length; lc++) { // logger name rebuild process if (logger_name == undefined) { logger_name = logger_composition[lc]; } else { logger_name = logger_name + "." + logger_composition[lc]; } // getting appender list by logger var logger_appenders = level_appenders[logger_name]; // using appender if (logger_appenders != undefined) { for (a in logger_appenders) { var appender = logger_appenders[a]; appender.write(record); } } } } } records.splice(0, OUT_SIZE); // clean interval identifier OUT_INTERVAL = undefined; // if still remain any record, start again the log process if (records.length > 0) { writeLog(); } }; // public interface return { "createLogger" : createLogger, "loadAppenderConfig" : loadAppenderConfig } })();
/** * @constructor */ var TwoSum = function() { this.dict = {}; }; /** * @param {number} input * @returns {void} */ TwoSum.prototype.add = function(input) { // no need to bigger that 2 this.dict[input] = this.dict[input] ? 2 : 1; }; /** * @param {number} val * @returns {boolean} */ TwoSum.prototype.find = function(val) { var dict = this.dict; var keys = Object.keys(dict); for (var i = 0; i < keys.length; i++) { var key = parseInt(keys[i]); var target = val - key; if (!dict[target]) continue; if ((target === key && dict[target] === 2) || target !== key) { return true; } } return false; }; var eq = require('assert').equal; var ts = new TwoSum(); ts.add(0); ts.find(0) eq(ts.find(0), false); ts = new TwoSum(); ts.add(0); ts.add(0); ts.find(0) eq(ts.find(0), true); ts = new TwoSum(); ts.add(1); ts.add(3); ts.add(5); eq(ts.find(1), false); eq(ts.find(4), true); eq(ts.find(7), false);
import Element from './Element' export default class extends Element { constructor ( val ) { super({ 'w:type': {} }) if (val) this.setVal(val || null) } setVal (value) { if (value) { this.src['w:type']['@w:val'] = value } else { delete this.src['w:type']['@w:val'] } } getVal () { return this.src['w:type']['@w:val'] || null } }
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars'); var index = require('./routes/index'); var project = require('./routes/project'); var palette = require('./routes/palette'); // Example route // var user = require('./routes/user'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('Intro HCI secret key')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } // Add routes here app.get('/', index.view); app.get('/project/:id', project.projectInfo); app.get('/palette', palette.randomPalette); // Example route // app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
var model = require('../model'); // ROUTES exports.saveAvailabilityChange = function(req, res) { console.log('hi im here') function afterSave(err){ if(err) { console.log(err) res.send(500) } else { backURL = req.header('Referer') || '/'; res.redirect(backURL); } } if(req.query.optionsRadios == 'available') { var curr_user = req.session.user req.session.user.isAvailable = true model.User.update({ "email":req.session.user.email }, { "isAvailable":true }).exec(afterSave) } else { var curr_user = req.session.user req.session.user.isAvailable = false model.User.update({ "email":req.session.user.email }, { "isAvailable":false }).exec(afterSave) } } exports.viewEditIntervieweeProfile = function(req, res) {
 function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewee/editIntervieweeProfile', req.session.user); } } ) } } if (req.query.email){ // form submit /* fname or firstname?? */ model.User.update({"email":req.session.user.email}, { "firstname":req.query.fname, "lastname":req.query.lname, "email":req.query.email, "education":req.query.education, "occupation":req.query.occupation, "location":req.query.location }).exec(afterFind); } else afterFind(null) 
} exports.viewEditInterviewerProfile = function(req, res) {
 function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/editInterviewerProfile', req.session.user); } } ) } } if (req.query.email){ // form submit /* fname or firstname?? */ model.User.update({"email":req.session.user.email}, { "firstname":req.query.fname, "lastname":req.query.lname, "email":req.query.email, "education":req.query.education, "occupation":req.query.occupation, "location":req.query.location, "company":req.query.company }).exec(afterFind); } else afterFind(null) 
} exports.view = function(req, res){ if (req.query.invalid) res.render('prelogin/index', { 'invalid': req.query.invalid }) else res.render('prelogin/index'); }; exports.viewIntervieweeAreasToImprove = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; console.log(req.session.user.isAlternate) res.render('interviewee/intervieweeAreasToImprove', req.session.user); } } ) } } if (req.query.improvements){ // form submit model.User.update({"email":req.session.user.email}, {"improvements":req.query.improvements}).exec(afterFind); } else afterFind(null) }; exports.viewIntervieweeFeedback = function(req, res){ model.User.find({"email":req.session.user.email}).exec(renderFeedbacks); function renderFeedbacks(err, users) { var user = users[0] console.log(user.feedback) res.render('interviewee/intervieweeFeedback', { 'feedbacks': user.feedback, 'isAvailable':req.session.user.isAvailable }); } }; exports.viewInterviewerFeedback = function(req, res){ model.User.find({"email":req.session.user.email}).exec(renderFeedbacks); function renderFeedbacks(err, users) { var user = users[0] console.log(user.feedback) res.render('interviewer/interviewerFeedback', { 'feedbacks': user.feedback, 'isAvailable':req.session.user.isAvailable }); } }; exports.viewIntervieweeSkills = function(req, res){ console.log('Skills + isAvailable:' + req.session.user.isAvailable) function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var curr_user = users[0] req.session.user = curr_user; res.render('interviewee/intervieweeSkills',req.session.user); } } ) } } if (req.query.programmingLang){ // form submit model.User.update({ "email":req.session.user.email }, { "programmingLang":req.query.programmingLang, "softSkills":req.query.softSkills, "frameworks":req.query.frameworks }) .exec(afterFind); } else afterFind(null) }; exports.dosurveyInterviewee = function(req, res) {
 model.User.find({ "email": req.query.email }).exec(function(err, users){ if (err) { console.log(err); res.send(500) } else { if (users.length == 0){ var random = Math.random() var isAlternate = true //(random > 0.5), chose alternate version var newUser = model.User({ "firstname": req.query.fname, "lastname": req.query.lname, "email": req.query.email, "password": req.query.password, "ghangout": req.query.ghangout, "interviewer": false, "education": req.query.education, "occupation": req.query.occupation, "location": req.query.location, "programmingLang": "For example: Java, C++, Python", "softSkills": "For example: Good communication skills, Experience managing teams", "frameworks": "For example: DJango, MongoDB, Google AppEngine", "improvements": "For example: practicing more technical questions, learning to clearly express ideas", "isAlternate": isAlternate, "isAvailable": true }); console.log(newUser) newUser.save(function(err){ if (err) { console.log(err) res.send(500) } else { req.session.user = newUser res.render('interviewee/intervieweeSurvey',newUser); } }); } else { console.log('Associated email address already used.') res.send(500) } } }); 
} exports.viewInterviewerAboutMe = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerAboutMe', req.session.user); } } ) } } if (req.query.mission){ // form submit model.User.update({"email":req.session.user.email}, {"mission":req.query.mission,"hobbies":req.query.hobbies}).exec(afterFind); } else afterFind(null) }; exports.viewInterviewerPastExp = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({ "email":req.session.user.email }).exec(function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerPastExp', req.session.user); } }) } } if (req.query.description1){ // form submit model.User.update({ "email":req.session.user.email }, { "description1":req.query.description1, "description2":req.query.description2 }).exec(afterFind); } else afterFind(null) }; exports.dosurveyInterviewer = function(req, res) {
 model.User.find({ "email": req.query.email }).exec(function(err, users){ if (err) console.log(err); else { if (users.length == 0){ var randnum = Math.random() var isAlternate = true; // (randnum > 0.5) chose alternate version var newUser = model.User({ "firstname": req.query.fname, "lastname": req.query.lname, "email": req.query.email, "password": req.query.password, "ghangout": req.query.ghangout, "interviewer": true, "education": req.query.education, "occupation": req.query.occupation, "location": req.query.location, "company": req.query.company, "mission": "Tell us more about yourself.", "hobbies": "What are your hobbies?", "description1": "What did you do? Where did you work?", "description2": "What did you do? Where did you work?", "isAlternate": isAlternate, "isAvailable": true }); console.log(isAlternate) newUser.save(function(err){ if (err) { console.log(err) res.send(500) } else { req.session.user = newUser res.render('interviewer/interviewerSurvey',newUser); } }); } else { console.log('Associated email address already used.') res.send(500) } } }); }; exports.viewLogin = function(req, res){ res.render('prelogin/login'); }; exports.viewMatchForInterviewer = function(req, res){ // get occupation console.log(req.session) if (req.session.user) occupation = req.session.user.occupation else occupation = '' // find users with matching occupation // eventually create req.session.set and store people already viewed // only allow non-viewed people into matching_occupation_users // also allow match page to let you know when you have exhausted all options matching_occupation_users = [] model.User.find({"occupation":occupation,"interviewer":false}).exec(afterFind); function afterFind(err,users){ if(err) { console.log(err) res.send(500) } else { for (i = 0; i < users.length; i++){ matching_occupation_users.push(users[i]); }; // select a random person num_matching = matching_occupation_users.length rand_index = Math.floor(Math.random() * num_matching) matched_user = matching_occupation_users[rand_index] var curr_user = req.session.user res.render('matchForInterviewer', { 'match': matched_user, 'curr_user': curr_user }); } }; }; exports.viewMatchForInterviewee = function(req, res){ // get occupation console.log(req.session) if (req.session.user) occupation = req.session.user.occupation else occupation = '' // find users with matching occupation // eventually create req.session.set and store people already viewed // only allow non-viewed people into matching_occupation_users // also allow match page to let you know when you have exhausted all options matching_occupation_users = [] model.User.find({"occupation":occupation,"interviewer":true}).exec(afterFind); function afterFind(err,users){ if(err) { console.log(err) res.send(500) } else { for (i = 0; i < users.length; i++){ matching_occupation_users.push(users[i]); }; // select a random person num_matching = matching_occupation_users.length rand_index = Math.floor(Math.random() * num_matching) matched_user = matching_occupation_users[rand_index] var curr_user = req.session.user res.render('matchForInterviewee', { 'match': matched_user, 'curr_user': curr_user, 'isAvailable':req.session.user.isAvailable }); } }; }; exports.kickoff = function(req, res) {
 var curr_user = req.session.user res.render('startInterview', { 'match':req.params.match, 'curr_user': curr_user, 'isAvailable':req.session.user.isAvailable }); }; exports.kickoffWithInterviewee = function(req, res){ res.render('interviewee/intervieweeSkills', req.session.user); }; exports.viewUnimplemented = function(req, res){ res.render('unimplemented'); }; exports.logout = function(req, res){ req.session.destroy(function(err){ if (err) console.log(err) console.log('cleared session') res.redirect('/'); }) }; exports.viewSignup = function(req, res){ res.render('prelogin/signup'); }; exports.viewInterviewerProfile = function(req, res) { // this route is only called after session is set res.render('interviewer/interviewerProfile', req.session.user); }; exports.viewInterviewerProfileAlter = function(req,res){ res.render('interviewer/interviewerProfileAlter',req.session.user); } exports.viewIntervieweeProfileAlter = function(req,res){ res.render('interviewee/intervieweeProfileAlter',req.session.user); } exports.viewIntervieweeProfile = function(req, res) { if (req.session && req.session.user){ console.log(req.session.user.isAlternate) if (req.query.persontype) { // means came from signup surveys console.log('came from signup') if (req.query.persontype == "interviewee") {// interviewee console.log('interviewee') // update user obj in db model.User.update({ '_id': req.session.user._id }, { 'occupation': req.query.occupation, 'education': req.query.education, 'location': req.query.location }).exec(function(err){ if (err) { console.log(err) res.send(500) } else { model.User.find({ '_id': req.session.user._id }).exec(function(err, users){ if (err) { console.log(err) res.send(500) } else { var user = users[0] req.session.user = user res.redirect('intervieweeProfile/alternate'); } }) } }) } else {// interviewer console.log('interviewer') model.User.update({'_id': req.session.user._id}, { 'occupation': req.query.occupation, 'education': req.query.education, 'location': req.query.location, 'company':req.query.company, }).exec(function(err){ if (err) { console.log(err) res.send(500) } else { model.User.find({ '_id': req.session.user._id }).exec(function(err, users){ if (err) { console.log(err) res.send(500) } else { var user = users[0] req.session.user = user res.redirect('interviewerProfile/alternate'); } }) } }); } } else { // just returning to the page if (req.session.user.interviewer){ res.redirect('interviewerProfile/alternate'); } else { res.redirect('intervieweeProfile/alternate'); } } } else if (req.query && req.query.uname){ // after login console.log('came from login') console.log('email:', req.query.uname) console.log('password:', req.query.password) model.User.find({ "email": req.query.uname, "password": req.query.password }).exec(afterFind); function afterFind(err, users){ if (err) { console.log(err) res.send(500) } else if (users.length > 0){ var user = users[0] console.log(user); console.log(user.password); console.log(user.isAlternate) req.session.user = user if (user.interviewer){ res.redirect('interviewerProfile/alternate'); } else { console.log('I AM HERE') res.redirect('intervieweeProfile/alternate'); } } else res.redirect('/?invalid=1') } } else res.redirect('/?invalid=1'); } exports.postFeedback = function(req,res){ function afterUpdate(err){ if(err) { console.log(err) res.send(500) } else { res.render('feedback', { 'match':req.params.match, 'curr_user':curr_user, 'isAvailable':req.session.user.isAvailable }); } } if(req.query.feedback){// form submit console.log("I came here! Pay attention!") var curr_user = req.session.user model.User.update({"email":req.params.match}, { $push: {"feedback":{"text":req.query.feedback,"by":curr_user.firstname}} }).exec(afterUpdate); } else afterUpdate(null); } exports.viewInterviewerPastExp = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({ "email":req.session.user.email }).exec(function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerPastExp', req.session.user); } }) } } if (req.query.description1){ // form submit model.User.update({ "email":req.session.user.email }, { "description1":req.query.description1, "description2":req.query.description2 }).exec(afterFind); } else afterFind(null) };
System.register(['core-js', './map-change-records', './collection-observation'], function (_export) { var core, getChangeRecords, ModifyCollectionObserver, _classCallCheck, _inherits, mapProto, ModifyMapObserver; _export('getMapObserver', getMapObserver); function getMapObserver(taskQueue, map) { return ModifyMapObserver.create(taskQueue, map); } return { setters: [function (_coreJs) { core = _coreJs['default']; }, function (_mapChangeRecords) { getChangeRecords = _mapChangeRecords.getChangeRecords; }, function (_collectionObservation) { ModifyCollectionObserver = _collectionObservation.ModifyCollectionObserver; }], execute: function () { 'use strict'; _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; mapProto = Map.prototype; ModifyMapObserver = (function (_ModifyCollectionObserver) { function ModifyMapObserver(taskQueue, map) { _classCallCheck(this, ModifyMapObserver); _ModifyCollectionObserver.call(this, taskQueue, map); } _inherits(ModifyMapObserver, _ModifyCollectionObserver); ModifyMapObserver.create = function create(taskQueue, map) { var observer = new ModifyMapObserver(taskQueue, map); map.set = function () { var oldValue = map.get(arguments[0]); var type = oldValue ? 'update' : 'add'; var methodCallResult = mapProto.set.apply(map, arguments); observer.addChangeRecord({ type: type, object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map['delete'] = function () { var oldValue = map.get(arguments[0]); var methodCallResult = mapProto['delete'].apply(map, arguments); observer.addChangeRecord({ type: 'delete', object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map.clear = function () { var methodCallResult = mapProto.clear.apply(map, arguments); observer.addChangeRecord({ type: 'clear', object: map }); return methodCallResult; }; return observer; }; return ModifyMapObserver; })(ModifyCollectionObserver); } }; });
var BoardVo = require(_path.src + "/vo/BoardVo.js"); var BoardDao = require(_path.src + "/dao/BoardDao.js"); var RoleDao = require(_path.src + "/dao/RoleDao.js"); module.exports.board = function($, el, param, req, next) { var template = this.getTemplate($, el); BoardDao.getBoard(param.id, function(board) { $(el).html(template(board)); next(); }); }; module.exports.boardList = function($, el, param, req, next) { var vo = new BoardVo(); if(req.session.user != null) { vo.signinUserId = req.session.user.id; vo.signinUserLevel = req.session.user.level; } var template = this.getTemplate($, el); BoardDao.getBoardList(vo, function(boardList) { RoleDao.getRoleList(function(roleList) { $(el).html(template({boardList : boardList, roleList : roleList})); next(); }); }); };
/** * Created by sh on 15/7/6. */ "use strict"; var type = require("../type"); exports.parse = function (object, define, addition) { return type.dataParse(object, {type: Object, contents: String}, addition); };
/** * Created with JetBrains WebStorm. * User: gbox3d * Date: 13. 3. 30. * Time: 오후 3:35 * version : 0.8 * it is parts of pig2d engine * this engine is base on html5 css3 최종수정 2015.11.5 - 배경적용안되는 버그 수정, 2015.11.5 */ Pig2d = { version : '1.0.0' }; ///////////////////// ///model Pig2d.model = Backbone.Model.extend({ initialize: function() { var element = document.createElement('div'); var name = this.get('name'); if(name != undefined) { element.setAttribute('id',name); } //2.3 이전 버전을 위한 if(element.classList != undefined) { element.classList.add('pig2d-node'); } else { $(element).addClass('pig2d-node'); } this.attributes.element = element; this.attributes.update_signal = 'none'; this.attributes.translation = new gbox3d.core.Vect2d(0,0); this.attributes.scale = new gbox3d.core.Vect2d(1,1); //this.attributes.matrix = mat2d.create(); //this.attributes.matrix = new WebKitCSSMatrix(); this.attributes.flipX = false; this.attributes.flipY = false; this.attributes.cssupdate = true; this.attributes.cancelTransition = false; this.attributes.offset = { x:0, y:0 }; }, defaults: { rotation : 0 }, getPosition : function() { //if(decompose == true) { //행렬분해후 적용 // this.decomposeCssMatrix(this.getCssMatrix()); //} return this.attributes.translation; }, getRotation : function() { return this.attributes.rotation; }, setPosition : function(x,y) { this.attributes.translation.set(x,y); return this; }, setRotation : function(angle) { this.attributes.rotation = angle; return this; }, rotate : function(angle_delata) { this.attributes.rotation += angle_delata; return this; }, setScale : function(x,y) { this.attributes.scale.set(x,y); return this; }, getScale : function() { return this.attributes.scale; }, translate: function () { var v1 = new gbox3d.core.Vect2d(); var center = new gbox3d.core.Vect2d(0,0); return function ( distance, axis ) { // axis is assumed to be normalized v1.copy( axis ); v1.multiply( distance ); v1.rotate( gbox3d.core.degToRad(-this.attributes.rotation),center); if(this.attributes.flipX) { v1.X *= -1; } if(this.attributes.flipY) { v1.Y *= -1; } this.attributes.translation.addToThis( v1 ); return this; }; }(), show : function(visible) { this.get('element').style.visibility = visible ? 'inherit' : 'hidden'; }, isVisible : function() { return (this.get('element').style.visibility == 'hidden') ? false : true; }, ///////////////////// ////행렬관련 ////////////////// getCssMatrix : function() { var el = this.get('element'); var computedStyle = window.getComputedStyle(el); var trans = computedStyle.getPropertyValue('-webkit-transform'); var cssmat = new WebKitCSSMatrix(trans); return cssmat; }, //주어진 행렬을 분해하여 노드변환값에 역적용하기 decomposeCssMatrix : function(cssmat) { //var cssmat = this.getCssMatrix(); //이동변환 얻기 this.attributes.translation.X = cssmat.e; this.attributes.translation.Y = cssmat.f; //스케일 얻기 var scalex = Math.sqrt(cssmat.a*cssmat.a + cssmat.b*cssmat.b); var scaley = Math.sqrt(cssmat.c*cssmat.c + cssmat.d*cssmat.d); this.attributes.scale.X = scalex; this.attributes.scale.Y = scaley; //회전 얻기 var angle = Math.round(Math.atan2(cssmat.b/scalex, cssmat.a/scalex) * (180/Math.PI)); this.attributes.rotation = angle; }, getDecomposePosition : function() { var cssmat = this.getCssMatrix(); return new gbox3d.core.Vect2d(cssmat.e,cssmat.f); }, ////////////// animator setupTransition : function(param) { var element = this.get('element'); element.style.WebkitTransition = ''; this.attributes.TransitionEndCallBack = param.TransitionEndCallBack; if(this.attributes._TransitionEndCallBack != undefined) { element.removeEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack); } this.attributes._TransitionEndCallBack = function(event) { if(this.attributes.cancelTransition == true) { this.attributes.cancelTransition = false; } else { this.attributes.cssupdate = true; element.style.WebkitTransition = ''; if(this.attributes.TransitionEndCallBack != undefined) { this.attributes.TransitionEndCallBack.apply(this); } } //이밴트 전달 금지 event.cancelBubble = true; event.stopPropagation(); }.bind(this); element.addEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack,false); // if(param.timing_function != undefined) { // element.style.webkitTransitionTimingFunction = 'linear'; // } return this; }, transition : function(param) { var element = this.get('element'); param.timing_function = param.timing_function ? param.timing_function : 'linear'; if(element.style.WebkitTransition !== '') return; if(param.position != undefined) { if(param.position.X == this.attributes.translation.X && param.position.Y == this.attributes.translation.Y ) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's ' + param.timing_function; this.setPosition(param.position.X,param.position.Y); } } } if(param.rotation != undefined) { if(param.rotation == this.attributes.rotation) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's '+ param.timing_function; } this.setRotation(param.rotation); } } if(param.scale != undefined) { if(param.scale.X == this.attributes.scale.X && param.scale.Y == this.attributes.scale.Y) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's ' + param.timing_function; } this.setScale(param.scale.X,param.scale.Y); } } }, stopTransition : function(param) { this.attributes.update_signal = 'stop_transition'; this.attributes.cancelTransition = true; return this; }, clearTransition : function() { var el = this.get('element'); el.removeEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack); this.attributes.update_signal = 'stop_transition'; }, //////////////////// updateCSS : function() { //if(this.attributes.cssupdate == false) return; var el = this.get('element'); switch (this.attributes.update_signal) { case 'none': (function() { //오브잭트변환값을 앨리먼트쪽으로 갱신해주기 if(this.attributes.cssupdate == true) { var trans = this.attributes.translation; var rot = this.attributes.rotation; var scalex = this.attributes.scale.X; var scaley = this.attributes.scale.Y; //반전 적용 if(this.attributes.flipX) { scaley = -scaley; } if(this.attributes.flipY) { scalex = -scalex; } var css_val = 'translate(' + trans.X + 'px,' + trans.Y +'px) ' + 'rotate(' + rot + 'deg) ' + 'scale(' + scalex + ',' + scaley + ')'; //브라우져 호환성을 위한 코드 el.style.WebkitTransform = css_val; el.style.MozTransform = css_val; el.style.oTransform = css_val; el.style.transform = css_val; //트랜지션 상태이면 css를 더이상 업데이트 못하게 한다 if(el.style.WebkitTransition !== '') { this.attributes.cssupdate = false; } } else { //현재 트랜지션 상태이므로 트래지션 취소는 무효화 된다. this.attributes.cancelTransition = false; } }).bind(this)(); break; case 'stop_transition': (function() { //행렬분해후 적용 this.decomposeCssMatrix(this.getCssMatrix()); el.style.WebkitTransition = ''; this.attributes.update_signal = 'none'; this.attributes.cssupdate = true; this.updateCSS(); }).bind(this)(); break; } return this; }, /////////////////////////////////////////// setupCssAnimation : function(option) { var element = this.get('element'); element.style.WebkitAnimationName = option.name; element.style.WebkitAnimationDuration = option.duration; if(option.timing_function) { element.style.WebkitAnimationTimingFunction = option.timing_function; } if(option.delay) { element.style.WebkitAnimationDelay = option.delay; } if(option.direction) { element.style.WebkitAnimationDirection = option.direction; } if(option.iteration_count) { element.style.WebkitAnimationIterationCount = option.iteration_count; } element.style.WebkitAnimationPlayState = 'running'; this.attributes.CssAnimationEndCallBack = option.EndCallBack; if(this.attributes._CssAnimationEndCallBack != undefined) { element.removeEventListener('webkitAnimationEnd',this.attributes._CssAnimationEndCallBack); } this.attributes._CssAnimationEndCallBack = function(event) { element.style.WebkitAnimation = ''; if(this.attributes.CssAnimationEndCallBack != undefined) { this.attributes.CssAnimationEndCallBack.apply(this); } //이밴트 전달 금지 event.cancelBubble = true; event.stopPropagation(); }.bind(this); element.addEventListener('webkitAnimationEnd',this.attributes._CssAnimationEndCallBack,false); return this; }, ////////////////////////// //노드에서 완전히 제거할때 사용됨 destroy : function() { var el = this.get('element'); //el.removeEventListener('webkitTransitionEnd'); this.clearTransition(); el.parentNode.removeChild(el); }, clone : function() { var model = Backbone.Model.prototype.clone.call(this); // console.log(model); model.set("element",this.get('element').cloneNode(true)); return model; } }); //end of base model ////////////////////// Pig2d.SpriteModel = Pig2d.model.extend({ initialize: function(param) { Pig2d.model.prototype.initialize.call(this); this.attributes.currentFrame = 0; //애니메이션 타이머 핸들 this.attributes.animationHID = null; var sheet = document.createElement('canvas'); sheet.classList.add('pig2d-sheet'); sheet.style.position = 'absolute'; this.get('element').appendChild(sheet); this.set('sheet',sheet); this.set('sheetCTX',sheet.getContext('2d')); this.attributes.currentTick = 0; this.attributes.scaler = 1; if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } //캔버스 클리어 일부 삼성폰들은 초기화를 안할경우 잔상이 생긴다. //this.get('sheetCTX').clearRect(0,0,sheet.width,sheet.height); //this.setFrame(-1); //this.attributes.AnimationStatus = 'ready'; }, setScaler : function(scale) { this.attributes.scaler = scale; if(this.attributes.data.canvas_size) { var sheet = this.get('sheet'); this.attributes.data.canvas_size.width *= scale; this.attributes.data.canvas_size.height *= scale; sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } }, changeDress : function(param) { this.attributes.imgObj = param.texture; this.attributes.data = param.animation; var sheet = this.get('sheet'); if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } this.setFrame(this.attributes.currentFrame); }, clone : function() { var model = Backbone.Model.prototype.clone.call(this); console.log('SpriteModel clone'); //model.set("element",this.get('element').cloneNode(true)); return model; }, updateCSS : function (deltaTime) { deltaTime = deltaTime || 0; this.applyAnimation(deltaTime); return Pig2d.model.prototype.updateCSS.call(this); }, ////////////////////////////////////////////// //애니메이션 관련 기능 ////////////////////////////////////////////// setFrame : function(index) { //프레임 노드 얻기 var imgObj = this.attributes.imgObj; if(this.attributes.data.frames.length <= index) { console.log('error exeed frame number : ' + index + ',' + this.attributes.data.frames.length); index = 0; } if(imgObj != undefined) { this.set('currentFrame',index); var sheet = this.attributes.sheet; var ctx = this.attributes.sheetCTX; /* 공백프레임을 만든 이유 : 일부 폰들(삼성폰)에서 캔버스를 처음생성한후 맨처음 랜더링된 이미지가 지워지지않고 남아 있는 현상들이 발생함 그래서 캔버스처음생성할때(changeDress,createSprite)할때는 반드시 공백프레임을 화면에 한번출력을 해주어야함 */ if(index < 0) { //공프레임 이면.. if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; ctx.clearRect(0,0,this.attributes.data.canvas_size.width,this.attributes.data.canvas_size.height); } } else { var frame = this.attributes.data.frames[this.attributes.currentFrame]; //console.log(this.attributes.currentFrame); var sheet_data = frame.sheets[0]; var scaler = this.attributes.scaler; if(this.attributes.data.canvas_size) { ctx.clearRect(0,0,this.attributes.data.canvas_size.width,this.attributes.data.canvas_size.height); //sheet.width = 1; //sheet.width = this.attributes.data.canvas_size.width; } else { sheet.width = sheet_data.width; sheet.height = sheet_data.height; } var offsetX = sheet_data.centerOffset.x; var offsetY = sheet_data.centerOffset.y; var destW = sheet_data.width; var destH = sheet_data.height; var cutx = -sheet_data.bp_x; var cuty = -sheet_data.bp_y; var srcW = sheet_data.width; var srcH = sheet_data.height; if(scaler < 1.0) { offsetX *= scaler; offsetY *= scaler; destW *= scaler; destH *= scaler; } sheet.style.webkitTransform = "translate(" + offsetX + "px," + offsetY + "px)"; ctx.drawImage( imgObj, cutx,cuty,srcW,srcH, 0,0,destW,destH ); } } return this; }, ///////////////////////////////////////////// /////new animation system//////////////////// ///////////////////////////////////////////// setupAnimation : function(param) { param = param ? param : {}; this.attributes.startFrame = param.startFrame ? param.startFrame : 0 ; this.attributes.endFrame = param.endFrame ? param.endFrame : (this.get('data').frames.length-1); if(param.isAnimationLoop !== undefined) { this.attributes.isAnimationLoop = param.isAnimationLoop; } else { this.attributes.isAnimationLoop = true; } this.attributes.AnimationEndCallback = param.AnimationEndCallback; this.attributes.AnimationStatus = param.AnimationStatus ? param.AnimationStatus : 'stop'; this.setFrame(this.attributes.startFrame); }, applyAnimation : function(delataTick) { if(this.attributes.AnimationStatus == 'play') { this.attributes.currentTick += delataTick; var frameindex = this.attributes.currentFrame; var Ani_data = this.get('data'); var delay = 300; if(frameindex >= 0) { delay = Ani_data.frames[frameindex].delay / 1000; } //var delay = Ani_data.frames[frameindex].delay / 1000; if(this.attributes.currentTick > delay) { this.attributes.currentTick = 0; ++frameindex; if(frameindex > this.attributes.endFrame) {//마지막 프레임이면 if(this.attributes.isAnimationLoop) { frameindex = this.attributes.startFrame; this.setFrame(frameindex); } else { this.attributes.AnimationStatus = 'stop'; frameindex = this.attributes.endFrame; } if(this.attributes.AnimationEndCallback != undefined) { this.attributes.AnimationEndCallback.bind(this)(); } } else { this.setFrame(frameindex); } } } else if(this.attributes.AnimationStatus == 'ready') { this.setFrame(-1); this.attributes.AnimationStatus = 'play'; this.attributes.currentFrame = this.attributes.startFrame; } }, stopAnimation : function() { this.attributes.AnimationStatus = 'stop'; }, //////////////////////// destroy : function() { //this.stop_animate(); //슈퍼 클래싱 Pig2d.model.prototype.destroy.call(this); } }); //end of sprite model /////////////////////// //////////////////node// ///////////////////////// Pig2d.node = Backbone.Model.extend({ initialize: function() { this.attributes.children = this.attributes.chiledren = new Array(); // _.bindAll(this,"update","clone"); }, traverse : function(callback,param) { callback.bind(this)(param); for(var index = 0;index < this.attributes.chiledren.length;index++ ) { this.attributes.chiledren[index].traverse(callback,param); } }, update: function(applyChild,deltaTime) { this.get('model').updateCSS(deltaTime); if( applyChild == true) { for(var index = 0;index < this.attributes.chiledren.length;index++ ) { this.attributes.chiledren[index].update(applyChild,deltaTime); } } return this; }, clone : function() { //딥 클로닝 var node = Backbone.Model.prototype.clone.call(this); if(node.get('model')) { var model = node.get('model').clone(); node.set({model:model}); } var chiledren = this.get('chiledren'); for(var i=0;i<chiledren.length;i++) { node.add(chiledren[i].clone()); } return node; }, findByName : function(name) { if(name == this.attributes.name) return this; for(var index in this.attributes.chiledren ) { var obj = this.attributes.chiledren[index].findByName(name); if(obj != null) return obj; } return null; }, findByID : function(cid) { if(cid == this.cid) return this; for(var index in this.attributes.chiledren ) { var obj = this.attributes.chiledren[index].findByID(cid); if(obj != null) return obj; } return null; }, add : function(child_node,parents) { if(parents == undefined || parents == null) { parents = this; } parents.get('chiledren').push(child_node); //child_node.setParent(parents); //모델이 존재하면 if(parents.get('model')) { var par_el = parents.get('model').get('element'); var child_el = child_node.get('model').get('element'); } par_el.appendChild(child_el); child_node.attributes.parent = parents; return this; }, //부모노드 바꾸기 setParent : function(parent) { var old_parent = this.get('parent'); var chiledren = old_parent.get('chiledren'); for(var i= chiledren.length-1;i >= 0;i--) { if(chiledren[i] === this) { chiledren.splice(i,1); parent.add(this); } } }, removeChild : function(node) { for(var i= this.attributes.chiledren.length-1;i >= 0;i--) { var _node = this.attributes.chiledren[i]; if(_node === node) { this.attributes.chiledren.splice(i,1); node.get('model').destroy(); return true; } else { _node.removeChild(node); //자식노드까지 검사 } } return false; }, removeChildAll : function() { for(var i= this.attributes.chiledren.length-1;i >= 0;i--) { this.removeChild(this.attributes.chiledren[i]); } return false; }, show : function(visible) { //console.log(this.get('model').get('element')); //this.get('model').get('element').style.visibility = visible ? 'inherit' : 'hidden'; this.get('model').show(visible); }, isVisible : function() { //return (this.get('model').get('element').style.visibility == 'hidden') ? false : true; return this.get('model').isVisible(); } }); //end of node /////////////// /// Pig2d.SceneManager = Backbone.Model.extend({ initialize: function(param) { var rootNode = new Pig2d.node( { model : new Pig2d.model({ name : 'root_' + (new Date()).getTime() + '_' }) } ); rootNode.get('model').setPosition(0,0); //this.attributes.container.append(rootNode.get('model').get('element')); var rootElement = rootNode.get('model').get('element'); //console.log(rootElement); if(param.window_size != undefined) { rootElement.style.overflow = 'hidden'; rootElement.style.width = param.window_size.width + 'px' ; rootElement.style.height = param.window_size.height + 'px' ; } if(param.bkg_color != undefined) { //2015.11.5 수정 ,배경적용안되는 버그 수정 this.attributes.container.style.backgroundColor = param.bkg_color; } this.attributes.container.appendChild(rootElement); this.attributes.rootNode = rootNode; }, getRootNode : function() { return this.attributes.rootNode; }, updateAll : function(deltaTime) { deltaTime = deltaTime ? deltaTime : 0.01; this.attributes.rootNode.update(true,deltaTime); }, add : function(node,parent) { if(parent == undefined) { this.attributes.rootNode.add(node); } else { parent.add(node); } }, addImageNode : function(param) { //var node = Pig2d.util.createImage(param.img_info); //this.add(node,param.parent); var center_x = param.center ? param.center.x : 0; var center_y = param.center ? param.center.y : 0; var node = Pig2d.util.createDummy(); var imgObj = new Image(); imgObj.onload = function(evt) { //console.log(this.width); imgObj.style.position = 'absolute'; imgObj.style.left = -this.width/2 + parseInt(center_x) + 'px'; imgObj.style.top = -this.height/2 + parseInt(center_y) + 'px'; var element = node.get('model').get('element'); element.appendChild(imgObj); node.get('model').set('imgObj', imgObj); if(param.onload) { param.onload(node); } } imgObj.src = param.src; this.add(node,param.parent); return node; }, addSpriteSceneNode : function(param) { var node = Pig2d.util.createSprite(param.spr_info); node.show(true); this.add(node,param.parent); return node; } }); //end of scene manager
/** * @author Iftikhar Ul Hassan * @date 4/10/17. */ const util = require('../util'); module.exports = function (length) { length = length || 21; var isValid; var kidNumber; do { kidNumber = util.generateRandomNumber(0, 9, length) + ""; var controlDigit = kidNumber.charAt(kidNumber.length - 1); isValid = parseInt(controlDigit, 10) === util.mod11(kidNumber) || parseInt(controlDigit, 10) === util.luhnValue(kidNumber); } while (!isValid); return kidNumber; };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['assets/magnific.js', 'assets/jquery-vimeothumb.js'], dest: 'magnific_popup/blocks/magnific_popup/magnific/magnific-combined-1.0.0.js' } }, uglify: { options: { // the banner is inserted at the top of the output banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'magnific_popup/blocks/magnific_popup/magnific/magnific-combined-1.0.0.min.js': ['<%= concat.dist.dest %>'] } } }, }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['concat', 'uglify']); };
'use strict'; // ================================== // // Load modules. // // ================================== var config = require('../config.js'); var gulp = require('gulp'); // ================================== // // Fonts // // ================================== gulp.task('fonts', function () { gulp.src([config.fonts.src]) .pipe(gulp.dest(config.fonts.dest)); });
export default { name: 'help-view', data() { return { } }, methods: { } }
var counter = require('mongodb-counter'); var s3redirect = require('./s3redirect'); module.exports = shortener; module.exports.redis = require('./redisStore'); module.exports.mongodb = require('./mongoStore'); module.exports.s3 = s3redirect; module.exports.counter = counter; function shortener(options) { var store = options.store || s3redirect(options); var uniqueIdGenerator = options.uniqueIdGenerator || (options.counters || counter.createCounters( _({}).assign(options).assign({collectionName: options.countersCollectionName}).value() ))(options.uniqueIdCounterName || 'shortener'); return { shorten: shorten, shortenUnique: shortenUnique, unshorten: unshorten }; function shorten(longUrl, done) { getUniqueId(function (err, uniqueId) { if (err) return done(err); store.set(uniqueId, longUrl, finish); function finish(err, path) { return done(null, options.shortUrlPrefix + uniqueId); } }); } function shortenUnique(longUrl, done) { getUniqueId(function (err, uniqueId) { if (err) return done(err); store.getOrSet(uniqueId, longUrl, finish); function finish(err, path) { return done(null, options.shortUrlPrefix + uniqueId); } }); } function unshorten(shortUrl, done) { store.get(shortUrl.replace(options.shortUrlPrefix, ''), done); } function getUniqueId(done) { if (typeof(uniqueIdGenerator) == 'function') return uniqueIdGenerator(complete); return uniqueIdGenerator.getUniqueId(complete); function complete(err, value) { if (err) return done(err); var prefix = config.uniqueIdPrefix || ''; if (typeof(value) == 'number') return done(null, prefix + value.toString(36)); return done(null, prefix + value.toString()); } } }
var todolist = require("./lib"); var assert = require("assert"); describe('findMarks', function() { it('Find TODOs, NOTES, and FIXMEs', function() { var result = todolist.findMarks("// TODO: This is a TODO\n// NOTE: This is a Note\n// FIXME: This is a fixme.\n"); assert.deepEqual(result, [{ content: 'TODO: This is a TODO', line: 0, assignee: null, type: 'TODOs' }, { content: 'NOTE: This is a Note', line: 1, assignee: null, type: 'NOTEs' }, { content: 'FIXME: This is a fixme.', line: 2, assignee: null, type: 'FIXMEs' }]); }); it('Case-insensitive matching', function() { var result = todolist.findMarks("// todo: This is a TODO\n// note: This is a Note\n// fixme: This is a fixme.\n"); assert.deepEqual(result, [{ content: 'todo: This is a TODO', line: 0, assignee: null, type: 'TODOs' }, { content: 'note: This is a Note', line: 1, assignee: null, type: 'NOTEs' }, { content: 'fixme: This is a fixme.', line: 2, assignee: null, type: 'FIXMEs' }]); }); it('Parse the assignee of a task', function() { var result = todolist.findMarks("// TODO(bob): This is a TODO assigned to bob."); assert.deepEqual(result, [{ content: 'TODO(bob): This is a TODO assigned to bob.', line: 0, assignee: 'bob', type: 'TODOs' }]); }); });
import { ADD_HISTORY_FILTER_EXCLUDE_TAG, REMOVE_HISTORY_FILTER_EXCLUDE_TAG, SAVE_HISTORY_FILTER_EXCLUDES_TAGS, DISMISS_HISTORY_FILTER_EXCLUDES_TAGS, } from 'app/configs+constants/ActionTypes'; export const saveTags = (tags = []) => ({ type: SAVE_HISTORY_FILTER_EXCLUDES_TAGS, tags: tags, }); export const dismissTags = () => ({ type: DISMISS_HISTORY_FILTER_EXCLUDES_TAGS }); export const cancelTags = () => ({ type: DISMISS_HISTORY_FILTER_EXCLUDES_TAGS });; export const tappedPill = () => ({ type: REMOVE_HISTORY_FILTER_EXCLUDE_TAG }); export const addPill = () => ({ type: ADD_HISTORY_FILTER_EXCLUDE_TAG });
var Service = require("./../service.js"); function DistanceService(deviceId, serviceId) { var distanceService = {} , _characteristics = { 'distance' : 1 , 'unit' : 2 } , _requests = { 'read-distance' : function () { return { packetType : 'read' , packetData :[_characteristics['distance']] } } , 'read-unit' : function () { return { packetType : 'read' , packetData :[_characteristics['unit']] } } , 'read-distance-with-unit' : function () { return { packetType : 'read' , packetData :[_characteristics['distance'], _characteristics['unit']] } } , 'set-unit' : function (unit) { return { packetType : 'write' , packetData :[ {id : _characteristics['unit'], data : new Buffer(unit)} ] } } } , _responses = {}; _responses[_characteristics['distance']] = function (distanceBufer) { var distance = distanceBufer.readUInt8(0, true); return { response : 'distance' , data : "" + (distance === undefined ? 0 : distance) }; }; _responses[_characteristics['unit']] = function (unitBuffer) { return { response : 'unit' , data : unitBuffer.toString() }; }; distanceService.__proto__ = Service( deviceId , serviceId , _requests , _responses ); return distanceService; } module.exports = DistanceService; (function(){ var assert = require("assert"); var ResponsePacket = require("../device-packets/response-packet"); var serviceId = 3 , distanceService = DistanceService("my-device-id", serviceId); (function(){ console.log("Should process read distance json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-distance'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 1, 1]) ); })(); (function(){ console.log("Should process read unit json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-unit'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 1, 2]) ); })(); (function(){ console.log("Should process read distance with unit json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-distance-with-unit'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 2, 1, 2]) ); })(); (function(){ console.log("Should process set unit json message."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'set-unit', data: unit} )), Buffer.concat([ new Buffer([1, 2, 0, 0, 0, serviceId, 1, 2, unitBuffer.length]) , unitBuffer ]) ); })(); (function(){ console.log("Should process distance response packet."); assert.deepEqual( distanceService.processResponse(ResponsePacket(new Buffer([ 1, 4, 0, 0, 0, serviceId, 1, 1, 1, 23 ]))), [{response: 'distance', data: 23}] ); })(); (function(){ console.log("Should process unit response packet."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processResponse(ResponsePacket(Buffer.concat([ new Buffer([1, 4, 0, 0, 0, serviceId, 1, 2, unitBuffer.length]) , unitBuffer ]))), [{response: 'unit', data: 'cm'}] ); })(); (function(){ console.log("Should process distance with unit response packet."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processResponse(ResponsePacket(Buffer.concat([ new Buffer([1, 4, 0, 0, 0, serviceId, 2, 1, 1, 54, 2, unitBuffer.length]) , unitBuffer ]))), [ {response: 'distance', data: '54'} , {response: 'unit', data: 'cm'} ] ); })(); })(this);
/** * @summary Returns deep equality between objects * {@link https://gist.github.com/egardner/efd34f270cc33db67c0246e837689cb9} * @param obj1 * @param obj2 * @return {boolean} * @private */ export function deepEqual(obj1, obj2) { if (obj1 === obj2) { return true; } else if (isObject(obj1) && isObject(obj2)) { if (Object.keys(obj1).length !== Object.keys(obj2).length) { return false; } for (const prop of Object.keys(obj1)) { if (!deepEqual(obj1[prop], obj2[prop])) { return false; } } return true; } else { return false; } } function isObject(obj) { return typeof obj === 'object' && obj != null; }
define(['jquery','xing'],function($,xing) { var $body = $('body'), $progress = $($body.data('progressDisplay')), $status = $($body.data('statusMessage')), curPath = window.location.pathname, baseDir = curPath.substring(0, curPath.lastIndexOf('/')), sitePath = '//'+window.location.host+baseDir, stackCount = 0, stackCall = function() { if( $progress.length > 0 ) { $progress.show(); stackCount++; } }, unstackCall = function() { if( --stackCount < 1 ) { stackCount = 0; $progress.hide(); } }, getErrorHandler = function( callback, doUnstack ) { return function( xhr ) { if( doUnstack ) { unstackCall(); } callback($.parseJSON(xhr.response)); }; } ; xing.http = { BasePath : baseDir, SitePath : sitePath, redirect : function( path ) { stackCall(); // show our processing loader when changing pages window.location.href = path.replace('~',this.BasePath); }, get : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('GET',path,data,callback,stopLoadingIcon); }, post : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('POST',path,data,callback,stopLoadingIcon); }, put : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('PUT',path,data,callback,stopLoadingIcon); }, ajax : function( type, path, data, callback, stopLoadingIcon ) { stopLoadingIcon = stopLoadingIcon || false; $.ajax( { type : type, url : path.replace('~',this.BasePath), data : data, success : stopLoadingIcon ? callback : function(response) { unstackCall(); callback(response); }, error : getErrorHandler(callback, !stopLoadingIcon) } ); if( !stopLoadingIcon ) { stackCall(); } }, stackCall : stackCall, unstackCall : unstackCall, forceEndStack : function() { stackCount = 0; unstackCall(); }, message : function( msg, isError, timeoutSecs, callback ) { if( $status.length ) { $status.find('.content').html(msg); $status.toggleClass('error',!!isError).show('fast'); // force isError to boolean with !! setTimeout( function() { $status.hide('fast'); if( callback ) { callback(); } }, typeof timeoutSecs == 'undefined' ? 1400 : (timeoutSecs * 1000)); } } }; return xing.http; });
var present = require('present-express'); var Base = require('./base'); module.exports = present.extend(Base, function(data) { if (data.title) { this.data.title = data.title; } })
'use strict'; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var init = require("Espresso/oop").init; var trim = require("Espresso/trim").trim; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var ScalarNode = require("Espresso/Config/Definition/ScalarNode"); var InvalidTypeException = require("Espresso/Config/Definition/Exception/InvalidTypeException"); var format = require("util").format; function BooleanNode(name,parent){ init(this,ScalarNode,name,parent); oop(this,"Espresso/Config/Definition/BooleanNode"); } /** * {@inheritdoc} */ function validateType($value) { if ( typeof $value !== 'boolean') { var $ex = new InvalidTypeException(format( 'Invalid type for path "%s". Expected boolean, but got %s.', this.getPath(), getClass($value) )); var $hint = this.getInfo(); if ($hint) { $ex.addHint($hint); } $ex.setPath(this.getPath()); throw $ex; } } /** * {@inheritdoc} */ function isValueEmpty($value) { // a boolean value cannot be empty return false; } BooleanNode.prototype = Object.create( ScalarNode.prototype ); BooleanNode.prototype.validateType = validateType; BooleanNode.prototype.isValueEmpty = isValueEmpty; module.exports = BooleanNode;
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge with env dependent settings module: { loaders: [{ test: /\.js$/, // Transform all .js files required somewhere with Babel loader: 'babel', exclude: /node_modules/, query: options.babelQuery, }, { // Do not transform vendor's CSS with CSS-modules // The point is that they remain in global scope. // Since we require these CSS files in our JS or CSS files, // they will be a part of our compilation either way. // So, no need for ExtractTextPlugin here. test: /\.css$/, include: /node_modules/, loaders: ['style-loader', 'css-loader'], }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', }, { test: /\.(jpg|png|gif)$/, loaders: [ 'file-loader', { loader: 'image-webpack', query: { progressive: true, optimizationLevel: 7, interlaced: false, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, loader: 'html-loader', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(mp4|webm)$/, loader: 'url-loader', query: { limit: 10000, }, }], }, plugins: options.plugins.concat([ new webpack.ProvidePlugin({ // make fetch available fetch: 'exports?self.fetch!whatwg-fetch', }), // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; UglifyJS will automatically // drop any unreachable code. new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), }, }), new webpack.NamedModulesPlugin(), ]), resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window });
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Altl\u0131k haritay\u0131 a\u00e7/kapa"});
"use strict" const process = require(`process`) const fs = require(`fs`) const path = require(`path`) const js2xmlparser = require(`js2xmlparser`) const abbrevJson = require(`../abbrevJson`) const asset = require(`../asset.js`) const loadMappoMap = require(`../loadMappoMap`) const mapFilename = process.argv[2] const mappoMap = loadMappoMap({mapFilename}) console.log(abbrevJson(mappoMap)) const tileset = mappoMap.tileset const tileWidth = tileset.tileWidth const tileHeight = tileset.tileHeight const vspFilename = path.basename(tileset.imageFilename) const tileColumns = 20 const tileRows = ~~((tileset.tileCount + 19) / 20) const vspPngWidth = tileWidth * tileColumns const vspPngHeight = tileHeight * tileRows const obj = { '@': { version: `1.0`, orientation: `orthogonal`, width: mappoMap.tileLayers[0].width, height: mappoMap.tileLayers[0].height, tilewidth: tileWidth, tileheight: tileHeight, }, tileset: { '@': { firstgid: 1, name: vspFilename, tilewidth: tileWidth, tileheight: tileHeight, spacing: 0, margin: 0, tilecount: tileset.tileCount, columns: tileColumns, }, image: { '@': { source: vspFilename, width: vspPngWidth, height: vspPngHeight, } }, } } obj.layer = mappoMap.mapLayerOrder.map(layerIndex => { const tileLayer = mappoMap.tileLayers[layerIndex] return { '@': { name: tileLayer.description, width: tileLayer.width, height: tileLayer.height, }, data: { '@': { encoding: `csv`, }, '#': tileLayer.tileIndexGrid.map(v => ++v).join(`,`), } } }) const targetFilename = mapFilename + `.tmx` const xml = js2xmlparser.parse(`map`, obj) fs.writeFileSync(targetFilename, xml) console.log(`converted`, mapFilename, `to`, targetFilename)
/* * * LoginContainer constants * */ export const LOGIN_REQUEST = 'app/LoginContainer/LOGIN_REQUEST'; export const LOGIN_SUCCESS = 'app/LoginContainer/LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'app/LoginContainer/LOGIN_FAILURE';
'use strict'; /** * data-set module * @module data-set * @see module:index */ const _ = require('lodash'); const try2get = require('try2get'); const Connector = require('../connector/base'); const util = require('../util/index'); function isValidDataSet(dataSet) { /** * Simply check the data structure of the data set. * @function isValidDataSet * @param {Array} data * @return {Boolean} * @example * // a valid data structure should be like this: * // `schema` is not strictly required. * { * data: [ * {genre: 'Sports', sold: 275}, * {genre: 'Strategy', sold: 115}, * {genre: 'Action', sold: 120}, * {genre: 'Shooter', sold: 350}, * {genre: 'Other', sold: 150} * ], * schema: [ * {name: 'genre', comments: '种类'}, * {name: 'sold', comments: '销量', formatter: '', type: 'number'} * ] * } * @example * isValidDataSet(dataSet); */ if (!_.isPlainObject(dataSet)) { return false; } const data = dataSet.data; if (!_.isArray(data)) { return false; } if (data.length && _.some(data, row => !_.isPlainObject(row))) { return false; } for (let i = 1; i < data.length; i++) { if (data[i] && !util.containsSameItems(_.keys(data[i]), _.keys(data[i - 1]))) { return false; } } return true; } class DataSet { constructor(source) { source = source || []; const me = this; if (source.constructor === me.constructor) { return source; } if (_.isArray(source)) { return new DataSet({ data: source, }); } if (!isValidDataSet(source)) { throw new TypeError('new DataSet(source): invalid data set'); } me.data = source.data; me.schema = source.schema || []; return me.processData(); } processData() { const me = this; const data = me.data; /* * schema info of every column: * [ * { * name, * index, * comments, * } * ] */ if (!me.schema.length) { if (data.length) { const keys = _.keys(data[0]); me.schema = _.map(keys, (name, index) => ({ index, name, })); } } // comments (default is name) _.each(me.schema, (colInfo) => { if (!_.has(colInfo, 'comments')) { colInfo.comments = colInfo.displayName || colInfo.name; } }); // 整理schema和data const currentSchemaNames = _.map(me.schema, item => item.name); _.each(me.data, (row) => { _.forIn(row, (value, key) => { if (!_.includes(currentSchemaNames, key)) { // 补全schema me.schema.push({ name: key, comments: key, index: currentSchemaNames.length, }); currentSchemaNames.push(key); } }); }); _.each(me.data, (row) => { _.each(currentSchemaNames, (name) => { if (!_.has(row, name)) { // 补全data row[name] = ''; } }); }); // flatten rows me.flattenRows = _.map(me.data, (row) => { const resultRow = []; _.each(me.schema, (colInfo, index) => { colInfo.index = index; resultRow.push(row[colInfo.name]); }); return resultRow; }); // colValuesByName me.colValuesByName = {}; _.each(me.data, (row) => { _.forIn(row, (value, key) => { me.colValuesByName[key] = me.colValuesByName[key] || []; me.colValuesByName[key].push(value); }); }); // type (by guessing or pre-defined) // colNames by type // col by name // cols by type // unique column values rate me.colNamesByType = { string: [], number: [], }; me.colsByType = {}; me.colByName = {}; _.each(me.schema, (colInfo) => { const name = colInfo.name; const colValues = me.colValuesByName[name]; colInfo.values = colValues; // add values const type = colInfo.type = colInfo.type || util.guessItemsTypes(colValues); if (!me.colNamesByType[type]) { me.colNamesByType[type] = []; } if (!me.colsByType[type]) { me.colsByType[type] = []; } if (colValues.length) { colInfo.uniqueRate = _.uniq(colValues).length / colValues.length; } else { colInfo.uniqueRate = 0; } me.colNamesByType[type].push(colInfo.name); me.colsByType[type].push(colInfo); me.colByName[colInfo.name] = colInfo; }); // alias me.cols = me.schema; // rows and cols info me.rowsCount = data.length; me.colsCount = me.cols.length; return me; } isEmpty() { const me = this; if (me.rowsCount === 0 && me.colsCount === 0) { return true; } return false; } } // connectors const connectors = []; _.assign(DataSet, { registerConnector(connector) { if (connector instanceof Connector) { connectors.push(connector); } else { try { connectors.push(new Connector(connector)); } catch (e) { } } connectors.sort((a, b) => (b.priority - a.priority)); }, registerConnectors(cs) { _.each(cs, (connector) => { DataSet.registerConnector(connector); }); }, try2init(source) { // the default DataSet is an empty DataSet return try2get.one(_.map(connectors, connector => () => connector.toDataSet(source))); }, }); require('../connector/csv')(DataSet); require('../connector/default')(DataSet); require('../connector/flatten-data')(DataSet); require('../connector/mock')(DataSet); module.exports = DataSet;
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), banner: [ '/**', ' * <%= pkg.name %> <%= pkg.version %>', ' * Copyright (C) <%= grunt.template.today("yyyy") %> <%= pkg.author %>', ' * Licensed under the MIT license.', ' * <%= _.pluck(pkg.licenses, "url").join(", ") %>', ' */\n' ].join('\n'), clean: { all: [ 'dist', 'tmp' ] }, jshint: { all: [ '*.js', 'lib/**/*.js', 'test/**/*.js', 'benchmark/**/*.js', 'tasks/**/*.js' ], options: { force: true, jshintrc: true } }, browserify: { dist: { src: 'index.js', dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js' }, test: { src: 'test/unit/**/*.js', dest: 'tmp/test-browser.js', options: { transform: [ 'espowerify' ] } }, 'benchmark-equip': { src: 'benchmark/equip-simu.js', dest: 'tmp/benchmark/equip-simu.js' }, 'benchmark-deco': { src: 'benchmark/deco-simu.js', dest: 'tmp/benchmark/deco-simu.js' }, 'benchmark-util': { src: 'benchmark/util.js', dest: 'tmp/benchmark/util.js' } }, usebanner: { dist: { options: { position: 'top', banner: '<%= banner %>', linebreak: false }, files: { src: [ '<%= browserify.dist.dest %>' ] } } }, uglify: { options: { banner: '<%= banner %>', report: 'min' }, js: { src: '<%= browserify.dist.dest %>', dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.min.js' } }, testdata: { mh4: { dest: 'tmp/testdata.js', urls: { 'equip_head' : 'http://sakusimu.net/data/mh4/equip_head.json', 'equip_body' : 'http://sakusimu.net/data/mh4/equip_body.json', 'equip_arm' : 'http://sakusimu.net/data/mh4/equip_arm.json', 'equip_waist': 'http://sakusimu.net/data/mh4/equip_waist.json', 'equip_leg' : 'http://sakusimu.net/data/mh4/equip_leg.json', 'deco' : 'http://sakusimu.net/data/mh4/deco.json', 'skill': 'http://sakusimu.net/data/mh4/skill.json' } } }, espower: { test: { files: [ { expand: true, cwd: 'test/unit', src: [ '**/*.js' ], dest: 'tmp/espowered/', ext: '.js' } ] } }, mochaTest: { test: { options: { reporter: 'spec' }, src: [ 'tmp/espowered/**/*.js' ] } }, karma: { test: { configFile: 'test/karma-conf.js', singleRun: true, options: { files: [ '<%= testdata.mh4.dest %>', '<%= browserify.test.dest %>' ] } } } }); require('load-grunt-tasks')(grunt); grunt.loadTasks('tasks'); grunt.registerTask('default', [ 'clean:all', 'test', 'dist' ]); grunt.registerTask('dist', [ 'browserify:dist', 'usebanner:dist', 'uglify' ]); grunt.registerTask('test', function (type, file) { switch (type) { case 'browser': grunt.task.run([ 'browserify:test', 'karma:test' ]); break; case 'node': var files = grunt.config.data.mochaTest.test.src; if (file) { file = file.replace('test/unit/', 'tmp/espowered/'); files.splice(-1, 1, file); } grunt.task.run([ 'jshint', 'espower:test', 'mochaTest:test' ]); /* falls through */ default: } }); grunt.registerTask('benchmark', [ 'browserify:benchmark-equip', 'browserify:benchmark-deco', 'browserify:benchmark-util' ]); };
'use strict'; var generators = require('yeoman-generator'); var chalk = require('chalk'); var path = require('path'); var extend = require('deep-extend'); var guid = require('uuid'); module.exports = generators.Base.extend({ /** * Setup the generator */ constructor: function () { generators.Base.apply(this, arguments); this.option('skip-install', { type: Boolean, required: false, defaults: false, desc: 'Skip running package managers (NPM, bower, etc) post scaffolding' }); this.option('name', { type: String, desc: 'Title of the Office Add-in', required: false }); this.option('root-path', { type: String, desc: 'Relative path where the Add-in should be created (blank = current directory)', required: false }); this.option('tech', { type: String, desc: 'Technology to use for the Add-in (html = HTML; ng = Angular)', required: false }); // create global config object on this generator this.genConfig = {}; }, // constructor() /** * Prompt users for options */ prompting: { askFor: function () { var done = this.async(); var prompts = [ // friendly name of the generator { name: 'name', message: 'Project name (display name):', default: 'My Office Add-in', when: this.options.name === undefined }, // root path where the addin should be created; should go in current folder where // generator is being executed, or within a subfolder? { name: 'root-path', message: 'Root folder of project?' + ' Default to current directory\n (' + this.destinationRoot() + '), or specify relative path\n' + ' from current (src / public): ', default: 'current folder', when: this.options['root-path'] === undefined, filter: /* istanbul ignore next */ function (response) { if (response === 'current folder') return ''; else return response; } }, // technology used to create the addin (html / angular / etc) { name: 'tech', message: 'Technology to use:', type: 'list', when: this.options.tech === undefined, choices: [ { name: 'HTML, CSS & JavaScript', value: 'html' }, { name: 'Angular', value: 'ng' }, { name: 'Manifest.xml only (no application source files)', value: 'manifest-only' }] }]; // trigger prompts this.prompt(prompts, function (responses) { this.genConfig = extend(this.genConfig, this.options); this.genConfig = extend(this.genConfig, responses); done(); }.bind(this)); }, // askFor() /** * If user specified tech:manifest-only, prompt for start page. */ askForStartPage: function () { if (this.genConfig.tech !== 'manifest-only') return; var done = this.async(); var prompts = [ // if tech = manifest only, prompt for start page { name: 'startPage', message: 'Add-in start URL:', when: this.options.startPage === undefined, }]; // trigger prompts this.prompt(prompts, function (responses) { this.genConfig = extend(this.genConfig, responses); done(); }.bind(this)); } // askForStartPage() }, // prompting() /** * save configurations & config project */ configuring: function () { // add the result of the question to the generator configuration object this.genConfig.projectnternalName = this.genConfig.name.toLowerCase().replace(/ /g, "-"); this.genConfig.projectDisplayName = this.genConfig.name; this.genConfig.rootPath = this.genConfig['root-path']; }, // configuring() /** * write generator specific files */ writing: { /** * If there is already a package.json in the root of this project, * get the name of the project from that file as that should be used * in bower.json & update packages. */ upsertPackage: function () { if (this.genConfig.tech !== 'manifest-only') { var done = this.async(); // default name for the root project = addin project this.genConfig.rootProjectName = this.genConfig.projectnternalName; // path to package.json var pathToPackageJson = this.destinationPath('package.json'); // if package.json doesn't exist if (!this.fs.exists(pathToPackageJson)) { // copy package.json to target this.fs.copyTpl(this.templatePath('common/_package.json'), this.destinationPath('package.json'), this.genConfig); } else { // load package.json var packageJson = this.fs.readJSON(pathToPackageJson, 'utf8'); // .. get it's name property this.genConfig.rootProjectName = packageJson.name; // update devDependencies /* istanbul ignore else */ if (!packageJson.devDependencies) { packageJson.devDependencies = {} } /* istanbul ignore else */ if (!packageJson.devDependencies['gulp']) { packageJson.devDependencies['gulp'] = "^3.9.0" } /* istanbul ignore else */ if (!packageJson.devDependencies['gulp-webserver']) { packageJson.devDependencies['gulp-webserver'] = "^0.9.1" } // overwrite existing package.json this.log(chalk.yellow('Adding additional packages to package.json')); this.fs.writeJSON(pathToPackageJson, packageJson); } done(); } }, // upsertPackage() /** * If bower.json already exists in the root of this project, update it * with the necessary addin packages. */ upsertBower: function () { if (this.genConfig.tech !== 'manifest-only') { var done = this.async(); var pathToBowerJson = this.destinationPath('bower.json'); // if doesn't exist... if (!this.fs.exists(pathToBowerJson)) { // copy bower.json => project switch (this.genConfig.tech) { case "ng": this.fs.copyTpl(this.templatePath('ng/_bower.json'), this.destinationPath('bower.json'), this.genConfig); break; case "html": this.fs.copyTpl(this.templatePath('html/_bower.json'), this.destinationPath('bower.json'), this.genConfig); break; } } else { // verify the necessary package references are present in bower.json... // if not, add them var bowerJson = this.fs.readJSON(pathToBowerJson, 'utf8'); // all addins need these if (!bowerJson.dependencies["microsoft.office.js"]) { bowerJson.dependencies["microsoft.office.js"] = "*"; } if (!bowerJson.dependencies["jquery"]) { bowerJson.dependencies["jquery"] = "~1.9.1"; } switch (this.genConfig.tech) { // if angular... case "ng": if (!bowerJson.dependencies["angular"]) { bowerJson.dependencies["angular"] = "~1.4.4"; } if (!bowerJson.dependencies["angular-route"]) { bowerJson.dependencies["angular-route"] = "~1.4.4"; } if (!bowerJson.dependencies["angular-sanitize"]) { bowerJson.dependencies["angular-sanitize"] = "~1.4.4"; } break; } // overwrite existing bower.json this.log(chalk.yellow('Adding additional packages to bower.json')); this.fs.writeJSON(pathToBowerJson, bowerJson); } done(); } }, // upsertBower() app: function () { // helper function to build path to the file off root path this._parseTargetPath = function (file) { return path.join(this.genConfig['root-path'], file); }; var done = this.async(); // create a new ID for the project this.genConfig.projectId = guid.v4(); if (this.genConfig.tech === 'manifest-only') { // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); } else { // copy .bowerrc => project this.fs.copyTpl( this.templatePath('common/_bowerrc'), this.destinationPath('.bowerrc'), this.genConfig); // create common assets this.fs.copy(this.templatePath('common/gulpfile.js'), this.destinationPath('gulpfile.js')); this.fs.copy(this.templatePath('common/content/Office.css'), this.destinationPath(this._parseTargetPath('content/Office.css'))); this.fs.copy(this.templatePath('common/images/close.png'), this.destinationPath(this._parseTargetPath('images/close.png'))); this.fs.copy(this.templatePath('common/scripts/MicrosoftAjax.js'), this.destinationPath(this._parseTargetPath('scripts/MicrosoftAjax.js'))); switch (this.genConfig.tech) { case 'html': // determine startpage for addin this.genConfig.startPage = 'https://localhost:8443/app/home/home.html'; // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); // copy addin files this.fs.copy(this.templatePath('html/app.css'), this.destinationPath(this._parseTargetPath('app/app.css'))); this.fs.copy(this.templatePath('html/app.js'), this.destinationPath(this._parseTargetPath('app/app.js'))); this.fs.copy(this.templatePath('html/home/home.html'), this.destinationPath(this._parseTargetPath('app/home/home.html'))); this.fs.copy(this.templatePath('html/home/home.css'), this.destinationPath(this._parseTargetPath('app/home/home.css'))); this.fs.copy(this.templatePath('html/home/home.js'), this.destinationPath(this._parseTargetPath('app/home/home.js'))); break; case 'ng': // determine startpage for addin this.genConfig.startPage = 'https://localhost:8443/index.html'; // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); // copy addin files this.genConfig.startPage = '{https-addin-host-site}/index.html'; this.fs.copy(this.templatePath('ng/index.html'), this.destinationPath(this._parseTargetPath('index.html'))); this.fs.copy(this.templatePath('ng/app.module.js'), this.destinationPath(this._parseTargetPath('app/app.module.js'))); this.fs.copy(this.templatePath('ng/app.routes.js'), this.destinationPath(this._parseTargetPath('app/app.routes.js'))); this.fs.copy(this.templatePath('ng/home/home.controller.js'), this.destinationPath(this._parseTargetPath('app/home/home.controller.js'))); this.fs.copy(this.templatePath('ng/home/home.html'), this.destinationPath(this._parseTargetPath('app/home/home.html'))); this.fs.copy(this.templatePath('ng/services/data.service.js'), this.destinationPath(this._parseTargetPath('app/services/data.service.js'))); break; } } done(); } // app() }, // writing() /** * conflict resolution */ // conflicts: { }, /** * run installations (bower, npm, tsd, etc) */ install: function () { if (!this.options['skip-install'] && this.genConfig.tech !== 'manifest-only') { this.npmInstall(); this.bowerInstall(); } } // install () /** * last cleanup, goodbye, etc */ // end: { } });
function(){ var db = $$(this).app.db, term = $(this).val(), nonce = Math.random(); $$($(this)).nonce = nonce; db.view("icd9lookup/by_code", { startkey : term, endkey : term+"\u9999", //I don't know why only \u9999 works, not \uFFFF limit : 100, success : function(names){ if($$($(this)).nonce = nonce){ $("#results").html( "<tr><th>ICD-9 Code</th><th>Long Description</th><th>Short Description</th></tr>"+ names.rows.map(function(r){ return '<tr><td>'+r.value.icd9code+'</td><td>'+r.value.long_description+'</td><td>'+r.value.short_description+'</td></tr>'; }).join("")); }}}); }
import cx from 'classnames' import _ from 'lodash' import React, { PropTypes } from 'react' import { createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' /** * A message can contain a header. */ function MessageHeader(props) { const { children, className, content } = props const classes = cx('header', className) const rest = getUnhandledProps(MessageHeader, props) const ElementType = getElementType(MessageHeader, props) return ( <ElementType {...rest} className={classes}> {_.isNil(children) ? content : children} </ElementType> ) } MessageHeader._meta = { name: 'MessageHeader', parent: 'Message', type: META.TYPES.COLLECTION, } MessageHeader.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.itemShorthand, } MessageHeader.create = createShorthandFactory(MessageHeader, val => ({ content: val })) export default MessageHeader
export default { userData: {}, isAuthenticated: false, registrationMode: false, registrationFailed: false, attemptFailed: false, reviewData: [] }
import Ember from 'ember'; const $ = Ember.$; import layout from './template'; import styles from './styles'; /* * Turn header transparent after scrolling * down a few pixels: */ const HEADER_OFFSET = 60; export default Ember.Component.extend({ layout, styles, tagName: 'nav', localClassNames: 'nav', localClassNameBindings: [ 'isSmall', 'invert', 'showComponents', ], isSmall: false, componentsTitle: "More components", showComponents: false, invertLogoColors: Ember.computed('isSmall', 'invert', function() { return !this.get('isSmall') && !this.get('invert'); }), githubURL: Ember.computed('config', function() { return this.get('config.githubURL'); }), _scrollListener: null, didInsertElement() { this._scrollListener = Ember.run.bind(this, this.didScroll); $(window).on('scroll', this._scrollListener); }, willDestroyElement() { if (this._scrollListener) { $(window).off('scroll', this._scrollListener); } }, didScroll() { let scrollPos = $(window).scrollTop(); let reachedOffset = (scrollPos > HEADER_OFFSET); this.set('isSmall', reachedOffset); }, /* * Determine if the user is on a touch device: */ hasTouch: Ember.computed(function() { return (('ontouchstart' in window) || window.DocumentTouch); }), actions: { toggleComponents(value, e) { if (e && e.stopPropagation) { e.stopPropagation(); } if (value !== null && value !== undefined) { this.set('showComponents', value); } else { this.toggleProperty('showComponents'); } }, }, });
'use strict'; // Configuring the Articles module angular.module('states').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'States', 'states', 'dropdown', '/states(/create)?'); Menus.addSubMenuItem('topbar', 'states', 'List States', 'states'); Menus.addSubMenuItem('topbar', 'states', 'New State', 'states/create'); } ]);