code
stringlengths
2
1.05M
'use strict'; var _express = require('express'); var _express2 = _interopRequireDefault(_express); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _db = require('./config/db'); var _db2 = _interopRequireDefault(_db); var _bodyParser = require('body-parser'); var _bodyParser2 = _interopRequireDefault(_bodyParser); var _routes = require('./routes.js'); var _routes2 = _interopRequireDefault(_routes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _db2.default.connectMongo(); var app = (0, _express2.default)(); app.set('port', process.env.PORT); app.use(_express2.default.static(_path2.default.join(__dirname, './build'))); app.use(_bodyParser2.default.json()); (0, _routes2.default)(app); app.get('*', function (req, res) { res.sendFile(_path2.default.join(__dirname, './build', 'index.html')); }); app.listen(app.get('port'), function () { //console.log("app running at "+app.get('port')); });
module.exports = function (api) { api.loadSource(store => { // Use the Data store API here: https://api.exemple.com }) }
const gulp = require('gulp'); const gulpif = require('gulp-if'); const babel = require('gulp-babel'); const isJavaScript = file => /\.js$/.test(file.path) && !/templates/.test(file.path); gulp.task('default', () => gulp.src('src/**/*') .pipe(gulpif(isJavaScript, babel())) .pipe(gulp.dest('generators/')) );
define(function () { app.registerController('UserCtrl', ['$scope', '$http', '$uibModal', '$rootScope', 'user', '$state', 'SweetAlert', function ($scope, $http, $modal, $rootScope, user, $state, SweetAlert) { $scope.user = user.data; $scope.is_self = $scope.user.id == $rootScope.user.id; $scope.updatePassword = function (pwd) { $http.post('/users/' + $scope.user.id + '/password', { password: pwd }).then(function () { SweetAlert.swal('OK', 'User profile & password were updated.'); }).catch(function (response) { SweetAlert.swal('Error', 'Setting password failed, API responded with HTTP ' + response.status, 'error'); }); } $scope.updateUser = function () { var pwd = $scope.user.password; $http.put('/users/' + $scope.user.id, $scope.user).then(function () { if ($rootScope.user.id == $scope.user.id) { $rootScope.user = $scope.user; } if (pwd && pwd.length > 0) { $scope.updatePassword(pwd); return; } SweetAlert.swal('OK', 'User has been updated!'); }).catch(function (response) { SweetAlert.swal('Error', 'User profile could not be updated: ' + response.status, 'error'); }); } $scope.deleteUser = function () { $http.delete('/users/' + $scope.user.id).then(function () { $state.go('users.list'); }).catch(function (response) { SweetAlert.swal('Error', 'User could not be deleted! ' + response.status, 'error'); }); } }]); });
module.exports = { production: false, development: true, node: false, };
var square = require('./square'); var side = 2; var area = square.area(2); console.log('square of', side, 'is', area);
/* Modules This example code is in the public domain. modified 10 Jan 2017 by Ngesa N Marvin */ var http = require ('http'); //var module1 = require('./module1'); var module2 = require('./module2'); var server = http.createServer (function (req, res) { // body... res.writeHead(200, {'Content-Type': 'text/plain'}); //res.write(module1.mySting); //module1.myFunction(); res.write(module2.mySting1); module2.myFunction1(); res.end(); }).listen(2323, function() { // body... console.log('server listening to port 2323'); });
/* $Id$ * * Copyright (C) 2013 RWW.IO * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ HTTP = Class.create(Ajax.Request, { request: function(url) { this.url = url; this.method = this.options.method; var params = Object.isString(this.options.parameters) ? this.options.parameters : Object.toQueryString(this.options.parameters); if (params) { if (this.method == 'get') this.url += (this.url.include('?') ? '&' : '?') + params; else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='; } this.parameters = params.toQueryParams(); try { var response = new Ajax.Response(this); if (this.options.onCreate) this.options.onCreate(response); Ajax.Responders.dispatch('onCreate', this, response); this.transport.open(this.method.toUpperCase(), this.url, this.options.asynchronous); if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); this.transport.onreadystatechange = this.onStateChange.bind(this); this.setRequestHeaders(); this.body = this.method == 'post' ? (this.options.postBody || params) : null; this.body = this.body || this.options.body || ''; this.transport.send(this.body); /* Force Firefox to handle ready state 4 for synchronous requests */ if (!this.options.asynchronous && this.transport.overrideMimeType) this.onStateChange(); } catch (e) { this.dispatchException(e); } } }); dirname = function(path) { return path.replace(/\\/g, '/').replace(/\/[^\/]*\/?$/, ''); } basename = function(path) { if (path.substring(path.length - 1) == '/') path = path.substring(0, path.length - 1); var a = path.split('/'); return a[a.length - 1]; } newJS = function(url, callback){ var script = document.createElement("script") script.async = true; script.type = "text/javascript"; script.src = url; if (callback) { if (script.readyState) { // IE script.onreadystatechange = function() { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else { // others script.onload = function() { callback(); }; } } return script; } /** Cookies **/ function setCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; // reload window.location.reload(true); } function readCookie(name) { var nameEQ = name+"="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function deleteCookie(name) { setCookie(name,"",-1); } function notify (message, cls) { if (message) { $('alertbody').update(message); if (cls) $('alertbody').addClassName(cls); $('alert').show(); } else { $('alert').hide(); $('alertbody').classNames().each(function(elt) { $('alertbody').removeClassName(elt); }); } } /** Web ACLs **/ wac = {}; wac.get = function(request_path, path) { // reset the checkboxes $('wac-read').checked = false; $('wac-write').checked = false; $('wac-append').checked = false; $('wac-recursive').checked = false; $('wac-users').value = ''; // remove trailing / from the file name we append after .acl console.log('Path='+path); var File = path; if (path.substring(path.length - 1) == '/') File = path.substring(0, path.length - 1); var aclBase = window.location.protocol+'//'+window.location.host+window.location.pathname; // if the resource in question is not the .acl file itself if (File.substr(0, 4) != '.acl') { if (File == '..') { // we need to use the parent dir name path = basename(window.location.pathname); var aclBase = window.location.protocol+'//'+window.location.host+dirname(window.location.pathname)+'/'; var aclFile = '.acl.'+basename(window.location.pathname); var aclURI = aclBase+aclFile; var innerRef = window.location.pathname; // the resource as inner ref var requestPath = request_path; var dir = window.location.protocol+'//'+window.location.host+innerRef; // Remove preceeding / from path if (innerRef.substr(0, 1) == '/') innerRef = innerRef.substring(1); innerRef = aclURI+'#'+innerRef; } else if (File == '') { // root path = '/'; var aclBase = window.location.protocol+'//'+window.location.host+'/'; var aclFile = '.acl'; var aclURI = aclBase+aclFile; var innerRef = aclBase; // the resource as inner ref var requestPath = request_path; var dir = window.location.protocol+'//'+window.location.host+request_path; } else { var aclFile = '.acl.'+File; var aclURI = aclBase+aclFile; var innerRef = path; // the resource as inner ref var dir = window.location.protocol+'//'+window.location.host+request_path+innerRef; var requestPath = request_path; // Remove preceeding / from path if (innerRef.substr(0, 1) == '/') innerRef = innerRef.substring(1); innerRef = aclURI+'#'+innerRef; } } else { // the resource IS the acl file var aclFile = File; var aclURI = aclBase+File; var innerRef = aclURI; var dir = innerRef; } // DEBUG console.log('resource='+innerRef); console.log('aclfile='+aclFile); console.log('RDFresource='+innerRef); console.log('aclBase='+aclBase); console.log('aclURI='+aclURI); // For quick access to those namespaces: var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); var WAC = $rdf.Namespace("http://www.w3.org/ns/auth/acl#"); var graph = $rdf.graph(); var resource = $rdf.sym(innerRef); var fetch = $rdf.fetcher(graph); fetch.nowOrWhenFetched(aclURI,undefined,function(){ // permissions var perms = graph.each(resource, WAC('mode')); // reset the checkboxes $('wac-read').checked = false; $('wac-write').checked = false; // we need to know if the .acl file doesn't exist or it's empty, so we // can later add default rules if (perms.length > 0) $('wac-exists').value = '1'; var i, n = perms.length, mode; for (i=0;i<n;i++) { var mode = perms[i]; if (mode == '<http://www.w3.org/ns/auth/acl#Read>') $('wac-read').checked = true; else if (mode == '<http://www.w3.org/ns/auth/acl#Write>') $('wac-write').checked = true; else if (mode == '<http://www.w3.org/ns/auth/acl#Append>') $('wac-append').checked = true; } // defaultForNew var defaultForNew = graph.each(resource, WAC('defaultForNew')); console.log('Rec-link='+defaultForNew.toString().replace(/\<(.*?)\>/g, "$1")); console.log('Resource='+dir); if (defaultForNew.toString().replace(/\<(.*?)\>/g, "$1") == dir) $('wac-recursive').checked = true; // users var users = graph.each(resource, WAC('agent')); // remove the < > signs from URIs $('wac-users').value=users.toString().replace(/\<(.*?)\>/g, "$1"); }); // set path value in the title $('wac-path').innerHTML=path; $('wac-reqpath').innerHTML=requestPath; } // load permissions and display WAC editor wac.edit = function(request_path, path) { var isDir = false; var File = path; if (path.substring(path.length - 1) == '/') { // we have a dir -> remove the recursive option from the editor isDir = true; File = path.substring(0, path.length - 1); } var aclBase = window.location.protocol+'//'+window.location.host+window.location.pathname; // if the resource in question is not the .acl file itself if (File.substr(0, 4) != '.acl') { if (File == '..') { // we need to use the parent dir name var aclBase = window.location.protocol+'//'+window.location.host+dirname(window.location.pathname)+'/'; var aclFile = '.acl.'+basename(window.location.pathname); var aclURI = aclBase+aclFile; } else if (File == '') { // root var aclBase = window.location.protocol+'//'+window.location.host+'/'; var aclFile = '.acl'; var aclURI = aclBase+aclFile; } else { var aclFile = '.acl.'+File; var aclURI = aclBase+aclFile; } } else { // the resource IS the acl file var aclURI = aclBase+File; } console.log('aclURI='+aclURI); new HTTP(aclURI, { method: 'get', requestHeaders: {'Content-Type': 'text/turtle'}, onSuccess: function() { // display the editor wac.get(request_path, path); $('wac-editor').show(); if (isDir) $('recursive').show(); else $('recursive').hide(); }, onFailure: function(r) { var status = r.status.toString(); if (status != '404') { var msg = 'Access denied'; console.log(msg); notify(msg, 'error'); window.setTimeout("notify()", 2000); } else { wac.get(request_path, path); $('wac-editor').show(); if (isDir) $('recursive').show(); else $('recursive').hide(); } } }); } // hide the editor wac.hide = function() { $('wac-editor').hide(); } // overwrite wac.put = function(uri, data, refresh) { new HTTP(uri, { method: 'put', body: data, requestHeaders: {'Content-Type': 'text/turtle'}, onSuccess: function() { if (refresh == true) window.location.reload(true); }, onFailure: function() { var msg = 'Access denied'; console.log(msg); notify(msg, 'error'); window.setTimeout("notify()", 2000); } }); } // append wac.post = function(uri, data, refresh) { new HTTP(uri, { method: 'post', body: data, contentType: 'text/turtle', onSuccess: function() { if (refresh == true) window.location.reload(true); }, onFailure: function() { var msg = 'Access denied'; console.log(msg); notify(msg, 'error'); window.setTimeout("notify()", 2000); } }); } // delete wac.rm = function(uri, refresh) { new HTTP(uri, { method: 'delete', onSuccess: function () { if (refresh == true) window.location.reload(true); }, onFailure: function (r) { var status = r.status.toString(); if (status == '404') { var msg = 'Access denied'; notify(msg, 'error'); window.setTimeout("notify()", 2000); } } }); } wac.save = function(elt) { var path = $('wac-path').innerHTML; var reqPath = $('wac-reqpath').innerHTML; var users = $('wac-users').value.split(","); var read = $('wac-read').checked; var write = $('wac-write').checked; var append = $('wac-append').checked; var recursive = $('wac-recursive').checked; var exists = $('wac-exists').value; var owner = $('wac-owner').value; // For quick access to those namespaces: var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); var WAC = $rdf.Namespace("http://www.w3.org/ns/auth/acl#"); var FOAF = $rdf.Namespace("http://xmlns.com/foaf/0.1/"); /**** Domain specific acl ****/ // If there is no .acl at the root level, we must create one! var rootMeta = window.location.protocol+'//'+window.location.host+'/.acl'; var rootDir = window.location.protocol+'//'+window.location.host+'/'; // check if we have a acl for domain control // DEBUG console.log("rootMeta="+rootMeta); var gotRootMeta = false; new HTTP(rootMeta, { method: 'get', requestHeaders: {'Content-Type': 'text/turtle'}, onSuccess: function() { gotRootMeta = true; } }); if (gotRootMeta == false) { var ng = new $rdf.graph(); // add default rules ng.add($rdf.sym(rootMeta), WAC('accessTo'), $rdf.sym(window.location.protocol+'//'+window.location.host+'/')); ng.add($rdf.sym(rootMeta), WAC('accessTo'), $rdf.sym(rootMeta)); ng.add($rdf.sym(rootMeta), WAC('agent'), $rdf.sym(owner)); ng.add($rdf.sym(rootMeta), WAC('mode'), WAC('Read')); ng.add(ng.sym(rootMeta), WAC('mode'), WAC('Write')); // add read for all ng.add($rdf.sym(rootDir), WAC('accessTo'), $rdf.sym(window.location.protocol+'//'+window.location.host+'/')); ng.add($rdf.sym(rootDir), WAC('accessTo'), $rdf.sym(rootDir)); ng.add($rdf.sym(rootDir), WAC('agentClass'), FOAF('Agent')); ng.add($rdf.sym(rootDir), WAC('defaultForNew'), $rdf.sym(window.location.protocol+'//'+window.location.host+'/')); ng.add($rdf.sym(rootDir), WAC('mode'), WAC('Read')); var rootMetaData = new $rdf.Serializer(ng).toN3(ng); wac.post(rootMeta, rootMetaData, false); } /**** File specific acl ****/ // don't do anything if no ACL mode is checked in the UI var aclBase = window.location.protocol+'//'+window.location.host+reqPath; // Remove preceeding / from path if (reqPath.substr(0, 1) == '/') reqPath = reqPath.substring(1); // remove trailing slash from acl file var File = path; if (path.substring(path.length - 1) == '/') File = path.substring(0, path.length - 1); // Build the full .acl path URI if (path == '/') { // we're at the root level var aclURI = aclBase+'.acl'; var innerRef = aclBase; } else if (path.substr(0, 4) != '.acl') { // got a normal file if (path+'/' == reqPath) { // we need to use the parent dir name path = reqPath; var aclBase = window.location.protocol+'//'+window.location.host+dirname(window.location.pathname)+'/'; var aclFile = '.acl.'+basename(window.location.pathname); var aclURI = aclBase+aclFile; var innerRef = '#'+path; } else { var aclURI = aclBase+'.acl.'+File; var innerRef = '#'+path; } } else { // got a .acl file var aclURI = aclBase+path; path = path; var innerRef = aclURI; } // DEBUG console.log('path='+path); console.log('reqPath='+reqPath); console.log('resource='+aclBase+path); console.log('aclBase='+aclBase); console.log('aclURI='+aclURI); // Create a new graph var graph = new $rdf.graph(); if (read == false && write == false && append == false) { wac.rm(aclURI, true); } else { // path graph.add(graph.sym(innerRef), WAC('accessTo'), graph.sym(aclBase+path)); // add allowed users if ((users.length > 0) && (users[0].length > 0)) { var i, n = users.length, user; for (i=0;i<n;i++) { var user = users[i].replace(/\s+|\n|\r/g,''); graph.add(graph.sym(innerRef), WAC('agent'), graph.sym(user)); } } else { graph.add(graph.sym(innerRef), WAC('agentClass'), FOAF('Agent')); } // add access modes if (read == true) { graph.add(graph.sym(innerRef), WAC('mode'), WAC('Read')); } if (write == true) { graph.add(graph.sym(innerRef), WAC('mode'), WAC('Write')); } else if (append == true) { graph.add(graph.sym(innerRef), WAC('mode'), WAC('Append')); } // add recursion if (recursive == true) { graph.add(graph.sym(innerRef), WAC('defaultForNew'), graph.sym(aclBase+path)); } // create default rules for the .acl file itself if we create it for the // first time if (exists == '0') { // Add the #Default rule for this domain graph.add(graph.sym(aclURI), WAC('accessTo'), graph.sym(aclURI)); graph.add(graph.sym(aclURI), WAC('accessTo'), graph.sym(aclBase+path)); graph.add(graph.sym(aclURI), WAC('agent'), graph.sym(owner)); graph.add(graph.sym(aclURI), WAC('mode'), WAC('Read')); graph.add(graph.sym(aclURI), WAC('mode'), WAC('Write')); // serialize var data = new $rdf.Serializer(graph).toN3(graph); console.log(data); // POST the new rules to the server .acl file wac.post(aclURI, data, true); } else { // copy rules from old acl var g = $rdf.graph(); var fetch = $rdf.fetcher(g); fetch.nowOrWhenFetched(aclURI,undefined,function(){ // add accessTo graph.add($rdf.sym(aclURI), WAC('accessTo'), $rdf.sym(aclURI)); // add agents var agents = g.each($rdf.sym(aclURI), WAC('agent')); if (agents.length > 0) { var i, n = agents.length; for (i=0;i<n;i++) { var agent = agents[i]['uri']; graph.add($rdf.sym(aclURI), WAC('agent'), $rdf.sym(agent)); } } else { graph.add($rdf.sym(aclURI), WAC('agentClass'), FOAF('Agent')); } // add permissions var perms = g.each($rdf.sym(aclURI), WAC('mode')); if (perms.length > 0) { var i, n = perms.length; for (i=0;i<n;i++) { var perm = perms[i]['uri']; graph.add($rdf.sym(aclURI), WAC('mode'), $rdf.sym(perm)); } } // serialize var data = new $rdf.Serializer(graph).toN3(graph); // DEBUG console.log(data); // PUT the new rules to the server .acl file wac.put(aclURI, data, true); }); } } // hide the editor $('wac-editor').hide(); } cloud = {}; cloud.append = function(path, data) { data = data || '' new HTTP(this.request_url+path, { method: 'post', body: data, contentType: 'text/turtle', onSuccess: function() { window.location.reload(); }, onFailure: function() { var msg = 'Access denied'; console.log(msg); alert(msg, 'error'); window.setTimeout("alert()", 2000); } }); } cloud.get = function(path) { var lastContentType = $F('editorType'); new HTTP(this.request_url+path, { method: 'get', evalJS: false, requestHeaders: {'Accept': lastContentType}, onSuccess: function(r) { $('editorpath').value = path; $('editorpath').enable(); $('editorarea').value = r.responseText; $('editorarea').enable(); var contentType = r.getResponseHeader('Content-Type'); var editorTypes = $$('#editorType > option'); for (var i = 0; i < editorTypes.length; i++) { var oneContentType = editorTypes[i].value; if (oneContentType == contentType || oneContentType == '') { editorTypes[i].selected = true; } } $('editor').show(); }, onFailure: function() { var msg = 'Access denied'; console.log(msg); notify(msg, 'error'); window.setTimeout("notify()", 2000); } }); } cloud.mkdir = function(path) { new HTTP(this.request_url+path, { method: 'mkcol', onSuccess: function() { window.location.reload(); }, onFailure: function() { var msg = 'Access denied'; console.log(msg); alert(msg, 'error'); window.setTimeout("alert()", 2000); } }); } cloud.put = function(path, data, type) { if (!type) type = 'text/turtle'; new HTTP(this.request_url+path, { method: 'put', body: data, requestHeaders: {'Content-Type': type}, onSuccess: function() { window.location.reload(); }, onFailure: function(r) { var status = r.status.toString(); var msg = ''; if (status == '400') msg = 'Bad request (check your syntax).'; else if (status == '401') msg = 'Unauthorized request (not logged in?).'; else if (status == '403') msg = 'Forbidden! You do not have access.'; else if (status == '406') msg = 'Content-Type not acceptable.'; else msg = 'Unknown error.'; notify(msg, 'error'); window.setTimeout("notify()", 2000); } }); } cloud.rm = function(path) { // also removes the corresponding .acl and .meta file if they exist var url = this.request_url; console.log('url='+url+' / path='+path); new HTTP(url+path, { method: 'delete', onSuccess: function() { if (path.substr(0, 4) != '.acl' || path.substr(0, 5) != '.meta') { // remove trailing slash if (path.substring(path.length - 1) == '/') path = path.substring(0, path.length - 1); // remove the .acl file new HTTP(url+'.acl.'+path, { method: 'delete', onSuccess: function() { window.location.reload(); }, onFailure: function() { // refresh anyway window.location.reload(); } }); // remove the .meta file new HTTP(url+'.meta.'+path, { method: 'delete', onSuccess: function() { window.location.reload(); }, onFailure: function() { // refresh anyway window.location.reload(); } }); } else { window.location.reload(); } }, onFailure: function() { var msg = 'Access denied'; console.log(msg); notify(msg, 'error'); window.setTimeout("notify()", 2000); } }); } cloud.edit = function(path) { $('editorpath').value = ''; $('editorpath').disable(); $('editorarea').value = ''; $('editorarea').disable(); cloud.get(path); } cloud.save = function(elt) { var path = $('editorpath').value; var data = $('editorarea').value; var type = $F('editorType'); cloud.put(path, data, type); } cloud.init = function(data) { var k; for (k in data) { this[k] = data[k]; } this.storage = {}; try { if ('localStorage' in window && window['localStorage'] !== null) this.storage = window.localStorage; } catch(e){} } cloud.refresh = function() { window.location.reload(); } cloud.remove = function(elt) { new Ajax.Request(this.request_base+'/json/'+elt, { method: 'delete' }); } cloud.updateStatus = function() { if (Ajax.activeRequestCount > 0) { $('statusLoading').show(); $('statusComplete').hide(); } else { $('statusComplete').show(); $('statusLoading').hide(); } } Ajax.Responders.register({ onCreate: cloud.updateStatus, onComplete: function(q, r, data) { cloud.updateStatus(); var msg = ''; var cls = q.success() ? 'info' : 'error'; try { msg += data.status.toString()+' '+data.message; } catch (e) { msg += r.status.toString()+' '+r.statusText; } var method = q.method.toUpperCase(); var triples = r.getHeader('Triples'); if (triples != null) { msg = triples.toString()+' triple(s): '+msg; } else { if (method == 'GET') { msg = r.responseText.length.toString()+' byte(s): '+msg; } else { msg = q.body.length.toString()+' byte(s): '+msg; } } // DEBUG console.log(msg); notify(method+' '+msg, cls); window.setTimeout("notify()", 3000); }, }); cloud.facebookInit = function() { FB.init({appId: '119467988130777', status: false, cookie: false, xfbml: true}); FB._login = FB.login; FB.login = function(cb, opts) { if (!opts) opts = {}; opts['next'] = cloud.request_base + '/login?id=facebook&display=popup'; return FB._login(cb, opts); } }; window.fbAsyncInit = cloud.facebookInit;
import React from 'react'; import PropTypes from 'prop-types'; import * as Styled from './styles'; const Container = ({ section, children }) => <Styled.Container section={section}>{children}</Styled.Container>; Container.propTypes = { section: PropTypes.bool, children: PropTypes.any.isRequired }; export default Container;
var searchData= [ ['mediarecorder_2ec',['MediaRecorder.c',['../MediaRecorder_8c.html',1,'']]], ['mediarecorder_2eh',['MediaRecorder.h',['../MediaRecorder_8h.html',1,'']]] ];
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var fs = require('fs'); var path = require('path'); var ipc = require('ipc'); var Handlebars = require('handlebars'); var development = process.env.ATOMIC_LACUNA_DEVELOPMENT || false; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is GCed. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit(); } }); // This method will be called when atom-shell has done all required // initialization and is ready to create browser windows. app.on('ready', function () { mainWindow = new BrowserWindow({width: 800, height: 600, show: false}); mainWindow.maximize(); mainWindow.loadUrl('file://' + doIndexStuff()); mainWindow.on('closed', function() { mainWindow = null; }); }); ipc.on('atomic-lacuna-window-show', function () { mainWindow.show(); }); // Method to run the Handlebars template for the index.html file and return the // url to the a file generated from this template. function doIndexStuff() { var template = getIndexTemplate(); var args = { development : development, atomShell : true // If this script is running, we're starting the atom-shell. }; // Figure location var location = ''; if (development) { location = path.join(__dirname, '..', 'public', 'index-compiled.html'); } else { location = path.join(__dirname, 'index-compiled.html'); } fs.writeFileSync(location, template(args)); return location; }; function getIndexTemplate() { return Handlebars.compile(fs.readFileSync(getIndexTemplatePath()).toString()); } function getIndexTemplatePath() { if (development) { return path.join(__dirname, '..', 'public', 'index-template.html'); } return path.join(__dirname, 'index-template.html'); }
// simulated latency in ms const LATENCY = 100; /** * Class representing a Widget Database. Before any operations * are performed against the in-memory datastore, a short timeout * takes place to simulate network latency and to create an asynconous * transaction. */ class WidgetDB { /** * Create an empty Widget Database. */ constructor() { this.db = {} } /** * Get a widget by its id. * @param {String} id - The widget id * @return {Promise<object>} A promise that contiains * the value of the widget when fulfilled. */ get(id) { return wait().then(() => this.db[id]) } /** * Stores a new value for a widget * @param {String} id - The widget id * @param {Object} value - The value of the widget * @return {Promise<object>} A promise that contiains * the value stored when fulfilled. */ put(id, value) { return wait().then(() => this.db[id] = value) } } /** * A function to simulate latency in a system * @return {Promise} An empty promise that is fulfilled * after a period of time defined by the LATENCY constant. */ function wait() { return new Promise((resolve, reject) => { setTimeout(resolve, LATENCY) }) } module.exports = new WidgetDB();
describe("About Objects", function () { describe("Properties", function () { var meglomaniac; beforeEach(function () { meglomaniac = { mastermind: "Joker", henchwoman: "Harley" }; }); it("should confirm objects are collections of properties", function () { expect(meglomaniac.mastermind).toBe('Joker'); }); it("should confirm that properties are case sensitive", function () { expect(meglomaniac.henchwoman).toBe('Harley'); expect(meglomaniac.henchWoman).toBe(); }); }); it("should know properties that are functions act like methods", function () { var meglomaniac = { mastermind : "Brain", henchman: "Pinky", battleCry: function (noOfBrains) { return "They are " + this.henchman + " and the" + Array(noOfBrains + 1).join(" " + this.mastermind); //Having trouble understanding the difference between a function and a method } }; var battleCry = meglomaniac.battleCry(4); expect('They are Pinky and the Brain Brain Brain Brain').toMatch(battleCry); }); it("should confirm that when a function is attached to an object, 'this' refers to the object", function () { var currentDate = new Date() var currentYear = (currentDate.getFullYear()); //why does this need to be wrapped in ()? var meglomaniac = { mastermind: "James Wood", henchman: "Adam West", birthYear: 1970, calculateAge: function () { return currentYear - this.birthYear; } }; expect(currentYear).toBe(2013); expect(meglomaniac.calculateAge()).toBe(43); }); describe("'in' keyword", function () { var meglomaniac; beforeEach(function () { meglomaniac = { mastermind: "The Monarch", henchwoman: "Dr Girlfriend", theBomb: true }; }); it("should have the bomb", function () { var hasBomb = "theBomb" in meglomaniac; //in is an operator that returns true if the specified property is in the specified object. expect(hasBomb).toBe(true); }); it("should not have the detonator however", function () { var hasDetonator = "theDetonator" in meglomaniac; expect(hasDetonator).toBe(false); }); }); it("should know that properties can be added and deleted", function () { var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" }; expect("secretary" in meglomaniac).toBe(false); meglomaniac.secretary = "Agent Smith"; expect("secretary" in meglomaniac).toBe(true); delete meglomaniac.henchman; expect("henchman" in meglomaniac).toBe(false); }); it("should use prototype to add to all objects", function () { function Circle(radius) { this.radius = radius; } var simpleCircle = new Circle(10); var colouredCircle = new Circle(5); colouredCircle.colour = "red"; expect(simpleCircle.colour).toBe(); expect(colouredCircle.colour).toBe('red'); Circle.prototype.describe = function () { return "This circle has a radius of: " + this.radius; //I think prototype is adding a new property called 'describe'? }; expect(simpleCircle.describe()).toBe('This circle has a radius of: 10'); expect(colouredCircle.describe()).toBe('This circle has a radius of: 5'); }); });
pc.extend(pc, function(){ /** * @name pc.KeyboardEvent * @class The KeyboardEvent is passed into all event callbacks from the {@link pc.Keyboard}. It corresponds to a key press or release. * @description Create a new KeyboardEvent * @param {pc.Keyboard} keyboard The keyboard object which is firing the event. * @param {KeyboardEvent} event The original browser event that was fired. * @property {Number} key The keyCode of the key that has changed. See the pc.KEY_* constants. * @property {Element} element The element that fired the keyboard event. * @property {KeyboardEvent} event The original browser event which was fired. * @example * var onKeyDown = function (e) { * if (e.key === pc.KEY_SPACE) { * // space key pressed * } * e.event.preventDefault(); // Use original browser event to prevent browser action. * }; * app.keyboard.on("keydown", onKeyDown, this); */ var KeyboardEvent = function (keyboard, event) { if (event) { this.key = event.keyCode; this.element = event.target; this.event = event; } else { this.key = null; this.element = null; this.event = null; } }; // internal global keyboard events var _keyboardEvent = new KeyboardEvent(); function makeKeyboardEvent(event) { _keyboardEvent.key = event.keyCode; _keyboardEvent.element = event.target; _keyboardEvent.event = event; return _keyboardEvent; } /** * @private * @function * @name pc.toKeyCode * @description Convert a string or keycode to a keycode * @param {String | Number} s */ function toKeyCode(s){ if (typeof(s) == "string") { return s.toUpperCase().charCodeAt(0); } else { return s; } } var _keyCodeToKeyIdentifier = { '9': 'Tab', '13': 'Enter', '16': 'Shift', '17': 'Control', '18': 'Alt', '27': 'Escape', '37': 'Left', '38': 'Up', '39': 'Right', '40': 'Down', '46': 'Delete', '91': 'Win' }; /** * @event * @name pc.Keyboard#keydown * @description Event fired when a key is pressed. * @param {pc.KeyboardEvent} event The Keyboard event object. Note, this event is only valid for the current callback. * @example * var onKeyDown = function (e) { * if (e.key === pc.KEY_SPACE) { * // space key pressed * } * e.event.preventDefault(); // Use original browser event to prevent browser action. * }; * app.keyboard.on("keydown", onKeyDown, this); */ /** * @event * @name pc.Keyboard#keyup * @description Event fired when a key is released. * @param {pc.KeyboardEvent} event The Keyboard event object. Note, this event is only valid for the current callback. * @example * var onKeyUp = function (e) { * if (e.key === pc.KEY_SPACE) { * // space key released * } * e.event.preventDefault(); // Use original browser event to prevent browser action. * }; * app.keyboard.on("keyup", onKeyUp, this); */ /** * @name pc.Keyboard * @class A Keyboard device bound to an Element. Allows you to detect the state of the key presses. * Note, Keyboard object must be attached to an Element before it can detect any key presses. * @description Create a new Keyboard object * @param {Element} [element] Element to attach Keyboard to. Note that elements like &lt;div&gt; can't * accept focus by default. To use keyboard events on an element like this it must have a value of 'tabindex' e.g. tabindex="0". For more details: <a href="http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html">http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html</a> * @param {Object} [options] * @param {Boolean} [options.preventDefault] Call preventDefault() in key event handlers. This stops the default action of the event occurring. e.g. Ctrl+T will not open a new browser tab * @param {Boolean} [options.stopPropagation] Call stopPropagation() in key event handlers. This stops the event bubbling up the DOM so no parent handlers will be notified of the event * @example * var keyboard = new pc.Keyboard(window); // attach keyboard listeners to the window */ var Keyboard = function(element, options) { options = options || {}; this._element = null; this._keyDownHandler = this._handleKeyDown.bind(this); this._keyUpHandler = this._handleKeyUp.bind(this); this._keyPressHandler = this._handleKeyPress.bind(this); pc.events.attach(this); this._keymap = {}; this._lastmap = {}; if (element) { this.attach(element); } this.preventDefault = options.preventDefault || false; this.stopPropagation = options.stopPropagation || false; }; /** * @function * @name pc.Keyboard#attach * @description Attach the keyboard event handlers to an Element * @param {Element} element The element to listen for keyboard events on. */ Keyboard.prototype.attach = function (element) { if(this._element) { // remove previous attached element this.detach(); } this._element = element; this._element.addEventListener("keydown", this._keyDownHandler, false); this._element.addEventListener("keypress", this._keyPressHandler, false); this._element.addEventListener("keyup", this._keyUpHandler, false); }; /** * @function * @name pc.Keyboard#detach * @description Detach the keyboard event handlers from the element it is attached to. */ Keyboard.prototype.detach = function () { this._element.removeEventListener("keydown", this._keyDownHandler); this._element.removeEventListener("keypress", this._keyPressHandler); this._element.removeEventListener("keyup", this._keyUpHandler); this._element = null; }; /** * @private * @function * @name pc.Keyboard#toKeyIdentifier * @description Convert a key code into a key identifier * @param {Number} keyCode */ Keyboard.prototype.toKeyIdentifier = function(keyCode){ keyCode = toKeyCode(keyCode); var count; var hex; var length; var id = _keyCodeToKeyIdentifier[keyCode.toString()]; if (id) { return id; } // Convert to hex and add leading 0's hex = keyCode.toString(16).toUpperCase(); length = hex.length; for (count = 0; count < (4 - length); count++) { hex = '0' + hex; } return 'U+' + hex; }; Keyboard.prototype._handleKeyDown = function(event) { var code = event.keyCode || event.charCode; // Google Chrome auto-filling of login forms could raise a malformed event if (code === undefined) return; var id = this.toKeyIdentifier(code); this._keymap[id] = true; // Patch on the keyIdentifier property in non-webkit browsers //event.keyIdentifier = event.keyIdentifier || id; this.fire("keydown", makeKeyboardEvent(event)); if (this.preventDefault) { event.preventDefault(); } if (this.stopPropagation) { event.stopPropagation(); } }; Keyboard.prototype._handleKeyUp = function(event){ var code = event.keyCode || event.charCode; // Google Chrome auto-filling of login forms could raise a malformed event if (code === undefined) return; var id = this.toKeyIdentifier(code); delete this._keymap[id]; // Patch on the keyIdentifier property in non-webkit browsers //event.keyIdentifier = event.keyIdentifier || id; this.fire("keyup", makeKeyboardEvent(event)); if (this.preventDefault) { event.preventDefault(); } if (this.stopPropagation) { event.stopPropagation(); } }; Keyboard.prototype._handleKeyPress = function(event){ var code = event.keyCode || event.charCode; // Google Chrome auto-filling of login forms could raise a malformed event if (code === undefined) return; var id = this.toKeyIdentifier(code); // Patch on the keyIdentifier property in non-webkit browsers //event.keyIdentifier = event.keyIdentifier || id; this.fire("keypress", makeKeyboardEvent(event)); if (this.preventDefault) { event.preventDefault(); } if (this.stopPropagation) { event.stopPropagation(); } }; /** * @private * @function * @name pc.Keyboard#update * @description Called once per frame to update internal state. */ Keyboard.prototype.update = function (dt) { var prop; // clear all keys for (prop in this._lastmap) { delete this._lastmap[prop]; } for(prop in this._keymap) { if(this._keymap.hasOwnProperty(prop)) { this._lastmap[prop] = this._keymap[prop]; } } }; /** * @function * @name pc.Keyboard#isPressed * @description Return true if the key is currently down. * @param {Number} key The keyCode of the key to test. See the pc.KEY_* constants. * @return {Boolean} True if the key was pressed, false if not. */ Keyboard.prototype.isPressed = function (key) { var keyCode = toKeyCode(key); var id = this.toKeyIdentifier(keyCode); return !!(this._keymap[id]); }; /** * @function * @name pc.Keyboard#wasPressed * @description Returns true if the key was pressed since the last update. * @param {Number} key The keyCode of the key to test. See the pc.KEY_* constants. * @return {Boolean} true if the key was pressed. */ Keyboard.prototype.wasPressed = function (key) { var keyCode = toKeyCode(key); var id = this.toKeyIdentifier(keyCode); return (!!(this._keymap[id]) && !!!(this._lastmap[id])); }; /** * @function * @name pc.Keyboard#wasReleased * @description Returns true if the key was released since the last update. * @param {Number} key The keyCode of the key to test. See the pc.KEY_* constants. * @return {Boolean} true if the key was pressed. */ Keyboard.prototype.wasReleased = function (key) { var keyCode = toKeyCode(key); var id = this.toKeyIdentifier(keyCode); return (!!!(this._keymap[id]) && !!(this._lastmap[id])); }; return { Keyboard: Keyboard, KeyboardEvent: KeyboardEvent }; }());
define(["src/dataseries/initialize.js"], function(initialize) { buster.testCase("initialize", { "initialize:": { "'initialize' returns a series initialized to a particular value": function() { buster.assert.equals(initialize(0, 3), [0, 0, 0]); buster.assert.equals(initialize("a", 3), ["a", "a", "a"]); buster.assert.equals(initialize({"a": 0}, 3), [{"a": 0}, {"a": 0}, {"a": 0}]); buster.assert.equals(initialize([1, 2, 3], 3), [[1, 2, 3], [1, 2, 3], [1, 2, 3]]); var data = [0, 1, 2]; buster.assert.equals(initialize(function() { return data.shift(); }, 3), [0, 1, 2]); }, "'initialize' returns a series initialized to clones of 'value'": function() { var data = { a: 0, b: 0 }; var series = initialize(data, 3); data.a = 1; data.b = 2; for (var i = 0; i < 3; i++) { buster.assert.equals(series[i].a, 0); buster.assert.equals(series[i].b, 0); } }, "'initialize' returns a series of length 1 if 'length' is undefined": function() { buster.assert.equals(initialize(0), [0]); buster.assert.equals(initialize("a"), ["a"]); buster.assert.equals(initialize({"a": 0}), [{"a": 0}]); buster.assert.equals(initialize([1, 2, 3]), [[1, 2, 3]]); var data = [0, 1, 2]; buster.assert.equals(initialize(function() { return data.shift(); }), [0]); }, "'initialize' throws if 'length' is provided and is not an integer number > 0": function() { buster.refute.exception(function() { initialize(0, 1); }); buster.assert.exception(function() { initialize(0, 0); }); buster.assert.exception(function() { initialize(0, "a"); }); buster.assert.exception(function() { initialize(0, []); }); buster.assert.exception(function() { initialize(0, function() {}); }); buster.assert.exception(function() { initialize(0, {}); }); buster.assert.exception(function() { initialize(0, null); }); buster.assert.exception(function() { initialize(0, undefined); }); } } }); });
module.exports = require("./webpack.make.examples.config")({ devServer: true });
var gulp = require('gulp'), plumber = require('gulp-plumber'), rename = require('gulp-rename'); var autoprefixer = require('gulp-autoprefixer'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var imagemin = require('gulp-imagemin'), cache = require('gulp-cache'); var minifycss = require('gulp-minify-css'); var sass = require('gulp-sass'); var browserSync = require('browser-sync'); var bourbon = require('node-bourbon').includePaths; gulp.task('browser-sync', function() { browserSync({ server: { baseDir: "./", index: "index.html" } }); }); gulp.task('bs-reload', function () { browserSync.reload(); }); gulp.task('bs-stream', function () { browserSync.stream(); }); gulp.task('images', function(){ gulp.src('img/**/*') .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))) .pipe(gulp.dest('dist/img/')); }); gulp.task('sass', function() { gulp.src(['sass/**/*.scss']) .pipe(plumber({ errorHandler: function(error) { console.log(error.message); this.emit('end'); } })) .pipe(sass({ includePaths: bourbon })) .pipe(autoprefixer('last 2 versions')) .pipe(gulp.dest('dist/styles/')) .pipe(rename({suffix: '.min'})) .pipe(minifycss()) .pipe(gulp.dest('dist/styles/')) }); gulp.task('styles', function(){ gulp.src(['css/**/*.css']) .pipe(plumber({ errorHandler: function (error) { console.log(error.message); this.emit('end'); }})) .pipe(autoprefixer('last 2 versions')) .pipe(gulp.dest('dist/styles/')) .pipe(rename({suffix: '.min'})) .pipe(minifycss()) .pipe(gulp.dest('dist/styles/')) //.pipe(browserSync.stream({match:'**.*.css'})) //.pipe(browserSync.reload({stream:true})) }); gulp.task('scripts', function(){ return gulp.src(['js/**/*.js', 'app/**/*.js']) .pipe(plumber({ errorHandler: function (error) { console.log(error.message); this.emit('end'); }})) .pipe(concat('main.js')) .pipe(gulp.dest('dist/scripts/')) .pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(gulp.dest('dist/scripts/')) //.pipe(browserSync.stream({match:'**.*.css'})) //.pipe(browserSync.reload({stream:true})) }); gulp.task('default', ['browser-sync'], function(){ gulp.watch("css/**/*.css", ['styles', 'bs-reload']); gulp.watch("sass/**/*.scss", ['sass', 'bs-reload']); gulp.watch(['js/**/*.js', 'app/**/*.js'], ['scripts', 'bs-reload']); gulp.watch("*.html", ['bs-reload']); });
function sym(args) { var args = Array.from(arguments); function diff(first, second){ var result = []; first.forEach(function(e){ console.log(e); if(second.indexOf(e) < 0 && result.indexOf(e) < 0){ result.push(e); } }); second.forEach(function(e){ // console.log(second.indexOf(e)); if(first.indexOf(e) < 0 && result.indexOf(e) < 0){ result.push(e); } }); return result; } return args.reduce(diff); } console.log(sym([1, 2, 3], [5, 2, 1, 4]));
(function (Jsonary) { Jsonary.render.Components.add("LIST_LINKS"); Jsonary.render.register({ component: Jsonary.render.Components.LIST_LINKS, update: function (element, data, context, operation) { // We don't care about data changes - when the links change, a re-render is forced anyway. return false; }, renderHtml: function (data, context) { if (!data.readOnly()) { return context.renderHtml(data); } var result = ""; if (context.uiState.editInPlace) { var html = '<span class="button action">save</span>'; result += context.actionHtml(html, "submit"); var html = '<span class="button action">cancel</span>'; result += context.actionHtml(html, "cancel"); result += context.renderHtml(context.uiState.submissionData, '~linkData'); return result; } var links = data.links(); if (links.length) { result += '<span class="link-list">'; for (var i = 0; i < links.length; i++) { var link = links[i]; var html = '<span class="button link">' + Jsonary.escapeHtml(link.title || link.rel) + '</span>'; result += context.actionHtml(html, false, link.href, 'follow-link', i); } result += '</span>'; } if (context.uiState.submitLink != undefined) { var link = data.links()[context.uiState.submitLink]; result += '<div class="prompt-outer"><div class="prompt-inner">'; result += context.actionHtml('<div class="prompt-overlay"></div>', 'cancel'); result += '<div class="prompt-box"><h1>' + Jsonary.escapeHtml(link.title || link.rel) + '</h1><h2>' + Jsonary.escapeHtml(link.method) + " " + Jsonary.escapeHtml(link.href) + '</h2>'; result += '<div>' + context.renderHtml(context.uiState.submissionData, '~linkData') + '</div>'; result += '</div>'; result += '<div class="prompt-buttons">'; result += context.actionHtml('<span class="button">Submit</span>', 'submit'); result += context.actionHtml('<span class="button">cancel</span>', 'cancel'); result += '</div>'; result += '</div></div>'; } result += context.renderHtml(data, "data"); return result; }, action: function (context, actionName, arg1) { if (actionName == "follow-link") { var link = context.data.links()[arg1]; if (link.method == "GET" && link.submissionSchemas.length == 0) { // There's no data to prompt for, and GET links are safe, so we don't put up a dialog link.follow(); return false; } context.uiState.submitLink = arg1; if (link.method == "PUT" && link.submissionSchemas.length == 0) { context.uiState.editing = context.data.editableCopy(); context.uiState.submissionData = context.data.editableCopy(); } else { context.uiState.submissionData = Jsonary.create().addSchema(link.submissionSchemas); link.submissionSchemas.createValue(function (submissionValue) { context.uiState.submissionData.setValue(submissionValue); }); } if (link.method == "PUT") { context.uiState.editInPlace = true; } return true; } else if (actionName == "submit") { var link = context.data.links()[context.uiState.submitLink]; link.follow(context.uiState.submissionData); delete context.uiState.submitLink; delete context.uiState.editInPlace; delete context.uiState.submissionData; return true; } else { delete context.uiState.submitLink; delete context.uiState.editInPlace; delete context.uiState.submissionData; return true; } }, filter: function () { return true; }, saveState: function (uiState, subStates) { var result = {}; for (var key in subStates.data) { result[key] = subStates.data[key]; } if (result.link != undefined || result.inPlace != undefined || result.linkData != undefined || result[""] != undefined) { var newResult = {"":"-"}; for (var key in result) { newResult["-" + key] = result[key]; } result = newResult; } if (uiState.submitLink !== undefined) { var parts = [uiState.submitLink]; parts.push(uiState.editInPlace ? 1 : 0); parts.push(this.saveStateData(uiState.submissionData)); result['link'] = parts.join("-"); } return result; }, loadState: function (savedState) { var uiState = {}; if (savedState['link'] != undefined) { var parts = savedState['link'].split("-"); uiState.submitLink = parseInt(parts.shift()) || 0; if (parseInt(parts.shift())) { uiState.editInPlace = true } uiState.submissionData = this.loadStateData(parts.join("-")); delete savedState['link']; if (!uiState.submissionData) { uiState = {}; } } if (savedState[""] != undefined) { delete savedState[""]; var newSavedState = {}; for (var key in savedState) { newSavedState[key.substring(1)] = savedState[key]; } savedState = newSavedState; } return [ uiState, {data: savedState} ]; } }); })(Jsonary);
// returns null or the Sprite at layer position export function getTileAt(state, { x, y, layerName }) { const layer = state.level.find((i) => i.type === 'tilelayer' && i.name === layerName); if (!layer) { throw new Error(`Could not find tilelayer named "${layerName}"`); } const sprite = state[layerName].children.find((i) => i.x === x && i.y === y); return sprite.data; }
{"filter":false,"title":"claims-service.js","tooltip":"/public/javascripts/claims/claims-service.js","ace":{"folds":[],"scrolltop":0,"scrollleft":0,"selection":{"start":{"row":7,"column":6},"end":{"row":9,"column":11},"isBackwards":true},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"hash":"642d77d78a3999b6905ba5d7cd1ae511852dc6b2","undoManager":{"mark":0,"position":-1,"stack":[]},"timestamp":1419629659986}
'use strict' const path = require('path') const utils = require('./utils') const webpack = require('webpack') const config = require('../config') const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) module.exports = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, extract: true }) }, // cheap-module-eval-source-map is faster for development devtool: '#cheap-module-eval-source-map', output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[hash].js'), chunkFilename: utils.assetsPath('js/[id].[hash].js') }, plugins: [ new webpack.DefinePlugin({ 'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true, chunksSortMode: 'dependency' }), new FriendlyErrorsPlugin(), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] })
var debug = process.env.NODE_ENV !== 'production'; var webpack = require('webpack'); module.exports = { context: __dirname, entry: './src/index.js', output: { path: __dirname, filename: 'index.js' }, module: { loaders: [ { test: /.jsx|js?$/, exclude: /node_modules/, loaders: [ 'babel-loader?presets[]=es2015,presets[]=stage-0,presets[]=react,plugins[]=transform-decorators-legacy', 'eslint-loader' ] }, { test: /.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader'] } ] }, plugins: debug ? [ new webpack.DefinePlugin({ DOMAIN_NAME: "'http://localhost:3000'" }) ] : [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), new webpack.DefinePlugin({ DOMAIN_NAME: "'https://www.pacdiv.io'" }) ], };
/** * i18n-lint json reporter tests * * Copyright (c) 2015 James Warwood * Licensed under the MIT license. */ /* global describe, it */ /* jshint -W030 */ 'use strict'; var expect = require('chai').expect; var fs = require('fs'); var hooker = require('hooker'); var stripAnsi = require('strip-ansi'); var reporter = require('../../../lib/reporters/json.js'); var errors = require('../../fixtures/errors/1.js')(); describe('i18n-lint reporters json', function() { it('should format the output correctly', function(done) { var actual = ''; hooker.hook(process.stdout, 'write', { pre: function(out) { actual += stripAnsi(out); return hooker.preempt(); } }); var expected = fs.readFileSync( __dirname + '/../../expected/reporters/json.txt' ).toString().replace(/\r/gi,''); // Execute method under test reporter(errors); hooker.unhook(process.stdout, 'write'); expect(actual).to.equal(expected); // Test that valid json is output expect(JSON.stringify.bind(JSON, actual)).not.throw(); done(); }); it('should not output anything if there are no errors', function(done) { var actual = ''; hooker.hook(process.stdout, 'write', { pre: function(out) { actual += stripAnsi(out); return hooker.preempt(); } }); // Execute method under test reporter([]); hooker.unhook(process.stdout, 'write'); expect(actual).to.equal(''); done(); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware, compose } from 'redux'; //import { createLogger } from 'redux-logger'; import './assets/production/css/style.css'; import App from './App'; import reducer from './reducers'; //const loggerMiddleware = createLogger(); function configureStore(initialState, reducer) { const enhancer = compose( applyMiddleware( //thunkMiddleware, //loggerMiddleware, ), ); return createStore(reducer, initialState, enhancer); } const store = configureStore({}, reducer); const AppContainer = () => ( <Provider store={store}> <App className="App" /> </Provider> ); ReactDOM.render(<AppContainer />, document.getElementById('root'));
import thunkMiddleware from 'redux-thunk'; import { createLogger } from 'redux-logger'; import { createStore, applyMiddleware } from 'redux'; import rootReducer from '../reducers'; export default function configureStore() { const loggerMiddleware = createLogger(); // Middleware // Only enable loggerMiddleware in debug mode const createStoreWithMiddleware = applyMiddleware( thunkMiddleware, loggerMiddleware )(createStore); const store = createStoreWithMiddleware(rootReducer); return store; }
import React, { PropTypes } from 'react' const Link = ({ active, children, onClick }) => { if (active) { return <span>{children}</span> } return ( <Text> Hi </Text> ) } Link.propTypes = { active: PropTypes.bool.isRequired, children: PropTypes.node.isRequired, onClick: PropTypes.func.isRequired } export default Link
var enums = require('../../enums.json'), generic = require('../generic'); var url = require('url'), request = require('supertest'); var rootUrl = url.format(enums.options); request = request(rootUrl); //Data for creation of question comment var createData = { text: 'question comment text', author: 'my author name' }; var updateData = { text: 'New questioncomment text', author: 'my New author name' }; // Set the ETag we get back for question 1, so we can use it for testing // in cacheCheck for the same question. var question1ETag; exports.create = function (test, doNotRun) { var returner = {}, path = '/question/1/comments', data = createData; returner.path = path; returner.data = data; if (!doNotRun) { request .post(path) .send(data) .expect(201) .end(function (err, res) { if (err) { console.log(err.message); } var valid = generic.valid(err, data, res.body.question_comment); test.ok(valid); test.done(); }); } return returner; }; exports.get = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/1'; returner.path = path; // If doNotRun flag not defined or false, // then make the request. if (!doNotRun) { request .get(path) .expect(200) .end(function (err, res) { if (err) { console.log(err.message); } question1ETag = res.get(enums.eTag); var valid = generic.valid(err, createData, res.body.question_comment); test.ok(valid); test.done(); }); } return returner; }; // If-None-Match check with ETag for resource on server. exports.cacheCheck = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/1'; returner.path = path; // If doNotRun flag not defined or false, // then make the request. if (!doNotRun) { request .get(path) .set('If-None-Match', question1ETag) .expect(304) .end(function (err, res) { if (err) { console.log(err.message); } test.ok(!err); test.done(); }); } return returner; }; exports.update = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/1', data = updateData; returner.path = path; returner.data = data; if (!doNotRun) { request .put(path) .send(data) .expect(204) .end(function (err, res) { if (err) { console.log(err.message); } test.ok(!err); test.done(); }); } return returner; }; exports.get_after_update = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/1', data = updateData; returner.path = path; if (!doNotRun) { request .get(path) .expect(200) .end(function (err, res) { if (err) { console.log(err.message); } var valid = generic.valid(err, data, res.body.question_comment); test.ok(valid); test.done(); }); } return returner; }; // Head after update exports.head = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/1'; returner.path = path; if (!doNotRun) { request .get(path) .expect(200) .end(function (err, res) { if (err) { console.log(err.message); } test.ok(!err); test.done(); }); } return returner; }; exports.create2 = function (test, doNotRun) { var returner = {}, path = '/question/1/comments', data = createData; returner.path = path; returner.data = data; if (!doNotRun) { request .post(path) .send(data) .expect(201) .end(function (err, res) { if (err) { console.log(err.message); } var valid = generic.valid(err, data, res.body.question_comment); test.ok(valid); test.done(); }); } return returner; }; exports.remove = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/2'; returner.path = path; if (!doNotRun) { request .del(path) .expect(204) .end(function (err, res) { if (err) { console.log(err.message); } test.ok(!err); test.done(); }); } return returner; }; exports.get_after_remove = function (test, doNotRun) { var returner = {}, path = '/question/1/comment/2', data = createData; returner.path = path; // If doNotRun flag not defined or false, // then make the request. if (!doNotRun) { request .post(path) .send(data) .expect(404) .end(function (err, res) { if (err) { console.log(err.message); } test.ok(!err); test.done(); }); } return returner; }; exports.create_lastly = function (test, doNotRun) { var returner = {}, path = '/question/1/comments', data = createData; returner.path = path; returner.data = data; if (!doNotRun) { request .post(path) .send(data) .expect(201) .end(function (err, res) { if (err) { console.log(err.message); } var valid = generic.valid(err, data, res.body.question_comment); test.ok(valid); test.done(); }); } return returner; }; //Get all comments exports.all = function (test, doNotRun) { var returner = {}, path = '/question/1/comments', expected = [updateData, createData]; returner.path = path; // If doNotRun flag not defined or false, // then make the request. if (!doNotRun) { request .get(path) .expect(200) .end(function (err, res) { if (err) { console.log(err.message); } var valid = generic.validArray(err, expected, res.body.question_comments); test.ok(valid); test.done(); }); } return returner; };
// We really need this thing to send GLOBAL ui event messages. // It might not be nicely done but it does its job so far KineticUI.Event = { _blur : null, blur : function(object){ if (!this._blur) { KineticUI.trace('ui_blur event is not set up', true); return; } else if (object) { this._blur.object = object; window.dispatchEvent(this._blur); } else return this._blur.type; } }; if (document.createEvent) { KineticUI.Event._blur = document.createEvent('Event'); KineticUI.Event._blur.initEvent('ui_blur', true, true); } else { KineticUI.Event._blur = new CustomEvent('ui_blur',{bubbles:true,cancelable:true}); }
/* smooth scroll to anchor */ // uses history to keep back/forward button working $(function(){ $('a[href*="#"]').click(function(event) { var aid = $(this).attr('href').split('#')[1]; var dom_aid = (aid == '') ? 'home' : aid; var $destination = $('a[name="'+ dom_aid +'"], #' + dom_aid).first(); if ( $destination.length ){ event.preventDefault(); history.pushState({}, "", '#'+aid); var navbar_height = $('.navbar-fixed-top').height(); $('html,body').animate({scrollTop: $destination.offset().top - navbar_height},'fast'); } }); }); /* navbar active class */ $(function(){ $('.nav.navbar-nav a').on('click', function(){ $(this).parents('.nav.navbar-nav').find('.active').removeClass('active'); $(this).parent().addClass('active'); }); }); /* prevent the-alligator form from submitting */ $(function(){ $('#spit').css({ 'opacity': 1, 'display': 'block' }); var oTable = $('#results').dataTable({ "aoColumnDefs": [ { "aTargets": [ 1 ], "mRender": function ( data, type, full ) { return data.toString().toHHMMSS(); } } ], 'fnDrawCallback': function( oData ) { var total_events = 0, total_time = 0; for(var i=0; i<oData.aiDisplay.length; i++) { var row_data = oData.aoData[oData.aiDisplay[i]]._aData; total_events += row_data[2]; total_time += row_data[1]; } $(this).find('tfoot #total_events').html(total_events); $(this).find('tfoot #total_time').html(total_time.toString().toHHMMSS()); }, "sDom": 'T<"clear">lfrtip', "oTableTools": { } }); setTimeout(function(){ $('#spit').css({ 'opacity': 0, 'display': 'none' }); }, 200); $('form#the-alligator').on('submit', function(event){ event.preventDefault(); render(parse_food($(this).find('#food').val())); }); $('form#the-alligator #reset').on('click', function(event){ event.preventDefault(); reset(); }); }); /* Some useful classes */ var TimePoint = (function(spec, spec2) { var year, month, day, hour, min, sec; var fields = ['year', 'month', 'day', 'hour', 'min', 'sec']; var date; var i; /** * @constructor * @param spec another TimePoint to copy data from OR spec2 * @param spec2 object of format: {year: 2014, month: 12, day: 28, hour: 23, min: 54, sec: 40} All fields required unless spec is specified. */ function TimePoint(spec, spec2) { /* if user accidentally omits the new keyword, this will silently correct the problem */ if ( !(this instanceof TimePoint) ) return new TimePoint(spec, spec2); /* clone from another TimePoint */ if ( spec instanceof TimePoint) { for (i=0; i<fields.length; i++){ this[fields[i]] = spec[fields[i]]; } spec = spec2; } /* set provided data */ if ( typeof spec !== 'undefined' ) { for (i=0; i<fields.length; i++){ if (typeof spec[fields[i]] !== 'undefined') { this[fields[i]] = spec[fields[i]]; } } } this.date = new Date(this.year, this.month - 1, this.day, this.hour, this.min, this.sec); } /** * @returns {Array} */ TimePoint.prototype.arr = function() { var arr = []; for (i=0; i<fields.length; i++){ arr.push(this[fields[i]]); } return arr; }; /** * @returns {string} */ TimePoint.prototype.repr = function() { return this.arr().join('-'); }; TimePoint.prototype.clone = function() { return new TimePoint(this, {}); }; /** * Unix Epoch seconds * @returns {number} */ TimePoint.prototype.timestamp = function() { return this.date.getTime() / 1000; }; return TimePoint; })(); var TimeInterval = (function(tp_start, tp_stop){ function TimeInterval(tp_start, tp_stop) { /* if user accidentally omits the new keyword, this will silently correct the problem */ if ( !(this instanceof TimeInterval) ) return new TimeInterval(tp_start, tp_stop); this.tp_start = tp_start.clone(); this.tp_stop = tp_stop.clone(); } TimeInterval.prototype.seconds = function() { return this.tp_stop.timestamp() - this.tp_start.timestamp() }; return TimeInterval; })(); var CalEvent = (function(name){ function CalEvent(name) { /* if user accidentally omits the new keyword, this will silently correct the problem */ if ( !(this instanceof CalEvent) ) return new CalEvent(name); this.name = name; } CalEvent.prototype.set_start = function(tp_start) { this.tp_start = tp_start; this.try_set_interval(); }; CalEvent.prototype.set_stop = function(tp_start) { this.tp_stop = tp_start; this.try_set_interval(); }; CalEvent.prototype.try_set_interval = function() { if (this.tp_start instanceof TimePoint && this.tp_stop instanceof TimePoint) { this.ti = new TimeInterval(this.tp_start, this.tp_stop); } }; CalEvent.prototype.seconds = TimeInterval.prototype.seconds; return CalEvent; })(); /* handle formats storage and fetching */ $(function(){ var $select = $('#datetime_format'); var $custom_datetime = $('#custom_datetime'); var $custom_time = $('#custom_time'); var config_pack = function() { return { 'select': $select.val(), 'custom_datetime': $custom_datetime.val(), 'custom_time': $custom_time.val() } }; var config_unpack = function(config) { $select.val( config['select'] ); $custom_datetime.val( config['custom_datetime'] ); $custom_time.val( config['custom_time'] ); }; var fetch_config_from_cookie = function() { var format_config = $.cookie('format_config'); if (typeof format_config !== 'undefined') { config_unpack(JSON.parse(format_config)); } }; var save_config_to_cookie = function() { var format_config = config_pack(); $.cookie( 'format_config', JSON.stringify(format_config), { expires: 365 } ); }; var format_change_handler = function() { save_config_to_cookie(); }; $select.on('input change', format_change_handler); $custom_datetime.on('input change', format_change_handler); $custom_time.on('input change', format_change_handler); fetch_config_from_cookie(); }); /* handle show-hide for custom format inputs */ $(function(){ var $select = $('#datetime_format'); var $custom_box = $('#custom_box'); $custom_box.hide(); var toggle_the_custom_box = function() { if ($select.val() == 'custom') { $custom_box.show(); } else { $custom_box.hide(); } }; $select.on('input change', function() { toggle_the_custom_box(); }); toggle_the_custom_box(); }); /* parse the alligator food */ var parse_food = function(food) { var lines = food.split(/\n/); var events = [], aggregate = {}; var i, time_strings; var DATETIME_FORMAT = $('#datetime_format :selected').data('datetimeformat'); var TIME_FORMAT = $('#datetime_format :selected').data('timeformat'); if (DATETIME_FORMAT == 'custom') { DATETIME_FORMAT = $('#custom_datetime').val(); TIME_FORMAT = $('#custom_time').val(); } // TODO allow other languages ("to" and "Scheduled:") var SEPARATOR = ' to '; var parse_ical_datetime = function(datetime) { datetime = datetime.trim(); var the_moment = moment(datetime, TIME_FORMAT, true); // strict var what_data = 'time'; if (!the_moment.isValid()) { the_moment = moment(datetime, DATETIME_FORMAT, true); // strict what_data = 'datetime'; } if (!the_moment.isValid()) { if (console) { console.warn("cant parse: " + datetime); console.debug("used format: " + ((what_data == 'datetime') ? DATETIME_FORMAT : TIME_FORMAT)); //TODO: report the error to user, limit number of error messages } } var data = {}; if (what_data == 'datetime') { data['day'] = the_moment.format('D'); data['month'] = the_moment.format('M'); data['year'] = the_moment.format('YYYY'); } data['hour'] = the_moment.format('H'); data['min'] = the_moment.format('m'); data['sec'] = the_moment.format('s'); return data; }; var last_row = 'empty'; var tp_start, tp_stop; for (i=0; i<lines.length; i++) { var line = lines[i]; if (! line.trim().length) { last_row = 'empty'; continue; } if (last_row === 'empty') { last_row = new CalEvent(line.trim()); continue; } if (last_row instanceof CalEvent) { line = line.trim().replace('Scheduled: ', ''); time_strings = line.split(SEPARATOR); tp_start = TimePoint(parse_ical_datetime(time_strings[0])); tp_stop = TimePoint(tp_start, parse_ical_datetime(time_strings[1])); last_row.set_start(tp_start); last_row.set_stop(tp_stop); events.push(last_row); last_row = false; } } for (i=0; i<events.length; i++) { var event = events[i]; if (typeof aggregate[event.name] === 'undefined') { aggregate[event.name] = {'seconds': 0, 'events': []}; } aggregate[event.name]['seconds'] += event.seconds(); aggregate[event.name]['events'].push(event); } return aggregate; }; var render = function(aggregate) { var $results = $('#results'); $results.dataTable().fnClearTable(); for(var key in aggregate) { if (aggregate.hasOwnProperty(key)){ $results.dataTable().fnAddData([ key, aggregate[key]['seconds'], aggregate[key]['events'].length ]); } } var $alligator = $('#the-alligator'); var $food_tray = $alligator.find('#food-tray'); var $spit = $alligator.find('#spit'); $spit.show(); $alligator.animate({'height': $spit.height()}, 500); $spit.css({'opacity': 0}); $food_tray.animate({'opacity': 0}, 500); $spit.animate({'opacity': 1}, 500, function(){ $('#food').val(''); }); $spit.css({'position': 'absolute'}); $food_tray.css({'position': 'absolute'}); }; var reset = function(aggregate) { var $alligator = $('#the-alligator'); var $food_tray = $alligator.find('#food-tray'); var $spit = $alligator.find('#spit'); $food_tray.show(); $alligator.animate({'height': $food_tray.height()}, 500); $food_tray.css({'opacity': 0}); $spit.animate({'opacity': 0}, 500, function(){$spit.hide();}); $food_tray.animate({'opacity': 1}, 500); $food_tray.css({'position': 'absolute'}); $spit.css({'position': 'absolute'}); };
var KeyGame = (function(keygame) { keygame.Router.RoutesManager = Backbone.Router.extend({ initialize: function(args) { //this.collection = args.collection; //console.log("this.collection", this.collection); }, routes: { "hello" : "hello", "*path" : "root" }, root: function() { var that = this; console.log("Routes root"); /* this.collection.all().fetch({ success: function(result) { mainView.render(result); } }); */ }, hello: function() { $("h1").html("Hello World !!!"); } }); return keygame; }(KeyGame));
Ext.define('Ext.window.WindowActiveCls', { override: 'Ext.window.Window', statics: { _activeWindow: null }, shadow: false, ui: 'blue-window-active', border: false, setActive: function (active, newActive) { var me = this; if (!me.el) return; if (active) { me.addCls('x-window-active'); var paw = Ext.window.Window._activeWindow; Ext.window.Window._activeWindow = me; if (paw && paw != me && paw.el) { paw.removeCls('x-window-active'); } } else { me.removeCls('x-window-active'); } this.callParent(arguments); } });
// All symbols in the Miscellaneous Symbols block as per Unicode v10.0.0: [ '\u2600', '\u2601', '\u2602', '\u2603', '\u2604', '\u2605', '\u2606', '\u2607', '\u2608', '\u2609', '\u260A', '\u260B', '\u260C', '\u260D', '\u260E', '\u260F', '\u2610', '\u2611', '\u2612', '\u2613', '\u2614', '\u2615', '\u2616', '\u2617', '\u2618', '\u2619', '\u261A', '\u261B', '\u261C', '\u261D', '\u261E', '\u261F', '\u2620', '\u2621', '\u2622', '\u2623', '\u2624', '\u2625', '\u2626', '\u2627', '\u2628', '\u2629', '\u262A', '\u262B', '\u262C', '\u262D', '\u262E', '\u262F', '\u2630', '\u2631', '\u2632', '\u2633', '\u2634', '\u2635', '\u2636', '\u2637', '\u2638', '\u2639', '\u263A', '\u263B', '\u263C', '\u263D', '\u263E', '\u263F', '\u2640', '\u2641', '\u2642', '\u2643', '\u2644', '\u2645', '\u2646', '\u2647', '\u2648', '\u2649', '\u264A', '\u264B', '\u264C', '\u264D', '\u264E', '\u264F', '\u2650', '\u2651', '\u2652', '\u2653', '\u2654', '\u2655', '\u2656', '\u2657', '\u2658', '\u2659', '\u265A', '\u265B', '\u265C', '\u265D', '\u265E', '\u265F', '\u2660', '\u2661', '\u2662', '\u2663', '\u2664', '\u2665', '\u2666', '\u2667', '\u2668', '\u2669', '\u266A', '\u266B', '\u266C', '\u266D', '\u266E', '\u266F', '\u2670', '\u2671', '\u2672', '\u2673', '\u2674', '\u2675', '\u2676', '\u2677', '\u2678', '\u2679', '\u267A', '\u267B', '\u267C', '\u267D', '\u267E', '\u267F', '\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685', '\u2686', '\u2687', '\u2688', '\u2689', '\u268A', '\u268B', '\u268C', '\u268D', '\u268E', '\u268F', '\u2690', '\u2691', '\u2692', '\u2693', '\u2694', '\u2695', '\u2696', '\u2697', '\u2698', '\u2699', '\u269A', '\u269B', '\u269C', '\u269D', '\u269E', '\u269F', '\u26A0', '\u26A1', '\u26A2', '\u26A3', '\u26A4', '\u26A5', '\u26A6', '\u26A7', '\u26A8', '\u26A9', '\u26AA', '\u26AB', '\u26AC', '\u26AD', '\u26AE', '\u26AF', '\u26B0', '\u26B1', '\u26B2', '\u26B3', '\u26B4', '\u26B5', '\u26B6', '\u26B7', '\u26B8', '\u26B9', '\u26BA', '\u26BB', '\u26BC', '\u26BD', '\u26BE', '\u26BF', '\u26C0', '\u26C1', '\u26C2', '\u26C3', '\u26C4', '\u26C5', '\u26C6', '\u26C7', '\u26C8', '\u26C9', '\u26CA', '\u26CB', '\u26CC', '\u26CD', '\u26CE', '\u26CF', '\u26D0', '\u26D1', '\u26D2', '\u26D3', '\u26D4', '\u26D5', '\u26D6', '\u26D7', '\u26D8', '\u26D9', '\u26DA', '\u26DB', '\u26DC', '\u26DD', '\u26DE', '\u26DF', '\u26E0', '\u26E1', '\u26E2', '\u26E3', '\u26E4', '\u26E5', '\u26E6', '\u26E7', '\u26E8', '\u26E9', '\u26EA', '\u26EB', '\u26EC', '\u26ED', '\u26EE', '\u26EF', '\u26F0', '\u26F1', '\u26F2', '\u26F3', '\u26F4', '\u26F5', '\u26F6', '\u26F7', '\u26F8', '\u26F9', '\u26FA', '\u26FB', '\u26FC', '\u26FD', '\u26FE', '\u26FF' ];
Statistics.Controller.ProjectionController = Statistics.Class(Statistics.Controller, { /** * @private * @property {Statistics.Repository.Request} * Represents the request in progress */ requestObj: null, /** * @constructor * @param {Statistics.Model.Configuration} configuration * @param {Statistics.Repository} repository * @param {Statistics.View} control - The view/control to represent this controller/representation */ _init: function(configuration, repository, view) { Statistics.Controller.prototype._init.apply(this, arguments); // Register some events to configuration this.configuration.events.bind ( 'config::projectedDimensionsChanged', jQuery.proxy(this.onRenderData, this)); }, /** * abstract method. Renders the control and requests for data * @protected * @function * @retutns {Boolean} returns true, if there's filters to request data. False otherwise */ onRenderData: function() { var hasData = Statistics.Controller.prototype.onRenderData.apply(this, arguments); if(!hasData) return false; if(this.requestObj) this.requestObj.cancelRequest(); var metadata = this.configuration.getMetadata(); this.requestObj = this.repository.getIndicatorValues( metadata.sourceid, metadata.id, this.configuration.getDimensionsFilterConfig().getSelectedDimensions(), this.configuration.getSelectedDimensions(), { successCallback: jQuery.proxy(this._complete, this), errorCallback: jQuery.proxy(this._error, this) } ); return true; }, /** * @private * @function * @param {Statistics.Model.ServerData.DataSerie} data * Callback function. Called when the server responds with chart data */ _complete: function(data){ this.view.setData(data); }, /** * @private * @function * * MUST BE IMPLEMENTED... */ _fail: function(){ /*TODO: Do something... Cannot get data from the server*/ alert('Ups... Erro!'); } });
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function (mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); else // Plain browser env mod(CodeMirror); })(function (CodeMirror) { "use strict"; var defaultTags = { script: [ ["lang", /(javascript|babel)/i, "javascript"], ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"], ["type", /./, "text/plain"], [null, null, "javascript"] ], style: [ ["lang", /^css$/i, "css"], ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], ["type", /./, "text/plain"], [null, null, "css"] ] }; function maybeBackup(stream, pat, style) { var cur = stream.current(), close = cur.search(pat); if (close > -1) { stream.backUp(cur.length - close); } else if (cur.match(/<\/?$/)) { stream.backUp(cur.length); if (!stream.match(pat, false)) stream.match(cur); } return style; } var attrRegexpCache = {}; function getAttrRegexp(attr) { var regexp = attrRegexpCache[attr]; if (regexp) return regexp; return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); } function getAttrValue(text, attr) { var match = text.match(getAttrRegexp(attr)); return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" } function getTagRegexp(tagName, anchored) { return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); } function addTags(from, to) { for (var tag in from) { var dest = to[tag] || (to[tag] = []); var source = from[tag]; for (var i = source.length - 1; i >= 0; i--) dest.unshift(source[i]) } } function findMatchingMode(tagInfo, tagText) { for (var i = 0; i < tagInfo.length; i++) { var spec = tagInfo[i]; if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; } } CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { var htmlMode = CodeMirror.getMode(config, { name: "xml", htmlMode: true, multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag }); var tags = {}; var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; addTags(defaultTags, tags); if (configTags) addTags(configTags, tags); if (configScript) for (var i = configScript.length - 1; i >= 0; i--) tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) function html(stream, state) { var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName; if (tag && !/[<>\s\/]/.test(stream.current()) && (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && tags.hasOwnProperty(tagName)) { state.inTag = tagName + " " } else if (state.inTag && tag && />$/.test(stream.current())) { var inTag = /^([\S]+) (.*)/.exec(state.inTag); state.inTag = null; var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]); var mode = CodeMirror.getMode(config, modeSpec); var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); state.token = function (stream, state) { if (stream.match(endTagA, false)) { state.token = html; state.localState = state.localMode = null; return null; } return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); }; state.localMode = mode; state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "")); } else if (state.inTag) { state.inTag += stream.current(); if (stream.eol()) state.inTag += " " } return style; } return { startState: function () { var state = CodeMirror.startState(htmlMode); return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; }, copyState: function (state) { var local; if (state.localState) { local = CodeMirror.copyState(state.localMode, state.localState); } return { token: state.token, inTag: state.inTag, localMode: state.localMode, localState: local, htmlState: CodeMirror.copyState(htmlMode, state.htmlState) }; }, token: function (stream, state) { return state.token(stream, state); }, indent: function (state, textAfter) { if (!state.localMode || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter); else if (state.localMode.indent) return state.localMode.indent(state.localState, textAfter); else return CodeMirror.Pass; }, innerMode: function (state) { return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; } }; }, "xml", "javascript", "css"); CodeMirror.defineMIME("text/html", "htmlmixed"); });
(function($R) { $R.add('plugin', 'handle', { init: function(app) { this.app = app; this.opts = app.opts; this.$doc = app.$doc; this.$body = app.$body; this.editor = app.editor; this.marker = app.marker; this.keycodes = app.keycodes; this.container = app.container; this.selection = app.selection; // local this.handleTrigger = (typeof this.opts.handleTrigger !== 'undefined') ? this.opts.handleTrigger : '@'; this.handleStart = (typeof this.opts.handleStart !== 'undefined') ? this.opts.handleStart : 0; this.handleStr = ''; this.handleLen = this.handleStart; }, // public start: function() { if (!this.opts.handle) return; var $editor = this.editor.getElement(); $editor.on('keyup.redactor-plugin-handle', this._handle.bind(this)); }, stop: function() { var $editor = this.editor.getElement(); $editor.off('.redactor-plugin-handle'); this.$doc.off('.redactor-plugin-handle'); var $list = $R.dom('#redactor-handle-list'); $list.remove(); }, // private _handle: function(e) { var key = e.which; var ctrl = e.ctrlKey || e.metaKey; var arrows = [37, 38, 39, 40]; if (key === this.keycodes.BACKSPACE) { if (this._isShown() && (this.handleLen > this.handleStart)) { this.handleLen = this.handleLen - 2; if (this.handleLen <= this.handleStart) { this._hide(); } } else { return; } } if (key === this.keycodes.DELETE || key === this.keycodes.ESC || key === this.keycodes.SHIFT || ctrl || (arrows.indexOf(key) !== -1) ) { return; } var re = new RegExp('^' + this.handleTrigger); this.handleStr = this.selection.getTextBeforeCaret(this.handleLen + 1); // detect if (re.test(this.handleStr)) { this.handleStr = this.handleStr.replace(this.handleTrigger, ''); this.handleLen++; this._load(); } }, _load: function() { $R.ajax.post({ url: this.opts.handle, data: 'handle=' + this.handleStr, success: this._parse.bind(this) }); }, _parse: function(json) { if (json === '') return; var data = (typeof json === 'object') ? json : JSON.parse(json); this._build(); this._buildData(data); }, _build: function() { this.$list = $R.dom('#redactor-handle-list'); if (this.$list.length === 0) { this.$list = $R.dom('<div id="redactor-handle-list">'); this.$body.append(this.$list); } }, _buildData: function(data) { this.data = data; this._update(); this._show(); }, _update: function() { this.$list.html(''); for (var key in this.data) { var $item = $R.dom('<a href="#">'); $item.html(this.data[key].item); $item.attr('data-key', key); $item.on('click', this._replace.bind(this)); this.$list.append($item); } // position var $container = this.container.getElement(); var containerOffset = $container.offset(); var pos = this.selection.getPosition(); this.$list.css({ top: (pos.top + pos.height + this.$doc.scrollTop()) + 'px', left: pos.left + 'px' }); }, _isShown: function() { return (this.$list && this.$list.hasClass('open')); }, _show: function() { this.$list.addClass('open'); this.$list.show(); this.$doc.off('.redactor-plugin-handle'); this.$doc.on('click.redactor-plugin-handle keydown.redactor-plugin-handle', this._hide.bind(this)); }, _hide: function(e) { var hidable = false; var key = (e && e.which); if (!e) hidable = true; else if (e.type === 'click' || key === this.keycodes.ESC || key === this.keycodes.ENTER || key === this.keycodes.SPACE) hidable = true; if (hidable) { this.$list.removeClass('open'); this.$list.hide(); this._reset(); } }, _reset: function() { this.handleStr = ''; this.handleLen = this.handleStart; }, _replace: function(e) { e.preventDefault(); var $item = $R.dom(e.target); var key = $item.attr('data-key'); var replacement = this.data[key].replacement; var marker = this.marker.insert('start'); var $marker = $R.dom(marker); var current = marker.previousSibling; var currentText = current.textContent; var re = new RegExp('@' + this.handleStr + '$'); currentText = currentText.replace(re, ''); current.textContent = currentText; $marker.before(replacement); this.selection.restoreMarkers(); return; } }); })(Redactor);
import { toggleClass } from 'vuikit/src/util/class' import { assign } from 'vuikit/src/util/lang' import { ElementGrid } from '../elements' import VkMargin from 'vuikit/src/library/margin' export default { name: 'VkGrid', directives: { VkMargin }, props: assign({}, ElementGrid.props, { margin: { type: String, default: 'uk-grid-margin' }, firstColumn: { type: String, default: 'uk-first-column' } }), render (h) { const clsStack = 'uk-grid-stack' const { margin, firstColumn } = this return h(ElementGrid, { props: this.$props, directives: [{ name: 'vk-margin', value: { margin, firstColumn, onUpdate: (el, { stacks }) => { toggleClass(el, clsStack, stacks) } } }] }, this.$slots.default) } }
// @flow import React from 'react' import Cinput from './Cinput' class Child extends React.Component { handleChange = (e: KeyboardEvent) => { if (e.target instanceof HTMLInputElement) { this.props.onItemInput(e) } } render() { return ( <div> <Cinput placeholder={this.props.placeholder} onChange={this.handleChange}/> </div> ) } } Child.propTypes = { placeholder: React.PropTypes.string.isRequired, onItemInput: React.PropTypes.func.isRequired, } export default Child
cordova.commandProxy.add("NotificationHubs", { register: function (successCallback, errorCallback, args) { AzureNotificationHubs.AzureNotificationHubs.register(args[0].hubname, args[0].endpoint).done(function (result) { successCallback(result); }); }, unRegister: function (successCallback, errorCallback, args) { AzureNotificationHubs.AzureNotificationHubs.unRegister(args[0].hubname, args[0].endpoint).done(function (result) { successCallback(result); }); } });
exports.tokens = require('./tokens'); exports.signing = require('./signing');
$(document).ready(function(){ $("#add_err").css('display', 'none', 'important'); $("#loginbtn").click(function(){ var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: "POST", url: "proccesLogin.php", data: "username="+username+"&password="+password, success: function(html){ if(html!=null){ // Get the modal var modal = document.getElementById('signin'); modal.style.display = "none"; //reload nav bar $("#add_error").css('display', 'none', 'important'); $('#signinForm')[0].reset(); $('#navlog').load(document.URL + ' #navlog'); $('#logout').click(); } else { $("#add_err").css('display', 'inline', 'important'); $("#add_err").html(html); } }, beforeSend:function(){ $("#add_err").css('display', 'inline', 'important'); } }); return false; }); });
const { BASIC_EXTENSION_MAP } = require('../../output-gitignore/library/common/module/MIME.js') const { responderSendBufferCompress, prepareBufferData } = require('../../output-gitignore/library/node/server/Responder/Send.js') const { COMMON_LAYOUT, COMMON_STYLE, COMMON_SCRIPT } = require('../../output-gitignore/library/common/module/HTML.js') const createExampleServerHTMLResponder = () => { const bufferData = prepareBufferData(Buffer.from(COMMON_LAYOUT([ '<title>Example Server</title>', COMMON_STYLE() ], [ COMMON_SCRIPT({ onload: mainScriptInit }) ])), BASIC_EXTENSION_MAP.html) return (store) => responderSendBufferCompress(store, bufferData) } const mainScriptInit = () => { const { document, location, WebSocket, qS, cE, aCL } = window aCL(document.body, [ cE('button', { innerText: 'createWebSocket', onclick: () => createWebSocket() }), cE('button', { innerText: 'testWebSocket', onclick: () => testWebSocket() }), cE('button', { innerText: 'closeWebSocket', onclick: () => closeWebSocket() }), cE('pre', { id: 'log', innerText: 'LOG' }), cE('button', { innerText: 'clear Log', onclick: () => qS('#log', '') }) ]) const log = (...args) => { console.log(...args) qS('#log').innerHTML += '\n' + args.join(' ') } const createWebSocket = () => { closeWebSocket() const socket = new WebSocket( `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}`, [ 'json', 'a', 'b', encodeURIComponent('auth-token!0123ABCD') ] ) socket.addEventListener('open', (event) => log('open', socket, event)) socket.addEventListener('error', (event) => log('error', event)) socket.addEventListener('close', (event) => log('close', event)) socket.addEventListener('message', (event) => log('message', event, typeof (event.data), typeof (event.data) === 'string' ? event.data.length : event.data.size)) setCurrentSocket(socket) } const testWebSocket = () => { const socket = getCurrentSocket() if (!socket) return if (socket.readyState !== WebSocket.OPEN) return log(`[testWebSocket] wrong readyState ${socket.readyState}`) socket.send('[TEXT]123!@#abc<>\\\n!@#$%^&*()_+') socket.send(document.body.innerHTML) socket.send('BIG STRING') socket.send('BIG BUFFER') } const closeWebSocket = () => { const socket = getCurrentSocket() if (!socket) return if (socket.readyState !== WebSocket.OPEN) return log(`[closeWebSocket] wrong readyState ${socket.readyState}`) socket.send('CLOSE') setCurrentSocket(null) } let currentSocket = null const setCurrentSocket = (socket) => (currentSocket = socket) const getCurrentSocket = () => currentSocket } module.exports = { createExampleServerHTMLResponder }
var User = require('../models/users.js'); var jwt = require('jwt-simple'); module.exports = function(app, req, res, next) { var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token']; if (token) { try { var decoded = jwt.decode(token, app.get('superSecret')); if (decoded.exp <= Date.now()) { res.end('Access token has expired', 400); } User.findOne({ _id: decoded.iss }, function(err, user) { req.user = user; }); } catch (err) { return next(); } } else { next(); } };
var io = require('socket.io-client'); var ChatClient = require('./chat-client'); var Canvas = require('./canvas'); var global = require('./global'); var playerNameInput = document.getElementById('playerNameInput'); var socket; var reason; var debug = function(args) { if (console && console.log) { console.log(args); } }; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { global.mobile = true; } function startGame(type) { global.playerName = playerNameInput.value.replace(/(<([^>]+)>)/ig, '').substring(0, 25); global.playerType = type; global.screenWidth = window.innerWidth; global.screenHeight = window.innerHeight; document.getElementById('startMenuWrapper').style.maxHeight = '0px'; document.getElementById('gameAreaWrapper').style.opacity = 1; if (!socket) { socket = io({query: "type=" + type}); setupSocket(socket); } if (!global.animLoopHandle) animloop(); socket.emit('respawn'); window.chat.socket = socket; window.chat.registerFunctions(); window.canvas.socket = socket; global.socket = socket; } // Checks if the nick chosen contains valid alphanumeric characters (and underscores). function validNick() { var regex = /^\w*$/; debug('Regex Test', regex.exec(playerNameInput.value)); return regex.exec(playerNameInput.value) !== null; } window.onload = function () { var btn = document.getElementById('startButton'), btnS = document.getElementById('spectateButton'), nickErrorText = document.querySelector('#startMenu .input-error'); btnS.onclick = function () { startGame('spectate'); }; btn.onclick = function () { // Checks if the nick is valid. if (validNick()) { nickErrorText.style.opacity = 0; startGame('player'); } else { nickErrorText.style.opacity = 1; } }; var settingsMenu = document.getElementById('settingsButton'); var settings = document.getElementById('settings'); var instructions = document.getElementById('instructions'); settingsMenu.onclick = function () { if (settings.style.maxHeight == '300px') { settings.style.maxHeight = '0px'; } else { settings.style.maxHeight = '300px'; } }; playerNameInput.addEventListener('keypress', function (e) { var key = e.which || e.keyCode; if (key === global.KEY_ENTER) { if (validNick()) { nickErrorText.style.opacity = 0; startGame('player'); } else { nickErrorText.style.opacity = 1; } } }); }; // TODO: Break out into GameControls. var foodConfig = { border: 0, }; var playerConfig = { border: 6, textColor: '#FFFFFF', textBorder: '#000000', textBorderSize: 3, defaultSize: 30 }; var player = { id: -1, x: global.screenWidth / 2, y: global.screenHeight / 2, screenWidth: global.screenWidth, screenHeight: global.screenHeight, target: {x: global.screenWidth / 2, y: global.screenHeight / 2}, health: 100, attackDamage: 10 }; global.player = player; var foods = []; var viruses = []; var fireFood = []; var users = []; var leaderboard = []; var target = {x: player.x, y: player.y}; var missiles = []; global.target = target; window.canvas = new Canvas(); window.chat = new ChatClient(); var visibleBorderSetting = document.getElementById('visBord'); visibleBorderSetting.onchange = settings.toggleBorder; var showMassSetting = document.getElementById('showMass'); showMassSetting.onchange = settings.toggleMass; var continuitySetting = document.getElementById('continuity'); continuitySetting.onchange = settings.toggleContinuity; var roundFoodSetting = document.getElementById('roundFood'); roundFoodSetting.onchange = settings.toggleRoundFood; var c = window.canvas.canvas; var graph = c.getContext('2d'); $("#shoot").click(function () { socket.emit('shootMissile'); window.canvas.reenviar = false; }); $("#split").click(function () { socket.emit('splitCell'); window.canvas.reenviar = false; }); // socket stuff. function setupSocket(socket) { // Handle ping. socket.on('pongcheck', function () { var latency = Date.now() - global.startPingTime; debug('Latency: ' + latency + 'ms'); window.chat.addSystemLine('Ping: ' + latency + 'ms'); }); // Handle error. socket.on('connect_failed', function () { socket.close(); global.disconnected = true; }); socket.on('disconnect', function () { socket.close(); global.disconnected = true; }); // Handle connection. socket.on('welcome', function (playerSettings) { player = playerSettings; player.name = global.playerName; player.screenWidth = global.screenWidth; player.screenHeight = global.screenHeight; player.target = window.canvas.target; global.player = player; window.chat.player = player; socket.emit('gotit', player); global.gameStart = true; debug('Game started at: ' + global.gameStart); window.chat.addSystemLine('Connected to the game!'); window.chat.addSystemLine('Type <b>-help</b> for a list of commands.'); if (global.mobile) { document.getElementById('gameAreaWrapper').removeChild(document.getElementById('chatbox')); } c.focus(); }); socket.on('gameSetup', function (data) { global.gameWidth = data.gameWidth; global.gameHeight = data.gameHeight; resize(); }); socket.on('playerDied', function (data) { window.chat.addSystemLine('{GAME} - <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> was killed.'); }); socket.on('playerDisconnect', function (data) { window.chat.addSystemLine('{GAME} - <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> disconnected.'); }); socket.on('playerJoin', function (data) { window.chat.addSystemLine('{GAME} - <b>' + (data.name.length < 1 ? 'An unnamed cell' : data.name) + '</b> joined.'); }); socket.on('leaderboard', function (data) { leaderboard = data.leaderboard; var status = '<span class="title">Leaderboard</span>'; for (var i = 0; i < leaderboard.length; i++) { status += '<br />'; if (leaderboard[i].id == player.id) { if (leaderboard[i].name.length !== 0) status += '<span class="me">' + (i + 1) + '. ' + leaderboard[i].name + "</span>"; else status += '<span class="me">' + (i + 1) + ". An unnamed cell</span>"; } else { if (leaderboard[i].name.length !== 0) status += (i + 1) + '. ' + leaderboard[i].name; else status += (i + 1) + '. An unnamed cell'; } } //status += '<br />Players: ' + data.players; document.getElementById('status').innerHTML = status; }); socket.on('serverMSG', function (data) { window.chat.addSystemLine(data); }); // Chat. socket.on('serverSendPlayerChat', function (data) { window.chat.addChatLine(data.sender, data.message, false); }); // Handle movement. socket.on('serverTellPlayerMove', function (userData, visibleMissile) { console.log(userData, visibleMissile); var playerData; for (var i = 0; i < userData.length; i++) { if (typeof(userData[i].id) == "undefined") { playerData = userData[i]; i = userData.length; } } if (global.playerType == 'player') { var xoffset = player.x - playerData.x; var yoffset = player.y - playerData.y; player.x = playerData.x; player.y = playerData.y; player.hue = playerData.hue; player.score = playerData.score; player.cell = playerData.cell; player.xoffset = isNaN(xoffset) ? 0 : xoffset; player.yoffset = isNaN(yoffset) ? 0 : yoffset; } users = userData; missiles = visibleMissile; }); // Death. socket.on('RIP', function () { global.gameStart = false; global.died = true; window.setTimeout(function () { document.getElementById('gameAreaWrapper').style.opacity = 0; document.getElementById('startMenuWrapper').style.maxHeight = '1000px'; global.died = false; if (global.animLoopHandle) { window.cancelAnimationFrame(global.animLoopHandle); global.animLoopHandle = undefined; } }, 2500); }); socket.on('kick', function (data) { global.gameStart = false; reason = data; global.kicked = true; socket.close(); }); socket.on("increaseScore", function (scoreGain) { socket.emit('splitCell', scoreGain); reenviar = false; }); } function drawCircle(centerX, centerY, radius, sides) { var theta = 0; var x = 0; var y = 0; graph.beginPath(); for (var i = 0; i < sides; i++) { theta = (i / sides) * 2 * Math.PI; x = centerX + radius * Math.sin(theta); y = centerY + radius * Math.cos(theta); graph.lineTo(x, y); } graph.closePath(); graph.stroke(); graph.fill(); } function drawMissile(missile) { graph.strokeStyle = 'hsl(' + missile.hue + ', 100%, 45%)'; graph.fillStyle = 'hsl(' + missile.hue + ', 100%, 50%)'; graph.lineWidth = playerConfig.border; drawCircle(missile.x - player.x + global.screenWidth / 2, missile.y - player.y + global.screenHeight / 2, missile.radius, global.foodSides); } function drawFood(food) { graph.strokeStyle = 'hsl(' + food.hue + ', 100%, 45%)'; graph.fillStyle = 'hsl(' + food.hue + ', 100%, 50%)'; graph.lineWidth = foodConfig.border; drawCircle(food.x - player.x + global.screenWidth / 2, food.y - player.y + global.screenHeight / 2, food.radius, global.foodSides); } function drawVirus(virus) { graph.strokeStyle = virus.stroke; graph.fillStyle = virus.fill; graph.lineWidth = virus.strokeWidth; drawCircle(virus.x - player.x + global.screenWidth / 2, virus.y - player.y + global.screenHeight / 2, virus.radius, global.virusSides); } function drawFireFood(mass) { graph.strokeStyle = 'hsl(' + mass.hue + ', 100%, 45%)'; graph.fillStyle = 'hsl(' + mass.hue + ', 100%, 50%)'; graph.lineWidth = playerConfig.border + 10; drawCircle(mass.x - player.x + global.screenWidth / 2, mass.y - player.y + global.screenHeight / 2, mass.radius - 5, 18 + (~~(mass.masa / 5))); } function drawPlayers(order) { var start = { x: player.x - (global.screenWidth / 2), y: player.y - (global.screenHeight / 2) }; for (var z = 0; z < order.length; z++) { var userCurrent = users[order[z].nCell]; var cellCurrent = users[order[z].nCell].cell; var x = 0; var y = 0; var points = 30 + ~~(cellCurrent.mass / 5); var increase = Math.PI * 2 / points; graph.strokeStyle = 'hsl(' + userCurrent.hue + ', 100%, 45%)'; graph.fillStyle = 'hsl(' + userCurrent.hue + ', 100%, 50%)'; graph.lineWidth = playerConfig.border; var xstore = []; var ystore = []; global.spin += 0.0; var circle = { x: cellCurrent.x - start.x, y: cellCurrent.y - start.y }; for (var i = 0; i < points; i++) { x = cellCurrent.radius * Math.cos(global.spin) + circle.x; y = cellCurrent.radius * Math.sin(global.spin) + circle.y; if (typeof(userCurrent.id) == "undefined") { x = valueInRange(-userCurrent.x + global.screenWidth / 2, global.gameWidth - userCurrent.x + global.screenWidth / 2, x); y = valueInRange(-userCurrent.y + global.screenHeight / 2, global.gameHeight - userCurrent.y + global.screenHeight / 2, y); } else { x = valueInRange(-cellCurrent.x - player.x + global.screenWidth / 2 + (cellCurrent.radius / 3), global.gameWidth - cellCurrent.x + global.gameWidth - player.x + global.screenWidth / 2 - (cellCurrent.radius / 3), x); y = valueInRange(-cellCurrent.y - player.y + global.screenHeight / 2 + (cellCurrent.radius / 3), global.gameHeight - cellCurrent.y + global.gameHeight - player.y + global.screenHeight / 2 - (cellCurrent.radius / 3), y); } global.spin += increase; xstore[i] = x; ystore[i] = y; } /*if (wiggle >= player.radius/ 3) inc = -1; *if (wiggle <= player.radius / -3) inc = +1; *wiggle += inc; */ for (i = 0; i < points; ++i) { if (i === 0) { graph.beginPath(); graph.moveTo(xstore[i], ystore[i]); } else if (i > 0 && i < points - 1) { graph.lineTo(xstore[i], ystore[i]); } else { graph.lineTo(xstore[i], ystore[i]); graph.lineTo(xstore[0], ystore[0]); } } graph.lineJoin = 'round'; graph.lineCap = 'round'; graph.fill(); graph.stroke(); var nameCell = ""; if (typeof(userCurrent.id) == "undefined") nameCell = player.name; else nameCell = userCurrent.name; var fontSize = Math.max(cellCurrent.radius / 3, 12); graph.lineWidth = playerConfig.textBorderSize; graph.fillStyle = playerConfig.textColor; graph.strokeStyle = playerConfig.textBorder; graph.miterLimit = 1; graph.lineJoin = 'round'; graph.textAlign = 'center'; graph.textBaseline = 'middle'; graph.font = 'bold ' + fontSize + 'px sans-serif'; if (global.toggleMassState === 0) { graph.strokeText(nameCell, circle.x, circle.y); graph.fillText(nameCell, circle.x, circle.y); } else { graph.strokeText(nameCell, circle.x, circle.y); graph.fillText(nameCell, circle.x, circle.y); graph.font = 'bold ' + Math.max(fontSize / 3 * 2, 10) + 'px sans-serif'; if (nameCell.length === 0) fontSize = 0; graph.strokeText(Math.round(cellCurrent.mass), circle.x, circle.y + fontSize); graph.fillText(Math.round(cellCurrent.mass), circle.x, circle.y + fontSize); } } } function valueInRange(min, max, value) { return Math.min(max, Math.max(min, value)); } function drawgrid() { graph.lineWidth = 1; graph.strokeStyle = global.lineColor; graph.globalAlpha = 0.15; graph.beginPath(); for (var x = global.xoffset - player.x; x < global.screenWidth; x += global.screenHeight / 18) { graph.moveTo(x, 0); graph.lineTo(x, global.screenHeight); } for (var y = global.yoffset - player.y; y < global.screenHeight; y += global.screenHeight / 18) { graph.moveTo(0, y); graph.lineTo(global.screenWidth, y); } graph.stroke(); graph.globalAlpha = 1; } function drawborder() { graph.lineWidth = 1; graph.strokeStyle = playerConfig.borderColor; // Left-vertical. if (player.x <= global.screenWidth / 2) { graph.beginPath(); graph.moveTo(global.screenWidth / 2 - player.x, 0 ? player.y > global.screenHeight / 2 : global.screenHeight / 2 - player.y); graph.lineTo(global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y); graph.strokeStyle = global.lineColor; graph.stroke(); } // Top-horizontal. if (player.y <= global.screenHeight / 2) { graph.beginPath(); graph.moveTo(0 ? player.x > global.screenWidth / 2 : global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y); graph.lineTo(global.gameWidth + global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y); graph.strokeStyle = global.lineColor; graph.stroke(); } // Right-vertical. if (global.gameWidth - player.x <= global.screenWidth / 2) { graph.beginPath(); graph.moveTo(global.gameWidth + global.screenWidth / 2 - player.x, global.screenHeight / 2 - player.y); graph.lineTo(global.gameWidth + global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y); graph.strokeStyle = global.lineColor; graph.stroke(); } // Bottom-horizontal. if (global.gameHeight - player.y <= global.screenHeight / 2) { graph.beginPath(); graph.moveTo(global.gameWidth + global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y); graph.lineTo(global.screenWidth / 2 - player.x, global.gameHeight + global.screenHeight / 2 - player.y); graph.strokeStyle = global.lineColor; graph.stroke(); } } window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; })(); window.cancelAnimFrame = (function (handle) { return window.cancelAnimationFrame || window.mozCancelAnimationFrame; })(); function animloop() { global.animLoopHandle = window.requestAnimFrame(animloop); gameLoop(); } function gameLoop() { if (global.died) { graph.fillStyle = '#333333'; graph.fillRect(0, 0, global.screenWidth, global.screenHeight); graph.textAlign = 'center'; graph.fillStyle = '#FFFFFF'; graph.font = 'bold 30px sans-serif'; graph.fillText('You died!', global.screenWidth / 2, global.screenHeight / 2); } else if (!global.disconnected) { if (global.gameStart) { graph.fillStyle = global.backgroundColor; graph.fillRect(0, 0, global.screenWidth, global.screenHeight); drawgrid(); foods.forEach(drawFood); fireFood.forEach(drawFireFood); viruses.forEach(drawVirus); missiles.forEach(drawMissile); if (global.borderDraw) { drawborder(); } var orderMass = []; for (var i = 0; i < users.length; i++) { orderMass.push({ nCell: i, mass: users[i].cell.mass }); } orderMass.sort(function (obj1, obj2) { return obj1.mass - obj2.mass; }); drawPlayers(orderMass); socket.emit('0', window.canvas.target); // playerSendTarget "Heartbeat". } else { graph.fillStyle = '#333333'; graph.fillRect(0, 0, global.screenWidth, global.screenHeight); graph.textAlign = 'center'; graph.fillStyle = '#FFFFFF'; graph.font = 'bold 30px sans-serif'; graph.fillText('Game Over!', global.screenWidth / 2, global.screenHeight / 2); } } else { graph.fillStyle = '#333333'; graph.fillRect(0, 0, global.screenWidth, global.screenHeight); graph.textAlign = 'center'; graph.fillStyle = '#FFFFFF'; graph.font = 'bold 30px sans-serif'; if (global.kicked) { if (reason !== '') { graph.fillText('You were kicked for:', global.screenWidth / 2, global.screenHeight / 2 - 20); graph.fillText(reason, global.screenWidth / 2, global.screenHeight / 2 + 20); } else { graph.fillText('You were kicked!', global.screenWidth / 2, global.screenHeight / 2); } } else { graph.fillText('Disconnected!', global.screenWidth / 2, global.screenHeight / 2); } } } window.addEventListener('resize', resize); function resize() { if (!socket) return; player.screenWidth = c.width = global.screenWidth = global.playerType == 'player' ? window.innerWidth : global.gameWidth; player.screenHeight = c.height = global.screenHeight = global.playerType == 'player' ? window.innerHeight : global.gameHeight; if (global.playerType == 'spectate') { player.x = global.gameWidth / 2; player.y = global.gameHeight / 2; } socket.emit('windowResized', {screenWidth: global.screenWidth, screenHeight: global.screenHeight}); }
'use strict'; const request = require('superagent'); const Promise = require('bluebird'); const config = require('../../config/lib/bertly'); /** * executePost - sends the POST request to the Bertly service * * @param {Object} data * @return {Promise} */ async function executePost(data) { return request .post(config.baseUri) .type('form') .set(config.apiKeyHeader, config.apiKey) .send(data) .then(res => res.body); } /** * createRedirect * * @see https://github.com/DoSomething/bertly#create-redirect * @param {String} url * @return {Promise} */ async function createRedirect(url) { if (!url) { return Promise.reject(new TypeError('url is undefined')); } return executePost({ url }); } module.exports = { createRedirect, };
import { expect } from 'chai'; import sinon from 'sinon'; import apiMiddleware from './index.js'; const create = () => { const store = { getState: sinon.stub().returns({}), dispatch: sinon.stub(), }; const next = sinon.stub(); const invoke = (action) => apiMiddleware(store)(next)(action); return { store, next, invoke, }; }; describe('apiMiddleware', () => { let shouldCallAPI, callAPI, onStart, onSuccess, onError, payload; beforeEach(() => { shouldCallAPI = sinon.stub().returns(true); callAPI = sinon.stub().returns(Promise.resolve('my response')); onStart = sinon.stub(); onSuccess = sinon.stub(); onError = sinon.stub(); payload = { userId: 42, }; }); it(`passes through non-api action`, () => { const { next, invoke } = create(); const action = { type: 'TEST', }; invoke(action); expect(next.calledWith(action), 'next was not called with action').to.be.true; }); it(`sould call no functions if shouldCallAPI returns false`, (done) => { const { next, invoke, store } = create(); shouldCallAPI = sinon.stub().returns(false); const action = { types: ['START', 'SUCCESS', 'ERROR'], shouldCallAPI, callAPI, onStart, onSuccess, onError, payload, }; invoke(action) .then(() => { expect( shouldCallAPI.calledWith({ getState: store.getState, }), 'shouldCallAPI was not called with...' ).to.be.true; expect(callAPI.called, 'callAPI was called').to.be.false; expect(onStart.called, 'onStart was called').to.be.false; expect(onSuccess.called, 'onSuccess was called').to.be.false; expect(onError.called, 'onError was called').to.be.false; done(); }) .catch(done); }); it(`calls success functions`, (done) => { const { next, invoke, store } = create(); const action = { types: ['START', 'SUCCESS', 'ERROR'], shouldCallAPI, callAPI, onStart, onSuccess, onError, payload, }; invoke(action) .then(() => { expect( shouldCallAPI.calledWith({ getState: store.getState, }), 'shouldCallAPI was not called with...' ).to.be.true; expect( callAPI.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, }), 'callAPI was not called with...' ).to.be.true; expect( onStart.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, }), 'onStart was not called with...' ).to.be.true; expect( onSuccess.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, response: 'my response', }), 'onSuccess was not called with...' ).to.be.true; expect(onError.called, 'onError was called').to.be.false; done(); }) .catch(done); }); it(`calls error functions`, (done) => { const { next, invoke, store } = create(); callAPI = sinon.stub().returns(Promise.reject(new Error('my rejection'))); const action = { types: ['START', 'SUCCESS', 'ERROR'], shouldCallAPI, callAPI, onStart, onSuccess, onError, payload, }; invoke(action) .then(() => { expect.fail(0, 1, 'then() was called'); }) .catch((e) => { expect( shouldCallAPI.calledWith({ getState: store.getState, }), 'shouldCallAPI was not called with...' ).to.be.true; expect( callAPI.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, }), 'callAPI was not called with...' ).to.be.true; expect( onStart.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, }), 'onStart was not called with...' ).to.be.true; expect(onSuccess.called, 'onSuccess was called').to.be.false; expect( onError.calledWith({ dispatch: store.dispatch, getState: store.getState, payload: action.payload, error: e, }), 'onerror was not called with...' ).to.be.true; done(); }) .catch(done); }); });
var group__MISCELLANEOUS = [ [ "csoundCloseLibrary", "group__MISCELLANEOUS.html#ga738e84ba297d65c9ccc0d34e1ecb893c", null ], [ "csoundCreateCircularBuffer", "group__MISCELLANEOUS.html#ga22d06cd479b47eccfe428dbd19b185bb", null ], [ "csoundCreateGlobalVariable", "group__MISCELLANEOUS.html#ga584a23facb29e2a34e30079c58fdb21f", null ], [ "csoundDeleteUtilityList", "group__MISCELLANEOUS.html#gab0cba9171f64b5035bf1657b4080c970", null ], [ "csoundDestroyCircularBuffer", "group__MISCELLANEOUS.html#ga2da72498056cb27006f3a50a2279534a", null ], [ "csoundDestroyGlobalVariable", "group__MISCELLANEOUS.html#ga2e6e43d20001507ec96f534d48330051", null ], [ "csoundFlushCircularBuffer", "group__MISCELLANEOUS.html#ga90180f9307cec59b36d7d1a42ae29459", null ], [ "csoundGetCPUTime", "group__MISCELLANEOUS.html#ga38ef409d92cff0551aa98d76c290a1bc", null ], [ "csoundGetEnv", "group__MISCELLANEOUS.html#gaecb351940201c8c3e91f9cdd5f8b7002", null ], [ "csoundGetLibrarySymbol", "group__MISCELLANEOUS.html#ga7a6f1a0c39286a83a31518d351aa3a12", null ], [ "csoundGetRandomSeedFromTime", "group__MISCELLANEOUS.html#gae9225ea131782d2006db3e419497bec9", null ], [ "csoundGetRealTime", "group__MISCELLANEOUS.html#ga8c9ca7a1e2de6a17bbfece060d829a49", null ], [ "csoundGetUtilityDescription", "group__MISCELLANEOUS.html#gabacd73ad59e84640632a336aa4abd3ae", null ], [ "csoundInitTimerStruct", "group__MISCELLANEOUS.html#ga479914eb3234ab467671230dd16a95b9", null ], [ "csoundListUtilities", "group__MISCELLANEOUS.html#gae21ed2208e00ca90887a0575b3beb143", null ], [ "csoundOpenLibrary", "group__MISCELLANEOUS.html#ga80c8d9f053326aa5b61b718519adffa5", null ], [ "csoundPeekCircularBuffer", "group__MISCELLANEOUS.html#gac98f8eaf1fba6511c99981623cd25a0e", null ], [ "csoundQueryGlobalVariable", "group__MISCELLANEOUS.html#ga8290db73185095a9c19d6a2854541f3f", null ], [ "csoundQueryGlobalVariableNoCheck", "group__MISCELLANEOUS.html#gafa2549431499c3453f3af4e03592412a", null ], [ "csoundRand31", "group__MISCELLANEOUS.html#ga35cefe1740a0ba393367895c688ba7ce", null ], [ "csoundRandMT", "group__MISCELLANEOUS.html#gac4a49ff7378fbe0257ceeb87fa851c2f", null ], [ "csoundReadCircularBuffer", "group__MISCELLANEOUS.html#gabe365d2d5de513833564315f0e5afcca", null ], [ "csoundRunCommand", "group__MISCELLANEOUS.html#gad7c7646f9ec4364d53548954d0f231d2", null ], [ "csoundRunUtility", "group__MISCELLANEOUS.html#gacebcd493f66d5a77af8cbe36e035f404", null ], [ "csoundSeedRandMT", "group__MISCELLANEOUS.html#gaf410d3d69a62552c91159f3f92792569", null ], [ "csoundSetGlobalEnv", "group__MISCELLANEOUS.html#ga0183dad9bbc4961d66a280e5292091ed", null ], [ "csoundSetLanguage", "group__MISCELLANEOUS.html#ga7023e0f0ebbc6ac1be8306c5c28747ba", null ], [ "csoundWriteCircularBuffer", "group__MISCELLANEOUS.html#gad57b8dbb8917769ca2e09cdbc6a3ae60", null ] ];
function isReturnPressed (keyCode) { return keyCode === 13 } export { isReturnPressed }
const templatePath = 'pinaxcon/templates/'; const staticRoot = 'static/'; const staticSource = staticRoot + 'src/'; const staticBuild = staticRoot + '_build/'; const staticDist = staticRoot + 'dist/'; const npmRoot = 'node_modules/'; exports = module.exports = { staticUrlRoot: '/site_media/static', paths: { source: staticSource, build: staticBuild, dist: staticDist }, watch: { styles: [ staticSource + 'less/**/*.less' ], scripts: [ staticSource + 'js/**/*.js' ] }, templates: { destination: templatePath, manifestPath: staticBuild + 'manifest.json', scriptsTemplate: staticSource + 'hbs/_scripts.hbs', stylesTemplate: staticSource + 'hbs/_styles.hbs', }, fonts: { sources: [ npmRoot + 'font-awesome/fonts/**.*', npmRoot + 'bootstrap/fonts/**.*', staticSource + 'fonts/**/*', ], dist: staticDist + 'fonts/' }, styles: { source: staticSource + 'less/site.less', dist: staticBuild + 'css/', npmPaths: [ npmRoot + 'bootstrap/less', npmRoot + 'font-awesome/less', npmRoot ] }, scripts: { main: staticSource + 'js/site.js', source: [ staticSource + 'js/**/*' ], dist: staticBuild + 'js/' }, images: { sources: [ staticSource + 'images/**/*' ], dist: staticDist + 'images/' }, manifest: { source: [ staticBuild + '**/*.css', staticBuild + '**/*.js' ] }, test: { all: 'test/**/*.test.js', req: 'test/req/*.test.js', components: 'test/components/*.test.js' }, xo: { source: [ 'tasks/**/*.js', staticSource + '**/*.js' ] }, optimize: { css: { source: staticDist + 'css/*.css', options: {}, dist: staticDist + 'css/' }, js: { source: staticDist + 'js/*.js', options: {}, dist: staticDist + 'js/' } } };
var SourceMapConsumer = require('source-map').SourceMapConsumer; var path = require('path'); var fs = require('fs'); // Only install once if called multiple times var alreadyInstalled = false; // If true, the caches are reset before a stack trace formatting operation var emptyCacheBetweenOperations = false; // Maps a file path to a string containing the file contents var fileContentsCache = {}; // Maps a file path to a source map for that file var sourceMapCache = {}; function isInBrowser() { return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function')); } function retrieveFile(path) { // Trim the path to make sure there is no extra whitespace. path = path.trim(); if (path in fileContentsCache) { return fileContentsCache[path]; } try { // Use SJAX if we are in the browser if (isInBrowser()) { var xhr = new XMLHttpRequest(); xhr.open('GET', path, false); xhr.send(null); var contents = null if (xhr.readyState === 4 && xhr.status === 200) { contents = xhr.responseText } } // Otherwise, use the filesystem else { var contents = fs.readFileSync(path, 'utf8'); } } catch (e) { var contents = null; } return fileContentsCache[path] = contents; } // Support URLs relative to a directory, but be careful about a protocol prefix // in case we are in the browser (i.e. directories may start with "http://") function supportRelativeURL(file, url) { if (!file) return url; var dir = path.dirname(file); var match = /^\w+:\/\/[^\/]*/.exec(dir); var protocol = match ? match[0] : ''; return protocol + path.resolve(dir.slice(protocol.length), url); } function retrieveSourceMapURL(source) { var fileData; if (isInBrowser()) { var xhr = new XMLHttpRequest(); xhr.open('GET', source, false); xhr.send(null); fileData = xhr.readyState === 4 ? xhr.responseText : null; // Support providing a sourceMappingURL via the SourceMap header var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap"); if (sourceMapHeader) { return sourceMapHeader; } } // Get the URL of the source map fileData = retrieveFile(source); var re = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/mg; // Keep executing the search to find the *last* sourceMappingURL to avoid // picking up sourceMappingURLs from comments, strings, etc. var lastMatch, match; while (match = re.exec(fileData)) lastMatch = match; if (!lastMatch) return null; return lastMatch[1]; }; // Can be overridden by the retrieveSourceMap option to install. Takes a // generated source filename; returns a {map, optional url} object, or null if // there is no source map. The map field may be either a string or the parsed // JSON object (ie, it must be a valid argument to the SourceMapConsumer // constructor). function retrieveSourceMap(source) { var sourceMappingURL = retrieveSourceMapURL(source); if (!sourceMappingURL) return null; // Read the contents of the source map var sourceMapData; var dataUrlPrefix = "data:application/json;base64,"; if (sourceMappingURL.slice(0, dataUrlPrefix.length).toLowerCase() == dataUrlPrefix) { // Support source map URL as a data url sourceMapData = new Buffer(sourceMappingURL.slice(dataUrlPrefix.length), "base64").toString(); sourceMappingURL = null; } else { // Support source map URLs relative to the source URL sourceMappingURL = supportRelativeURL(source, sourceMappingURL); sourceMapData = retrieveFile(sourceMappingURL); } if (!sourceMapData) { return null; } return { url: sourceMappingURL, map: sourceMapData }; } function mapSourcePosition(position) { var sourceMap = sourceMapCache[position.source]; if (!sourceMap) { // Call the (overrideable) retrieveSourceMap function to get the source map. var urlAndMap = retrieveSourceMap(position.source); if (urlAndMap) { sourceMap = sourceMapCache[position.source] = { url: urlAndMap.url, map: new SourceMapConsumer(urlAndMap.map) }; // Load all sources stored inline with the source map into the file cache // to pretend like they are already loaded. They may not exist on disk. if (sourceMap.map.sourcesContent) { sourceMap.map.sources.forEach(function(source, i) { var contents = sourceMap.map.sourcesContent[i]; if (contents) { var url = supportRelativeURL(sourceMap.url, source); fileContentsCache[url] = contents; } }); } } else { sourceMap = sourceMapCache[position.source] = { url: null, map: null }; } } // Resolve the source URL relative to the URL of the source map if (sourceMap && sourceMap.map) { var originalPosition = sourceMap.map.originalPositionFor(position); // Only return the original position if a matching line was found. If no // matching line is found then we return position instead, which will cause // the stack trace to print the path and line for the compiled file. It is // better to give a precise location in the compiled file than a vague // location in the original file. if (originalPosition.source !== null) { originalPosition.source = supportRelativeURL( sourceMap.url, originalPosition.source); return originalPosition; } } return position; } // Parses code generated by FormatEvalOrigin(), a function inside V8: // https://code.google.com/p/v8/source/browse/trunk/src/messages.js function mapEvalOrigin(origin) { // Most eval() calls are in this format var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); if (match) { var position = mapSourcePosition({ source: match[2], line: match[3], column: match[4] - 1 }); return 'eval at ' + match[1] + ' (' + position.source + ':' + position.line + ':' + (position.column + 1) + ')'; } // Parse nested eval() calls using recursion match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); if (match) { return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; } // Make sure we still return useful information if we didn't find anything return origin; } // This is copied almost verbatim from the V8 source code at // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The // implementation of wrapCallSite() used to just forward to the actual source // code of CallSite.prototype.toString but unfortunately a new release of V8 // did something to the prototype chain and broke the shim. The only fix I // could find was copy/paste. function CallSiteToString() { var fileName; var fileLocation = ""; if (this.isNative()) { fileLocation = "native"; } else { fileName = this.getScriptNameOrSourceURL(); if (!fileName && this.isEval()) { fileLocation = this.getEvalOrigin(); fileLocation += ", "; // Expecting source position to follow. } if (fileName) { fileLocation += fileName; } else { // Source code does not originate from a file and is not native, but we // can still get the source position inside the source string, e.g. in // an eval string. fileLocation += "<anonymous>"; } var lineNumber = this.getLineNumber(); if (lineNumber != null) { fileLocation += ":" + lineNumber; var columnNumber = this.getColumnNumber(); if (columnNumber) { fileLocation += ":" + columnNumber; } } } var line = ""; var functionName = this.getFunctionName(); var addSuffix = true; var isConstructor = this.isConstructor(); var isMethodCall = !(this.isToplevel() || isConstructor); if (isMethodCall) { var typeName = this.getTypeName(); var methodName = this.getMethodName(); if (functionName) { if (typeName && functionName.indexOf(typeName) != 0) { line += typeName + "."; } line += functionName; if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { line += " [as " + methodName + "]"; } } else { line += typeName + "." + (methodName || "<anonymous>"); } } else if (isConstructor) { line += "new " + (functionName || "<anonymous>"); } else if (functionName) { line += functionName; } else { line += fileLocation; addSuffix = false; } if (addSuffix) { line += " (" + fileLocation + ")"; } return line; } function cloneCallSite(frame) { var object = {}; Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; }); object.toString = CallSiteToString; return object; } function wrapCallSite(frame, fromModule) { // Most call sites will return the source file from getFileName(), but code // passed to eval() ending in "//# sourceURL=..." will return the source file // from getScriptNameOrSourceURL() instead var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); if (source) { var line = frame.getLineNumber(); var column = frame.getColumnNumber() - 1; // Fix position in Node where some (internal) code is prepended. // See https://github.com/evanw/node-source-map-support/issues/36 if (fromModule && line === 1) { column -= 63; } var position = mapSourcePosition({ source: source, line: line, column: column }); frame = cloneCallSite(frame); frame.getFileName = function() { return position.source; }; frame.getLineNumber = function() { return position.line; }; frame.getColumnNumber = function() { return position.column + 1; }; frame.getScriptNameOrSourceURL = function() { return position.source; }; return frame; } // Code called using eval() needs special handling var origin = frame.isEval() && frame.getEvalOrigin(); if (origin) { origin = mapEvalOrigin(origin); frame = cloneCallSite(frame); frame.getEvalOrigin = function() { return origin; }; return frame; } // If we get here then we were unable to change the source position return frame; } // This function is part of the V8 stack trace API, for more info see: // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi function prepareStackTrace(error, stack) { if (emptyCacheBetweenOperations) { fileContentsCache = {}; sourceMapCache = {}; } var fromModule = !isInBrowser() && stack.length && stack[stack.length - 1].getFileName() === 'module.js' ; return error + stack.map(function(frame) { return '\n at ' + wrapCallSite(frame, fromModule); }).join(''); } // Generate position and snippet of original source with pointer function getErrorSource(error) { var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var source = match[1]; var line = +match[2]; var column = +match[3]; // Support the inline sourceContents inside the source map var contents = fileContentsCache[source]; // Support files on disk if (!contents && fs.existsSync(source)) { contents = fs.readFileSync(source, 'utf8'); } // Format the line from the original source code like node does if (contents) { var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; if (code) { return source + ':' + line + '\n' + code + '\n' + new Array(column).join(' ') + '^'; } } } return null; } // Mimic node's stack trace printing when an exception escapes the process function handleUncaughtExceptions(error) { if (!error || !error.stack) { console.error('Uncaught exception:', error); } else { var source = getErrorSource(error); if (source !== null) { console.error(); console.error(source); } console.error(error.stack); } process.exit(1); } exports.wrapCallSite = wrapCallSite; exports.getErrorSource = getErrorSource; exports.mapSourcePosition = mapSourcePosition; exports.retrieveSourceMap = retrieveSourceMap; exports.install = function(options) { if (!alreadyInstalled) { alreadyInstalled = true; Error.prepareStackTrace = prepareStackTrace; // Configure options options = options || {}; var installHandler = 'handleUncaughtExceptions' in options ? options.handleUncaughtExceptions : true; emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? options.emptyCacheBetweenOperations : false; // Allow sources to be found by methods other than reading the files // directly from disk. if (options.retrieveFile) retrieveFile = options.retrieveFile; // Allow source maps to be found by methods other than reading the files // directly from disk. if (options.retrieveSourceMap) retrieveSourceMap = options.retrieveSourceMap; // Provide the option to not install the uncaught exception handler. This is // to support other uncaught exception handlers (in test frameworks, for // example). If this handler is not installed and there are no other uncaught // exception handlers, uncaught exceptions will be caught by node's built-in // exception handler and the process will still be terminated. However, the // generated JavaScript code will be shown above the stack trace instead of // the original source code. if (installHandler && !isInBrowser()) { process.on('uncaughtException', handleUncaughtExceptions); } } };
/** * Hotdraw.js : EllipseFigure * * {Comments are copied from the Java Implementation of HotDraw} * * An ellipse figure. * * @author Adnan M.Sagar, Phd. <adnan@websemantics.ca> * @copyright 2004-2017 Web Semantics, Inc. * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://websemantics.ca * @since 5th January 2005 * @package websemantics/hotdraw/figures */ EllipseFigure.prototype = new AttributeFigure(); function EllipseFigure( /* Point */ origin, /* Point */ corner) { var argv = EllipseFigure.arguments; var argc = EllipseFigure.length; this.className = "EllipseFigure"; /* Rectangle */ this.fDisplayBox = null; if (argv.length > 0) this.initEllipseFigure(origin, corner); } //************* // initEllipseFigure // // Forms: // ====== // (1) EllipseFigure(); // (2) EllipseFigure(Point origin,Point corner); //************* EllipseFigure.prototype.initEllipseFigure = function(origin, corner) { this.initAttributeFigure(); if (!origin && !corner) { this.initEllipseFigure(new Point(0, 0), new Point(0, 0)); return; } this.basicDisplayBox(origin, corner); } //************* // basicDisplayBox //************* EllipseFigure.prototype.basicDisplayBox = function( /* Point */ origin, /* Point */ corner) { this.fDisplayBox = new gRectangle(origin); this.fDisplayBox.add(corner); } //************* // handles //************* /* Vector */ EllipseFigure.prototype.handles = function( /* Figure */ owner) { if (owner == undefined || owner == null) owner = this; // Sometimes a decorator figure needs to be the owner of a handle var handles = new Vector(); boxHandleKit.addHandles(owner, handles); return handles; } //************* // Use (ret_displayBox) istead of displayBox to return the current displaybox (see AbstractFigure [ displayBox ]) //************* /* Rectangle */ EllipseFigure.prototype.ret_displayBox = function() { return new gRectangle(this.fDisplayBox.x, this.fDisplayBox.y, this.fDisplayBox.width, this.fDisplayBox.height); } //************* // basicMoveBy //************* EllipseFigure.prototype.basicMoveBy = function(x, y) { this.fDisplayBox.translate(x, y); var r = this.displayBox(); } //************* // createSVGContent //************* EllipseFigure.prototype.createSVGContent = function( /* Graphics */ g) { var r = this.displayBox(); this.shape = g.drawOval(r.x, r.y, r.width / 2, r.height / 2); this.updateShapeAttributes(); } //************* // draw //************* EllipseFigure.prototype.draw = function( /* Graphics */ g) { this.drawEllipseFigure(g); } //************* // draw a figure and its subclass. //************* EllipseFigure.prototype.drawEllipseFigure = function( /* Graphics */ g) { this.drawAttributeFigure(g); var r = this.displayBox(); // Update the location and the size od the ellipse figure this.shape.setRadius(r.width / 2, r.height / 2); this.shape.translate(r.x, r.y); } //************* // NOT IMPLEMENTED //************* EllipseFigure.prototype.write = function( /* StorableOutput */ dw) {} //************* // NOT IMPLEMENTED //************* EllipseFigure.prototype.read = function( /* StorableInput dr */ ) {} //************* // //************* EllipseFigure.prototype.clone = function() { return new EllipseFigure(new Point(0, 0), new Point(0, 0)); }
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.addColumn("Inners", "warehouseId", { type: Sequelize.INTEGER, allowNull: false, references: { model: 'Warehouses', key: 'id' } }) }, down: (queryInterface, Sequelize) => { return queryInterface.removeColumn("Inners", "warehouseId") } };
var Backbone = require('backbone'); var $ = Backbone.$ = require('jquery'); var store = require('store'); var intro_template = require('../templates/intro.hbs'); module.exports = Backbone.View.extend({ events: { 'click a[href="#gotit"]': 'clickGotIt' }, initialize: function(){ // if view has already been seen by this browser, do not show it var intro_viewed = store.get('sfmovies:intro_viewed'); if( intro_viewed ) return this.remove(); this.render(); }, render: function(){ this.$el.html( intro_template() ); }, clickGotIt: function( e ){ console.log('clickind'); e.preventDefault(); this.remove(); // store the intro message's viewed state for subsequent page loads store.set( 'sfmovies:intro_viewed', true ); } });
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; /** * @description * This handler registers itself as an Express middleware that handles * a catchall route with a very low priority, for content items. */ var ContentRouteHandler = { service: 'middleware', feature: 'content-route-handler', routePriority: 9000, scope: 'shell', /** * Registers the default content middleware. * @param {object} scope The scope. * @param {object} context The context. * @param {object} context.expressApp The Express application object. */ register: function registerContentMiddleware(scope, context) { context.expressApp.register(ContentRouteHandler.routePriority, function bindContentMiddleware(app) { app.get('*', function contentMiddleware(request, response, next) { if (request.routed) {next();return;} var contentRenderer = request.require('renderer'); if (!contentRenderer) {next();return;} var id = ContentRouteHandler.getId(request.path); response.contentType('text/html'); contentRenderer.promiseToRender({ request: request, id: id, displayType: 'main', place: 'main:1' }); request.routed = true; next(); }); }); }, /** * Gets the URL for a regular content item (no id prefix). * @param {string} id The content item's id. * @returns {string} The URL for the content item. */ getUrl: function getUrl(id) { if (id.indexOf(':') === -1) { return id.length > 1 ? '/' + id : id; } return null; }, /** * Gets the ID for a URL. * @param {string} url the URL to map. */ getId: function getId(url) { return url ? url === '/' ? '/' :url.substr(1) : '/'; } }; module.exports = ContentRouteHandler;
/* * Socket.io Communication */ // module dependencies var crypto = require('crypto'); // variable declarations var socketCodes = {}; module.exports = function(socket) { // establish connection socket.emit('pair:init', {}); // pair mobile and PC // Reference: http://blog.artlogic.com/2013/06/21/phone-to-browser-html5-gaming-using-node-js-and-socket-io/ socket.on('pair:deviceType', function(data) { // if deviceType is 'pc', generate a unique code and send to PC if(data.deviceType == 'pc') { // generate a code var code = crypto.randomBytes(3).toString('hex'); // ensure code is unique while(code in socketCodes) { code = crypto.randomBytes(3).toString('hex'); } // store code / socket assocation socketCodes[code] = this; socket.code = code; // show code on PC socket.emit('pair:sendCode', { code: code }); } // if deviceType is 'mobile', check if submitted code is valid and pair else if(data.deviceType == 'mobile') { socket.on('pair:getCode', function(data) { if(data.code in socketCodes) { // save the code for mobile commands socket.code = data.code; // start mobile connection socket.emit('pair:connected', {}); // start PC connection socketCodes[data.code].emit('pair:connected', {}); } else { socket.emit('pair:fail', {}); //socket.disconnect(); } }); } }); // main page socket.on('main:init', function() { if(socket.code && socket.code in socketCodes) { socketCodes[socket.code].emit('main:connected', {}); } }); // gestures demo socket.on('gestures:init', function() { if(socket.code && socket.code in socketCodes) { socketCodes[socket.code].emit('gestures:connected', {}); } }); socket.on('gestures:detected', function(data) { if(socket.code && socket.code in socketCodes) { socketCodes[socket.code].emit('gestures:notify', { gesture: data.gesture }); } }); // dpad demo socket.on('dpad:init', function() { if(socket.code && socket.code in socketCodes) { socketCodes[socket.code].emit('dpad:connected', {}); } }); socket.on('dpad:select', function(data) { if(socket.code && socket.code in socketCodes) { socketCodes[socket.code].emit('dpad:move', { direction: data.direction, isSelected: data.isSelected }); } }); // clean up on disconnect socket.on('disconnect', function() { // remove code / socket assocation if(socket.code && socket.code in socketCodes) { delete socketCodes[socket.code]; } }); };
import styled from 'styled-components'; export default styled.h5` font-weight: 800; font-family: 'Avenir', 'Kaff', sans-serif; letter-spacing: 0; line-height: 1; font-size: 14px; line-height: 20px; `;
$(document).ready( function() { /*============================================================================= Skills meters =============================================================================*/ /** * Add delayed animations to skills gauges */ $(".js-meter > .js-fill").each( function(index, value) { var $_this = $(this); $_this .data("origWidth", $_this.attr('data-ratio')) .width(0) .velocity( { width: $_this.data("origWidth")+'%', }, { delay : index * 50, duration : 1000, animation : 'easeInOut', } ); }); /*============================================================================= Git Graphs =============================================================================*/ /** * Ugly function to resize svg graph of my CV page * @param {string} name */ function resizeGraph(name, ul) { var graphHeight = ul.clientHeight + 29; var graph = document.getElementsByClassName(name+'__git-graph')[0]; var paths = graph.getElementsByClassName('paths')[0]; var timelinePath = graph.getElementsByClassName('timeline-path')[0]; graph.setAttribute('viewBox', '0 0 170 '+graphHeight); graph.style.height = graphHeight; if (name=="experience") { paths.children[0].setAttribute('d', 'M 20,40 L 20,'+graphHeight); paths.children[1].setAttribute('d', 'M 60,40 L 60,'+graphHeight); paths.children[2].setAttribute('d', 'M 60,'+graphHeight+' L 60,600 20,560 20,120 60,80 60,40'); timelinePath.setAttribute('d', 'M 120,31 L 120,'+graphHeight+' 170,'+(graphHeight-29)+' 170,0'); } else if (name=="formation") { paths.children[0].setAttribute('d', 'M 20,40 L 20,'+graphHeight); paths.children[1].setAttribute('d', 'M 60,40 L 60,'+graphHeight); paths.children[2].setAttribute('d', 'M 60,'+graphHeight+' L 60,110 20,70 20,40'); timelinePath.setAttribute('d', 'M 120,29 L 120,'+graphHeight+' 170,'+(graphHeight-29)+' 170,0'); } } var experiencesUl = document.getElementsByClassName('experiences')[0]; var formationsUl = document.getElementsByClassName('formations')[0]; if (experiencesUl && formationsUl) { resizeGraph('experience', experiencesUl); resizeGraph('formation', formationsUl); $(window).resize( function() { resizeGraph('experience', experiencesUl); resizeGraph('formation', formationsUl); }); } });
export class DatasetConstructor { construct(object, element, prefix) { const dataset = element.dataset; for (let property of Object.keys(dataset)) { const value = dataset[property]; if (prefix) { property = property.match(`^${prefix}(.*?)$`); if (!property) { continue; } property = property[1].replace(/^./, c => c.toLowerCase()); } object[property] = value; } } }
'use strict'; var util = require('util'); var Connection = require('../Connection'); module.exports = UdpConnection; /** * @constructor * @extends {Connection} * @param {UdpConnection.Options|object} options * @event open Alias to the `listening` event of the underlying `dgram.Socket`. * @event close Alias to the `close` event of the underlying `dgram.Socket`. * @event error Emitted when the underlying `dgram.Socket` emits the `error` * event or its `send()` method throws. * @event write Emitted before writing any data to the underlying * `dgram.Socket` (even if the socket is closed). * @event data Alias to the `message` event of the underlying `dgram.Socket`. */ function UdpConnection(options) { Connection.call(this); /** * @readonly * @type {UdpConnection.Options} */ this.options = options instanceof UdpConnection.Options ? options : new UdpConnection.Options(options); /** * @private * @type {dgram.Socket} */ this.socket = this.setUpSocket(); } util.inherits(UdpConnection, Connection); /** * @constructor * @param {object} options * @param {dgram.Socket} options.socket * @param {string} [options.host] * @param {number} [options.port] */ UdpConnection.Options = function(options) { /** * @type {dgram.Socket} */ this.socket = options.socket; /** * @type {string} */ this.host = typeof options.host === 'string' ? options.host : '127.0.0.1'; /** * @type {number} */ this.port = typeof options.port === 'number' ? options.port : 502; }; UdpConnection.prototype.destroy = function() { this.removeAllListeners(); this.options = null; if (this.socket !== null) { this.socket.removeAllListeners(); this.socket.close(); this.socket = null; } }; /** * @returns {boolean} Returns `true` if the underlying `dgram.Socket` is bound, * i.e. the `bind()` method was called and the `listening` event was emitted. */ UdpConnection.prototype.isOpen = function() { try { this.socket.address(); return true; } catch (err) { return false; } }; /** * @param {Buffer} data */ UdpConnection.prototype.write = function(data) { this.emit('write', data); try { this.socket.send( data, 0, data.length, this.options.port, this.options.host ); } catch (err) { this.emit('error', err); } }; /** * @private * @returns {dgram.Socket} */ UdpConnection.prototype.setUpSocket = function() { var socket = this.options.socket; socket.on('listening', this.emit.bind(this, 'open')); socket.on('close', this.emit.bind(this, 'close')); socket.on('error', this.emit.bind(this, 'error')); socket.on('message', this.emit.bind(this, 'data')); return socket; };
'use strict'; const util = require('util'); const inherits = require('./utils/inherits'); const _ = require('lodash'); const wkx = require('wkx'); const sequelizeErrors = require('./errors'); const Validator = require('./utils/validator-extras').validator; const momentTz = require('moment-timezone'); const moment = require('moment'); const logger = require('./utils/logger'); const warnings = {}; function ABSTRACT() {} ABSTRACT.prototype.dialectTypes = ''; ABSTRACT.prototype.toString = function toString(options) { return this.toSql(options); }; ABSTRACT.prototype.toSql = function toSql() { return this.key; }; ABSTRACT.warn = function warn(link, text) { if (!warnings[text]) { warnings[text] = true; logger.warn(`${text} \n>> Check: ${link}`); } }; ABSTRACT.prototype.stringify = function stringify(value, options) { if (this._stringify) { return this._stringify(value, options); } return value; }; ABSTRACT.prototype.bindParam = function bindParam(value, options) { if (this._bindParam) { return this._bindParam(value, options); } return options.bindParam(this.stringify(value, options)); }; /** * STRING A variable length string * * @param {number} [length=255] length of string * @param {boolean} [binary=false] Is this binary? * * @namespace DataTypes.STRING * */ function STRING(length, binary) { const options = typeof length === 'object' && length || {length, binary}; if (!(this instanceof STRING)) return new STRING(options); this.options = options; this._binary = options.binary; this._length = options.length || 255; } inherits(STRING, ABSTRACT); STRING.prototype.key = STRING.key = 'STRING'; STRING.prototype.toSql = function toSql() { return `VARCHAR(${this._length})${this._binary ? ' BINARY' : ''}`; }; STRING.prototype.validate = function validate(value) { if (Object.prototype.toString.call(value) !== '[object String]') { if (this.options.binary && Buffer.isBuffer(value) || _.isNumber(value)) { return true; } throw new sequelizeErrors.ValidationError(util.format('%j is not a valid string', value)); } return true; }; Object.defineProperty(STRING.prototype, 'BINARY', { get() { this._binary = true; this.options.binary = true; return this; } }); /** * CHAR A fixed length string * * @param {number} [length=255] length of string * @param {boolean} [binary=false] Is this binary? * * @namespace DataTypes.CHAR */ function CHAR(length, binary) { const options = typeof length === 'object' && length || {length, binary}; if (!(this instanceof CHAR)) return new CHAR(options); STRING.apply(this, arguments); } inherits(CHAR, STRING); CHAR.prototype.key = CHAR.key = 'CHAR'; CHAR.prototype.toSql = function toSql() { return `CHAR(${this._length})${this._binary ? ' BINARY' : ''}`; }; /** * Unlimited length TEXT column * * @param {string} [length=''] could be tiny, medium, long. * * @namespace DataTypes.TEXT */ function TEXT(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof TEXT)) return new TEXT(options); this.options = options; this._length = options.length || ''; } inherits(TEXT, ABSTRACT); TEXT.prototype.key = TEXT.key = 'TEXT'; TEXT.prototype.toSql = function toSql() { switch (this._length.toLowerCase()) { case 'tiny': return 'TINYTEXT'; case 'medium': return 'MEDIUMTEXT'; case 'long': return 'LONGTEXT'; default: return this.key; } }; TEXT.prototype.validate = function validate(value) { if (!_.isString(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid string', value)); } return true; }; /** * An unlimited length case-insensitive text column. * Original case is preserved but acts case-insensitive when comparing values (such as when finding or unique constraints). * Only available in Postgres and SQLite. * * @namespace DataTypes.CITEXT */ function CITEXT() { if (!(this instanceof CITEXT)) return new CITEXT(); } inherits(CITEXT, ABSTRACT); CITEXT.prototype.key = CITEXT.key = 'CITEXT'; CITEXT.prototype.toSql = function toSql() { return 'CITEXT'; }; CITEXT.prototype.validate = function validate(value) { if (!_.isString(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid string', value)); } return true; }; /** * Base number type which is used to build other types * * @param {Object} options type options * @param {string|number} [options.length] length of type, like `INT(4)` * @param {boolean} [options.zerofill] Is zero filled? * @param {boolean} [options.unsigned] Is unsigned? * @param {string|number} [options.decimals] number of decimal points, used with length `FLOAT(5, 4)` * @param {string|number} [options.precision] defines precision for decimal type * @param {string|number} [options.scale] defines scale for decimal type * * @namespace DataTypes.NUMBER */ function NUMBER(options) { this.options = options; this._length = options.length; this._zerofill = options.zerofill; this._decimals = options.decimals; this._precision = options.precision; this._scale = options.scale; this._unsigned = options.unsigned; } inherits(NUMBER, ABSTRACT); NUMBER.prototype.key = NUMBER.key = 'NUMBER'; NUMBER.prototype.toSql = function toSql() { let result = this.key; if (this._length) { result += `(${this._length}`; if (typeof this._decimals === 'number') { result += `,${this._decimals}`; } result += ')'; } if (this._unsigned) { result += ' UNSIGNED'; } if (this._zerofill) { result += ' ZEROFILL'; } return result; }; NUMBER.prototype.validate = function(value) { if (!Validator.isFloat(String(value))) { throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${_.toLower(this.key)}`, value)); } return true; }; Object.defineProperty(NUMBER.prototype, 'UNSIGNED', { get() { this._unsigned = true; this.options.unsigned = true; return this; } }); Object.defineProperty(NUMBER.prototype, 'ZEROFILL', { get() { this._zerofill = true; this.options.zerofill = true; return this; } }); /** * A 32 bit integer * * @param {string|number} [length] Integer length, INT(12) * * @namespace DataTypes.INTEGER */ function INTEGER(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof INTEGER)) return new INTEGER(options); NUMBER.call(this, options); } inherits(INTEGER, NUMBER); INTEGER.prototype.key = INTEGER.key = 'INTEGER'; INTEGER.prototype.validate = function validate(value) { if (!Validator.isInt(String(value))) { throw new sequelizeErrors.ValidationError(util.format(`%j is not a valid ${_.toLower(this.key)}`, value)); } return true; }; /** * A 8 bit integer * * @param {string|number} [length] Integer length * * @namespace DataTypes.TINYINT */ function TINYINT(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof TINYINT)) return new TINYINT(options); NUMBER.call(this, options); } inherits(TINYINT, INTEGER); TINYINT.prototype.key = TINYINT.key = 'TINYINT'; /** * A 16 bit integer * * @param {string|number} [length] Integer length * * @namespace DataTypes.SMALLINT */ function SMALLINT(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof SMALLINT)) return new SMALLINT(options); NUMBER.call(this, options); } inherits(SMALLINT, INTEGER); SMALLINT.prototype.key = SMALLINT.key = 'SMALLINT'; /** * A 24 bit integer * * @param {string|number} [length] Integer length * * @namespace DataTypes.MEDIUMINT */ function MEDIUMINT(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof MEDIUMINT)) return new MEDIUMINT(options); NUMBER.call(this, options); } inherits(MEDIUMINT, INTEGER); MEDIUMINT.prototype.key = MEDIUMINT.key = 'MEDIUMINT'; /** * A 64 bit integer * * @param {string|number} [length] Integer length * * @namespace DataTypes.BIGINT */ function BIGINT(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof BIGINT)) return new BIGINT(options); NUMBER.call(this, options); } inherits(BIGINT, INTEGER); BIGINT.prototype.key = BIGINT.key = 'BIGINT'; /** * Floating point number (4-byte precision). * * @param {string|number} [length] length of type, like `FLOAT(4)` * @param {string|number} [decimals] number of decimal points, used with length `FLOAT(5, 4)` * * @namespace DataTypes.FLOAT */ function FLOAT(length, decimals) { const options = typeof length === 'object' && length || {length, decimals}; if (!(this instanceof FLOAT)) return new FLOAT(options); NUMBER.call(this, options); } inherits(FLOAT, NUMBER); FLOAT.prototype.key = FLOAT.key = 'FLOAT'; FLOAT.prototype.validate = function validate(value) { if (!Validator.isFloat(String(value))) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid float', value)); } return true; }; /** * Floating point number (4-byte precision). * * @param {string|number} [length] length of type, like `REAL(4)` * @param {string|number} [decimals] number of decimal points, used with length `REAL(5, 4)` * * @namespace DataTypes.REAL */ function REAL(length, decimals) { const options = typeof length === 'object' && length || {length, decimals}; if (!(this instanceof REAL)) return new REAL(options); NUMBER.call(this, options); } inherits(REAL, NUMBER); REAL.prototype.key = REAL.key = 'REAL'; /** * Floating point number (8-byte precision). * * @param {string|number} [length] length of type, like `DOUBLE PRECISION(25)` * @param {string|number} [decimals] number of decimal points, used with length `DOUBLE PRECISION(25, 10)` * * @namespace DataTypes.DOUBLE */ function DOUBLE(length, decimals) { const options = typeof length === 'object' && length || {length, decimals}; if (!(this instanceof DOUBLE)) return new DOUBLE(options); NUMBER.call(this, options); } inherits(DOUBLE, NUMBER); DOUBLE.prototype.key = DOUBLE.key = 'DOUBLE PRECISION'; /** * Decimal type, variable precision, take length as specified by user * * @param {string|number} [precision] defines precision * @param {string|number} [scale] defines scale * * @namespace DataTypes.DECIMAL */ function DECIMAL(precision, scale) { const options = typeof precision === 'object' && precision || {precision, scale}; if (!(this instanceof DECIMAL)) return new DECIMAL(options); NUMBER.call(this, options); } inherits(DECIMAL, NUMBER); DECIMAL.prototype.key = DECIMAL.key = 'DECIMAL'; DECIMAL.prototype.toSql = function toSql() { if (this._precision || this._scale) { return `DECIMAL(${[this._precision, this._scale].filter(_.identity).join(',')})`; } return 'DECIMAL'; }; DECIMAL.prototype.validate = function validate(value) { if (!Validator.isDecimal(String(value))) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid decimal', value)); } return true; }; for (const floating of [FLOAT, DOUBLE, REAL]) { floating.prototype.escape = false; floating.prototype._value = function _value(value) { if (isNaN(value)) { return 'NaN'; } else if (!isFinite(value)) { const sign = value < 0 ? '-' : ''; return `${sign}Infinity`; } return value; }; floating.prototype._stringify = function _stringify(value) { return `'${this._value(value)}'`; }; floating.prototype._bindParam = function _bindParam(value, options) { return options.bindParam(this._value(value)); }; } /** * A boolean / tinyint column, depending on dialect * * @namespace DataTypes.BOOLEAN */ function BOOLEAN() { if (!(this instanceof BOOLEAN)) return new BOOLEAN(); } inherits(BOOLEAN, ABSTRACT); BOOLEAN.prototype.key = BOOLEAN.key = 'BOOLEAN'; BOOLEAN.prototype.toSql = function toSql() { return 'TINYINT(1)'; }; BOOLEAN.prototype.validate = function validate(value) { if (!Validator.isBoolean(String(value))) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid boolean', value)); } return true; }; BOOLEAN.prototype._sanitize = function _sanitize(value) { if (value !== null && value !== undefined) { if (Buffer.isBuffer(value) && value.length === 1) { // Bit fields are returned as buffers value = value[0]; } if (_.isString(value)) { // Only take action on valid boolean strings. value = value === 'true' ? true : value === 'false' ? false : value; } else if (_.isNumber(value)) { // Only take action on valid boolean integers. value = value === 1 ? true : value === 0 ? false : value; } } return value; }; BOOLEAN.parse = BOOLEAN.prototype._sanitize; /** * A time column * * @namespace DataTypes.TIME */ function TIME() { if (!(this instanceof TIME)) return new TIME(); } inherits(TIME, ABSTRACT); TIME.prototype.key = TIME.key = 'TIME'; TIME.prototype.toSql = function toSql() { return 'TIME'; }; /** * Date column with timezone, default is UTC * * @param {string|number} [length] precision to allow storing milliseconds * * @namespace DataTypes.DATE */ function DATE(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof DATE)) return new DATE(options); this.options = options; this._length = options.length || ''; } inherits(DATE, ABSTRACT); DATE.prototype.key = DATE.key = 'DATE'; DATE.prototype.toSql = function toSql() { return 'DATETIME'; }; DATE.prototype.validate = function validate(value) { if (!Validator.isDate(String(value))) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid date', value)); } return true; }; DATE.prototype._sanitize = function _sanitize(value, options) { if ((!options || options && !options.raw) && !(value instanceof Date) && !!value) { return new Date(value); } return value; }; DATE.prototype._isChanged = function _isChanged(value, originalValue) { if ( originalValue && !!value && ( value === originalValue || value instanceof Date && originalValue instanceof Date && value.getTime() === originalValue.getTime() ) ) { return false; } // not changed when set to same empty value if (!originalValue && !value && originalValue === value) { return false; } return true; }; DATE.prototype._applyTimezone = function _applyTimezone(date, options) { if (options.timezone) { if (momentTz.tz.zone(options.timezone)) { date = momentTz(date).tz(options.timezone); } else { date = moment(date).utcOffset(options.timezone); } } else { date = momentTz(date); } return date; }; DATE.prototype._stringify = function _stringify(date, options) { date = this._applyTimezone(date, options); // Z here means current timezone, _not_ UTC return date.format('YYYY-MM-DD HH:mm:ss.SSS Z'); }; /** * A date only column (no timestamp) * * @namespace DataTypes.DATEONLY */ function DATEONLY() { if (!(this instanceof DATEONLY)) return new DATEONLY(); } util.inherits(DATEONLY, ABSTRACT); DATEONLY.prototype.key = DATEONLY.key = 'DATEONLY'; DATEONLY.prototype.toSql = function() { return 'DATE'; }; DATEONLY.prototype._stringify = function _stringify(date) { return moment(date).format('YYYY-MM-DD'); }; DATEONLY.prototype._sanitize = function _sanitize(value, options) { if ((!options || options && !options.raw) && !!value) { return moment(value).format('YYYY-MM-DD'); } return value; }; DATEONLY.prototype._isChanged = function _isChanged(value, originalValue) { if (originalValue && !!value && originalValue === value) { return false; } // not changed when set to same empty value if (!originalValue && !value && originalValue === value) { return false; } return true; }; /** * A key / value store column. Only available in Postgres. * * @namespace DataTypes.HSTORE */ function HSTORE() { if (!(this instanceof HSTORE)) return new HSTORE(); } inherits(HSTORE, ABSTRACT); HSTORE.prototype.key = HSTORE.key = 'HSTORE'; HSTORE.prototype.validate = function validate(value) { if (!_.isPlainObject(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid hstore', value)); } return true; }; /** * A JSON string column. Available in MySQL, Postgres and SQLite * * @namespace DataTypes.JSON */ function JSONTYPE() { if (!(this instanceof JSONTYPE)) return new JSONTYPE(); } inherits(JSONTYPE, ABSTRACT); JSONTYPE.prototype.key = JSONTYPE.key = 'JSON'; JSONTYPE.prototype.validate = function validate() { return true; }; JSONTYPE.prototype._stringify = function _stringify(value) { return JSON.stringify(value); }; /** * A binary storage JSON column. Only available in Postgres. * * @namespace DataTypes.JSONB */ function JSONB() { if (!(this instanceof JSONB)) return new JSONB(); JSONTYPE.call(this); } inherits(JSONB, JSONTYPE); JSONB.prototype.key = JSONB.key = 'JSONB'; /** * A default value of the current timestamp * * @namespace DataTypes.NOW */ function NOW() { if (!(this instanceof NOW)) return new NOW(); } inherits(NOW, ABSTRACT); NOW.prototype.key = NOW.key = 'NOW'; /** * Binary storage * * @param {string} [length=''] could be tiny, medium, long. * * @namespace DataTypes.BLOB * */ function BLOB(length) { const options = typeof length === 'object' && length || {length}; if (!(this instanceof BLOB)) return new BLOB(options); this.options = options; this._length = options.length || ''; } inherits(BLOB, ABSTRACT); BLOB.prototype.key = BLOB.key = 'BLOB'; BLOB.prototype.toSql = function toSql() { switch (this._length.toLowerCase()) { case 'tiny': return 'TINYBLOB'; case 'medium': return 'MEDIUMBLOB'; case 'long': return 'LONGBLOB'; default: return this.key; } }; BLOB.prototype.validate = function validate(value) { if (!_.isString(value) && !Buffer.isBuffer(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid blob', value)); } return true; }; BLOB.prototype.escape = false; BLOB.prototype._stringify = function _stringify(value) { if (!Buffer.isBuffer(value)) { if (Array.isArray(value)) { value = Buffer.from(value); } else { value = Buffer.from(value.toString()); } } const hex = value.toString('hex'); return this._hexify(hex); }; BLOB.prototype._hexify = function _hexify(hex) { return `X'${hex}'`; }; BLOB.prototype._bindParam = function _bindParam(value, options) { if (!Buffer.isBuffer(value)) { if (Array.isArray(value)) { value = Buffer.from(value); } else { value = Buffer.from(value.toString()); } } return options.bindParam(value); }; /** * Range types are data types representing a range of values of some element type (called the range's subtype). * Only available in Postgres. See [the Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details * * @param {<DataTypes>} subtype A subtype for range, like RANGE(DATE) * * @namespace DataTypes.RANGE */ function RANGE(subtype) { const options = _.isPlainObject(subtype) ? subtype : {subtype}; if (!options.subtype) options.subtype = new INTEGER(); if (_.isFunction(options.subtype)) { options.subtype = new options.subtype(); } if (!(this instanceof RANGE)) return new RANGE(options); this._subtype = options.subtype.key; this.options = options; } inherits(RANGE, ABSTRACT); const pgRangeSubtypes = { integer: 'int4range', bigint: 'int8range', decimal: 'numrange', dateonly: 'daterange', date: 'tstzrange', datenotz: 'tsrange' }; const pgRangeCastTypes = { integer: 'integer', bigint: 'bigint', decimal: 'numeric', dateonly: 'date', date: 'timestamptz', datenotz: 'timestamp' }; RANGE.prototype.key = RANGE.key = 'RANGE'; RANGE.prototype.toSql = function toSql() { return pgRangeSubtypes[this._subtype.toLowerCase()]; }; RANGE.prototype.toCastType = function toCastType() { return pgRangeCastTypes[this._subtype.toLowerCase()]; }; RANGE.prototype.validate = function validate(value) { if (!Array.isArray(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid range', value)); } if (value.length !== 2) { throw new sequelizeErrors.ValidationError('A range must be an array with two elements'); } return true; }; /** * A column storing a unique universal identifier. * Use with `UUIDV1` or `UUIDV4` for default values. * * @namespace DataTypes.UUID */ function UUID() { if (!(this instanceof UUID)) return new UUID(); } inherits(UUID, ABSTRACT); UUID.prototype.key = UUID.key = 'UUID'; UUID.prototype.validate = function validate(value, options) { if (!_.isString(value) || !Validator.isUUID(value) && (!options || !options.acceptStrings)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuid', value)); } return true; }; /** * A default unique universal identifier generated following the UUID v1 standard * * @namespace DataTypes.UUIDV1 */ function UUIDV1() { if (!(this instanceof UUIDV1)) return new UUIDV1(); } inherits(UUIDV1, ABSTRACT); UUIDV1.prototype.key = UUIDV1.key = 'UUIDV1'; UUIDV1.prototype.validate = function validate(value, options) { if (!_.isString(value) || !Validator.isUUID(value) && (!options || !options.acceptStrings)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuid', value)); } return true; }; /** * A default unique universal identifier generated following the UUID v4 standard * * @namespace DataTypes.UUIDV4 */ function UUIDV4() { if (!(this instanceof UUIDV4)) return new UUIDV4(); } inherits(UUIDV4, ABSTRACT); UUIDV4.prototype.key = UUIDV4.key = 'UUIDV4'; UUIDV4.prototype.validate = function validate(value, options) { if (!_.isString(value) || !Validator.isUUID(value, 4) && (!options || !options.acceptStrings)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid uuidv4', value)); } return true; }; /** * A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB. * * You could also use it to validate a value before permuting and storing it. VIRTUAL also takes a return type and dependency fields as arguments * If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well. * Return type is mostly useful for setups that rely on types like GraphQL. * * @example <caption>Checking password length before hashing it</caption> * sequelize.define('user', { * password_hash: DataTypes.STRING, * password: { * type: DataTypes.VIRTUAL, * set: function (val) { * // Remember to set the data value, otherwise it won't be validated * this.setDataValue('password', val); * this.setDataValue('password_hash', this.salt + val); * }, * validate: { * isLongEnough: function (val) { * if (val.length < 7) { * throw new Error("Please choose a longer password") * } * } * } * } * }) * * # In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB. * * @example <caption>Virtual with dependency fields</caption> * { * active: { * type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']), * get: function() { * return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000) * } * } * } * * @param {<DataTypes>} [ReturnType] return type for virtual type * @param {Array} [fields] array of fields this virtual type is dependent on * * @namespace DataTypes.VIRTUAL * */ function VIRTUAL(ReturnType, fields) { if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields); if (typeof ReturnType === 'function') ReturnType = new ReturnType(); this.returnType = ReturnType; this.fields = fields; } inherits(VIRTUAL, ABSTRACT); VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL'; /** * An enumeration, Postgres Only * * @example * DataTypes.ENUM('value', 'another value') * DataTypes.ENUM(['value', 'another value']) * DataTypes.ENUM({ * values: ['value', 'another value'] * }) * * @param {Array|Object} value either array of values or options object with values array. It also supports variadic values * * @namespace DataTypes.ENUM * */ function ENUM(value) { const options = typeof value === 'object' && !Array.isArray(value) && value || { values: Array.prototype.slice.call(arguments).reduce((result, element) => { return result.concat(Array.isArray(element) ? element : [element]); }, []) }; if (!(this instanceof ENUM)) return new ENUM(options); this.values = options.values; this.options = options; } inherits(ENUM, ABSTRACT); ENUM.prototype.key = ENUM.key = 'ENUM'; ENUM.prototype.validate = function validate(value) { if (!this.values.includes(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid choice in %j', value, this.values)); } return true; }; /** * An array of `type`. Only available in Postgres. * * @example * DataTypes.ARRAY(DataTypes.DECIMAL)`. * * @param {<DataTypes>} type type of array values * * @namespace DataTypes.ARRAY */ function ARRAY(type) { const options = _.isPlainObject(type) ? type : {type}; if (!(this instanceof ARRAY)) return new ARRAY(options); this.type = typeof options.type === 'function' ? new options.type() : options.type; } inherits(ARRAY, ABSTRACT); ARRAY.prototype.key = ARRAY.key = 'ARRAY'; ARRAY.prototype.toSql = function toSql() { return `${this.type.toSql()}[]`; }; ARRAY.prototype.validate = function validate(value) { if (!Array.isArray(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid array', value)); } return true; }; ARRAY.is = function is(obj, type) { return obj instanceof ARRAY && obj.type instanceof type; }; /** * A column storing Geometry information. * It is only available in PostgreSQL (with PostGIS) or MySQL. * In MySQL, allowable Geometry types are `POINT`, `LINESTRING`, `POLYGON`. * * GeoJSON is accepted as input and returned as output. * * In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`. * In MySQL it is parsed using the function `GeomFromText`. * * Therefore, one can just follow the [GeoJSON spec](http://geojson.org/geojson-spec.html) for handling geometry objects. See the following examples: * * @example <caption>Defining a Geometry type attribute</caption> * DataTypes.GEOMETRY * DataTypes.GEOMETRY('POINT') * DataTypes.GEOMETRY('POINT', 4326) * * @example <caption>Create a new point</caption> * const point = { type: 'Point', coordinates: [39.807222,-76.984722]}; * * User.create({username: 'username', geometry: point }); * * @example <caption>Create a new linestring</caption> * const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] }; * * User.create({username: 'username', geometry: line }); * * @example <caption>Create a new polygon</caption> * const polygon = { type: 'Polygon', coordinates: [ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], * [100.0, 1.0], [100.0, 0.0] ] * ]}; * * User.create({username: 'username', geometry: polygon }); * @example <caption>Create a new point with a custom SRID</caption> * const point = { * type: 'Point', * coordinates: [39.807222,-76.984722], * crs: { type: 'name', properties: { name: 'EPSG:4326'} } * }; * * User.create({username: 'username', geometry: point }) * * @param {string} [type] Type of geometry data * @param {string} [srid] SRID of type * * @see {@link DataTypes.GEOGRAPHY} * @namespace DataTypes.GEOMETRY */ function GEOMETRY(type, srid) { const options = _.isPlainObject(type) ? type : {type, srid}; if (!(this instanceof GEOMETRY)) return new GEOMETRY(options); this.options = options; this.type = options.type; this.srid = options.srid; } inherits(GEOMETRY, ABSTRACT); GEOMETRY.prototype.key = GEOMETRY.key = 'GEOMETRY'; GEOMETRY.prototype.escape = false; GEOMETRY.prototype._stringify = function _stringify(value, options) { return `GeomFromText(${options.escape(wkx.Geometry.parseGeoJSON(value).toWkt())})`; }; GEOMETRY.prototype._bindParam = function _bindParam(value, options) { return `GeomFromText(${options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt())})`; }; /** * A geography datatype represents two dimensional spacial objects in an elliptic coord system. * * __The difference from geometry and geography type:__ * * PostGIS 1.5 introduced a new spatial type called geography, which uses geodetic measurement instead of Cartesian measurement. * Coordinate points in the geography type are always represented in WGS 84 lon lat degrees (SRID 4326), * but measurement functions and relationships ST_Distance, ST_DWithin, ST_Length, and ST_Area always return answers in meters or assume inputs in meters. * * __What is best to use? It depends:__ * * When choosing between the geometry and geography type for data storage, you should consider what you’ll be using it for. * If all you do are simple measurements and relationship checks on your data, and your data covers a fairly large area, then most likely you’ll be better off storing your data using the new geography type. * Although the new geography data type can cover the globe, the geometry type is far from obsolete. * The geometry type has a much richer set of functions than geography, relationship checks are generally faster, and it has wider support currently across desktop and web-mapping tools * * @example <caption>Defining a Geography type attribute</caption> * DataTypes.GEOGRAPHY * DataTypes.GEOGRAPHY('POINT') * DataTypes.GEOGRAPHY('POINT', 4326) * * @param {string} [type] Type of geography data * @param {string} [srid] SRID of type * * @namespace DataTypes.GEOGRAPHY */ function GEOGRAPHY(type, srid) { const options = _.isPlainObject(type) ? type : {type, srid}; if (!(this instanceof GEOGRAPHY)) return new GEOGRAPHY(options); this.options = options; this.type = options.type; this.srid = options.srid; } inherits(GEOGRAPHY, ABSTRACT); GEOGRAPHY.prototype.key = GEOGRAPHY.key = 'GEOGRAPHY'; GEOGRAPHY.prototype.escape = false; GEOGRAPHY.prototype._stringify = function _stringify(value, options) { return `GeomFromText(${options.escape(wkx.Geometry.parseGeoJSON(value).toWkt())})`; }; GEOGRAPHY.prototype._bindParam = function _bindParam(value, options) { return `GeomFromText(${options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt())})`; }; /** * The cidr type holds an IPv4 or IPv6 network specification. Takes 7 or 19 bytes. * * Only available for Postgres * * @namespace DataTypes.CIDR */ function CIDR() { if (!(this instanceof CIDR)) return new CIDR(); } inherits(CIDR, ABSTRACT); CIDR.prototype.key = CIDR.key = 'CIDR'; CIDR.prototype.validate = function validate(value) { if (!_.isString(value) || !Validator.isIPRange(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid CIDR', value)); } return true; }; /** * The INET type holds an IPv4 or IPv6 host address, and optionally its subnet. Takes 7 or 19 bytes * * Only available for Postgres * * @namespace DataTypes.INET */ function INET() { if (!(this instanceof INET)) return new INET(); } inherits(INET, ABSTRACT); INET.prototype.key = INET.key = 'INET'; INET.prototype.validate = function validate(value) { if (!_.isString(value) || !Validator.isIP(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid INET', value)); } return true; }; /** * The MACADDR type stores MAC addresses. Takes 6 bytes * * Only available for Postgres * * @namespace DataTypes.MACADDR */ function MACADDR() { if (!(this instanceof MACADDR)) return new MACADDR(); } inherits(MACADDR, ABSTRACT); MACADDR.prototype.key = MACADDR.key = 'MACADDR'; MACADDR.prototype.validate = function validate(value) { if (!_.isString(value) || !Validator.isMACAddress(value)) { throw new sequelizeErrors.ValidationError(util.format('%j is not a valid MACADDR', value)); } return true; }; const helpers = { BINARY: [STRING, CHAR], UNSIGNED: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL], ZEROFILL: [NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL], PRECISION: [DECIMAL], SCALE: [DECIMAL] }; for (const helper of Object.keys(helpers)) { for (const DataType of helpers[helper]) { if (!DataType[helper]) { Object.defineProperty(DataType, helper, { get() { const dataType = new DataType(); if (typeof dataType[helper] === 'object') { return dataType; } return dataType[helper].apply(dataType, arguments); } }); } } } /** * A convenience class holding commonly used data types. The data types are used when defining a new model using `Sequelize.define`, like this: * ```js * sequelize.define('model', { * column: DataTypes.INTEGER * }) * ``` * When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean * that that column will be returned as an instance of `Buffer` when being fetched by sequelize. * * To provide a length for the data type, you can invoke it like a function: `INTEGER(2)` * * Some data types have special properties that can be accessed in order to change the data type. * For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`. * The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well. * * * All number types (`INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `REAL`, `DECIMAL`) expose the properties `UNSIGNED` and `ZEROFILL` * * The `CHAR` and `STRING` types expose the `BINARY` property * * Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for * defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard: * ```js` * sequelize.define('model',` { * uuid: { * type: DataTypes.UUID, * defaultValue: DataTypes.UUIDV1, * primaryKey: true * } * }) * ``` * There may be times when you want to generate your own UUID conforming to some other algorithm. This is accomplished * using the defaultValue property as well, but instead of specifying one of the supplied UUID types, you return a value * from a function. * ```js * sequelize.define('model', { * uuid: { * type: DataTypes.UUID, * defaultValue: function() { * return generateMyId() * }, * primaryKey: true * } * }) * ``` * * @namespace DataTypes */ const DataTypes = module.exports = { ABSTRACT, STRING, CHAR, TEXT, NUMBER, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, TIME, DATE, DATEONLY, BOOLEAN, NOW, BLOB, DECIMAL, NUMERIC: DECIMAL, UUID, UUIDV1, UUIDV4, HSTORE, JSON: JSONTYPE, JSONB, VIRTUAL, ARRAY, ENUM, RANGE, REAL, DOUBLE, 'DOUBLE PRECISION': DOUBLE, GEOMETRY, GEOGRAPHY, CIDR, INET, MACADDR, CITEXT }; _.each(DataTypes, dataType => { dataType.types = {}; }); DataTypes.postgres = require('./dialects/postgres/data-types')(DataTypes); DataTypes.mysql = require('./dialects/mysql/data-types')(DataTypes); DataTypes.sqlite = require('./dialects/sqlite/data-types')(DataTypes); DataTypes.mssql = require('./dialects/mssql/data-types')(DataTypes); module.exports = DataTypes;
'use strict'; (function() { // Dancers Controller Spec describe('Dancers Controller Tests', function() { // Initialize global variables var DancersController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Dancers controller. DancersController = $controller('DancersController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Dancer object fetched from XHR', inject(function(Dancers) { // Create sample Dancer using the Dancers service var sampleDancer = new Dancers({ name: 'New Dancer' }); // Create a sample Dancers array that includes the new Dancer var sampleDancers = [sampleDancer]; // Set GET response $httpBackend.expectGET('dancers').respond(sampleDancers); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.dancers).toEqualData(sampleDancers); })); it('$scope.findOne() should create an array with one Dancer object fetched from XHR using a dancerId URL parameter', inject(function(Dancers) { // Define a sample Dancer object var sampleDancer = new Dancers({ name: 'New Dancer' }); // Set the URL parameter $stateParams.dancerId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/dancers\/([0-9a-fA-F]{24})$/).respond(sampleDancer); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.dancer).toEqualData(sampleDancer); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Dancers) { // Create a sample Dancer object var sampleDancerPostData = new Dancers({ name: 'New Dancer' }); // Create a sample Dancer response var sampleDancerResponse = new Dancers({ _id: '525cf20451979dea2c000001', name: 'New Dancer' }); // Fixture mock form input values scope.name = 'New Dancer'; // Set POST response $httpBackend.expectPOST('dancers', sampleDancerPostData).respond(sampleDancerResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Dancer was created expect($location.path()).toBe('/dancers/' + sampleDancerResponse._id); })); it('$scope.update() should update a valid Dancer', inject(function(Dancers) { // Define a sample Dancer put data var sampleDancerPutData = new Dancers({ _id: '525cf20451979dea2c000001', name: 'New Dancer' }); // Mock Dancer in scope scope.dancer = sampleDancerPutData; // Set PUT response $httpBackend.expectPUT(/dancers\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/dancers/' + sampleDancerPutData._id); })); it('$scope.remove() should send a DELETE request with a valid dancerId and remove the Dancer from the scope', inject(function(Dancers) { // Create new Dancer object var sampleDancer = new Dancers({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Dancers array and include the Dancer scope.dancers = [sampleDancer]; // Set expected DELETE response $httpBackend.expectDELETE(/dancers\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleDancer); $httpBackend.flush(); // Test array after successful delete expect(scope.dancers.length).toBe(0); })); }); }());
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "./public"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _FunctionalNetworkNetworkJs = __webpack_require__(1); var _FunctionalNetworkNetworkJs2 = _interopRequireDefault(_FunctionalNetworkNetworkJs); var networkParams = { topology: [2, 4, 1], alpha: 0.5, eta: 0.15, recentAverageSmoothingFactor: 100 }; var network = _FunctionalNetworkNetworkJs2['default'].createNetwork(networkParams); var table = [{ input: [0, 0], output: [0] }, { input: [1, 1], output: [0] }, { input: [1, 0], output: [1] }, { input: [0, 1], output: [1] }]; function learn() { var tableLength = table.length; var t1 = new Date(); for (var i = 0; i < 500000; i++) { var index = Math.floor(Math.random() * tableLength); table.push(table[index]); } console.info('create lessons', new Date() - t1); t1 = new Date(); for (var i = 0; i < table.length; i++) { var data = table[i]; _FunctionalNetworkNetworkJs2['default'].feedForward(data.input, network); _FunctionalNetworkNetworkJs2['default'].backProp(data.output, network); } console.info('learn', new Date() - t1); console.info(network.recentAverageError); } learn(); console.info(network); window.network = _FunctionalNetworkNetworkJs2['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _utilsJs = __webpack_require__(2); var _NeuronFunctionsJs = __webpack_require__(3); var network = { "eta": 0.15, "alpha": 0.5, "error": 0, "recentAverageError": 0, "recentAverageSmoothingFactor": 0, "layers": [] }; function createNetwork(struct) { network.error = struct.error || 0; network.recentAverageError = struct.recentAverageError || 0; network.recentAverageSmoothingFactor = struct.recentAverageSmoothingFactor || 0; var topology = struct.topology; var numLayers = topology.length; for (var layerNum = 0; layerNum < numLayers; ++layerNum) { var layer = []; network.layers.push(layer); var numOutputs = getNumOfOutputs(layerNum, topology); var lastLayer = (0, _utilsJs.getLast)(network.layers); for (var neuronNum = 0; neuronNum <= topology[layerNum]; ++neuronNum) { var neuron = { eta: struct.eta || 0.15, alpha: struct.alpha || 0.5, outputVal: 0, gradient: 0, index: neuronNum, outputWeights: getOutputWeights(numOutputs) }; lastLayer.push(neuron); } (0, _utilsJs.getLast)(lastLayer).outputVal = 1; } return network; } function getNumOfOutputs(layerNum, topology) { return layerNum == topology.length - 1 ? 0 : topology[layerNum + 1]; } function getOutputWeights(num) { var res = []; for (var i = 0; i < num; i++) { res.push({ weight: Math.random(), deltaWeight: 0 }); } return res; } function feedForward(inputVals, network) { var layers = network.layers; for (var i = 0; i < inputVals.length; ++i) { (0, _utilsJs.getFirst)(layers)[i].outputVal = inputVals[i]; } for (var layerNum = 1; layerNum < layers.length; ++layerNum) { var prevLayer = layers[layerNum - 1]; for (var n = 0; n < layers[layerNum].length - 1; ++n) { (0, _NeuronFunctionsJs.feedForwardNeuron)(layers[layerNum][n], prevLayer); } } } function backProp(targetVals, network) { var layers = network.layers; var outputLayer = (0, _utilsJs.getLast)(layers); network.error = 0; for (var n = 0; n < outputLayer.length - 1; ++n) { var delta = targetVals[n] - outputLayer[n].outputVal; network.error += delta * delta; } network.error /= outputLayer.length - 1; network.error = Math.sqrt(network.error); network.recentAverageError = (network.recentAverageError * network.recentAverageSmoothingFactor + network.error) / (network.recentAverageSmoothingFactor + 1.0); for (var n = 0; n < outputLayer.length - 1; ++n) { (0, _NeuronFunctionsJs.calcOutputGradients)(outputLayer[n], targetVals[n]); } for (var layerNum = layers.length - 2; layerNum > 0; --layerNum) { var hiddenLayer = layers[layerNum]; var nextLayer = layers[layerNum + 1]; for (var n = 0; n < hiddenLayer.length; ++n) { (0, _NeuronFunctionsJs.calcHiddenGradients)(hiddenLayer[n], nextLayer); } } for (var layerNum = layers.length - 1; layerNum > 0; --layerNum) { var layer = layers[layerNum]; var prevLayer = layers[layerNum - 1]; for (var n = 0; n < layer.length - 1; ++n) { (0, _NeuronFunctionsJs.updateInputWeights)(layer[n], prevLayer); } } } var networkFunctions = { createNetwork: createNetwork, feedForward: feedForward, backProp: backProp }; exports['default'] = networkFunctions; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getLast(arr) { return arr[arr.length - 1]; } function getFirst(arr) { return arr[0]; } var utils = { getLast: getLast, getFirst: getFirst }; exports["default"] = utils; module.exports = exports["default"]; /***/ }, /* 3 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function transferFunction(x) { return Math.tanh(x); } function transferFunctionDerivative(x) { return 1 - x * x; } function feedForwardNeuron(neuron, prevLayer) { var sum = 0; for (var n = 0; n < prevLayer.length; ++n) { sum += prevLayer[n].outputVal * prevLayer[n].outputWeights[neuron.index].weight; } neuron.outputVal = transferFunction(sum); } function calcOutputGradients(neuron, targetVal) { var delta = targetVal - neuron.outputVal; neuron.gradient = delta * transferFunctionDerivative(neuron.outputVal); } function sumDOW(neuron, nextLayer) { var sum = 0.0; for (var n = 0; n < nextLayer.length - 1; ++n) { sum += neuron.outputWeights[n].weight * nextLayer[n].gradient; } return sum; } function calcHiddenGradients(neuron, nextLayer) { var dow = sumDOW(neuron, nextLayer); neuron.gradient = dow * transferFunctionDerivative(neuron.outputVal); } function updateInputWeights(neuron, prevLayer) { for (var n = 0; n < prevLayer.length; ++n) { var neuronFromPrevLayer = prevLayer[n]; var oldDeltaWeight = neuronFromPrevLayer.outputWeights[neuron.index].deltaWeight; var newDeltaWeight = neuron.eta * neuronFromPrevLayer.outputVal * neuron.gradient + neuron.alpha * oldDeltaWeight; neuronFromPrevLayer.outputWeights[neuron.index].deltaWeight = newDeltaWeight; neuronFromPrevLayer.outputWeights[neuron.index].weight += newDeltaWeight; } } var neuronFunctions = { updateInputWeights: updateInputWeights, calcHiddenGradients: calcHiddenGradients, calcOutputGradients: calcOutputGradients, feedForwardNeuron: feedForwardNeuron }; exports["default"] = neuronFunctions; module.exports = exports["default"]; /***/ } /******/ ]);
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' import { Card, CardText } from 'material-ui/Card' import RaisedButton from 'material-ui/RaisedButton' import TextField from 'material-ui/TextField' const LoginForm = ({ onSubmit, onChange, errors, successMessage, user }) => ( <Card className='container'> <form action='/' onSubmit={onSubmit}> <h2 className='card-heading'>Login</h2> {successMessage && <p className='success-message'>{successMessage}</p>} {errors.summary && <p className='error-message'>{errors.summary}</p>} <div className='field-line'> <TextField floatingLabelText='Email' name='email' errorText={errors.email} onChange={onChange} value={user.email} pattern='[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$' /> </div> <div className='field-line'> <TextField floatingLabelText='Password' type='password' name='password' onChange={onChange} errorText={errors.password} value={user.password} /> </div> <div className='button-line'> <RaisedButton type='submit' label='Log in' primary /> </div> <CardText>Don't have an account? <Link to={'/signup'}>Create one</Link>.</CardText> </form> </Card> ) LoginForm.propTypes = { onSubmit: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, successMessage: PropTypes.string.isRequired, user: PropTypes.object.isRequired } export default LoginForm
"use strict"; var Assert = require("assert"); var Client = require("./../../index"); describe("[companies]", function() { var client; var token = "c286e38330e15246a640c2cf32a45ea45d93b2ba"; beforeEach(function() { client = new Client({ version: "1" }); client.authenticate({ type: "oauth", token: token }); }); it("should successfully execute GET /companies (all)", function(next) { client.companies.all( { "url-field-selector": "String", "is-company-admin": "Boolean", "start": "Number", "count": "Number" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id (get)", function(next) { client.companies.get( { "company-id": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/ (getByUniversalName)", function(next) { client.companies.getByUniversalName( { "universal-name": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies (getByEmailDomain)", function(next) { client.companies.getByEmailDomain( { "email-domain": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/updates (getUpdate)", function(next) { client.companies.getUpdate( { "company-id": "String", "event-type": "String", "start": "Number", "count": "Number" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/updates/key=:company-update-key/update-comments (getUpdateComments)", function(next) { client.companies.getUpdateComments( { "company-id": "String", "company-update-key": "String", "event-type": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/updates/key=:company-update-key/likes (getUpdateCommentsLike)", function(next) { client.companies.getUpdateCommentsLike( { "company-id": "String", "company-update-key": "String", "event-type": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute POST /companies/:company-id/shares (addShare)", function(next) { client.companies.addShare( { "company-id": "String", "data": "Json" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/is-company-share-enabled (getShareEnabled)", function(next) { client.companies.getShareEnabled( { "company-id": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/relation-to-viewer/is-company-share-enabled (getCurrentShareEnabled)", function(next) { client.companies.getCurrentShareEnabled( { "company-id": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/historical-follow-statistics (getHistoricalFollowersStatistics)", function(next) { client.companies.getHistoricalFollowersStatistics( { "company-id": "String", "start-timestamp": "Number", "end-timestamp": "Number", "time-granularity": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/historical-status-update-statistics (getHistoricalStatusUpdate)", function(next) { client.companies.getHistoricalStatusUpdate( { "company-id": "String", "start-timestamp": "Number", "end-timestamp": "Number", "time-granularity": "String", "update-key": "String", "url-field-selector": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/company-statistics (getStatistics)", function(next) { client.companies.getStatistics( { "company-id": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /companies/:company-id/num-followers (getNumFollowers)", function(next) { client.companies.getNumFollowers( { "seniorities": "String", "geos": "String", "companySizes": "String", "jobFunc": "String", "industries": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute POST /people/~/network/updates/key=:update-key/update-comments (addShareComment)", function(next) { client.companies.addShareComment( { "update-key": "String", "data": "Json" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute PUT /people/~/network/updates/key=:update-key/is-liked (likeShareComment)", function(next) { client.companies.likeShareComment( { "update-key": "String", "data": "Json" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute PUT /companies/:company-id/updates/key=:update-key/update-comments-as-company/ (addUpdateComment)", function(next) { client.companies.addUpdateComment( { "update-key": "String", "company-id": "String", "data": "Json" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); it("should successfully execute GET /company-search (search)", function(next) { client.companies.search( { "keywords": "String", "hq-only": "String", "facet": "String", "facets": "String", "start": "Number", "count": "Number", "sort": "String", "url-field-selector": "String" }, function(err, res) { Assert.equal(err, null); // other assertions go here next(); } ); }); });
/* Copyright 2017 Mozilla Foundation * * 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. */ 'use strict'; var sharedUtil = require('../../shared/util.js'); var CMapCompressionType = sharedUtil.CMapCompressionType; var NodeCMapReaderFactory = function NodeCMapReaderFactoryClosure() { function NodeCMapReaderFactory(params) { this.baseUrl = params.baseUrl || null; this.isCompressed = params.isCompressed || false; } NodeCMapReaderFactory.prototype = { fetch: function (params) { var name = params.name; if (!name) { return Promise.reject(new Error('CMap name must be specified.')); } return new Promise(function (resolve, reject) { var url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : ''); var fs = require('fs'); fs.readFile(url, function (error, data) { if (error || !data) { reject(new Error('Unable to load ' + (this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url)); return; } resolve({ cMapData: new Uint8Array(data), compressionType: this.isCompressed ? CMapCompressionType.BINARY : CMapCompressionType.NONE }); }.bind(this)); }.bind(this)); } }; return NodeCMapReaderFactory; }(); exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
Ext.define('GestPrivilege.view.PrivilegeTree', { extend: 'Ext.tree.Panel', alias: 'widget.privilegetree', rootVisible: true, store: 'Privilege', title: Raptor.getTag('priv'), iconCls:'icon-privilege', height:400, initComponent: function() { this.dockedItems = [{ dock: 'top', xtype: 'toolbar', items: [{ xtype: 'button', text: Raptor.getTag('addcontainer'), privilegeName:'addDir', action:'addContainer', iconCls:'icon-vendor', disabled:true },{ xtype: 'button', text: Raptor.getTag('addindex'), disabled:true, privilegeName:'addIndex', action:'addIndex', iconCls:'icon-add' },{ xtype: 'button', text: Raptor.getTag('edit'), disabled:true, privilegeName:'edit', action:'editPrivilege', iconCls:'icon-edit' },{ xtype: 'button', text: Raptor.getTag('delete'), privilegeName:'delete', disabled:true, action:'deletePrivilege', iconCls:'icon-del' },{ xtype: 'button', text: Raptor.getTag('actions'), privilegeName:'listaction', disabled:true, action:'actionsWindow', iconCls:'icon-actions' }] }]; this.callParent(); } });
// This is the text editor interface. // Anything you type or change here will be seen by the other person in real time. // more than 5 times in 3 seconds => return false; normally just return true // store // [{ts: }] // lookup in this array for last 3 seconds, return false / true // c c c c c // TODO: circular array would be good var assert = require('assert'); var callTimeline = []; function rateCounter() { var ts = new Date(); var tMinus3s = new Date(ts.getTime() - 3000); // console.log(tMinus3s); if (callTimeline.length === 6) { callTimeline.shift(); } callTimeline.push(ts); // what happened in last 3 seconds var count = 0; for (var i = callTimeline.length - 1; i >= 0; i--) { var t = callTimeline[i]; if (t > tMinus3s) { count++; if (count > 5) { return false; } } } return true; } for(var i = 0; i < 6; i++) { console.log(rateCounter()); } setTimeout(function() { for(var i = 0; i < 6; i++) { console.log(rateCounter()); } }, 3500);
AccountsTemplates.removeField('email'); AccountsTemplates.addFields([ { _id: "username", type: "text", displayName: "username", required: true, minLength: 5, } ]);
'use strict'; const { expect } = require('chai'); const Knex = require('../../../knex'); const _ = require('lodash'); const sinon = require('sinon'); const { KnexTimeoutError } = require('../../../lib/util/timeout'); const delay = require('../../../lib/util/delay'); module.exports = function (knex) { // Certain dialects do not have proper insert with returning, so if this is true // then pick an id to use as the "foreign key" just for testing transactions. const constid = /redshift/.test(knex.client.driverName); let fkid = 1; describe('Transactions', function () { it('can run with asCallback', function (ok) { knex .transaction(function (t) { t.commit(); }) .asCallback(ok); }); it('should throw when undefined transaction is sent to transacting', function () { return knex .transaction(function (t) { knex('accounts').transacting(undefined); }) .catch(function handle(error) { expect(error.message).to.equal( 'Invalid transacting value (null, undefined or empty object)' ); }); }); it('supports direct retrieval of a transaction without a callback', () => { const trxPromise = knex.transaction(); const query = knex.client.driverName === 'oracledb' ? '1 as "result" from DUAL' : '1 as result'; let transaction; return trxPromise .then((trx) => { transaction = trx; expect(trx.client.transacting).to.equal(true); return knex.transacting(trx).select(knex.raw(query)); }) .then((rows) => { expect(rows[0].result).to.equal(1); return transaction.commit(); }); }); it('should throw when null transaction is sent to transacting', function () { return knex .transaction(function (t) { knex('accounts').transacting(null); }) .catch(function handle(error) { expect(error.message).to.equal( 'Invalid transacting value (null, undefined or empty object)' ); }); }); it('should throw when empty object transaction is sent to transacting', function () { return knex .transaction(function (t) { knex('accounts').transacting({}); }) .catch(function handle(error) { expect(error.message).to.equal( 'Invalid transacting value (null, undefined or empty object)' ); }); }); it('should be able to commit transactions', function () { let id = null; return knex .transaction(function (t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email: 'transaction-test1@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (resp) { return knex('test_table_two') .transacting(t) .insert({ account_id: constid ? ++fkid : (id = resp[0]), details: '', status: 1, }); }) .then(function () { t.commit('Hello world'); }); }) .then(function (commitMessage) { expect(commitMessage).to.equal('Hello world'); return knex('accounts').where('id', id).select('first_name'); }) .then(function (resp) { if (!constid) { expect(resp).to.have.length(1); } }); }); it('should be able to rollback transactions', function () { let id = null; const err = new Error('error message'); return knex .transaction(function (t) { knex('accounts') .transacting(t) .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email: 'transaction-test2@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (resp) { return knex('test_table_two') .transacting(t) .insert({ account_id: constid ? ++fkid : (id = resp[0]), details: '', status: 1, }); }) .then(function () { t.rollback(err); }); }) .catch(function (msg) { expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }) .then(function (resp) { expect(resp.length).to.equal(0); }); }); it('should be able to commit transactions with a resolved trx query', function () { let id = null; return knex .transaction(function (trx) { return trx('accounts') .returning('id') .insert({ first_name: 'Transacting', last_name: 'User', email: 'transaction-test3@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (resp) { return trx('test_table_two').insert({ account_id: constid ? ++fkid : (id = resp[0]), details: '', status: 1, }); }) .then(function () { return 'Hello World'; }); }) .then(function (commitMessage) { expect(commitMessage).to.equal('Hello World'); return knex('accounts').where('id', id).select('first_name'); }) .then(function (resp) { if (!constid) { expect(resp).to.have.length(1); } }); }); it('should be able to rollback transactions with rejected trx query', function () { let id = null; const err = new Error('error message'); let __knexUid, count = 0; return knex .transaction(function (trx) { return trx('accounts') .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email: 'transaction-test4@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (resp) { return trx .insert({ account_id: constid ? ++fkid : (id = resp[0]), details: '', status: 1, }) .into('test_table_two'); }) .then(function () { throw err; }); }) .on('query', function (obj) { count++; if (!__knexUid) __knexUid = obj.__knexUid; expect(__knexUid).to.equal(obj.__knexUid); }) .catch(function (msg) { // oracle & mssql: BEGIN & ROLLBACK not reported as queries const expectedCount = knex.client.driverName === 'oracledb' || knex.client.driverName === 'mssql' ? 2 : 4; expect(count).to.equal(expectedCount); expect(msg).to.equal(err); return knex('accounts').where('id', id).select('first_name'); }) .then(function (resp) { expect(resp).to.eql([]); }); }); it('should be able to run schema methods', async () => { let __knexUid, count = 0; const err = new Error('error message'); if (knex.client.driverName === 'pg') { return knex .transaction(function (trx) { return trx.schema .createTable('test_schema_transactions', function (table) { table.increments(); table.string('name'); table.timestamps(); }) .then(function () { return trx('test_schema_transactions').insert({ name: 'bob' }); }) .then(function () { return trx('test_schema_transactions').count('*'); }) .then(function (resp) { const _count = parseInt(resp[0].count, 10); expect(_count).to.equal(1); throw err; }); }) .on('query', function (obj) { count++; if (!__knexUid) __knexUid = obj.__knexUid; expect(__knexUid).to.equal(obj.__knexUid); }) .catch(function (msg) { expect(msg).to.equal(err); expect(count).to.equal(5); return knex('test_schema_migrations').count('*'); }) .then(() => expect.fail('should never reach this line')) .catch(function (e) { // https://www.postgresql.org/docs/8.2/static/errcodes-appendix.html expect(e.code).to.equal('42P01'); }); } else { let id = null; const promise = knex .transaction(function (trx) { return trx('accounts') .returning('id') .insert({ first_name: 'Transacting', last_name: 'User3', email: 'transaction-test5@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (resp) { return trx('test_table_two').insert({ account_id: constid ? ++fkid : (id = resp[0]), details: '', status: 1, }); }) .then(function () { return trx.schema.createTable( 'test_schema_transactions', function (table) { table.increments(); table.string('name'); table.timestamps(); } ); }); }) .on('query', function (obj) { count++; if (!__knexUid) __knexUid = obj.__knexUid; expect(__knexUid).to.equal(obj.__knexUid); }) .then(function () { if (knex.client.driverName === 'mssql') { expect(count).to.equal(3); } else if (knex.client.driverName === 'oracledb') { expect(count).to.equal(4); } else { expect(count).to.equal(5); } return knex('accounts').where('id', id).select('first_name'); }) .then(function (resp) { if (!constid) { expect(resp).to.have.length(1); } }); try { await promise; } finally { await knex.schema.dropTableIfExists('test_schema_transactions'); } } }); it('should resolve with the correct value, #298', function () { return knex .transaction(function (trx) { trx.debugging = true; return Promise.resolve(null); }) .then(function (result) { expect(result).to.equal(null); }); }); it('does not reject promise when rolling back a transaction', async () => { const trxProvider = knex.transactionProvider(); const trx = await trxProvider(); await trx.rollback(); await trx.executionPromise; }); it('should allow for nested transactions', function () { if (/redshift/i.test(knex.client.driverName)) { return Promise.resolve(); } return knex.transaction(function (trx) { return trx .select('*') .from('accounts') .then(function () { return trx.transaction(function () { return trx.select('*').from('accounts'); }); }); }); }); it('#2213 - should wait for sibling transactions to finish', function () { if (/redshift/i.test(knex.client.driverName)) { return this.skip(); } const first = delay(50); const second = first.then(() => delay(50)); return knex.transaction(function (trx) { return Promise.all([ trx.transaction(function (trx2) { return first; }), trx.transaction(function (trx3) { return second; }), ]); }); }); it('#2213 - should not evaluate a Transaction container until all previous siblings have completed', async function () { if (/redshift/i.test(knex.client.driverName)) { return this.skip(); } const TABLE_NAME = 'test_sibling_transaction_order'; await knex.schema.dropTableIfExists(TABLE_NAME); await knex.schema.createTable(TABLE_NAME, function (t) { t.string('username'); }); await knex.transaction(async function (trx) { await Promise.all([ trx.transaction(async function (trx1) { // This delay provides `trx2` with an opportunity to run first. await delay(200); await trx1(TABLE_NAME).insert({ username: 'bob' }); }), trx.transaction(async function (trx2) { const rows = await trx2(TABLE_NAME); // Even though `trx1` was delayed, `trx2` waited patiently for `trx1` // to finish. Therefore, `trx2` discovers that there is already 1 row. expect(rows.length).to.equal(1); }), ]); }); }); it('#855 - Query Event should trigger on Transaction Client AND main Client', function () { let queryEventTriggered = false; knex.once('query', function (queryData) { queryEventTriggered = true; return queryData; }); function expectQueryEventToHaveBeenTriggered() { expect(queryEventTriggered).to.equal(true); } return knex .transaction(function (trx) { trx.select('*').from('accounts').then(trx.commit).catch(trx.rollback); }) .then(expectQueryEventToHaveBeenTriggered) .catch(expectQueryEventToHaveBeenTriggered); }); it('#1040, #1171 - When pool is filled with transaction connections, Non-transaction queries should not hang the application, but instead throw a timeout error', function () { //To make this test easier, I'm changing the pool settings to max 1. const knexConfig = _.clone(knex.client.config); knexConfig.pool.min = 0; knexConfig.pool.max = 1; knexConfig.acquireConnectionTimeout = 1000; const knexDb = new Knex(knexConfig); //Create a transaction that will occupy the only available connection, and avoid trx.commit. return knexDb.transaction(function (trx) { let sql = 'SELECT 1'; if (knex.client.driverName === 'oracledb') { sql = 'SELECT 1 FROM DUAL'; } trx .raw(sql) .then(function () { //No connection is available, so try issuing a query without transaction. //Since there is no available connection, it should throw a timeout error based on `aquireConnectionTimeout` from the knex config. return knexDb.raw('select * FROM accounts WHERE username = ?', [ 'Test', ]); }) .then(function () { //Should never reach this point expect(false).to.be.ok(); }) .catch(function (error) { expect(error.bindings).to.be.an('array'); expect(error.bindings[0]).to.equal('Test'); expect(error.sql).to.equal( 'select * FROM accounts WHERE username = ?' ); expect(error.message).to.equal( 'Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?' ); trx.commit(); //Test done }); }); }); it('#1694, #1703 it should return connections to pool if acquireConnectionTimeout is triggered', async function () { const knexConfig = _.clone(knex.client.config); knexConfig.pool = { min: 0, max: 1, }; knexConfig.acquireConnectionTimeout = 300; const db = new Knex(knexConfig); await expect( db.transaction(() => db.transaction(() => ({}))) ).to.be.rejectedWith(KnexTimeoutError); }); /** * In mssql, certain classes of failures will "abort" a transaction, which * causes the subsequent ROLLBACK to fail (because the transaction has * been rolled back automatically). * An example of this type of auto-aborting error is creating a table with * a foreign key that references a non-existent table. */ if (knex.client.driverName === 'mssql') { it('should rollback when transaction aborts', function () { let insertedId = null; let originalError = null; function transactionAbortingQuery(transaction) { return transaction.schema.createTable( 'test_schema_transaction_fails', function (table) { table.string('name').references('id').on('non_exist_table'); } ); } function insertSampleRow(transaction) { return transaction('accounts') .returning('id') .insert({ first_name: 'Transacting', last_name: 'User2', email: 'transaction-test2@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .then(function (res0) { insertedId = res0[0]; }); } function querySampleRow() { return knex('accounts').where('id', insertedId).select('first_name'); } function captureAndRethrowOriginalError(err) { originalError = err; throw err; } return knex .transaction(function (t) { return insertSampleRow(t) .then(function () { return transactionAbortingQuery(t); }) .catch(captureAndRethrowOriginalError); }) .then(function () { //Should never reach this point expect(false).to.be.ok; }) .catch(function (err) { expect(err).to.exist; expect(err.originalError).to.equal(originalError); // confirm transaction rolled back return querySampleRow().then(function (resp) { expect(resp).to.be.empty; }); }); }); } it('Rollback without an error should not reject with undefined #1966', function () { return knex .transaction(function (tr) { tr.rollback(); }) .then(function () { expect(true).to.equal(false, 'Transaction should not have commited'); }) .catch(function (error) { expect(error instanceof Error).to.equal(true); expect(error.message).to.equal( 'Transaction rejected with non-error: undefined' ); }); }); it('#1052 - transaction promise mutating', function () { const transactionReturning = knex.transaction(function (trx) { return trx .insert({ first_name: 'foo', last_name: 'baz', email: 'fbaz@example.com', logins: 1, about: 'Lorem ipsum Dolore labore incididunt enim.', created_at: new Date(), updated_at: new Date(), }) .into('accounts'); }); return Promise.all([transactionReturning, transactionReturning]).then( ([ret1, ret2]) => { expect(ret1).to.equal(ret2); } ); }); it('should pass the query context to wrapIdentifier', function () { const originalWrapIdentifier = knex.client.config.wrapIdentifier; const spy = sinon.spy().named('calledWithContext'); function restoreWrapIdentifier() { knex.client.config.wrapIdentifier = originalWrapIdentifier; } knex.client.config.wrapIdentifier = (value, wrap, queryContext) => { spy(queryContext); return wrap(value); }; return knex .transaction(function (trx) { return trx.select().from('accounts').queryContext({ foo: 'bar' }); }) .then(function () { expect(spy.callCount).to.equal(1); expect(spy.calledWith({ foo: 'bar' })).to.equal(true); }) .then(function () { restoreWrapIdentifier(); }) .catch(function (e) { restoreWrapIdentifier(); throw e; }); }); it('connection should contain __knexTxId which is also exposed in query event', function () { return knex.transaction(function (trx) { const builder = trx.select().from('accounts'); trx.on('query', function (obj) { expect(typeof obj.__knexTxId).to.equal(typeof ''); }); builder.on('query', function (obj) { expect(typeof obj.__knexTxId).to.equal(typeof ''); }); return builder; }); }); it('#3690 does not swallow exception when error during transaction occurs', async function () { const mysqlKillConnection = async (connection) => knex.raw('KILL ?', [connection.threadId]); const killConnectionMap = { mysql: mysqlKillConnection, mysql2: mysqlKillConnection, pg: async (connection) => knex.raw('SELECT pg_terminate_backend(?)', [connection.processID]), /* TODO FIX mssql: async (connection, trx) => { const id = (await trx.raw('select @@SPID as id'))[0].id; return knex.raw(`KILL ${id}`); }, oracledb: async (connection, trx) => { // https://stackoverflow.com/a/28815685 const row = (await trx.raw( `SELECT * FROM V$SESSION WHERE AUDSID = Sys_Context('USERENV', 'SESSIONID')` ))[0]; return knex.raw( `Alter System Kill Session '${row.SID}, ${ row['SERIAL#'] }' immediate` ); }, */ }; const killConnection = killConnectionMap[knex.client.driverName]; if (!killConnection) { this.skip(); return; } await expect( knex.transaction(async (trx2) => { await killConnection(await trx2.client.acquireConnection(), trx2); await trx2.transaction(async () => 2); }) ).to.be.rejected; }); }); it('handles promise rejections in nested Transactions (#3706)', async function () { const fn = sinon.stub(); process.on('unhandledRejection', fn); try { await knex.transaction(async function (trx1) { // These two lines together will cause the underlying Transaction // to be rejected. Prior to #3706, this rejection would be unhandled. const trx2 = await trx1.transaction(undefined, { doNotRejectOnRollback: false, }); await trx2.rollback(); await expect(trx2.executionPromise).to.have.been.rejected; }); expect(fn).have.not.been.called; } finally { process.removeListener('unhandledRejection', fn); } }); context('when a `connection` is passed in explicitly', function () { beforeEach(function () { this.sandbox = sinon.createSandbox(); }); afterEach(function () { this.sandbox.restore(); }); it('assumes the caller will release the connection', async function () { this.sandbox.spy(knex.client, 'releaseConnection'); const conn = await knex.client.acquireConnection(); try { await knex.transaction( async function (trx) { // Do nothing! }, { connection: conn } ); } catch (err) { // Do nothing. The transaction could have failed due to some other // bug, and it might have still released the connection in the process. } expect(knex.client.releaseConnection).to.have.not.been.calledWith(conn); // By design, this line will only be reached if the connection // was never released. knex.client.releaseConnection(conn); // Note: It's still possible that the test might fail due to a Timeout // even after concluding. This is because the underlying implementation // might have opened another connection by mistake, but never actually // closed it. (Ex: this was the case for OracleDB before fixing #3721) }); }); };
var _ = require('lodash'); module.exports = { clone: function(obj) { return _.cloneDeep(obj); }, extend: function(obj, obj2) { return _.extend(obj, obj2); } }
git://github.com/cypherq/templater.js.git
// Generated by CoffeeScript 1.7.1 (function() { "use strict"; angular.module("fbpoc.CompanyFormCtrl", []).controller("CompanyFormCtrl", [ "$scope", "$routeParams", "$log", "$builder", "$validator", "sessionService", "dataService", function($scope, $routeParams, $log, $builder, $validator, sessionService, dataService) { var get_kv, init, init_select, name_pos, o_code_format_type, o_company, o_currencycode, o_domainmanagerid, o_objectclass, o_texths, obj_list, set_sysdata; $("div.fb-builder").popover('hide'); $scope.table = "company"; $scope.system = { modifiedon: null, modifiedby: null, createdon: null, createdby: null, rowversion: null }; name_pos = {}; o_company = { name: "company", component: "sampleInput", label: "company", description: "", placeholder: "company", required: true, editable: false }; o_texths = { name: "texths", component: "sampleInput", label: "texths", description: "", placeholder: "texths", required: false, editable: false }; o_currencycode = { name: "currencycode", component: "select4", label: "currencycode", description: "", placeholder: "currencycode", required: false, editable: false }; o_code_format_type = { name: "code_format_type", component: "select4", label: "code_format_type", description: "", placeholder: "code_format_type", required: false, editable: false }; o_domainmanagerid = { name: "domainmanagerid", component: "sampleInput", label: "domainmanagerid", description: "", placeholder: "domainmanagerid", required: false, editable: false }; o_objectclass = { name: "objectclass", component: "sampleInput", label: "objectclass", description: "", placeholder: "objectclass", required: false, editable: false }; $scope.pkey = 'company'; obj_list = [o_company, o_texths, o_currencycode, o_code_format_type, o_domainmanagerid, o_objectclass]; init_select = function() {}; init = function() { var j, obj; j = 0; $scope.zmodel = []; $scope.defaultValue = {}; j = 0; while (j < obj_list.length) { obj = obj_list[j]; name_pos[obj.name] = j; if ("default_" in obj) { $scope.defaultValue[j] = obj.default_; } $builder.addFormObject("zform", obj); j++; } $scope.zform = $builder.forms["zform"]; init_select(); }; get_kv = function(field) { return dataService.getkv(params).then(function(data) { return $log.debug(data); }, function(result) { return $log.debug("error", data); }); }; init_select = function() { var field, select_fields, _i, _len, _results; select_fields = []; _results = []; for (_i = 0, _len = select_fields.length; _i < _len; _i++) { field = select_fields[_i]; _results.push(get_kv(field)); } return _results; }; set_sysdata = function(data) { var col, cols, _i, _len, _results; cols = ["modifiedon", "modifiedby", "createdon", "createdby", "rowversion"]; _results = []; for (_i = 0, _len = cols.length; _i < _len; _i++) { col = cols[_i]; _results.push($scope.system[col] = data[col]); } return _results; }; $scope.get = function() { return dataService.get(params).then(function(data) { $log.debug(data); return $scope.defaultValue[0] = "abc"; }, function(result) { return $log.debug("error", result); }); }; $scope.refresh = function() { return $scope.get(); }; $scope.save = function() { var context, fields, item, params, _i, _len, _ref; fields = {}; if ($scope.system.rowversion) { fields.rowversion = $scope.system.rowversion; } context = { languageid: 1033, user: 'idea' }; _ref = $scope.zmodel; for (_i = 0, _len = _ref.length; _i < _len; _i++) { item = _ref[_i]; if (item.value.length === 0) { fields[item.name] = null; } else { fields[item.name] = item.value; } } params = { table: $scope.table, pkey: $scope.pkey, columns: fields, context: context }; $log.debug(fields); $log.debug(params); return dataService.save(params).then(function(data) { var pos; $scope.system = data.returning[0]; pos = name_pos['company']; $builder.forms["zform"][pos].readonly = true; return $log.debug(data); }, function(reason) { return $log.debug("error", reason); }); }; return init(); } ]); }).call(this);
//= require test_helper //= require_self //= require_tree ./unit //= require_tree ./integration /* global emq, setResolver */ // Ember configuration App.rootElement = '#ember-testing'; App.setupForTesting(); App.injectTestHelpers(); // QUnit configuration emq.globalize(); setResolver(Ember.DefaultResolver.create({namespace: App}));
const path = require('path'); const fs = require('fs'); const readline = require('readline'); const EventEmitter = require('events'); const colors = require('colors/safe'); const encodings = ['utf8', 'base64', 'hex', 'binary', 'latin1', 'ucs2', 'utf16le', 'ascii']; class FileLiner extends EventEmitter { // constructor constructor(file, encoding = encodings[0]) { super(); this.nbLines = 0; this.closed = false; if (!~encodings.indexOf(encoding.toLowerCase())) encoding = encodings[0]; this.encoding = encoding; if(!Object.prototype.isPrototypeOf.call(String.prototype, Object(file))) file = ''; else file = path.normalize(file); this.file = file; this.rstream = fs.createReadStream(this.file, this.encoding); this.rl = null; this.handleRstreamEvents(); } // handle createReadStream events handleRstreamEvents() { this.rstream.on('error', (err) => { this.emit('error', new Error(`${colors.red('FileLiner:')} ${this.file ? 'file "' + this.file + '"' : ''}:\n${err.message})`)); }); this.rstream.on('readable', () => { this.rl = readline.createInterface({ input: this.rstream }); this.handleRlEvents(); }); this.rstream.on('close', () => { if (!this.closed){ this.closed = true; this.emit('close'); } }); } // handle readline events handleRlEvents() { this.rl.on('line', (line) => { this.nbLines++; this.emit('line', line, this.nbLines); }); this.rl.on('close', () => { if (!this.closed){ this.closed = true; this.emit('close'); } }); } } module.exports = FileLiner;
import "random"; import "transform";
(function($) { test('Basic plugin functionality', function() { // Given this state machine: $("#test").machine({ one: { defaultState: true, onEnter: function() { this.data("lastEntered", "one"); }, onExit: function() { this.data("lastExited", "one"); }, events: { click: "two", customevent: "three", keypress: "deadlock", mouseover: function(evt) { this.data("IHazAccessTo", evt.type); return false; } } }, two: { onEnter: function(evt, previousState) { this.data("lastEntered", "two"); this.data("enteredWithEvt", evt.type); this.data("previousState", previousState); }, onExit: function(evt, nextState) { this.data("lastExited", "two"); this.data("exitedWithEvt", evt.type); this.data("nextState", nextState); }, events: { click: "one", customevent: function() { return "three"; } } }, three: { events: { customevent: "one" } }, deadlock: {} }); $("#test").on("click", function(){ $("#test").data("clicked", "yes"); }); equal($("#test").data("state"), "one", "State should be initially set to default value of 'one'"); equal($("#test").data("lastEntered"), "one", "onEnter should be called even at initialization"); $("#test").trigger("click"); equal($("#test").data("state"), "two", "When in state 'one' and click is triggered, state should transition to 'two'"); equal($("#test").data("lastEntered"), "two", "onEnter should be called correctly"); equal($("#test").data("lastExited"), "one", "onExit should be called correctly"); equal($("#test").data("enteredWithEvt"), "click", "onEnter should be passed the event object."); equal($("#test").data("previousState"), "one", "onEnter should be passed the previous state as the second argument."); $("#test").trigger("customevent"); equal($("#test").data("state"), "three", "When in state 'two' and customevent is triggered, state should transition to 'three' (function returns 'three')"); equal($("#test").data("lastEntered"), "two", "onEnter should not be called if not defined"); equal($("#test").data("lastExited"), "two", "onExit should be called correctly"); equal($("#test").data("exitedWithEvt"), "customevent", "onExit should be passed the event object."); equal($("#test").data("nextState"), "three", "onExit should be passed the next state as the second argument."); $("#test").trigger("click"); equal($("#test").data("state"), "three", "When in state 'three' and click is triggered, nothing should happen"); equal($("#test").data("lastEntered"), "two", "onEnter should not be called"); equal($("#test").data("lastExited"), "two", "onExit should not be called"); $("#test").trigger("customevent"); equal($("#test").data("state"), "one", "When in state 'three' and customevent is triggered, state should transition to 'one'"); equal($("#test").data("lastEntered"), "one", "onEnter should be called correctly"); equal($("#test").data("lastExited"), "two", "onExit should not be called if not defined"); $("#test").trigger("mouseover"); equal($("#test").data("state"), "one", "When in state 'one' and mouseover is triggered, state should stay the same (function returns false)"); equal($("#test").data("IHazAccessTo"), "mouseover", "Exit function for mouseover should have access to event object, and 'this' should be $('#test')"); $("#test").trigger("keypress"); equal($("#test").data("state"), "deadlock", "When in state 'one' and keypress is triggered, state should transition to 'deadlock'"); $("#test").trigger("click"); equal($("#test").data("state"), "deadlock", "When in state 'deadlock' and keypress is triggered, state should stay the same"); $("#test").data("clicked", ""); $("#test").trigger("click"); equal($("#test").data("clicked"), "yes", "It should not unbind event handlers not set by jquery-machine"); }); test("scoped state machines", function() { // Given this state machine: $("#test").machine({ defaultState: { events: { click: "two" } }, two: { events: { click: "defaultState" } } }, { scope: "myScope" }); // And this other state machine $("#test").machine({ abc: { defaultState: true, events: { mouseover: "def" } }, def: { events: { click: "abc" } } }, { scope: "myOtherScope" }); equal($("#test").data("myScope-state"), "defaultState", "State with scope 'myScope' should be initially set to default value of 'defaultState'"); equal($("#test").data("myOtherScope-state"), "abc", "State with scope 'myOtherScope' should co-exist and be initially set to default value of 'abc'"); $("#test").trigger("click"); equal($("#test").data("myScope-state"), "two", "When myScope-state is 'start' and click is triggered, state should transition to 'two'"); equal($("#test").data("myOtherScope-state"), "abc", "myOtherScope-state shouldn't be affected by changes of myScope-state"); $("#test").trigger("mouseover"); equal($("#test").data("myOtherScope-state"), "def", "When myOtherScope-state is 'abc' and mouseover is triggered, state should transition to 'def'"); $("#test").trigger("click"); equal($("#test").data("myScope-state"), "defaultState", "When myScope-state is 'two' and click is triggered, state should transition to 'defaultState'"); equal($("#test").data("myOtherScope-state"), "abc", "myOtherScope-state should transition to 'abc' when in 'def' and click is triggered"); }); test("setClass option", function() { // Given this state machine, where setClass option is set to true: $("#test2").machine({ defaultState: { events: { click: "two" } }, two: { events: { click: "defaultState" } } }, { setClass: true }); ok($("#test2").hasClass("defaultState"), "When state is initially set to default value, a corresponding class should be set."); $("#test2").trigger("click"); ok($("#test2").hasClass("two"), "When state transitions to 'two', a corresponding class should be set."); ok(!$("#test2").hasClass("defaultState"), "When state transitions, the class corresponding to the previous state should be removed."); // And given this state machine, where setClass option is set to true and a scope is used: $("#test2").machine({ defaultState: { events: { mouseover: "two" } }, two: { events: { mouseover: "defaultState" } } }, { setClass: true, scope: "myScope" }); ok($("#test2").hasClass("myScope-defaultState"), "When state is initially set to default value, a corresponding scoped class should be set."); $("#test2").trigger("mouseover"); ok($("#test2").hasClass("myScope-two"), "When state transitions to 'two', a corresponding scoped class should be set."); ok(!$("#test2").hasClass("myScope-defaultState"), "When state transitions, the scoped class corresponding to the previous state should be removed."); }); test("Option defaultState", function() { // Given this state machine, where default state is overridden by option defaultState $("#test3").machine({ defaultState: {}, stateTwo: {} }, { setClass: true, defaultState: "stateTwo" }); equal($("#test3").data("state"), "stateTwo", "Option defaultState should override default state as defined in the machine object"); }); test("Option defaultState with function evaluation", function() { // Given this state machine, where defaultClass is overridden by option defaultState using a function $("#test3").machine({ stateOne: { defaultState: true }, stateTwo: {} }, { scope: "myscope", setClass: true, defaultState: function() { if (this.attr("id") === "test3") { return "stateTwo"; } }}); equal($("#test3").data("myscope-state"), "stateTwo", "Option defaultState should override default state as defined in the machine object"); }); test("Namespaced custom events", function() { // Given this state machine, where a transition occurs due to a namespaced event $("#test4").machine({ defaultState: { events: { "custom_event.my_namespace": "stateTwo" } }, stateTwo: {} }, { setClass: true }); $("#test4").trigger("custom_event.my_namespace"); equal($("#test4").data("state"), "stateTwo", "Namespaced events should be handled correctly."); }); test("Self-triggered transition from default state", function() { // Given this state machine, where a transition occurs immediately due to the state machine raising an event in it's own onEnter callback $("#test5").machine({ defaultState: { onEnter: function() { this.trigger("custom_event.my_namespace"); }, events: { "custom_event.my_namespace": "stateTwo" } }, stateTwo: {} }, { setClass: true }); equal($("#test5").data("state"), "stateTwo", "It should be possible to trigger a transition immediately from the default state onEnter callback."); }); test("Selectors in event map", function() { // Given this state machine, where a transition occurs immediately due to the state machine raising an event in it's own onEnter callback $("#test6").machine({ defaultState: { events: { "click .handle": "stateTwo" } }, stateTwo: { events: { "click .handle #nested, keypress .handle #nested": function() { return "stateThree"; } } }, stateThree: {} }); $("#test6").trigger("click"); equal($("#test6").data("state"), "defaultState", "If a selector is specified in the event map, the state transition should not be triggered by events on elements outside the selected ones"); $("#test6 .handle").trigger("click"); equal($("#test6").data("state"), "stateTwo", "If a selector is specified in the event map, the state transition should be triggered by events on the selected element"); $("#test6 .handle #nested").trigger("keypress"); equal($("#test6").data("state"), "stateThree", "It should be possible to specify multiple comma-separated events/selectors"); }); test("Missing defaultState throws an error", function() { throws(function(){ $("#test7").machine({ stateOne: { events: { update: "stateTwo" } }, stateTwo: { events: { update: "stateOne" } } }); }, "must throw an error"); }); }(jQuery));
/** * Created by QingWang on 2014/7/21. * Useage: * var DbConfigInfo = require('../lib/DbConfigInfo'); * var DbHelper = require('../lib/DbHelper'); * * var ConfigInfo = new DbConfigInfo(); * var pool = new DbHelper(ConfigInfo.LocalDB); * pool.Execute(....); * pool.ExecuteQuery(....); * pool.mysql.escape(field); * and so on. * */ var mysql = require("mysql"); var JsonResult = require('./JsonResult'); module.exports = DbHelper; function DbHelper(config){ this.config = config; this.pool = mysql.createPool(config); this.mysql = mysql; }; DbHelper.prototype.Execute = function(sqlparameter,callback) { var that = this; var jsonResult = new JsonResult(); jsonResult.Result = false; that.pool.getConnection(function(err, connection) { if (err) { jsonResult.Data = err; jsonResult.Message = err; return callback(jsonResult); } // Use the connection connection.query(sqlparameter.Query, function (err, rows) { // And done with the connection. if (err) { jsonResult.Data = err; jsonResult.Message = err; return callback(jsonResult); //throw err; } jsonResult.Data = rows; jsonResult.Message = ""; jsonResult.Result = true; connection.release(); return callback(jsonResult); }); }); }; DbHelper.prototype.ExecuteQuery = function(query,params,cb) { var that = this; console.log('*********************************************************************************'); console.log({'SQL':query,'PARAMETER':params}); console.log('*********************************************************************************'); that.pool.getConnection(function (err, connection) { if (err) { console.log(err); cb(err); return ; } if (typeof(params) == 'function') { cb = params, params = []; } connection.query(query, params, function (err, res) { cb(err, res); connection.release(); }); }); };
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const _ = require("underscore") const rewire = require("rewire") const routes = rewire("../routes") const sinon = require("sinon") const Backbone = require("backbone") const { fabricate } = require("@artsy/antigravity") const CurrentUser = require("../../../models/current_user") const moment = require("moment") const openSale = fabricate("sale", { name: "Awesome Sale", is_auction: true, auction_state: "open", start_at: moment().subtract(1, "minutes").format(), end_at: moment().add(3, "minutes").format(), }) let analyticsConstructorArgs = [] let analyticsTrackArgs = [] const resetAnalytics = function () { analyticsTrackArgs = [] return (analyticsConstructorArgs = []) } describe("#modalAuctionRegistration", function () { beforeEach(function () { let AnalyticsStub sinon.stub(Backbone, "sync") const analytics = (AnalyticsStub = class AnalyticsStub { constructor() { analyticsConstructorArgs = arguments } track() { return (analyticsTrackArgs = arguments) } }) routes.__set__("Analytics", analytics) this.req = { params: { id: "awesome-sale" }, query: {} } this.res = { status: sinon.stub(), render: sinon.stub(), redirect: sinon.stub(), locals: { sd: { API_URL: "http://localhost:5000", SEGMENT_WRITE_KEY: "foo", }, asset() {}, }, } return (this.next = sinon.stub()) }) afterEach(function () { Backbone.sync.restore() resetAnalytics() return (this.req.query = {}) }) it("redirects to login without user", function () { routes.modalAuctionRegistration(this.req, this.res) return this.res.redirect.args[0][0].should.equal( "/login?redirectTo=/auction-registration/awesome-sale" ) }) return describe("with current user", function () { beforeEach(function () { return (this.req.user = new CurrentUser()) }) it("redirects to success url if sale is registerable and user has already registered", function () { routes.modalAuctionRegistration(this.req, this.res) Backbone.sync.args[0][2].success(openSale) Backbone.sync.args[1][2].success([{ foo: "bar" }]) routes.modalAuctionRegistration(this.req, this.res) return this.res.redirect.args[0][0].should.equal( "/auction/whtney-art-party/confirm-registration" ) }) it("creates bidder and redirects to sale if sale is registerable and user has credit card on file and user accepted conditions", function () { this.req.query = { "accepted-conditions": "true" } routes.modalAuctionRegistration(this.req, this.res) Backbone.sync.args[0][2].success(openSale) Backbone.sync.args[1][2].success([]) Backbone.sync.args[2][2].success([{ foo: "bar" }]) Backbone.sync.args[3][2].success([{}]) // it sends analytics const sentAnalytics = analyticsTrackArgs[0] sentAnalytics["event"].should.equal("Registration submitted") sentAnalytics["properties"]["auction_slug"].should.equal( "whtney-art-party" ) return this.res.redirect.args[0][0].should.equal( "/auction/whtney-art-party/confirm-registration" ) }) it("redirects to registration flow if sale is registerable and user has credit card on file but user did not accept conditions", function () { routes.modalAuctionRegistration(this.req, this.res) Backbone.sync.args[0][2].success(openSale) Backbone.sync.args[1][2].success([]) Backbone.sync.args[2][2].success([{ foo: "bar" }]) // no analytics analyticsTrackArgs.should.be.empty() return this.res.redirect.args[0][0].should.equal( "/auction/whtney-art-party/registration-flow" ) }) it("renders registration error page if sale is an auction and is not registerable", function () { routes.modalAuctionRegistration(this.req, this.res) Backbone.sync.args[0][2].success( fabricate("sale", { name: "Awesome Sale", is_auction: true, auction_state: "closed", }) ) this.res.render.args[0][0].should.equal("registration-error") return this.res.render.args[0][1].sale .get("name") .should.equal("Awesome Sale") }) return it("404 if sale is not auction", function () { routes.modalAuctionRegistration(this.req, this.res, this.next) Backbone.sync.args[0][2].success( fabricate("sale", { name: "Awesome Sale", is_auction: false }) ) this.next.args[0][0].status.should.equal(404) return this.next.args[0][0].message.should.equal("Not Found") }) }) })
// Generated by CoffeeScript 1.7.1 (function() { var NoPlusPlus; module.exports = NoPlusPlus = (function() { function NoPlusPlus() {} NoPlusPlus.prototype.rule = { name: 'no_plusplus', level: 'ignore', message: 'The increment and decrement operators are forbidden', description: "This rule forbids the increment and decrement arithmetic operators.\nSome people believe the <tt>++</tt> and <tt>--</tt> to be cryptic\nand the cause of bugs due to misunderstandings of their precedence\nrules.\nThis rule is disabled by default." }; NoPlusPlus.prototype.tokens = ["++", "--"]; NoPlusPlus.prototype.lintToken = function(token, tokenApi) { return { context: "found '" + token[0] + "'" }; }; return NoPlusPlus; })(); }).call(this); //# sourceMappingURL=no_plusplus.map
import { CognitoUser } from 'amazon-cognito-identity-js' import debug from 'debug' import { userPool } from './config' const log = debug('graphql:resendVerification') export default function resendVerification({ email }) { return new Promise((res, rej) => { const userData = { Username: email, Pool: userPool, } const cognitoUser = new CognitoUser(userData) cognitoUser.resendConfirmationCode((error) => { log('resent verfication', error) if (error) { rej(error) return } res({ success: true }) }) }) }
/** * @file: 1.1-2 * @author: gejiawen * @date: 15/10/27 15:07 * @description: 1.1-2 */ var async = require('async'); var t = require('../../t'); var log = t.log; /** * 并行执行多个函数,每个函数都是立即执行,不需要等待其它函数先执行。传给最终callback的数组中的数据按照tasks中声明的顺序,而不是执行完成的顺序。 * * 如果某个函数出错,则立刻将err和已经执行完的函数的结果值传给parallel最终的callback。其它未执行完的函数的值不会传到最终数据,但要占个位置。 * 同时支持json形式的tasks,其最终callback的结果也为json形式。 */ /** * 以json形式传入tasks,最终results也为json */ async.parallel({ a: function (cb) { t.fire2('a400', cb, 400) }, b: function (cb) { t.fire2('c300', cb, 300) } }, function (err, results) { log('1.1-2 err: ', err); log('1.1-2 results: ', results); }); //27.005> enter: "a400", delay: 400 //27.013> enter: "c300", delay: 300 //27.320> handle: "c300", delay: 300 //27.417> handle: "a400", delay: 400 //27.418> 1.1-2 err: null //27.419> 1.1-2 results: { b: 'c300', a: 'a400' }
// Run suites require('./module');
'use strict' // try "git status" and "svn info" and check exit codes? ... slow // look up for .git or .svn dirs? // [todo] Make async [/todo] const findup = require('findup-sync') const getPathDistance = function (path) { if (typeof path !== 'string') { return -1 } const sep = require('path').sep return path.split(sep).length } const getPkgRepoType = function (pkgjson) { if (typeof pkgjson !== 'string') { return null } const pkg = require(pkgjson) return pkg.repository && pkg.repository.type ? pkg.repository.type : null } module.exports = function (cb) { const gitfldr = findup('.git') const svnfldr = findup('.svn') const pkgjson = findup('package.json') const distanceGit = getPathDistance(gitfldr) const distanceSvn = getPathDistance(svnfldr) const distancePkg = getPathDistance(pkgjson) const pkgjsonType = getPkgRepoType(pkgjson) // Check if there is a version control folder next to the package.json... if (distancePkg > -1) { if (distancePkg === distanceGit && distancePkg === distanceSvn) { if (pkgjsonType === 'git' || pkgjsonType === 'svn') { return cb(null, pkgjsonType) } else { return cb(null, 'git') } } if (distancePkg === distanceGit) { return cb(null, 'git') } if (distancePkg === distanceSvn) { return cb(null, 'svn') } } // Otherwise use the closest option we've got if (distanceGit >= distanceSvn) { return cb(null, 'git') } if (distanceSvn > -1) { return cb(null, 'svn') } cb(new Error('Could not determine repo type, try --repo-type')) }
/** * Module dependencies */ var assert = require('assert') var https = require('https') /** * Expose `serverUrl`. */ module.exports = serverUrl /** * Get the server url. * * @param {Object} server * @return {String} * @api public */ function serverUrl(server) { assert.equal(typeof server, 'object') assert(server.address, 'server.address should exist'); var protocol = 'http' + (server instanceof https.Server ? 's' : '') var address = server.address(); var port = address.port; return protocol + '://' + address.address + ':' + port }
'use strict'; angular.module('myApp.gameEditor', ['ngRoute', 'ngMaterial']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/gameEditor', { templateUrl: 'views/gameEditor/gameEditor.html', controller: 'inputController' }); }]) /* FORM */ .controller('inputController', ['$http', function ($http) { var self = this; //self.game = function(){}; self.game = { description : null, locationId: null, timeOut: 1 }; /**checks if the user input is valid for sending * * @returns {boolean} */ self.validInput = function(){ var title = self.game.description; var mapBoxId = self.game.locationId; var punishTime = self.game.timeOut; if(title == null || title.length == 0){ return false; } if(mapBoxId == null || mapBoxId.length == 0){ return false; } return !(punishTime == null || punishTime <= 0); }; var config = { headers: { "token": sessionStorage.getItem('token'), "Content-Type": "application/json" } }; var gamesEndpoint = "http://zaxion.nl/api/games"; self.sendGameData = function() { $http.post(gamesEndpoint, JSON.stringify(self.game), config). success(function(data, status, headers, config) { $route.reload(); }). error(function(data, status, headers, config) { window.alert("error posting game " + data + " " + status) // log error }); }; return true; }]) /* TABLE */ .controller('tableController', ['$http' , function ($http) { var self = this; self.editGame = function(game){ window.location.href= "http://www.mapbox.com/editor/?id=" + game.locationId } // TODO TOKEN HEADER, CORRECT LINK var config = { headers: { "token": sessionStorage.getItem('token') } } var gamesEndpoint = "http://zaxion.nl/api/games" $http.get(gamesEndpoint, config). success(function(data, status, headers, config) { //window.alert(data) self.games = data }). error(function(data, status, headers, config) { window.alert("error retrieving games" + data + " " + status) // log error }); return true; }]);;
import Component from '@ember/component'; import {computed} from '@ember/object'; import {inject as service} from '@ember/service'; import {sort} from '@ember/object/computed'; export default Component.extend({ store: service(), // public attrs member: null, labelName: '', // internal attrs _availableLabels: null, selectedLabels: computed.reads('member.labels'), availableLabels: sort('_availableLabels.[]', function (labelA, labelB) { // ignorePunctuation means the # in label names is ignored return labelA.name.localeCompare(labelB.name, undefined, {ignorePunctuation: true}); }), availableLabelNames: computed('availableLabels.@each.name', function () { return this.availableLabels.map(label => label.name.toLowerCase()); }), init() { this._super(...arguments); // perform a background query to fetch all users and set `availableLabels` // to a live-query that will be immediately populated with what's in the // store and be updated when the above query returns this.store.query('label', {limit: 'all'}); this.set('_availableLabels', this.store.peekAll('label')); }, actions: { matchLabels(labelName, term) { return labelName.toLowerCase() === term.trim().toLowerCase(); }, hideCreateOptionOnMatchingLabel(term) { return !this.availableLabelNames.includes(term.toLowerCase()); }, updateLabels(newLabels) { let currentLabels = this.get('member.labels'); // destroy new+unsaved labels that are no longer selected currentLabels.forEach(function (label) { if (!newLabels.includes(label) && label.get('isNew')) { label.destroyRecord(); } }); // update labels return this.set('member.labels', newLabels); }, createLabel(labelName) { let currentLabels = this.get('member.labels'); let currentLabelNames = currentLabels.map(label => label.get('name').toLowerCase()); let labelToAdd; labelName = labelName.trim(); // abort if label is already selected if (currentLabelNames.includes(labelName.toLowerCase())) { return; } // find existing label if there is one labelToAdd = this._findLabelByName(labelName); // create new label if no match if (!labelToAdd) { labelToAdd = this.store.createRecord('label', { name: labelName }); } // push label onto member relationship return currentLabels.pushObject(labelToAdd); } }, // methods _findLabelByName(name) { let withMatchingName = function (label) { return label.name.toLowerCase() === name.toLowerCase(); }; return this.availableLabels.find(withMatchingName); } });
'use strict'; angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus', '$location', '$mdSidenav', '$mdUtil', 'Headerpath', function($scope, Authentication, Menus, $location, $mdSidenav, $mdUtil, Headerpath) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $scope.getHeaderPath = function() { var headerPath = $location.$$path; if (headerPath === '/') { headerPath = 'Welcome'; } else { //Remove the first instance of / headerPath = headerPath.substring(headerPath.indexOf('/') + 1, headerPath.length); if (headerPath.indexOf('edit') !== -1 && headerPath.indexOf('projects') !== -1) { var projectID = headerPath.substring(headerPath.indexOf('projects') + 9, headerPath.indexOf('edit') - 1); headerPath = headerPath.replace(projectID, Headerpath.getProjectPath()); headerPath = headerPath.substring(0, headerPath.indexOf('edit') - 1); } else if (headerPath.indexOf('edit') !== -1 && headerPath.indexOf('organisations') !== -1) { var organisationID = headerPath.substring(headerPath.indexOf('organisations') + 14, headerPath.indexOf('edit') - 1); headerPath = headerPath.replace(organisationID, Headerpath.getOrganisationPath()); headerPath = headerPath.substring(0, headerPath.indexOf('edit') - 1); } else if (headerPath.indexOf('reports') !== -1 && headerPath.indexOf('/') !== -1) { var reportID = headerPath.substring(headerPath.indexOf('reports') + 8, headerPath.length); headerPath = headerPath.replace(reportID, Headerpath.getReportPath()); } var tokens = headerPath.split('/'); headerPath = ''; for (var i = 0; i < tokens.length; i++) { tokens[i] = capitalizeFirstLetter(tokens[i]); headerPath += tokens[i]; if (i !== tokens.length - 1) { headerPath += ' > '; } } } return headerPath.trim(); }; var capitalizeFirstLetter = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); $scope.goTo = function(route) { $location.path(route); }; $scope.onProjects = function() { // console.log($location); return $location.path() === '/projects'; }; $scope.onOrganisations = function() { // console.log($location); return $location.path() === '/organisations'; }; $scope.sidenav = $mdSidenav; function buildToggler(navID) { var debounceFn = $mdUtil.debounce(function() { $mdSidenav(navID) .toggle() .then(function() { }); }, 300); return debounceFn; } $scope.toggleLeft = buildToggler('left'); $scope.navigateToCreatePage = function() { if ($location.$$path.indexOf('projects') !== -1) { $scope.goTo('projects/create'); } else if ($location.$$path.indexOf('organisations') !== -1) { $scope.goTo('organisations/create'); } }; } ]);
/** * Test.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { description: { type: 'string', required: true }, isPublic: { type: 'boolean', defaultsTo: true }, startDate: { type: 'datetime', defaultsTo: null }, endDate:{ type: 'datetime', defaultsTo: null }, isHidden: { type: 'boolean', defaultsTo: false }, questions: { collection: 'question', via: 'test' } } };
require( 'wTesting' ); let _ = _realGlobal_._globals_.testing.wTools; // function routine1( test ) { test.identical( 1, 1 ); } // function onSuiteEnd() { var con = _.time.out( 1000, () => 1 ) return con; } // const Proto = { name : 'DelayedMessageByConsequence', onSuiteEnd, suiteEndTimeOut : 1500, tests : { routine1, } } // const Self = wTestSuite( Proto ); if( typeof module !== 'undefined' && !module.parent ) wTester.test( Self.name );
import { expect } from 'chai'; import sinon from 'sinon'; import Mediator from './index'; // Clone mediator. Integration tests will fail without it. const mediator = {}; Object.setPrototypeOf(mediator, Mediator.instance()); mediator.handlers = {}; describe('Core', () => { describe('Model', () => { describe('addHook', () => { beforeEach(() => { mediator.handlers = {}; }); it('should add a hook\'s handler to the given stage', () => { const handler = () => Promise.resolve({ test: 'test' }); mediator.addHook('component:method:stage', handler); expect(mediator.handlers).to.have.key('component:method:stage'); expect(mediator.handlers['component:method:stage']).to.be.an('array'); expect(mediator.handlers['component:method:stage']).to.have.lengthOf(1); expect(mediator.handlers['component:method:stage'][0]).to.equal(handler); }); it('should add the given hook handler to the end of an existing list of handlers for a given stage', () => { const handler = () => Promise.resolve({ test: 'test' }); const handler2 = () => Promise.resolve({ test2: 'test2' }); mediator.addHook('component:method:stage', handler); mediator.addHook('component:method:stage', handler2); expect(mediator.handlers).to.have.key('component:method:stage'); expect(mediator.handlers['component:method:stage']).to.be.an('array'); expect(mediator.handlers['component:method:stage']).to.have.lengthOf(2); expect(mediator.handlers['component:method:stage'][0]).to.equal(handler); expect(mediator.handlers['component:method:stage'][1]).to.equal(handler2); }); }); describe('runHooks', () => { beforeEach(() => { mediator.handlers = {}; }); it('should return a Promise that resolves to an empty object if a given stage is not in handlers', () => mediator.runHooks('someStage', {}, {}) .then((result) => { expect(result).to.deep.equal({}); })); it('should return a promise that resolves to an object with all hadlers\' results', () => { const handler = () => Promise.resolve({ test: 'test' }); const handler2 = () => Promise.resolve({ test2: 'test2' }); mediator.addHook('component:method:stage', handler); mediator.addHook('component:method:stage', handler2); return mediator.runHooks('component:method:stage', {}, {}) .then((result) => { expect(result).to.deep.equal({ test: 'test', test2: 'test2', }); }); }); it('should call all handlres with given args', () => { const handler = sinon.stub(); handler.returns(Promise.resolve({ test: 'test' })); const handler2 = sinon.stub(); handler2.returns(Promise.resolve({ test2: 'test2' })); mediator.addHook('component:method:stage', handler); mediator.addHook('component:method:stage', handler2); const request = Symbol('request'); const data = Symbol('data'); return mediator.runHooks('component:method:stage', request, data) .then(() => { expect(handler.calledWith(request, data)); expect(handler2.calledWith(request, data)); }); }); }); }); });
#!/usr/bin/env node const sh = require('shelljs') const vars = require('./vars') const log = require('npmlog') vars.packagesWithDocs.forEach(([dest, src]) => { log.info('docs', src) sh.exec(`yarn typedoc --out docs/api/${dest} --tsconfig ${src}/tsconfig.typings.json ${src}/src/index.ts`, { fatal: true }) })
//Create by Geoffrey Cheung 2015 var socket = io(); Encoder.EncodeType = "entity"; socket.on('reconnect', function(){ $("#messages").empty(); }); //Receiving messages socket.on('chat message', function (timestamp, name, msg, id, color) { var d = new Date(timestamp); var n = d.toString(); $('#messages').append($('<div class="panel panel-default shadow-z-1">') .append($('<div class="panel-heading" >').text(n)).append($('<div class="panel-body">') .append('<strong>'+name + ' (ID. ' + id + '):</strong> ' + BBCode.parser(Encoder.htmlEncode(msg))).css('color', color))); $('#messages').append($('<p>')); //$("#messages_area").animate({ scrollTop: $("#messages_area")[0].scrollHeight + $(window).height()}, 1000); }); socket.on('get online user',function (count){ $('#onlineuser').text('Online user: '+count); });
var keystone = require('keystone'); var User = keystone.list('User'); exports = module.exports = function(req, res) { var view = new keystone.View(req, res), locals = res.locals; locals.section = 'members'; var membersQuery = User.model.find() .sort('name') .where('isPublic', true) .populate('organisation'); if (req.params.filter == 'mentors') { membersQuery.where('mentoring.available', true); } view.query('members', membersQuery, 'posts talks[meetup]'); if (req.params.filter == 'mentors') { view.render('site/mentors'); } else { view.render('site/members'); } }
'use strict'; module.exports = function (grunt) { grunt.initConfig({ 'md5sum': { md5: { files: [ { cwd: 'tests/fixtures/', src: ['**/*'], dest: 'tests/tmp/file.md5' } ] }, 'md5.exclude_path': { options: { exclude_path: true }, files: [ { cwd: 'tests/fixtures/', src: ['**/*'], dest: 'tests/tmp/file.md5.exclude_path' } ] }, 'md5.prefix': { options: { exclude_path: true, path_prefix : '/' }, files: [ { cwd: 'tests/fixtures/', src: ['**/*'], dest: 'tests/tmp/file.md5.prefix' } ] }, json: { options: { process: function (content) { return content; } }, files: [ { cwd: 'tests/fixtures/', src: ['**/*'], dest: 'tests/tmp/file.json' } ] } }, nodeunit: { tasks: ['tests/test.js'] }, clean: { test: ['tests/tmp/**'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('default', []); grunt.registerTask('test', ['md5sum', 'nodeunit']); };
import Controller from '@ember/controller'; import { action } from '@ember/object'; import { set } from '@ember/object'; export default class extends Controller { constructor(...args) { super(...args); this.priority = 0; } @action changeSetting(name, e) { set(this, name, e.target.value); } @action applyCheckedValue(name, e) { set(this, name, e.target.checked); } @action changePriority(e) { set(this, 'priority', e.target.value); } @action onEnterPressedInInput() { set(this, 'wasEnterPressedInInput', true); } }
"enable aexpr"; import AbstractAstNode from './abstract-ast-node.js' export default class AstNodeTryStatement extends AbstractAstNode { async initialize() { await super.initialize(); this.windowTitle = "AstNodeTryStatement"; } async updateProjection() { await this.createSubElementForPath(this.path.get('block'), 'block'); this.classList.toggle('has-handler', this.node.handler) if (this.node.handler) { await this.createSubElementForPath(this.path.get('handler'), 'handler'); } else { this.removeSubElementInSlot('handler'); } this.classList.toggle('has-finalizer', this.node.finalizer) if (this.node.finalizer) { await this.createSubElementForPath(this.path.get('finalizer'), 'finalizer'); } else { this.removeSubElementInSlot('finalizer'); } } }
VirtualKeyboard.addLayout({code:'LA' ,name:'Lakhota Standard' ,normal:'`1234567890-=\\ǧweštyuiop[]asdŋghȟkl;\'zžčvbnm,./' ,shift:{0:'~!@#$%^&*()_+|',24:'{}',32:'Ȟ',35:':"',44:'<>?'} ,caps:{14:'Q',17:'R',32:'J',38:'XC'} ,'cbk':/** * $Id: lakhota-standard.js 643 2009-07-09 15:19:14Z wingedfox $ * * Lakhota char processor * * This software is protected by patent No.2009611147 issued on 20.02.2009 by Russian Federal Service for Intellectual Property Patents and Trademarks. * * @author Konstantin Wiolowan * @copyright 2008-2009 Konstantin Wiolowan <wiolowan@mail.ru> * @version $Rev: 643 $ * @lastchange $Author: wingedfox $ $Date: 2009-07-09 19:19:14 +0400 (Чт, 09 июл 2009) $ */ VirtualKeyboard.Langs.LA.charProcessor});
(function() { 'use strict'; /** * @ngdoc directive * @name tagsInput.directive:tagsInput * * @description * ngTagsInput is an Angular directive that renders an input box with tag editing support. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} ngClass CSS class to style the control. * @param {number} tabindex Tab order of the control. * @param {string=Add a tag} placeholder Placeholder text for the control. * @param {number=3} minLength Minimum length for a new tag. * @param {number=} maxLength Maximum length allowed for a new tag. * @param {string=×} removeTagSymbol Symbol character for the remove tag button. * @param {boolean=true} addOnEnter Flag indicating that a new tag will be added on pressing the ENTER key. * @param {boolean=false} addOnSpace Flag indicating that a new tag will be added on pressing the SPACE key. * @param {boolean=true} addOnComma Flag indicating that a new tag will be added on pressing the COMMA key. * @param {boolean=true} replaceSpacesWithDashes Flag indicating that spaces will be replaced with dashes. * @param {string=^[a-zA-Z0-9\s]+$*} allowedTagsPattern Regular expression that determines whether a new tag is valid. * @param {boolean=false} enableEditingLastTag Flag indicating that the last tag will be moved back into * the new tag input box instead of being removed when the backspace key * is pressed and the input box is empty. */ angular.module('tags-input', []).directive('tagsInput', function($interpolate) { function loadOptions(scope, attrs) { function getStr(name, defaultValue) { return attrs[name] ? $interpolate(attrs[name])(scope.$parent) : defaultValue; } function getInt(name, defaultValue) { var value = getStr(name, null); return value ? parseInt(value, 10) : defaultValue; } function getBool(name, defaultValue) { var value = getStr(name, null); return value ? value === 'true' : defaultValue; } scope.options = { cssClass: getStr('ngClass', ''), placeholder: getStr('placeholder', 'Add a tag'), tabindex: getInt('tabindex', ''), removeTagSymbol: getStr('removeTagSymbol', String.fromCharCode(215)), replaceSpacesWithDashes: getBool('replaceSpacesWithDashes', true), minLength: getInt('minLength', 3), maxLength: getInt('maxLength', ''), addOnEnter: getBool('addOnEnter', true), addOnSpace: getBool('addOnSpace', false), addOnComma: getBool('addOnComma', true), allowedTagsPattern: new RegExp(getStr('allowedTagsPattern', '^[a-zA-Z0-9\\s]+$')), enableEditingLastTag: getBool('enableEditingLastTag', false) }; } return { restrict: 'A,E', scope: { tags: '=ngModel' }, replace: false, template: '<div class="ngTagsInput {{ options.cssClass }}">' + ' <ul>' + ' <li ng-repeat="tag in tags" ng-class="getCssClass($index)">' + ' <span>{{ tag.name }}</span>' + ' <button type="button" ng-click="remove($index)">{{ options.removeTagSymbol }}</button>' + ' </li>' + ' </ul>' + ' <input type="text" placeholder="{{ options.placeholder }}" size="{{ options.placeholder.length }}" maxlength="{{ options.maxLength }}" tabindex="{{ options.tabindex }}" ng-model="newTag">' + '</div>', controller: function($scope, $attrs) { loadOptions($scope, $attrs); $scope.newTag = ''; $scope.tags = $scope.tags || []; $scope.tryAdd = function() { var changed = false; var tag = $scope.newTag; if (tag.length >= $scope.options.minLength && $scope.options.allowedTagsPattern.test(tag)) { if ($scope.options.replaceSpacesWithDashes) { tag = tag.replace(/\s/g, '-'); } for (var i = $scope.tags.length - 1; i >= 0; i--) { if ($scope.tags[i].name === tag) { return changed; } }; $scope.tags.push({'id': 'new', 'name': tag}); $scope.newTag = ''; changed = true; } return changed; }; $scope.tryRemoveLast = function() { var changed = false; if ($scope.tags.length > 0) { if ($scope.options.enableEditingLastTag) { $scope.newTag = $scope.tags.pop(); } else { if ($scope.shouldRemoveLastTag) { $scope.tags.pop(); $scope.shouldRemoveLastTag = false; } else { $scope.shouldRemoveLastTag = true; } } changed = true; } return changed; }; $scope.remove = function(index) { $scope.tags.splice(index, 1); }; $scope.getCssClass = function(index) { var isLastTag = index === $scope.tags.length - 1; return $scope.shouldRemoveLastTag && isLastTag ? 'selected' : ''; }; $scope.$watch(function() { return $scope.newTag.length > 0; }, function() { $scope.shouldRemoveLastTag = false; }); }, link: function(scope, element) { var ENTER = 13, COMMA = 188, SPACE = 32, BACKSPACE = 8; element.find('input') .bind('keydown', function(e) { if (e.keyCode === ENTER && scope.options.addOnEnter || e.keyCode === COMMA && scope.options.addOnComma || e.keyCode === SPACE && scope.options.addOnSpace) { if (scope.tryAdd()) { scope.$apply(); } e.preventDefault(); } else if (e.keyCode === BACKSPACE && this.value.length === 0) { if (scope.tryRemoveLast()) { scope.$apply(); e.preventDefault(); } } }); element.find('div').bind('click', function() { element.find('input')[0].focus(); }); } }; }); }());
/*! * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 * @version 2.4.0 * * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced * features including the FileReader API. * * The plugin drastically enhances the HTML file input to preview multiple files on the client before * upload. In addition it provides the ability to preview content of images, text, videos, audio, html, * flash and other objects. * * Author: Kartik Visweswaran * Copyright: 2014, Kartik Visweswaran, Krajee.com * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ (function ($) { var STYLE_SETTING = 'style="width:{width};height:{height};"'; var PREVIEW_LABEL = ' <div class="text-center"><small>{caption}</small></div>\n'; var OBJECT_PARAMS = ' <param name="controller" value="true" />\n' + ' <param name="allowFullScreen" value="true" />\n' + ' <param name="allowScriptAccess" value="always" />\n' + ' <param name="autoPlay" value="false" />\n' + ' <param name="autoStart" value="false" />\n'+ ' <param name="quality" value="high" />\n'; var DEFAULT_PREVIEW = '<div class="file-preview-other" ' + STYLE_SETTING + '>\n' + ' <h2><i class="glyphicon glyphicon-file"></i></h2>\n' + ' </div>'; var defaultLayoutTemplates = { main1: '{preview}\n' + '<div class="input-group {class}">\n' + ' {caption}\n' + ' <div class="input-group-btn">\n' + ' {remove}\n' + ' {upload}\n' + ' {browse}\n' + ' </div>\n' + '</div>', main2: '{preview}\n{remove}\n{upload}\n{browse}\n', preview: '<div class="file-preview {class}">\n' + ' <div class="close fileinput-remove text-right">&times;</div>\n' + ' <div class="file-preview-thumbnails"></div>\n' + ' <div class="clearfix"></div>' + ' <div class="file-preview-status text-center text-success"></div>\n' + '</div>', caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' + ' <span class="glyphicon glyphicon-file kv-caption-icon"></span><div class="file-caption-name"></div>\n' + '</div>', modal: '<div id="{id}" class="modal fade">\n' + ' <div class="modal-dialog modal-lg">\n' + ' <div class="modal-content">\n' + ' <div class="modal-header">\n' + ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' + ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' + ' </div>\n' + ' <div class="modal-body">\n' + ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>\n' }; var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object']; var defaultPreviewTemplates = { generic: '<div class="file-preview-frame" id="{previewId}">\n' + ' {content}\n' + '</div>\n', html: '<div class="file-preview-frame" id="{previewId}">\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + PREVIEW_LABEL + '</div>', image: '<div class="file-preview-frame" id="{previewId}">\n' + ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' + '</div>\n', text: '<div class="file-preview-frame" id="{previewId}">\n' + ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' + ' {data}\n' + ' </div>\n' + '</div>\n', video: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <video width="{width}" height="{height}" controls>\n' + ' <source src="{data}" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </video>\n' + PREVIEW_LABEL + '</div>\n', audio: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <audio controls>\n' + ' <source src="{data}" type="{type}">\n' + ' ' + DEFAULT_PREVIEW + '\n' + ' </audio>\n' + PREVIEW_LABEL + '</div>\n', flash: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + PREVIEW_LABEL + '</div>\n', object: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' + ' <param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' + ' </object>\n' + PREVIEW_LABEL + '</div>', other: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' + ' ' + DEFAULT_PREVIEW + '\n' + PREVIEW_LABEL + '</div>', }; var defaultPreviewSettings = { image: {width: "auto", height: "160px"}, html: {width: "320px", height: "180px"}, text: {width: "160px", height: "160px"}, video: {width: "320px", height: "240px"}, audio: {width: "320px", height: "80px"}, flash: {width: "320px", height: "240px"}, object: {width: "320px", height: "300px"}, other: {width: "160px", height: "120px"} }; var defaultFileTypeSettings = { image: function(vType, vName) { return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i); }, html: function(vType, vName) { return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i); }, text: function(vType, vName) { return typeof vType !== "undefined" && vType.match('text.*') || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i); }, video: function (vType, vName) { return typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i) || vName.match(/\.(og?|mp4|webm)$/i); }, audio: function (vType, vName) { return typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i) || vName.match(/\.(ogg|mp3|wav)$/i); }, flash: function (vType, vName) { return typeof vType !== "undefined" && vType == 'application/x-shockwave-flash' || vName.match(/\.(swf)$/i); }, object: function (vType, vName) { return true; }, other: function (vType, vName) { return true; }, }; var isEmpty = function (value, trim) { return value === null || value === undefined || value == [] || value === '' || trim && $.trim(value) === ''; }, isArray = function (a) { return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; }, isSet = function (needle, haystack) { return (typeof haystack == 'object' && needle in haystack); }, getValue = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : options[param]; }, getElement = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]); }, uniqId = function () { return Math.round(new Date().getTime() + (Math.random() * 100)); }, hasFileAPISupport = function () { return window.File && window.FileReader && window.FileList && window.Blob; }, vUrl = window.URL || window.webkitURL; var FileInput = function (element, options) { this.$element = $(element); if (hasFileAPISupport()) { this.init(options); this.listen(); } else { this.$element.removeClass('file-loading'); } }; FileInput.prototype = { constructor: FileInput, init: function (options) { var self = this; self.reader = null; self.showCaption = options.showCaption; self.showPreview = options.showPreview; self.maxFileSize = options.maxFileSize; self.maxFileCount = options.maxFileCount; self.msgSizeTooLarge = options.msgSizeTooLarge; self.msgFilesTooMany = options.msgFilesTooMany; self.msgFileNotFound = options.msgFileNotFound; self.msgFileNotReadable = options.msgFileNotReadable; self.msgFilePreviewAborted = options.msgFilePreviewAborted; self.msgFilePreviewError = options.msgFilePreviewError; self.msgValidationError = options.msgValidationError; self.msgErrorClass = options.msgErrorClass; self.initialDelimiter = options.initialDelimiter; self.initialPreview = options.initialPreview; self.initialCaption = options.initialCaption; self.initialPreviewCount = options.initialPreviewCount; self.initialPreviewContent = options.initialPreviewContent; self.overwriteInitial = options.overwriteInitial; self.layoutTemplates = options.layoutTemplates; self.previewTemplates = options.previewTemplates; self.allowedPreviewTypes = isEmpty(options.allowedPreviewTypes) ? defaultPreviewTypes : options.allowedPreviewTypes; self.allowedPreviewMimeTypes = options.allowedPreviewMimeTypes; self.previewSettings = options.previewSettings; self.fileTypeSettings = options.fileTypeSettings; self.showRemove = options.showRemove; self.showUpload = options.showUpload; self.captionClass = options.captionClass; self.previewClass = options.previewClass; self.mainClass = options.mainClass; self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2'); self.captionTemplate = self.getLayoutTemplate('caption'); self.previewGenericTemplate = self.getPreviewTemplate('generic'); self.browseLabel = options.browseLabel; self.browseIcon = options.browseIcon; self.browseClass = options.browseClass; self.removeLabel = options.removeLabel; self.removeIcon = options.removeIcon; self.removeClass = options.removeClass; self.uploadLabel = options.uploadLabel; self.uploadIcon = options.uploadIcon; self.uploadClass = options.uploadClass; self.uploadUrl = options.uploadUrl; self.msgLoading = options.msgLoading; self.msgProgress = options.msgProgress; self.msgSelected = options.msgSelected; self.previewFileType = options.previewFileType; self.wrapTextLength = options.wrapTextLength; self.wrapIndicator = options.wrapIndicator; self.isError = false; self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly'); if (isEmpty(self.$element.attr('id'))) { self.$element.attr('id', uniqId()); } if (typeof self.$container == 'undefined') { self.$container = self.createContainer(); } else { self.refreshContainer(); } self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption')); self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name')); self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview')); self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails')); self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status')); var content = self.initialPreview; self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialDelimiter).length : 0) self.initPreview(); self.original = { preview: self.$preview.html(), caption: self.$caption.html() }; self.options = options; self.$element.removeClass('file-loading'); }, getLayoutTemplate: function(t) { var self = this; return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t]; }, getPreviewTemplate: function(t) { var self = this; return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t]; }, listen: function () { var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile; $el.on('change', $.proxy(self.change, self)); $btnFile.on('click', function (ev) { self.clear(false); $cap.focus(); }); $($el[0].form).on('reset', $.proxy(self.reset, self)); self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self)); }, refresh: function (options) { var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options; self.init(params); }, initPreview: function () { var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount, cap = self.initialCaption.length, previewId = "preview-" + uniqId(), caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len); if (isArray(content) && len > 0) { for (var i = 0; i < len; i++) { previewId += '-' + i; html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g, content[i]); } if (len > 1 && cap == 0) { caption = self.msgSelected.replace(/\{n\}/g, len); } } else { if (len > 0) { var fileList = content.split(self.initialDelimiter); for (var i = 0; i < len; i++) { previewId += '-' + i; html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g, fileList[i]); } if (len > 1 && cap == 0) { caption = self.msgSelected.replace(/\{n\}/g, len); } } else { if (cap > 0) { self.$caption.html(caption); self.$captionContainer.attr('title', caption); return; } else { return; } } } self.initialPreviewContent = html; self.$preview.html(html); self.$caption.html(caption); self.$captionContainer.attr('title', caption); self.$container.removeClass('file-input-new'); }, clearObjects: function() { var self = this, $preview = self.$preview; $preview.find('video audio').each(function() { this.pause(); delete(this); $(this).remove(); }); $preview.find('img object div').each(function() { delete(this); $(this).remove(); }); }, clear: function (e) { var self = this; if (e) { e.preventDefault(); } if (self.reader instanceof FileReader) { self.reader.abort(); } self.$element.val(''); self.resetErrors(true); if (e !== false) { self.$element.trigger('change'); self.$element.trigger('fileclear'); } if (self.overwriteInitial) { self.initialPreviewCount = 0; } if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) { self.showFileIcon(); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.$container.removeClass('file-input-new'); } else { self.clearObjects(); self.$preview.html(''); var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.original.caption : ''; self.$caption.html(cap); self.$captionContainer.attr('title', ''); self.$container.removeClass('file-input-new').addClass('file-input-new'); } self.hideFileIcon(); self.$element.trigger('filecleared'); self.$captionContainer.focus(); }, reset: function (e) { var self = this; self.clear(false); self.$preview.html(self.original.preview); self.$caption.html(self.original.caption); self.$container.find('.fileinput-filename').text(''); self.$element.trigger('filereset'); if (self.initialPreview.length > 0) { self.$container.removeClass('file-input-new'); } }, disable: function (e) { var self = this; self.isDisabled = true; self.$element.attr('disabled', 'disabled'); self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true); }, enable: function (e) { var self = this; self.isDisabled = false; self.$element.removeAttr('disabled'); self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled"); }, hideFileIcon: function () { if (this.overwriteInitial) { this.$captionContainer.find('.kv-caption-icon').hide(); } }, showFileIcon: function () { this.$captionContainer.find('.kv-caption-icon').show(); }, resetErrors: function (fade) { var self = this, $error = self.$previewContainer.find('.kv-fileinput-error'); self.isError = false; if (fade) { $error.fadeOut('slow'); } else { $error.remove(); } }, showError: function (msg, file, previewId, index) { var self = this, $error = self.$previewContainer.find('.kv-fileinput-error'); if (isEmpty($error.attr('class'))) { self.$previewContainer.append( '<div class="kv-fileinput-error ' + self.msgErrorClass + '">' + msg + '</div>' ); } else { $error.html(msg); } $error.hide(); $error.fadeIn(800); self.$element.trigger('fileerror', [file, previewId, index]); self.$element.val(''); return true; }, errorHandler: function (evt, caption) { var self = this; switch (evt.target.error.code) { case evt.target.error.NOT_FOUND_ERR: self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption)); break; case evt.target.error.NOT_READABLE_ERR: self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption)); break; case evt.target.error.ABORT_ERR: self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption)); break; default: self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption)); } }, parseFileType: function(file) { var isValid, vType; for (var i = 0; i < defaultPreviewTypes.length; i++) { cat = defaultPreviewTypes[i]; isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat]; vType = isValid(file.type, file.name) ? cat : ''; if (vType != '') { return vType; } } return 'other'; }, previewDefault: function(file, previewId) { var self = this, data = vUrl.createObjectURL(file), $obj = $('#' + previewId), previewOtherTemplate = isSet('other', self.previewTemplates) ? self.previewTemplates['other'] : defaultPreviewTemplates['other']; self.$preview.append("\n" + previewOtherTemplate .replace(/\{previewId\}/g, previewId) .replace(/\{caption\}/g, file.name) .replace(/\{type\}/g, file.type) .replace(/\{data\}/g, data)); $obj.on('load', function(e) { vUrl.revokeObjectURL($obj.attr('data')); }); }, previewFile: function(file, theFile, previewId, data) { var self = this, i, cat = self.parseFileType(file), caption = file.name, data, obj, content, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type, template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat], config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat], wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview, chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)); if (chkTypes && chkMimes) { if (cat == 'text') { var strText = theFile.target.result; vUrl.revokeObjectURL(data); if (strText.length > wrapLen) { var id = 'text-' + uniqId(), height = window.innerHeight * .75, modal = self.getLayoutTemplate('modal').replace(/\{id\}/g, id).replace(/\{title\}/g, caption).replace(/\{body\}/g, strText).replace(/\{height\}/g, height); wrapInd = wrapInd.replace(/\{title\}/g, caption).replace(/\{dialog\}/g, "$('#" + id + "').modal('show')"); strText = strText.substring(0, (wrapLen - 1)) + wrapInd; } content = template .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption) .replace(/\{type\}/g, file.type).replace(/\{data\}/g, strText) .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height) + modal; } else { content = template .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption) .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data) .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height); } $preview.append("\n" + content); } else { self.previewDefault(file, previewId); } }, readFiles: function (files) { this.reader = new FileReader(); var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader, $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, previewInitId = "preview-" + uniqId(), numFiles = files.length, isText = isSet('text', self.fileTypeSettings) ? self.fileTypeSettings['text'] : defaultFileTypeSettings['text']; function readFile(i) { if (i >= numFiles) { $container.removeClass('loading'); $status.html(''); return; } var previewId = previewInitId + "-" + i, file = files[i], caption = file.name, fileSize = (file.size ? file.size : 0) / 1000, previewData = vUrl.createObjectURL(file); fileSize = fileSize.toFixed(2); if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { var msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g, fileSize).replace(/\{maxSize\}/g, self.maxFileSize); self.isError = self.showError(msg, file, previewId, i); return; } if (!self.showPreview) { setTimeout(readFile(i + 1), 1000); return; } if ($preview.length > 0 && typeof FileReader !== "undefined") { $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)); $container.addClass('loading'); reader.onerror = function (evt) { self.errorHandler(evt, caption); }; reader.onload = function (theFile) { self.previewFile(file, theFile, previewId, previewData); }; reader.onloadend = function (e) { var msg = msgProgress .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles) .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption); setTimeout(function () { $status.html(msg); vUrl.revokeObjectURL(previewData); }, 1000); setTimeout(function () { readFile(i + 1); }, 1500); $el.trigger('fileloaded', [file, previewId, i]); }; reader.onprogress = function (data) { if (data.lengthComputable) { var progress = parseInt(((data.loaded / data.total) * 100), 10); var msg = msgProgress .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles) .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption); setTimeout(function () { $status.html(msg); }, 1000); } }; if (isText(file.type, caption)) { reader.readAsText(file); } else { reader.readAsArrayBuffer(file); } } else { self.previewDefault(file, previewId); $el.trigger('fileloaded', [file, previewId, i]); setTimeout(readFile(i + 1), 1000); } } readFile(0); }, change: function (e) { var self = this, $el = self.$element, label = $el.val().replace(/\\/g, '/').replace(/.*\//, ''), total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected, numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles; self.hideFileIcon(); if (e.target.files === undefined) { tfiles = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []; } else { tfiles = e.target.files; } if (tfiles.length === 0) { return; } self.resetErrors(); $preview.html(''); if (!self.overwriteInitial) { $preview.html(self.initialPreviewContent); } var total = tfiles.length; if (self.maxFileCount > 0 && total > self.maxFileCount) { var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total); self.isError = self.showError(msg, null, null, null); self.$captionContainer.find('.kv-caption-icon').hide(); self.$caption.html(self.msgValidationError); self.$container.removeClass('file-input-new'); return; } self.readFiles(files); self.reader = null; var log = numFiles > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label; if (self.isError) { self.$captionContainer.find('.kv-caption-icon').hide(); log = self.msgValidationError; } else { self.showFileIcon(); } self.$caption.html(log); self.$captionContainer.attr('title', log); self.$container.removeClass('file-input-new'); $el.trigger('fileselect', [numFiles, label]); }, initBrowse: function ($container) { var self = this; self.$btnFile = $container.find('.btn-file'); self.$btnFile.append(self.$element); }, createContainer: function () { var self = this; var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain()); self.$element.before($container); self.initBrowse($container); return $container; }, refreshContainer: function () { var self = this, $container = self.$container; $container.before(self.$element); $container.html(self.renderMain()); self.initBrowse($container); }, renderMain: function () { var self = this; var preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass) : ''; var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass; var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption'); return self.mainTemplate.replace(/\{class\}/g, self.mainClass). replace(/\{preview\}/g, preview). replace(/\{caption\}/g, caption). replace(/\{upload\}/g, self.renderUpload()). replace(/\{remove\}/g, self.renderRemove()). replace(/\{browse\}/g, self.renderBrowse()); }, renderBrowse: function () { var self = this, css = self.browseClass + ' btn-file', status = ''; if (self.isDisabled) { status = ' disabled '; } return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>'; }, renderRemove: function () { var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = ''; if (!self.showRemove) { return ''; } if (self.isDisabled) { status = ' disabled '; } return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>'; }, renderUpload: function () { var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = ''; if (!self.showUpload) { return ''; } if (self.isDisabled) { status = ' disabled '; } if (isEmpty(self.uploadUrl)) { content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>'; } else { content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>'; } return content; } } //FileInput plugin definition $.fn.fileinput = function (option) { if (!hasFileAPISupport()) { return; } var args = Array.apply(null, arguments); args.shift(); return this.each(function () { var $this = $(this), data = $this.data('fileinput'), options = typeof option === 'object' && option; if (!data) { $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data())))); } if (typeof option === 'string') { data[option].apply(data, args); } }); }; $.fn.fileinput.defaults = { showCaption: true, showPreview: true, showRemove: true, showUpload: true, mainClass: '', previewClass: '', captionClass: '', mainTemplate: null, initialDelimiter: '*$$*', initialPreview: '', initialCaption: '', initialPreviewCount: 0, initialPreviewContent: '', overwriteInitial: true, layoutTemplates: defaultLayoutTemplates, previewTemplates: defaultPreviewTemplates, allowedPreviewTypes: defaultPreviewTypes, allowedPreviewMimeTypes: null, previewSettings: defaultPreviewSettings, fileTypeSettings: defaultFileTypeSettings, browseLabel: 'Browse &hellip;', browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;', browseClass: 'btn btn-primary', removeLabel: 'Remove', removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ', removeClass: 'btn btn-default', uploadLabel: 'Upload', uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ', uploadClass: 'btn btn-default', uploadUrl: null, maxFileSize: 0, maxFileCount: 0, msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!', msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!', msgFileNotFound: 'File "{name}" not found!', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>', msgErrorClass: 'file-error-message', msgLoading: 'Loading file {index} of {files} &hellip;', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} files selected', previewFileType: 'image', wrapTextLength: 250, wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>', elCaptionContainer: null, elCaptionText: null, elPreviewContainer: null, elPreviewImage: null, elPreviewStatus: null }; /** * Convert automatically file inputs with class 'file' * into a bootstrap fileinput control. */ $(document).ready(function () { var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0; if (count > 0) { $input.fileinput(); } }); })(window.jQuery);
'use strict'; var fs = require('fs'); exports.takeScreenshot = function (browser, filename) { browser.takeScreenshot().then(function (png) { fs.writeFileSync('./client/test/screenshots/' + filename + '.png', png, 'base64'); }); };