code
stringlengths
2
1.05M
/** * Palindrome * * Implement a function to check if a linked list is a palindrome */ const LinkedList = require('../../../collections/LinkedList'); // 1st Approach: traverse the list, and compare each against its Kth last pairing for equality ~ O(n^2) // Better Approach: we can reverse the linked list, and compare the two orientations for equality ~ O(n) // Simpler Approach: copy data to an array, and then compare first and last elements in constant time ~ O(n) function isPalindrome(node) { let stack = []; while (node) { stack.push(node.value); node = node.next; } while (stack.length > 1) { let left = stack.shift(); let right = stack.pop(); if (left !== right) { return false; } } return true; } const tests = [ new LinkedList({data: [0, 1, 2, 1, 0]}), new LinkedList({data: [0, 1, 2, 2, 0]}), new LinkedList({data: [0, 1, 2, 2, 1, 0]}), new LinkedList({data: [0, 1, 2, 2, 1, 3]}) ]; const expected = [ true, false, true, false ]; const should = require('should'); for (let i in tests) { console.log(`isPalindrome: ${tests[i].toString()}`); let result = isPalindrome(tests[i].head); result.should.eql(expected[i]); console.log(` -> ${result}`); console.log(); } console.log('Success!\n'); module.exports = isPalindrome;
$(function(){ var JSON_PATH = 'inc/data/data.json'; var items = new App.Items(JSON_PATH); App.DataBind.init(items); App.DataBind.implement_change(); App.Gallery.init(); });
import Component from '@ember/component'; import { inject as service } from '@ember/service'; export default Component.extend({ wtEvents: service(), classNameBindings: ['showUpperPanel', 'showLowerPanel'], showUpperPanel: true, showLowerPanel: false, init() { this._super(...arguments); const self = this; let events = self.get('wtEvents').events; // Wait for an event that asks for the file browser to be disabled events.on('onDisableRightPanel', function () { self.set('showLowerPanel', false); }); }, willDestroyElement () { this._super(...arguments); let events = this.get('wtEvents').events; events.off('onDisableRightPanel'); }, actions: { dummy: function() { //this.sendAction('action'); }, onLeftModelChange : function (model) { this.sendAction('onLeftModelChange', model); // sends to parent component }, } });
(function(){'use strict'; angular .module('swb.app', ['ngRoute', 'smartAdmin', 'swb.constants', 'swb.controllers']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/home', { templateUrl: 'templates/home.html', controller: 'swb.controller.home', }); $routeProvider.when('/angular', { templateUrl: 'templates/angular.html', controller: 'swb.controller.angular' }); $routeProvider.otherwise({redirectTo: 'home'}); }]); })();
import { convertObjectPropsToCamelCase, convertObjectPropsToSnakeCase, } from '~/lib/utils/common_utils'; /** * Converts a release object into a JSON object that can sent to the public * API to create or update a release. * @param {Object} release The release object to convert * @param {string} createFrom The ref to create a new tag from, if necessary */ export const releaseToApiJson = (release, createFrom = null) => { const name = release.name?.trim().length > 0 ? release.name.trim() : null; const milestones = release.milestones ? release.milestones.map(milestone => milestone.title) : []; return convertObjectPropsToSnakeCase( { name, tagName: release.tagName, ref: createFrom, description: release.description, milestones, assets: release.assets, }, { deep: true }, ); }; /** * Converts a JSON release object returned by the Release API * into the structure this Vue application can work with. * @param {Object} json The JSON object received from the release API */ export const apiJsonToRelease = json => { const release = convertObjectPropsToCamelCase(json, { deep: true }); release.milestones = release.milestones || []; return release; };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), qunit: { all: 'test/index.html' }, jshint: { grunt: 'Gruntfile.js', npm: 'package.json', bower: 'bower.json', source: 'src/**/*.js', tests: 'test/**/*.js', options: { jshintrc: true } }, uglify: { main: { files: { 'dist/jquery.readtime.min.js': ['src/jquery.readtime.js'] } }, options: { preserveComments: 'some', report: 'min' } }, watch: { files: '{src,test}/**/*.js', tasks: 'default', options: { livereload: true } } }); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['qunit', 'jshint', 'uglify']); };
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/clojure', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/clojure_highlight_rules', 'ace/mode/matching_parens_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ClojureHighlightRules = require("./clojure_highlight_rules").ClojureHighlightRules; var MatchingParensOutdent = require("./matching_parens_outdent").MatchingParensOutdent; var Range = require("../range").Range; var Mode = function() { var highlighter = new ClojureHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$keywordList = new Rules(rules.$keywordList); this.$outdent = new MatchingParensOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, ";"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/[\(\[]/); if (match) { indent += " "; } match = line.match(/[\)]/); if (match) { indent = ""; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/clojure_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ClojureHighlightRules = function() { var builtinFunctions = ( '* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* ' + '*command-line-args* *compile-files* *compile-path* *e *err* *file* ' + '*flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* ' + '*print-dup* *print-length* *print-level* *print-meta* *print-readably* ' + '*read-eval* *source-path* *use-context-classloader* ' + '*warn-on-reflection* + - -> ->> .. / < <= = ' + '== > &gt; >= &gt;= accessor aclone ' + 'add-classpath add-watch agent agent-errors aget alength alias all-ns ' + 'alter alter-meta! alter-var-root amap ancestors and apply areduce ' + 'array-map aset aset-boolean aset-byte aset-char aset-double aset-float ' + 'aset-int aset-long aset-short assert assoc assoc! assoc-in associative? ' + 'atom await await-for await1 bases bean bigdec bigint binding bit-and ' + 'bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left ' + 'bit-shift-right bit-test bit-xor boolean boolean-array booleans ' + 'bound-fn bound-fn* butlast byte byte-array bytes cast char char-array ' + 'char-escape-string char-name-string char? chars chunk chunk-append ' + 'chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? ' + 'class class? clear-agent-errors clojure-version coll? comment commute ' + 'comp comparator compare compare-and-set! compile complement concat cond ' + 'condp conj conj! cons constantly construct-proxy contains? count ' + 'counted? create-ns create-struct cycle dec decimal? declare definline ' + 'defmacro defmethod defmulti defn defn- defonce defstruct delay delay? ' + 'deliver deref derive descendants destructure disj disj! dissoc dissoc! ' + 'distinct distinct? doall doc dorun doseq dosync dotimes doto double ' + 'double-array doubles drop drop-last drop-while empty empty? ensure ' + 'enumeration-seq eval even? every? false? ffirst file-seq filter find ' + 'find-doc find-ns find-var first float float-array float? floats flush ' + 'fn fn? fnext for force format future future-call future-cancel ' + 'future-cancelled? future-done? future? gen-class gen-interface gensym ' + 'get get-in get-method get-proxy-class get-thread-bindings get-validator ' + 'hash hash-map hash-set identical? identity if-let if-not ifn? import ' + 'in-ns inc init-proxy instance? int int-array integer? interleave intern ' + 'interpose into into-array ints io! isa? iterate iterator-seq juxt key ' + 'keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list ' + 'list* list? load load-file load-reader load-string loaded-libs locking ' + 'long long-array longs loop macroexpand macroexpand-1 make-array ' + 'make-hierarchy map map? mapcat max max-key memfn memoize merge ' + 'merge-with meta method-sig methods min min-key mod name namespace neg? ' + 'newline next nfirst nil? nnext not not-any? not-empty not-every? not= ' + 'ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ' + 'ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? ' + 'or parents partial partition pcalls peek persistent! pmap pop pop! ' + 'pop-thread-bindings pos? pr pr-str prefer-method prefers ' + 'primitives-classnames print print-ctor print-doc print-dup print-method ' + 'print-namespace-doc print-simple print-special-doc print-str printf ' + 'println println-str prn prn-str promise proxy proxy-call-with-super ' + 'proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot ' + 'rand rand-int range ratio? rational? rationalize re-find re-groups ' + 're-matcher re-matches re-pattern re-seq read read-line read-string ' + 'reduce ref ref-history-count ref-max-history ref-min-history ref-set ' + 'refer refer-clojure release-pending-sends rem remove remove-method ' + 'remove-ns remove-watch repeat repeatedly replace replicate require ' + 'reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq ' + 'rsubseq second select-keys send send-off seq seq? seque sequence ' + 'sequential? set set-validator! set? short short-array shorts ' + 'shutdown-agents slurp some sort sort-by sorted-map sorted-map-by ' + 'sorted-set sorted-set-by sorted? special-form-anchor special-symbol? ' + 'split-at split-with str stream? string? struct struct-map subs subseq ' + 'subvec supers swap! symbol symbol? sync syntax-symbol-anchor take ' + 'take-last take-nth take-while test the-ns time to-array to-array-2d ' + 'trampoline transient tree-seq true? type unchecked-add unchecked-dec ' + 'unchecked-divide unchecked-inc unchecked-multiply unchecked-negate ' + 'unchecked-remainder unchecked-subtract underive unquote ' + 'unquote-splicing update-in update-proxy use val vals var-get var-set ' + 'var? vary-meta vec vector vector? when when-first when-let when-not ' + 'while with-bindings with-bindings* with-in-str with-loading-context ' + 'with-local-vars with-meta with-open with-out-str with-precision xml-seq ' + 'zero? zipmap' ); var keywords = ('throw try var ' + 'def do fn if let loop monitor-enter monitor-exit new quote recur set!' ); var buildinConstants = ("true false nil"); var keywordMapper = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "support.function": builtinFunctions }, "identifier", false, " "); this.$rules = { "start" : [ { token : "comment", regex : ";.*$" }, { token : "keyword", //parens regex : "[\\(|\\)]" }, { token : "keyword", //lists regex : "[\\'\\(]" }, { token : "keyword", //vectors regex : "[\\[|\\]]" }, { token : "keyword", //sets and maps regex : "[\\{|\\}|\\#\\{|\\#\\}]" }, { token : "keyword", // ampersands regex : '[\\&]' }, { token : "keyword", // metadata regex : '[\\#\\^\\{]' }, { token : "keyword", // anonymous fn syntactic sugar regex : '[\\%]' }, { token : "keyword", // deref reader macro regex : '[@]' }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", regex : '[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]' }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b" }, { token : "string", // single line regex : '"', next: "string" }, { token : "string", // symbol regex : /:[\w*+!\-_?:\/]+/ }, { token : "string.regexp", //Regular Expressions regex : '/#"(?:\\.|(?:\\\")|[^\""\n])*"/g' } ], "string" : [ { token : "constant.language.escape", regex : "\\\\.|\\\\$" }, { token : "string", regex : '[^"\\\\]+' }, { token : "string", regex : '"', next : "start" } ] }; }; oop.inherits(ClojureHighlightRules, TextHighlightRules); exports.ClojureHighlightRules = ClojureHighlightRules; }); define('ace/mode/matching_parens_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingParensOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\)/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\))/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingParensOutdent.prototype); exports.MatchingParensOutdent = MatchingParensOutdent; });
/* global HTMLElement */ import standard_gamepad from './standard_gamepad.svg!text' export default document.registerElement('x-gamepad', class extends HTMLElement { createdCallback () { this.id = 'x-gamepad' this.connected = false this.mapping = 'standard' this.axes = [] this.buttons = [] for (let button = 0; button <= 16; button++) { this.buttons[button] = {pressed: false} } this.innerHTML = standard_gamepad this.svg = this.children[0] } attachedCallback () { this.connected = true for (let button in this.buttons) { if (this.svg.getElementById('button-' + button)) { this.svg.getElementById('button-' + button) .addEventListener('mousedown', function (button) { button.pressed = true }.bind(this, this.buttons[button])) this.svg.getElementById('button-' + button) .addEventListener('mouseup', function (button) { button.pressed = false }.bind(this, this.buttons[button])) } } } detachedCallback () { this.connected = false for (let button in this.buttons) { if (this.svg.getElementById('button-' + button)) { this.svg.removeEventListener('mousedown') this.svg.removeEventListener('mouseup') } } } })
import styled from 'styled-components'; import get from 'extensions/themeGet'; export default styled.h1` font-family: ${get('fonts.brand')}; font-size: 22px; font-weight: 100; height: 30px; line-height: 30px; display: inline-block; white-space: nowrap; `;
'use strict'; var Generators = require('yeoman-generator'); module.exports = class extends Generators { constructor(args, options) { super(args, options); this.option('generateInto', { type: String, required: false, defaults: '', desc: 'Relocate the location of the generated files.' }); } initializing() { this.fs.copy( this.templatePath('settings.json'), this.destinationPath(this.options.generateInto, '.vscode/settings.json') ); } }
import Ember from 'ember'; import Mock from './mock'; import { test as qunitTest } from 'qunit'; import { getContext } from 'ember-test-helpers'; export function test (testName, callback, wrapped) { function wrapper (assert) { var context = getContext(), mocks = Ember.A(); context.mock = function (name) { var mock = Mock.create({ name: name }); mocks.pushObject(mock); return mock; }; callback.call(context, assert); mocks.forEach(function (mock) { mock.validate(assert); }); } (wrapped || qunitTest)(testName, wrapper); } export var ANYTHING = '<<mock-arg:anything>>'; export default test;
var cmdline = 'pslist'; var out = executeCommand('Volatility', {memdump:args.memdump, profile:args.profile, system: args.system, cmd:cmdline}); return out;
// Dependencies const mongoose = require('mongoose'); const Schema = mongoose.Schema; let DataPointSchema = new Schema({ variableName: { type: String }, variableDescription: { type: String }, variableUnit: { type: String }, value: { type: Number }, date: { type: Date } }); let SiteDataSchema = new Schema({ _id: { type: String, required: true, max: 15 }, siteName: { type: String, required: true }, siteId: { type: String, required: true, max: 15 }, lastUpdated: { type: Date, required: true }, minPrecip: { type: Number }, minPrecipDate: { type: Date }, maxPrecip: { type: Number }, maxPrecipDate: { type: Date }, minStreamFlow: { type: Number }, minStreamFlowDate: { type: Date }, maxStreamFlow: { type: Number }, maxStreamFlowDate: { type: Date }, minGageHeight: { type: Number }, minGageHeightDate: { type: Date }, maxGageHeight: { type: Number }, maxGageHeightDate: { type: Date }, data: {type: [DataPointSchema], default: undefined} }); // Export the Model module.exports = mongoose.model('SiteData', SiteDataSchema);
var request = require('request'); var authKey = "[YOUR_AUTHKEY]"; var senderID = "FSROLL"; exports.otpToNumber = function(otp, mobile) { otp = otp+ " is your verification code for Fussroll."; var query = "http://api.msg91.com/api/sendhttp.php?authkey="+authKey+"&mobiles="+mobile+"&message="+otp+"&sender="+senderID+"&route=4" request(query, function(err, res, body) { //console.log(body); }); }
import $ from 'jquery'; import { clearStyles } from '../util'; export default function () { let jews = {}; jews.title = $('#font_title').text().trim(); jews.subtitle = $('#font_subtitle').text(); jews.content = (function () { var content = $('#media_body')[0].cloneNode(true); $('.ad_lumieyes_area', content).each(function (i, el) { $(el).closest('tr').remove(); }); return clearStyles(content).innerHTML; })(); jews.timestamp = (function () { var data = {}; $('td[align="left"] table td', $('#font_email').closest('table').closest('td').closest('table')).text().split(/(입력|노출)\s*:([\d\-\.\s:]+)/).forEach(function (v, i, arr) { if (v === '입력') data.created = new Date(arr[i + 1].trim().replace(/\s+/g, ' ').replace(/[-\.]/g, '/') + '+0900'); else if (v === '노출') data.lastModified = new Date(arr[i + 1].trim().replace(/\s+/g, ' ').replace(/[-\.]/g, '/') + '+0900'); }); return data; })(); jews.reporters = (function () { var parsedData = $('#font_email').text().split('|'); return [{ name: parsedData[0].trim(), mail: parsedData[1].trim() }]; })(); jews.cleanup = function () { $('#scrollDiv').remove(); }; return jews; }
// @flow declare module 'multiparty' { declare module.exports: *; }
define(['jquery', 'rsvp', './class'], function ($, RSVP, Class) { 'use strict'; var timeout = 5000; var MainHttpRequester = Class.create({ init: function () { this.jsonRequester = new JsonRequester(); } }); var JsonRequester = Class.create({ init: function () { this.contentType = "application/json"; }, get: function (serviceUrl, headers) { var self = this; var promise = new RSVP.Promise(function (resolve, reject) { $.ajax({ url: serviceUrl, type: "GET", contentType: self.contentType, timeout: timeout, headers: headers, success: function (data) { resolve(data); }, error: function (error) { reject(error); } }); }); return promise; }, post: function (serviceUrl, data, headers) { var self = this; var promise = new RSVP.Promise(function (resolve, reject) { $.ajax({ url: serviceUrl, type: "POST", contentType: self.contentType, data: JSON.stringify(data), timeout: timeout, headers: headers, success: function (data) { resolve(data); }, error: function (error) { reject(error); } }); }); return promise; }, put: function (serviceUrl, data, headers) { var self = this; var promise = new RSVP.Promise(function (resolve, reject) { $.ajax({ url: serviceUrl, type: "PUT", contentType: self.contentType, data: JSON.stringify(data), timeout: timeout, headers: headers, success: function (data) { resolve(data); }, error: function (error) { reject(error); } }); }); return promise; }, delete: function (serviceUrl, headers) { var self = this; var promise = new RSVP.Promise(function (resolve, reject) { $.ajax({ url: serviceUrl, type: "DELETE", contentType: self.contentType, timeout: timeout, headers: headers, success: function (data) { resolve(data); }, error: function (error) { reject(error); } }); }); return promise; } }); return { get: function () { return new MainHttpRequester(); } } });
const should = require('should'); const supertest = require('supertest'); const _ = require('lodash'); const ObjectId = require('bson-objectid'); const moment = require('moment-timezone'); const testUtils = require('../../../utils'); const localUtils = require('./utils'); const config = require('../../../../server/config'); const models = require('../../../../server/models'); const ghost = testUtils.startGhost; let request; describe('Posts API', function () { let ghostServer; let ownerCookie; before(function () { return ghost() .then(function (_ghostServer) { ghostServer = _ghostServer; request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request, 'users:extra', 'posts'); }) .then(function (cookie) { ownerCookie = cookie; }); }); it('Can retrieve all posts', function (done) { request.get(localUtils.API.getApiQuery('posts/')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(13); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination'); _.isBoolean(jsonResponse.posts[0].featured).should.eql(true); // Ensure default order jsonResponse.posts[0].slug.should.eql('scheduled-post'); jsonResponse.posts[12].slug.should.eql('html-ipsum'); // Absolute urls by default jsonResponse.posts[0].url.should.match(new RegExp(`${config.get('url')}/p/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}`)); jsonResponse.posts[2].url.should.eql(`${config.get('url')}/welcome/`); jsonResponse.posts[11].feature_image.should.eql(`${config.get('url')}/content/images/2018/hey.jpg`); jsonResponse.posts[0].tags.length.should.eql(0); jsonResponse.posts[2].tags.length.should.eql(1); jsonResponse.posts[2].authors.length.should.eql(1); jsonResponse.posts[2].tags[0].url.should.eql(`${config.get('url')}/tag/getting-started/`); jsonResponse.posts[2].authors[0].url.should.eql(`${config.get('url')}/author/ghost/`); done(); }); }); it('Can retrieve multiple post formats', function (done) { request.get(localUtils.API.getApiQuery('posts/?formats=plaintext,mobiledoc&limit=3&order=title%20ASC')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(3); localUtils.API.checkResponse(jsonResponse.posts[0], 'post', ['plaintext']); localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination'); _.isBoolean(jsonResponse.posts[0].featured).should.eql(true); // ensure order works jsonResponse.posts[0].slug.should.eql('apps-integrations'); done(); }); }); it('Can includes single relation', function (done) { request.get(localUtils.API.getApiQuery('posts/?include=tags')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(13); localUtils.API.checkResponse( jsonResponse.posts[0], 'post', null, ['authors', 'primary_author'] ); localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination'); done(); }); }); it('Can filter posts', function (done) { request.get(localUtils.API.getApiQuery('posts/?filter=featured:true')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(2); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); localUtils.API.checkResponse(jsonResponse.meta.pagination, 'pagination'); done(); }); }); it('Cannot receive pages', function (done) { request.get(localUtils.API.getApiQuery('posts/?filter=page:true')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(0); done(); }); }); it('Can paginate posts', function (done) { request.get(localUtils.API.getApiQuery('posts/?page=2')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } const jsonResponse = res.body; should.equal(jsonResponse.meta.pagination.page, 2); done(); }); }); it('Can request a post by id', function (done) { request.get(localUtils.API.getApiQuery('posts/' + testUtils.DataGenerator.Content.posts[0].id + '/')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); jsonResponse.posts[0].id.should.equal(testUtils.DataGenerator.Content.posts[0].id); _.isBoolean(jsonResponse.posts[0].featured).should.eql(true); testUtils.API.isISO8601(jsonResponse.posts[0].created_at).should.be.true(); done(); }); }); it('Can retrieve a post by slug', function (done) { request.get(localUtils.API.getApiQuery('posts/slug/welcome/')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); jsonResponse.posts[0].slug.should.equal('welcome'); _.isBoolean(jsonResponse.posts[0].featured).should.eql(true); done(); }); }); it('Can include relations for a single post', function (done) { request .get(localUtils.API.getApiQuery('posts/' + testUtils.DataGenerator.Content.posts[0].id + '/?include=authors,tags')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); jsonResponse.posts[0].authors[0].should.be.an.Object(); localUtils.API.checkResponse(jsonResponse.posts[0].authors[0], 'user'); jsonResponse.posts[0].tags[0].should.be.an.Object(); localUtils.API.checkResponse(jsonResponse.posts[0].tags[0], 'tag', ['url']); done(); }); }); it('Can add a post', function () { const post = { title: 'My post', status: 'draft', published_at: '2016-05-30T07:00:00.000Z', mobiledoc: testUtils.DataGenerator.markdownToMobiledoc('my post'), created_at: moment().subtract(2, 'days').toDate(), updated_at: moment().subtract(2, 'days').toDate(), created_by: ObjectId.generate(), updated_by: ObjectId.generate() }; return request.post(localUtils.API.getApiQuery('posts')) .set('Origin', config.get('url')) .send({posts: [post]}) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { res.body.posts.length.should.eql(1); localUtils.API.checkResponse(res.body.posts[0], 'post'); res.body.posts[0].url.should.match(new RegExp(`${config.get('url')}/p/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}`)); should.not.exist(res.headers['x-cache-invalidate']); return models.Post.findOne({ id: res.body.posts[0].id, status: 'draft' }, testUtils.context.internal); }) .then((model) => { model.get('title').should.eql(post.title); model.get('status').should.eql(post.status); model.get('published_at').toISOString().should.eql('2016-05-30T07:00:00.000Z'); model.get('created_at').toISOString().should.not.eql(post.created_at.toISOString()); model.get('updated_at').toISOString().should.not.eql(post.updated_at.toISOString()); model.get('updated_by').should.not.eql(post.updated_by); model.get('created_by').should.not.eql(post.created_by); }); }); it('Can update draft', function () { const post = { title: 'update draft' }; return request .get(localUtils.API.getApiQuery(`posts/${testUtils.DataGenerator.Content.posts[3].id}/`)) .set('Origin', config.get('url')) .expect(200) .then((res) => { post.updated_at = res.body.posts[0].updated_at; return request.put(localUtils.API.getApiQuery('posts/' + testUtils.DataGenerator.Content.posts[3].id)) .set('Origin', config.get('url')) .send({posts: [post]}) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200); }) .then((res) => { res.headers['x-cache-invalidate'].should.eql('/p/' + res.body.posts[0].uuid + '/'); }); }); it('Can unpublish a post', function () { const post = { status: 'draft' }; return request .get(localUtils.API.getApiQuery(`posts/${testUtils.DataGenerator.Content.posts[1].id}/?`)) .set('Origin', config.get('url')) .expect(200) .then((res) => { post.updated_at = res.body.posts[0].updated_at; return request .put(localUtils.API.getApiQuery('posts/' + testUtils.DataGenerator.Content.posts[1].id + '/')) .set('Origin', config.get('url')) .send({posts: [post]}) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200); }) .then((res) => { res.headers['x-cache-invalidate'].should.eql('/*'); res.body.posts[0].status.should.eql('draft'); }); }); it('Can destroy a post', function () { return request .del(localUtils.API.getApiQuery('posts/' + testUtils.DataGenerator.Content.posts[0].id + '/')) .set('Origin', config.get('url')) .expect('Cache-Control', testUtils.cacheRules.private) .expect(204) .then((res) => { res.body.should.be.empty(); res.headers['x-cache-invalidate'].should.eql('/*'); }); }); it('Cannot get post via pages endpoint', function () { return request.get(localUtils.API.getApiQuery(`pages/${testUtils.DataGenerator.Content.posts[3].id}/`)) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(404); }); it('Cannot update post via pages endpoint', function () { const post = { title: 'fails', updated_at: new Date().toISOString() }; return request.put(localUtils.API.getApiQuery('pages/' + testUtils.DataGenerator.Content.posts[3].id)) .set('Origin', config.get('url')) .send({pages: [post]}) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(404); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import type {Fiber, ContextDependency} from './ReactInternalTypes'; import type {StackCursor} from './ReactFiberStack.new'; import type {ExpirationTimeOpaque} from './ReactFiberExpirationTime.new'; import {isPrimaryRenderer} from './ReactFiberHostConfig'; import {createCursor, push, pop} from './ReactFiberStack.new'; import {MAX_SIGNED_31_BIT_INT} from './MaxInts'; import { ContextProvider, ClassComponent, DehydratedFragment, } from './ReactWorkTags'; import {isSameOrHigherPriority} from './ReactFiberExpirationTime.new'; import invariant from 'shared/invariant'; import is from 'shared/objectIs'; import {createUpdate, enqueueUpdate, ForceUpdate} from './ReactUpdateQueue.new'; import {NoWork} from './ReactFiberExpirationTime.new'; import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork.new'; import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags'; const valueCursor: StackCursor<mixed> = createCursor(null); let rendererSigil; if (__DEV__) { // Use this to detect multiple renderers using the same context rendererSigil = {}; } let currentlyRenderingFiber: Fiber | null = null; let lastContextDependency: ContextDependency<mixed> | null = null; let lastContextWithAllBitsObserved: ReactContext<any> | null = null; let isDisallowedContextReadInDEV: boolean = false; export function resetContextDependencies(): void { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; if (__DEV__) { isDisallowedContextReadInDEV = false; } } export function enterDisallowedContextReadInDEV(): void { if (__DEV__) { isDisallowedContextReadInDEV = true; } } export function exitDisallowedContextReadInDEV(): void { if (__DEV__) { isDisallowedContextReadInDEV = false; } } export function pushProvider<T>(providerFiber: Fiber, nextValue: T): void { const context: ReactContext<T> = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); context._currentValue = nextValue; if (__DEV__) { if ( context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer = rendererSigil; } } else { push(valueCursor, context._currentValue2, providerFiber); context._currentValue2 = nextValue; if (__DEV__) { if ( context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer2 = rendererSigil; } } } export function popProvider(providerFiber: Fiber): void { const currentValue = valueCursor.current; pop(valueCursor, providerFiber); const context: ReactContext<any> = providerFiber.type._context; if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } export function calculateChangedBits<T>( context: ReactContext<T>, newValue: T, oldValue: T, ) { if (is(oldValue, newValue)) { // No change return 0; } else { const changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT; if (__DEV__) { if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) { console.error( 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits, ); } } return changedBits | 0; } } export function scheduleWorkOnParentPath( parent: Fiber | null, renderExpirationTime: ExpirationTimeOpaque, ) { // Update the child expiration time of all the ancestors, including // the alternates. let node = parent; while (node !== null) { const alternate = node.alternate; if ( !isSameOrHigherPriority( node.childExpirationTime_opaque, renderExpirationTime, ) ) { node.childExpirationTime_opaque = renderExpirationTime; if ( alternate !== null && !isSameOrHigherPriority( alternate.childExpirationTime_opaque, renderExpirationTime, ) ) { alternate.childExpirationTime_opaque = renderExpirationTime; } } else if ( alternate !== null && !isSameOrHigherPriority( alternate.childExpirationTime_opaque, renderExpirationTime, ) ) { alternate.childExpirationTime_opaque = renderExpirationTime; } else { // Neither alternate was updated, which means the rest of the // ancestor path already has sufficient priority. break; } node = node.return; } } export function propagateContextChange( workInProgress: Fiber, context: ReactContext<mixed>, changedBits: number, renderExpirationTime: ExpirationTimeOpaque, ): void { let fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { let nextFiber; // Visit this fiber. const list = fiber.dependencies_new; if (list !== null) { nextFiber = fiber.child; let dependency = list.firstContext; while (dependency !== null) { // Check if the context matches. if ( dependency.context === context && (dependency.observedBits & changedBits) !== 0 ) { // Match! Schedule an update on this fiber. if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. const update = createUpdate(-1, renderExpirationTime, null); update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. enqueueUpdate(fiber, update); } if ( !isSameOrHigherPriority( fiber.expirationTime_opaque, renderExpirationTime, ) ) { fiber.expirationTime_opaque = renderExpirationTime; } const alternate = fiber.alternate; if ( alternate !== null && !isSameOrHigherPriority( alternate.expirationTime_opaque, renderExpirationTime, ) ) { alternate.expirationTime_opaque = renderExpirationTime; } scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. if ( !isSameOrHigherPriority(list.expirationTime, renderExpirationTime) ) { list.expirationTime = renderExpirationTime; } // Since we already found a match, we can stop traversing the // dependency list. break; } dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { // Don't scan deeper if this is a matching provider nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if ( enableSuspenseServerRenderer && fiber.tag === DehydratedFragment ) { // If a dehydrated suspense bounudary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates. const parentSuspense = fiber.return; invariant( parentSuspense !== null, 'We just came from a parent so we must have had a parent. This is a bug in React.', ); if ( !isSameOrHigherPriority( parentSuspense.expirationTime_opaque, renderExpirationTime, ) ) { parentSuspense.expirationTime_opaque = renderExpirationTime; } const alternate = parentSuspense.alternate; if ( alternate !== null && !isSameOrHigherPriority( alternate.expirationTime_opaque, renderExpirationTime, ) ) { alternate.expirationTime_opaque = renderExpirationTime; } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. scheduleWorkOnParentPath(parentSuspense, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } const sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } export function prepareToReadContext( workInProgress: Fiber, renderExpirationTime: ExpirationTimeOpaque, ): void { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; const dependencies = workInProgress.dependencies_new; if (dependencies !== null) { const firstContext = dependencies.firstContext; if (firstContext !== null) { if ( isSameOrHigherPriority( dependencies.expirationTime, renderExpirationTime, ) ) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list dependencies.firstContext = null; } } } export function readContext<T>( context: ReactContext<T>, observedBits: void | number | boolean, ): T { if (__DEV__) { // This warning would fire if you read context inside a Hook like useMemo. // Unlike the class check below, it's not enforced in production for perf. if (isDisallowedContextReadInDEV) { console.error( 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().', ); } } if (lastContextWithAllBitsObserved === context) { // Nothing to do. We already observe everything in this context. } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { let resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types. if ( typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT ) { // Observe all updates. lastContextWithAllBitsObserved = ((context: any): ReactContext<mixed>); resolvedObservedBits = MAX_SIGNED_31_BIT_INT; } else { resolvedObservedBits = observedBits; } const contextItem = { context: ((context: any): ReactContext<mixed>), observedBits: resolvedObservedBits, next: null, }; if (lastContextDependency === null) { invariant( currentlyRenderingFiber !== null, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().', ); // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies_new = { expirationTime: NoWork, firstContext: contextItem, responders: null, }; } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } return isPrimaryRenderer ? context._currentValue : context._currentValue2; }
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, brackets, $ */ define(function (require, exports, module) { "use strict"; var Dialogs = brackets.getModule("widgets/Dialogs"); var DefaultDialogs = brackets.getModule("widgets/DefaultDialogs"); var ProjectManager = brackets.getModule("project/ProjectManager"); var CommandManager = brackets.getModule("command/CommandManager"); var Commands = brackets.getModule("command/Commands"); var MainViewManager = brackets.getModule("view/MainViewManager"); var LiveDevMultiBrowser = brackets.getModule("LiveDevelopment/LiveDevMultiBrowser"); var KeyEvent = brackets.getModule("utils/KeyEvent"); var StartupState = brackets.getModule("bramble/StartupState"); var FileSystem = brackets.getModule("filesystem/FileSystem"); var BracketsFiler = brackets.getModule("filesystem/impls/filer/BracketsFiler"); var Path = BracketsFiler.Path; var Strings = brackets.getModule("strings"); var StringUtils = brackets.getModule("utils/StringUtils"); var MoveUtils = require("MoveUtils"); var dialogTemplate = require("text!htmlContent/move-to-dialog.html"); var directoryTreeTemplate = require("text!htmlContent/directory-tree.html"); var BASE_INDENT = 20; Mustache.parse(dialogTemplate); Mustache.parse(directoryTreeTemplate); function _finishMove(source, destination, newPath) { var fileInEditor = MainViewManager.getCurrentlyViewedPath(); var relPath; var fileToOpen; function afterFileTreeRefresh() { FileSystem.off("change", afterFileTreeRefresh); ProjectManager.showInTree(FileSystem.getFileForPath(fileToOpen)); LiveDevMultiBrowser.reload(); } if(newPath) { relPath = Path.relative(Path.dirname(source), fileInEditor); if(relPath === '') { relPath = Path.basename(fileInEditor); } fileToOpen = Path.join(destination, relPath); // Reload the editor if the current file that is in the // editor is a) what is being moved or b) is somewhere in // in the folder that is being moved. if(fileInEditor.indexOf(source) === 0) { CommandManager.execute(Commands.CMD_OPEN, {fullPath: fileToOpen}); // Once the file tree has been refreshed, a `change` event // on the FileSystem is fired. // This is unfortunately the only way to make sure // the file tree first reflects the (delete + create) move // operation and only then do `afterFileTreeRefresh` which // expands the parent directories and reloads the preview. // If it is not done in this order, you'll see the directories // expand first with the file shown in its old location and // after a delay, the file will jump to the new location. FileSystem.on("change", afterFileTreeRefresh); ProjectManager.refreshFileTree(); return; } } ProjectManager.refreshFileTree(); LiveDevMultiBrowser.reload(); } function _failMove(source, destination, error) { var from = Path.basename(source); var to = Path.basename(destination); if(error.type === MoveUtils.NEEDS_RENAME) { Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, Strings.ERROR_MOVING_FILE_DIALOG_HEADER, StringUtils.format(Strings.ERROR_MOVING_FILE_SAME_NAME, from, to) ); return; } Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, Strings.ERROR_MOVING_FILE_DIALOG_HEADER, StringUtils.format(Strings.ERROR_MOVING_FILE, from, to) ); console.error("[Bramble] Failed to move `", source, "` to `", destination, "` with: ", error); } function _handleDialogEvents(dialog) { $(window.document.body).one("keyup.installDialog", function(e) { if(e.keyCode === KeyEvent.DOM_VK_ESCAPE) { dialog.close(); } }); dialog.getElement().one("buttonClick", function(e, button) { if(button === Dialogs.DIALOG_BTN_CANCEL) { return dialog.close(); } if(button !== Dialogs.DIALOG_BTN_OK) { return; } var $directories = $(".move-to-dialog .directories"); var source = $directories.attr("data-source"); var destination = $directories.attr("data-destination"); MoveUtils.move(source, destination) .done(_finishMove.bind(null, source, destination)) .fail(_failMove.bind(null, source, destination)) .always(function() { dialog.close(); }); }); } function _handleClicksOnDirectories(pathToMove) { var $directories = $(".move-to-dialog .directories"); $(".move-to-dialog .directory-name") .mousedown(function(e) { $(e.currentTarget).addClass("active-directory"); }) .click(function(e) { var $selectedDirectory = $(e.currentTarget); $(".move-to-dialog .directory-name").removeClass("active-directory"); $directories.attr("data-destination", $selectedDirectory.parent().attr("data-path")); $selectedDirectory.addClass("active-directory"); }); } function _getListOfDirectories(defaultPath, callback) { var projectRoot = StartupState.project("root"); var parentPath = projectRoot.replace(/\/?$/, ""); var directories = [{ path: parentPath, name: Strings.PROJECT_ROOT, children: false, indent: 0, noIcon: true, defaultPath: parentPath === defaultPath }]; var currentIndent = 0; function constructDirTree(tree, currentNode, index) { if(currentNode.type !== "DIRECTORY") { return tree; } var currentPath = Path.join(parentPath, currentNode.path); var directory = { name: currentNode.path, path: currentPath, children: false, indent: currentIndent, defaultPath: currentPath === defaultPath }; if(currentNode.contents && currentNode.contents.length > 0) { currentIndent += BASE_INDENT; parentPath = currentPath; directory.children = currentNode.contents.reduce(constructDirTree, false); parentPath = Path.dirname(currentPath); currentIndent -= BASE_INDENT; } tree = tree || []; tree.push(directory); return tree; } BracketsFiler.fs().ls(projectRoot, { recursive: true }, function(err, nodes) { if(err) { return callback(err); } callback(null, nodes.reduce(constructDirTree, directories)); }); } function open() { var context = ProjectManager.getContext(); if(!context) { return; } var defaultPath = Path.dirname(context.fullPath); _getListOfDirectories(defaultPath, function(err, directories) { if(err) { return console.error("Failed to get list of directories with: ", err); } var dialogContents = { defaultPath: defaultPath, source: context.fullPath, PICK_A_FOLDER_TO_MOVE_TO: Strings.PICK_A_FOLDER_TO_MOVE_TO, OK: Strings.OK, CANCEL: Strings.CANCEL }; var subdirectoryContents = { subdirectories: directoryTreeTemplate }; var directoryContents = { directories: Mustache.render(directoryTreeTemplate, directories, subdirectoryContents) }; var dialogHTML = Mustache.render(dialogTemplate, dialogContents, directoryContents); var dialog = Dialogs.showModalDialogUsingTemplate(dialogHTML, false); _handleDialogEvents(dialog); _handleClicksOnDirectories(context.fullPath); }); } exports.open = open; });
// describe はテストをグループ化する describe('FizzBuzzConverter 1', function(){ // describe はネストできる // (rspec にある context は jasmine では存在しない) describe('convert', function(){ // it はテストケース(rspec 用語では example) it('1 は 1, 2 = 2, 4 = 4', function(){ var subject = new FizzBuzzConverter(); expect(subject.convert(1)).toBe(1); expect([subject.convert(2), subject.convert(4)]).toEqual([2,4]); // toEqual は深い比較 }); it('3 は fizz', function(){ var subject = new FizzBuzzConverter(); expect(subject.convert(3)).toBe('fizz'); }); it('5 は buzz', function(){ var subject = new FizzBuzzConverter(); expect(subject.convert(5)).toBe('buzz'); }); it('15 は fizzbuzz', function(){ var subject = new FizzBuzzConverter(); expect(subject.convert(15)).toBe('fizzbuzz'); expect(subject.convert(15)).not.toBe('fizz'); // 否定形 expect(subject.convert(15)).toMatch(/fizz/); // regex }); it('数値以外の入力では例外が発生する', function(){ var subject = new FizzBuzzConverter(); // 例外のテストでは、関数オブジェクトを expect の引数として渡す expect(function(){ subject.convert("foo"); }).toThrow(); expect(function(){ subject.convert(null); }).toThrow(); expect(function(){ subject.convert(1.1); }).not.toThrow(); }); }); });
export const SET_MOVIE_LIST = "SET_MOVIE_LIST" export const SET_MUSIC_LIST = "SET_MUSIC_LIST" export const SET_MOVIE_INFO = "SET_MOVIE_INFO" export const SET_MUSIC_INFO = "SET_MUSIC_INFO" export const SHOW_LOADING = "SHOW_LOADING" export const HIDE_LOADING = "HIDE_LOADING"
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define(["require","exports"],function(f,c){Object.defineProperty(c,"__esModule",{value:!0});c.create=function(){var a=new Float32Array(4);a[3]=1;return a};c.clone=function(a){var b=new Float32Array(4);b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];return b};c.fromValues=function(a,b,c,e){var d=new Float32Array(4);d[0]=a;d[1]=b;d[2]=c;d[3]=e;return d};c.createView=function(a,b){return new Float32Array(a,b,4)}});
import Ember from 'ember'; import { toggle } from '../../../helpers/toggle'; import { module, test } from 'qunit'; const { Object: EmberObject, get } = Ember; module('Unit | Helper | toggle'); test('it toggles the property', function(assert) { let Person = EmberObject.extend({ isAlive: false }); let jimBob = Person.create(); let action = toggle([jimBob, 'isAlive']); action(); assert.ok(get(jimBob, 'isAlive') === true, 'it toggles the property'); }); test('it toggles the property of a POJO', function(assert) { let jimBob = { isAlive: false }; let action = toggle([jimBob, 'isAlive']); action(); assert.ok(get(jimBob, 'isAlive') === true, 'it toggles the property of a POJO'); }); test('it correctly toggles non-boolean falsy values', function(assert) { let jimBob = { isAlive: undefined }; let action = toggle([jimBob, 'isAlive']); action(); assert.ok(get(jimBob, 'isAlive') === true, 'it toggles the property of a POJO'); }); test('it correctly toggles non-boolean truthy values', function(assert) { let jimBob = { isAlive: {} }; let action = toggle([jimBob, 'isAlive']); action(); assert.ok(get(jimBob, 'isAlive') === false, 'it toggles the property of a POJO'); });
/*! * Middleware Chain. * Nested async example usage. * * @author Jarrad Seers <jarrad@seers.me> * @created 23/08/2015 * @license MIT */ // Module dependencies. var chain = require(__dirname + '/../'); /** * Function One. * Example function, logs 'hello' and currect context. * * @param {Object} context Current context object. * @param {Function} next Next middleware in chain. */ function one(context, next) { setTimeout(function() { context.one = 'Hello'; console.log('Hello from one', context); return next(); }, 1000); } /** * Function Two. * Example function, logs 'hello' and currect context. * Calls a new nested chain. * * @param {Object} context Current context object. * @param {Function} next Next middleware in chain. */ function two(context, next) { setTimeout(function() { context.two = 'Hello'; console.log('Hello from two', context); chain({ nested: 'Hello' }, [ one, three ]); return next(); }, 1000); } /** * Function Three. * Example function, logs 'hello' and currect context. * * @param {Object} context Current context object. * @param {Function} next Next middleware in chain. */ function three(context, next) { setTimeout(function() { context.three = 'Hello'; console.log('Hello from three', context); }, 1000); } // Chain all three functions, passes in initial context. chain({ main: 'Hello' }, [ one, two, three ]);
function onError (err) { setTimeout(function () { throw err }, 0) } function isPromise (val) { return val && typeof val.then === 'function' } module.exports = () => { return next => action => { return isPromise(action) ? action.then(next, onError) : next(action) } }
// DESCRIPTION = disallow self assignment // STATUS = 2 /* eslint no-undef: 0*/ // <!START // Bad /* foo = foo; */ // END!>
var express = require('express'); var router = express.Router(); var auth = require('../controllers/authorization'); var restler = require('restler'); var cookie = require('cookie'); var _ = require("underscore"); function getCookies(req){ var cookies = _.map(req.cookies, function(val, key) { if(key == "connect.sid"){ return key + "=" + val['connect.sid']; } }).join("; "); return cookies; } /* GET home page. */ router.get('/', auth.requiresLogin, function(req, res, next) { try{ restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/collections/ldcvia-ideas/ideas", {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ if(response.statusCode == 200){ res.render('index', {"tab":"home", "email": req.cookies.email, "ideas": data, "title": "LDC Via Ideas"}); }else{ res.render("login", {"error": data}); } }); }catch(e){ res.render("login", {"error": e}); } }); router.get('/newidea', auth.requiresLogin, function(req, res, next){ res.render("idea-new", {"tab": "newidea", "email": req.cookies.email, "title": "New Idea | LDC Via Ideas"}); }) router.post('/newidea', auth.requiresLogin, function(req, res, next){ var data = {}; data.body = req.body.body; data.title = req.body.title; data.priority = req.body.priority; data.status = req.body.status; data.createdby = req.cookies.email; data.datecreated = new Date(); data.__form = "ideas"; data.votes = 0; var unid = data.datecreated.getTime(); data.__unid = unid; restler.putJson( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + unid, data, {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ res.redirect("/"); }) }) router.get('/idea/:unid', auth.requiresLogin, function(req, res, next){ try{ restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid + "?all", {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ res.render('idea-read', {"tab":"idea", "email": req.cookies.email, "idea": data, "title": data.title + " | LDC Via Ideas"}); }); }catch(e){ res.render("login", {"error": e}); } }) router.get('/editidea/:unid', auth.requiresLogin, function(req, res, next){ try{ restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid + "?all", {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ data.priorities = ["High", "Medium", "Low"]; data.statuses = ["New","In Progress","Rejected","Complete"]; if (data.__iseditable){ res.render('idea-edit', {"tab":"idea", "email": req.cookies.email, "idea": data, "title": data.title + " | LDC Via Ideas"}); }else{ res.render('idea-read', {"tab":"idea", "email": req.cookies.email, "idea": data, "title": data.title + " | LDC Via Ideas"}); } }); }catch(e){ res.render("login", {"error": e}); } }) router.post('/editidea/:unid', auth.requiresLogin, function(req, res, next){ var data = {}; data.body = req.body.body; data.title = req.body.title; data.priority = req.body.priority; data.status = req.body.status; restler.postJson( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid, data, {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ res.redirect("/idea/" + req.params.unid); }) }) router.get('/upvote/:unid', auth.requiresLogin, function(req, res, next){ castVote(req, res, 1, function(votes, votecast, err){ if (err){ res.status(200).send({"votes": votes, "votecast": votecast, "error": err}); }else{ res.status(200).send({"votes": votes, "votecast": votecast}); } }) }) router.get('/downvote/:unid', auth.requiresLogin, function(req, res, next){ castVote(req, res, -1, function(votes, votecast, err){ if (err){ res.status(200).send({"votes": votes, "votecast": votecast, "error": err}); }else{ res.status(200).send({"votes": votes, "votecast": votecast}); } }) }) function castVote(req, res, score, callback){ var email = req.cookies.email; var data = {"filters": [ { "operator": "equals", "field": "__parentid", "value": req.params.unid }, { "operator": "equals", "field": "createdby", "value": email } ]}; restler.postJson( process.env.LDCVIA_IDEAS_APIHOST + "/search/ldcvia-ideas/votes?join=and", data, {headers: {'cookie': getCookies(req)} } ).on('complete', function(data, response){ console.log("Got " + data.count + " votes"); if (data.count == 0){ //Insert a new vote var vote = {}; var date = new Date(); var unid = date.getTime(); vote.__unid = unid; vote.createdby = email; vote.vote = score; vote.__parentid = req.params.unid; vote.__form = "vote"; restler.putJson( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/votes/" + unid, vote, {headers: {'cookie': getCookies(req)} } ).on('complete', function(data, response){ //Update the idea with the score restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid, {headers: {'cookie': getCookies(req)} } ).on('complete', function(data, response){ if (!data.votes){ data.votes = 0; } var newscore = data.votes + score; restler.postJson( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid, {"votes": newscore}, {headers: {'cookie': getCookies(req)} } ).on('complete', function(data, response){ callback(newscore, true); }) }) }) }else{ //The user has already cast a vote so return current score restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid, {headers: {'cookie': getCookies(req)} } ).on('complete', function(data, response){ if(data.votes){ callback(data.votes, false, "Vote already cast"); }else{ callback(0, false, "Vote already cast"); } }) } }) } router.get("/deleteidea/:unid", auth.requiresLogin, function(req, res, next){ try{ restler.del( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/ideas/" + req.params.unid, {headers: {'cookie': getCookies(req)} } ) .on('complete', function(data, response){ res.redirect("/"); }); }catch(e){ res.render("login", {"error": e}); } }) router.get('/about', function(req, res, next) { try{ restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/staticpages/about", {headers: {'apikey': process.env.LDCVIA_IDEAS_ADMINAPIKEY} } ) .on('complete', function(data, response){ res.render('static', {"tab":"about", "email": req.cookies.email, "page": data, "title": "About | LDC Via Ideas"}); }); }catch(e){ res.render("login", {"error": e}); } }); router.get('/contact', function(req, res, next) { try{ restler.get( process.env.LDCVIA_IDEAS_APIHOST + "/document/ldcvia-ideas/staticpages/contact", {headers: {'apikey': process.env.LDCVIA_IDEAS_ADMINAPIKEY} } ) .on('complete', function(data, response){ res.render('static', {"tab":"contact", "email": req.cookies.email, "page": data, "title": "Contact | LDC Via Ideas"}); }); }catch(e){ res.render("login", {"error": e}); } }); /* GET login page */ router.get('/login', function(req, res, next) { res.render('login', {"tab": "home", "title": "Login | LDC Via Ideas"}); }); router.post('/login', function(req, res, next){ try{ restler.postJson( "https://eu.ldcvia.com/login", {'username': req.body.email, 'email': req.body.email, 'password': req.body.password} ).on('complete', function (data, response){ // display returned cookies in header var setcookie = response.headers["set-cookie"]; var cookieobj = {}; for (var i=0; i<setcookie.length; i++){ if (setcookie[i].indexOf("connect.sid=") > -1){ cookieobj = cookie.parse(setcookie[i]); } } if (cookieobj['connect.sid'] && data.success){ res.cookie('connect.sid', cookieobj); res.cookie('email', req.body.email); res.redirect("/"); }else{ res.render("login", {"error": data.errors[0]}); }; }); }catch(e){ res.render("/login"); } }) router.get('/logout', auth.requiresLogin, function(req, res, next){ res.clearCookie('connect.sid'); res.clearCookie('email'); res.redirect('/'); }) module.exports = router;
class PausableTimeout { constructor(callback, duration) { this.callback = () => { this.cancel(); callback.call(null); }; this.remaining = duration; this.timeout = null; this.startTime = null; this.resume(); this.done = false; } pause() { if (!this.done && this.timeout != null) { clearTimeout(this.timeout); this.timeout = null; this.remaining -= Date.now() - this.startTime; } } resume() { if (!this.done) { this.startTime = Date.now(); this.timeout = setTimeout(this.callback, this.remaining); } } cancel() { if (!this.done && this.timeout != null) { this.done = true; clearTimeout(this.timeout); this.timeout = null; } } }
define([ 'jquery', 'backbone', 'text!templates/artists/artists_toolbar.html' ], function($, Backbone, artistsToolbarTemplate) { var ArtistsToolbarView = Backbone.View.extend({ tagName: 'div', id: 'artists-toolbar', model: null, initialize: function(options) { console.log("controllers/ArtistsToolbarView::initialize()"); _.extend(this, options); }, render: function () { console.log("controllers/ArtistsToolbarView::render()"); this.$el.html(artistsToolbarTemplate); return this; } }); return ArtistsToolbarView; });
$(document).ready(function(){ // Validate function validate_global_allow(key){ if(key==8 || key==9 || (key>=35 && key<=40) || key==46) { return true; } }; function validate_numeric_keys(key){ if(key>=48 && key<=57 || key>=96 && key<=105) { return true; } }; function validate_comma_dot(key){ if (key == 188 || key == 110 || key == 190 || key == 191) { return true; } } function validate_enter(key){ if (key == 13) { return true; } } function validate_space(key){ if (key == 32) { return true; } } // compatible with jquery.validator $('body').on('keydown', 'input[data-rule-number=true]', function(e){ var key = O_o.key_code(e), allow = false; if(validate_comma_dot(key)) { var val = $(this).val(), pos_start = e.target.selectionStart, pos_end = e.target.selectionEnd, len = val.length, val_left = val.substr(0,pos_start), val_right = val.substr(pos_end,len); $(this).val(val_left + '.' + val_right); this.selectionStart = this.selectionEnd = pos_start +1; } if( validate_numeric_keys(key) || key == 46 || validate_global_allow(key) || validate_enter(key) ) allow = true; if(!allow) e.preventDefault(); }); /* unuse $('.allow_int').keypress(function(e){ if(e.keyCode<48 || e.keyCode>57) e.preventDefault(); }); $('.allow_float').keypress(function(e){ var key = O_o.key_code(e), allow = false; if(key == 44) { var val = $(this).val(), pos_start = e.target.selectionStart, pos_end = e.target.selectionEnd, len = val.length, val_left = val.substr(0,pos_start), val_right = val.substr(pos_end,len); $(this).val(val_left + '.' + val_right); this.selectionStart = this.selectionEnd = pos_start +1; } if(key>=48 && key<=57 || key == 46 || validate_global_allow(key)) allow = true; if(!allow) e.preventDefault(); }); */ });
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/data-visualization-repository', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
/** * Dependencies */ const pkg = require('../package.json'); /** * Interface */ module.exports.ATOM_REGISTRY = 'https://atom.io'; module.exports.GITHUB_API = 'https://api.github.com'; module.exports.headers = { 'User-Agent': `LastReleaseApm/${pkg.version}`, };
"use strict"; import React from "react"; import { ActionCard, MatchCardList, TitleBanner, PartnerCard } from "../components"; import { ActionActions } from "../actions"; import { ActionStore } from "../stores"; export default class ActionPage extends React.Component { constructor(props) { super(props); this.state = { action: null, requests: null }; } componentWillMount() { ActionActions.getAction(this.props.params.id); } /* * We use ComponentWillReceiveProps because a transition can occur on this * component with just a parameter change (params.id). Hence, we want to * force an update of this component's state (ie. load a new action in * depending on the new params.id) */ componentWillReceiveProps(nextProps) { ActionActions.getAction(nextProps.params.id); } componentDidMount() { this.unsubscribe = ActionStore.listen(this.onActionChange.bind(this)); } componentWillUnmount() { this.unsubscribe(); } onActionChange(change) { this.setState( { action: change.action , requests: change.requests } ); } render() { if (this.state.action !== null) { let action = this.state.action; if (!action.match) { return ( <div id="content"> <TitleBanner history={this.props.history} title={action.title} /> <ActionCard action={action} showTitle={false} isSummary={false} /> <MatchCardList heading="This action has been liked by:" subject="principal" principal={action} actions={this.state.requests} history={this.props.history} /> </div> ); } else { return ( <div id="content"> <TitleBanner history={this.props.history} title={action.title} /> <ActionCard action={action} showTitle={false} isSummary={false} /> <PartnerCard action={action} partner={action.match} /> </div> ); } } else { return ( <div id="content"> <article className="card"> <main> <p>Action loading...</p> </main> </article> </div> ); } } }
import { equal, notEqual, deepEqual } from 'assert' import axios from 'axios' import moxios from './index' const USER_FRED = { id: 12345, firstName: 'Fred', lastName: 'Flintstone' } describe('moxios', function () { it('should install', function () { let defaultAdapter = axios.defaults.adapter moxios.install() notEqual(axios.defaults.adapter, defaultAdapter) moxios.uninstall() }) it('should uninstall', function () { let defaultAdapter = axios.defaults.adapter moxios.install() moxios.uninstall() equal(axios.defaults.adapter, defaultAdapter) }) describe('requests', function () { let onFulfilled let onRejected beforeEach(function () { moxios.install() onFulfilled = sinon.spy() onRejected = sinon.spy() }) afterEach(function () { moxios.uninstall() }) it('should intercept requests', function (done) { axios.get('/users/12345') moxios.wait(function () { let request = moxios.requests.mostRecent() equal(moxios.requests.count(), 1) done() }) }) it('should mock responses', function (done) { axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let request = moxios.requests.mostRecent() request.respondWith({ status: 200, response: USER_FRED }).then(function () { let response = onFulfilled.getCall(0).args[0] equal(onFulfilled.called, true) equal(response.status, 200) deepEqual(response.data, USER_FRED) done() }) }) }) it('should mock responses Error', function (done) { axios.get('/users/12346').then(onFulfilled, onRejected) moxios.wait(function () { let request = moxios.requests.mostRecent() request.respondWith({ status: 404 }).then(function () { equal(onFulfilled.called, false) equal(onRejected.called, true) done() }) }) }) it('should mock one time', function (done) { moxios.uninstall() moxios.withMock(function () { axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let request = moxios.requests.mostRecent() request.respondWith({ status: 200, response: USER_FRED }).then(function () { equal(onFulfilled.called, true) done() }) }) }) }) it('should timeout requests one time', function(done) { moxios.uninstall() moxios.withMock(function() { axios.get('/users/12345') moxios.wait(function() { let request = moxios.requests.mostRecent() request.respondWithTimeout().catch(function(err) { equal(err.code, 'ECONNABORTED') done() }) }) }) }) it('should stub requests', function (done) { moxios.stubRequest('/users/12345', { status: 200, response: USER_FRED }) axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, USER_FRED) done() }) }) it('should stub requests with callback', function (done) { moxios.stubRequest('/whoami', (request) => { return { status: 200, response: request.url } }) axios.get('/whoami').then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, '/whoami') done() }) }) it('should stub GET requests', function (done) { moxios.stubRequest('GET', '/users/12345', { status: 200, response: USER_FRED }) axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, USER_FRED) done() }) }) it('should stub POST requests, but not GET requests', function (done) { moxios.stubRequest('POST', '/users/', { status: 200, response: USER_FRED }) axios.get('/users/').then(onFulfilled) axios.post('/users/', USER_FRED).then(onFulfilled) moxios.wait(function () { equal(onFulfilled.calledOnce, true) let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, USER_FRED) done() }) }) it('should pick the correct stub based on method', function (done) { const USER_WILMA = { id: 54321, firstName: 'Wilma', lastName: 'Flintstone' } moxios.stubRequest('GET', '/users/', { status: 200, response: USER_FRED }) moxios.stubRequest('POST', '/users/', { status: 200, response: USER_WILMA }) moxios.stubRequest('PUT', '/users/', { status: 200, response: USER_FRED }) axios.put('/users/', USER_FRED).then(onFulfilled) axios.post('/users/', USER_WILMA).then(onFulfilled) moxios.wait(function () { equal(onFulfilled.calledTwice, true) let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, USER_FRED) response = onFulfilled.getCall(1).args[0] deepEqual(response.data, USER_WILMA) done() }) }) it('should stub timeout', function (done) { moxios.stubTimeout('/users/12345') axios.get('/users/12345').catch(onRejected) moxios.wait(function () { let err = onRejected.getCall(0).args[0] deepEqual(err.code, 'ECONNABORTED') done() }) }) it('should stub requests RegExp', function (done) { moxios.stubRequest(/\/users\/\d*/, { status: 200, response: USER_FRED }) axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] deepEqual(response.data, USER_FRED) done() }) }) it('should include a timestamp', function () { axios.get('/users/12345') return moxios.wait().then(function () { const request = moxios.requests.mostRecent() const timestamp = moxios.requests.mostRecent().timestamp; const diff = Date.now() - timestamp.getTime(); equal(diff >= 0 && diff <= 1000, true); }) }) it('should include timestamp in debug output', function () { axios.get('/users/12345') axios.get('/users/12346') axios.delete('/users/12345') return moxios.wait(function () { const logs = []; let log = sinon.stub(console, 'log', str => logs.push(str)); moxios.requests.debug(); log.restore(); equal(logs.filter(str => str).every(str => str.match(/^\d\d:\d\d\.\d{1,3}/)), true); }) }) describe('stubs', function () { it('should track multiple stub requests', function () { moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) equal(moxios.stubs.count(), 2) }) it('should find single stub by method', function () { moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) let request = moxios.stubs.get('PUT', '/users/12345') notEqual(request, undefined) }) it('should remove a single stub by method', function () { moxios.stubOnce('PUT', '/users/12346', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12345', { status: 200, response: USER_FRED }) moxios.stubs.remove('PUT', '/users/12345') equal(moxios.stubs.count(), 3) }) it('should not find stub with invalid method', function () { moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) let request = moxios.stubs.get('GET', '/users/12345') equal(request, undefined) }) it('should not find request on invalid method', function () { moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) axios.put('/users/12346', USER_FRED) let request = moxios.requests.get('TEST') equal(request, undefined) }) it('should find request after multiple stubs using same URI', function (done) { moxios.stubOnce('POST', '/users/12345', { status: 204 }) moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12345', { status: 200, response: USER_FRED }) axios.put('/users/12345', USER_FRED).then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] equal(response.status, 204) let request = moxios.requests.get('PUT', '/users/12345') notEqual(request, undefined) done() }) }) it('Should stub and find multiple requests by method', function (done) { moxios.stubOnce('PUT', '/users/12345', { status: 204 }) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) axios.put('/users/12345', USER_FRED).then(onFulfilled) axios.get('/users/12346', {}).then(onFulfilled) moxios.wait(function () { equal(onFulfilled.calledTwice, true) let response1 = onFulfilled.getCall(0).args[0] let response2 = onFulfilled.getCall(1).args[0] equal(response1.status, 204) equal(response2.status, 200) equal(response2.data.firstName, 'Fred') let request = moxios.requests.get('PUT', '/users/12345'); notEqual(request, undefined) request = moxios.requests.get('GET', '/users/12346'); notEqual(request, undefined) done() }) }) it('should stub requests with custom axios instance', function (done) { moxios.uninstall() const instance = axios.create({ baseURL: 'https://api.example.com' }) moxios.install(instance) moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) instance.get('/users/12346').then(onFulfilled) moxios.wait(function () { let response = onFulfilled.getCall(0).args[0] equal(response.status, 200) equal(response.data, USER_FRED) done() }) }) it('should remove stubs when uninstalling', function () { moxios.stubRequest('/users/12345', { status: 200, response: USER_FRED }) equal(moxios.stubs.count(), 1); moxios.uninstall(); equal(moxios.stubs.count(), 0); moxios.stubRequest('/users/12346', { status: 200, response: USER_FRED }) equal(moxios.stubs.count(), 1); }) it('should replace existing stub when stubbing same url and method', function () { moxios.stubRequest('/users/12346', { status: 200, response: USER_FRED }) moxios.stubRequest('/users/12346', { status: 500 }) let status; return axios.get('/users/12346') .then(response => status = response.status) .catch(error => status = error.response.status) .then(_ => equal(status, 500)) }) it('should not replace existing stubb for different url', function () { moxios.stubRequest('/users/12346', { status: 200, response: USER_FRED }) moxios.stubRequest('/users/12345', { status: 500 }) let status; return axios.get('/users/12346') .then(response => status = response.status) .catch(error => status = error.response.status) .then(_ => equal(status, 200)) }) it('should not replace existing stubb for different method', function () { moxios.stubOnce('GET', '/users/12346', { status: 200, response: USER_FRED }) moxios.stubOnce('POST', '/users/12346', { status: 500 }) let status; return axios.get('/users/12346') .then(response => status = response.status) .catch(error => status = error.response.status) .then(_ => equal(status, 200)) }) }) describe('wait', function() { let timeSpy beforeEach(function() { timeSpy = sinon.spy(global, 'setTimeout'); }) afterEach(function() { global.setTimeout.restore(); }) it('should return promise', function () { return moxios.wait().then(() => { equal(timeSpy.calledWith(sinon.match.any, moxios.delay), true); }) }) it('should return promise that resolves after specified delay', function () { return moxios.wait(33).then(() => { equal(timeSpy.calledWith(sinon.match.any, 33), true); }) }) it('should call both callback and `then`-function', function () { let cbPromiseResolver = null; let thenPromiseResolver = null; const cbPromise = new Promise(resolve => cbPromiseResolver = resolve); const thenPromise = new Promise(resolve => thenPromiseResolver = resolve); moxios.wait(() => { cbPromiseResolver(); }).then(() => { thenPromiseResolver(); }) return Promise.all([cbPromise, thenPromise]); }) }) }) })
angular.module('communicators').factory('stompCommunicator', ['tokenGenerator', function(tokenGenerator) { var stompClient; var disconnectCallback; var connectFunc = function(address, receiveMessagesCallback, closeConnectionCallback) { var ws = new SockJS('http://' + address + '/stomp'); stompClient = Stomp.over(ws); stompClient.connect({}, function() { stompClient.subscribe('/topic/messages', function(messagesStompDto) { receiveMessagesCallback(JSON.parse(messagesStompDto.body)); }, function(errorMessage) { closeConnectionCallback(errorMessage); }); }); ws.onclose = closeConnectionCallback; disconnectCallback = closeConnectionCallback; }; var disconnectFunc = function() { stompClient.disconnect(); disconnectCallback(); }; var sendMessageFunc = function(message, successCallback, errorCallback) { var token = tokenGenerator.generate(32); var stompMessage = { messageId: token, message: message }; var confirmSubscription = stompClient.subscribe('/topic/receive-confirm/' + token, function() { successCallback(); confirmSubscription.unsubscribe(); confirmSubscription = undefined; }, function() { errorCallback(); confirmSubscription.unsubscribe(); confirmSubscription = undefined; }); stompClient.send('/app/send-text-message', {}, JSON.stringify(stompMessage)); setTimeout(function() { if (confirmSubscription) { errorCallback(); confirmSubscription.unsubscribe(); } }, 5000); }; return { connect: connectFunc, disconnect: disconnectFunc, sendMessage: sendMessageFunc } }] );
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { addNotification } from '../../Modules/Notifications'; class Alerts extends Component { constructor(props) { super(props); let error; } componentWillUpdate() { if (this.props.typenotification) { this.props.addNotification({ type: this.props.typenotification, title: this.props.titlenotification || '', msg: this.error //'No está disponible el artículo seleccionado' }); if (this.props.redirect !== undefined) { this.props.history.replace(this.props.redirect); } } } render () { this.error = this.props.error; let status = (this.error.status !== undefined && this.error.status !== 200) ? '[' + this.error.status + ']' : ''; if (Object.keys(this.error).length !== 0 && this.error.constructor === Object) { this.error = status + ' ' + this.error.text; } else if (Object.keys(this.error).length !== 0 || this.error.constructor === Object) { return null; } if (this.props.typenotification && this.props.redirect) { return null; } return ( <div className="alert alert-danger" dangerouslySetInnerHTML={{__html: this.error}}> </div> ); } } // Mapea la acciones a despachar (Actions cretors) a props const mapDispatchToProps = { addNotification }; /** * Para poder navegar desde el código react-router-dom * ofrece un decorador withRouter() para envolver cualquier * componente en el árbol del router (al estilo connect() de Redux), * es decir, cualquier componente que sea hijo de alguno de los que * se están pintando como parte de la ruta. * Va a inyectar como prop un objeto router con métodos al componente que está envolviendo. */ export default withRouter(connect(null, mapDispatchToProps)(Alerts));
import TableModel from 'app/core/table_model'; import moment from 'moment'; export class BosunDatasource { constructor(instanceSettings, $q, backendSrv, templateSrv) { this.annotateUrl = instanceSettings.jsonData.annotateUrl; this.type = instanceSettings.type; this.url = instanceSettings.url; this.name = instanceSettings.name; this.showHelper = instanceSettings.jsonData.enableQueryHelper; this.q = $q; this.backendSrv = backendSrv; this.templateSrv = templateSrv; } makeTable(result) { var table = new TableModel(); if (!result || Object.keys(result).length < 1) { return [table]; } var tagKeys = []; _.each(result[0].Group, function (v, tagKey) { tagKeys.push(tagKey); }); tagKeys.sort(); table.columns = _.map(tagKeys, function (tagKey) { return { "text": tagKey }; }); table.columns.push({ "text": "value" }); _.each(result, function (res) { var row = []; _.each(res.Group, function (tagValue, tagKey) { row[tagKeys.indexOf(tagKey)] = tagValue; }); row.push(res.Value); table.rows.push(row); }); return [table]; } transformMetricData(result, target, options) { var tagData = []; _.each(result.Group, function (v, k) { tagData.push({ 'value': v, 'key': k }); }); var sortedTags = _.sortBy(tagData, 'key'); var metricLabel = ""; if (target.alias) { var scopedVars = _.clone(options.scopedVars || {}); _.each(sortedTags, function (value) { scopedVars['tag_' + value.key] = { "value": value.value }; }); metricLabel = this.templateSrv.replace(target.alias, scopedVars); } else { tagData = []; _.each(sortedTags, function (tag) { tagData.push(tag.key + '=' + tag.value); }); metricLabel = '{' + tagData.join(', ') + '}'; } var dps = []; _.each(result.Value, function (v, k) { dps.push([v, parseInt(k) * 1000]); }); return { target: metricLabel, datapoints: dps }; } performTimeSeriesQuery(query, target, options) { var exprDate = options.range.to.utc().format('YYYY-MM-DD'); var exprTime = options.range.to.utc().format('HH:mm:ss'); var url = this.url + '/api/expr?date=' + encodeURIComponent(exprDate) + '&time=' + encodeURIComponent(exprTime); return this.backendSrv.datasourceRequest({ url: url, method: 'POST', data: query, datasource: this }).then(response => { if (response.status === 200) { var result; if (response.data.Type === 'series') { result = _.map(response.data.Results, function (result) { return response.config.datasource.transformMetricData(result, target, options); }); } if (response.data.Type === 'number') { result = response.config.datasource.makeTable(response.data.Results); } return { data: result }; } }); } _metricsStartWith(metricRoot) { return this.backendSrv.datasourceRequest({ url: this.url + "/api/metric", method: 'GET', datasource: this }).then((data) => { var filtered = _.filter(data.data, (v) => { return v.startsWith(metricRoot); }); return filtered; }); } _tagKeysForMetric(metric) { return this.backendSrv.datasourceRequest({ url: this.url + "/api/tagk/" + metric, method: 'GET', datasource: this }).then((data) => { return data.data; }); } _tagValuesForMetricAndTagKey(metric, key) { return this.backendSrv.datasourceRequest({ url: this.url + "/api/tagv/" + key + "/" + metric, method: 'GET', datasource: this }).then((data) => { return data.data; }); } _metricMetadata(metric) { return this.backendSrv.datasourceRequest({ url: this.url + "/api/metadata/metrics?metric=" + metric, method: 'GET', datasource: this }).then((data) => { return data.data; }); } metricFindQuery(query) { var findTransform = function (result) { return _.map(result, function (value) { return { text: value }; }); }; // Get Metrics that start with the first argument var metricsRegex = /metrics\((.*)\)/; // Get tag keys for the given metric (first argument) var tagKeysRegex = /tagkeys\((.*)\)/; // Get tag values for the given metric (first argument) and tag key (second argument) var tagValuesRegex = /tagvalues\((.*),(.*)\)/; var metricsQuery = query.match(metricsRegex) if (metricsQuery) { return this._metricsStartWith(metricsQuery[1]).then(findTransform); } var tagKeysQuery = query.match(tagKeysRegex) if (tagKeysQuery) { return this._tagKeysForMetric(tagKeysQuery[1]).then(findTransform); } var tagValuesQuery = query.match(tagValuesRegex) if (tagValuesQuery) { return this._tagValuesForMetricAndTagKey(tagValuesQuery[1].trim(), tagValuesQuery[2].trim()).then(findTransform); } return this.q.when([]); } query(options) { var queries = []; // Get time values to replace $start // The end time is what bosun regards as 'now' var secondsAgo = options.range.to.diff(options.range.from.utc(), 'seconds'); secondsAgo += 's'; _.each(options.targets, _.bind(function (target) { if (!target.expr || target.hide) { return; } var query = {}; query = this.templateSrv.replace(target.expr, options.scopedVars, 'pipe'); query = query.replace(/\$start/g, secondsAgo); query = query.replace(/\$ds/g, options.interval); queries.push(query); }, this)); // No valid targets, return the empty result to save a round trip. if (_.isEmpty(queries)) { var d = this.q.defer(); d.resolve({ data: [] }); return d.promise; } var allQueryPromise = _.map(queries, _.bind(function (query, index) { return this.performTimeSeriesQuery(query, options.targets[index], options); }, this)); return this.q.all(allQueryPromise) .then(function (allResponse) { var result = []; _.each(allResponse, function (response) { _.each(response.data, function (d) { result.push(d); }); }); return { data: result }; }); } _processAnnotationQueryParam(annotation, fieldName, fieldObject, params) { var param = {}; var key = fieldName; if (!fieldObject) { return params; } if (fieldObject.empty) { key += ":Empty" } if (fieldObject.not) { if (!fieldObject.empty) { key += ":" } key += ":Empty" } params[key] = fieldObject.value; return params } annotationQuery(options) { var annotation = options.annotation; var params = {}; params.StartDate = options.range.from.unix(); params.EndDate = options.range.to.unix(); params = this._processAnnotationQueryParam(annotation, "Source", annotation.Source, params) params = this._processAnnotationQueryParam(annotation, "Host", annotation.Host, params) params = this._processAnnotationQueryParam(annotation, "CreationUser", annotation.CreationUser, params) params = this._processAnnotationQueryParam(annotation, "Owner", annotation.Owner, params) params = this._processAnnotationQueryParam(annotation, "Category", annotation.Category, params) params = this._processAnnotationQueryParam(annotation, "Url", annotation.Url, params) var url = this.url + '/api/annotation/query?'; if (Object.keys(params).length > 0) { url += jQuery.param(params); } var rawUrl = this.rawUrl; return this.backendSrv.datasourceRequest({ url: url, method: 'GET', datasource: this }).then(response => { if (response.status === 200) { var events = []; _.each(response.data, (a) => { var text = []; if (a.Source) { text.push("Source: " + a.Source); } if (a.Host) { text.push("Host: " + a.Host); } if (a.CreationUser) { text.push("User: " + a.CreationUser); } if (a.Owner) { text.push("Host: " + a.Owner); } if (a.Url) { text.push('<a href="' + a.Url + '">' + a.Url.substring(0, 50) + '</a>'); } if (a.Message) { text.push(a.Message); } var grafanaAnnotation = { annotation: annotation, time: moment(a.StartDate).utc().unix() * 1000, title: a.Category, text: text.join("<br>") } events.push(grafanaAnnotation); }); return events; } }); } // Required // Used for testing datasource in datasource configuration pange testDatasource() { return this.backendSrv.datasourceRequest({ url: this.url + '/', method: 'GET' }).then(response => { if (response.status === 200) { return { status: "success", message: "Data source is working", title: "Success" }; } }); } }
(function(global, $, routie, app, controller) { /** * Inform the user about errors during processing. * * @param {string} msg Message to write. */ var alert = function(msg) { var form = $('.mainbar form:first'); var container = form.find('.message-list'); if (container.length === 0) { container = $('<div/>').addClass('message-list'); form.prepend(container); } container.message('alert', msg); }; /** * Custom panel field. * * @type {Object} */ var field = { /** * Field type. * * @type {string} */ type: 'Comments', /** * Version of the field plugin. * * @type {string} */ version: '2.x-1.0-beta', /** * Initialize field plugin. * * @return {self} */ init: function() { this.routes(); return this; }, /** * Initialize field routes. * * @return {object} */ routes: function() { // Register custom field routes this.routes = { '/pages/show/*/c:*/action:*/*?': $.proxy(this.handleRoute, this), }; global.routes = $.extend(this.routes, global.routes || {}); // Flush and reload application routes setTimeout(function() { routie.removeAll(); routie(global.routes); }, 250); }, /** * Retrieve the hash value for a page object. * * @param {string} page Page uri. * @return {string} */ getHash: function(page) { var deferred = $.Deferred(); var notFound = function() { alert('Page not found'); deferred.reject(); }; $.get('/api/pages/hash/' + page).fail(notFound).done(function(response) { var hash = response.data && response.data.hash ? response.data.hash : false; if (hash) { deferred.resolve(hash); } else { notFound(); } }); return deferred; }, /** * Route callback. * * @param {string} uri * @param {integer} id * @param {string} action */ handleRoute: function(uri, id, action) { this.getHash(uri).then(function(hash) { switch(action) { case 'edit': controller.edit(hash, parseInt(id)); break; default: app.modal.alert('Unknown action to perform'); break; } }); } }; return field.init(); })(window, window.jQuery, window.routie, window.app, window.CommentsController);
function jsonFlickrFeed(item) { console.log(item); }
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/voteroid' } };
import React from 'react'; import Assessments from '../Assessments/Assessments'; import AssessmentsList from '../AssessmentsList/AssessmentsList'; import Controls from '../Controls/Controls'; import Header from '../Header/Header'; import LandingPage from '../LandingPage/LandingPage'; import Login from '../Login/Login'; import PersonalityTypes from '../PersonalityTypes/PersonalityTypes'; import Profile from '../Profile/Profile'; import Signup from '../Signup/Signup'; import Results from '../Results/Results'; import './App.css'; import { Switch, Route } from 'react-router'; const App = () => { return( <div className='app-container'> <Switch> <Route exact path='/' component={LandingPage} /> <Route path='/' component={Header} /> </Switch> <Route exact path='/login' component={Login} /> <Route exact path='/signup' component={Signup} /> <Route exact path='/controls' component={Controls} /> <Route exact path='/profile' component={Profile} /> <Route exact path='/personality-types' component={PersonalityTypes} /> <Route exact path='/assessments' component={AssessmentsList} /> <Route exact path='/assessments/core' render={() => <Assessments testType={"core"} />} /> <Route exact path='/assessments/career' render={() => <Assessments testType={"career-deck"} />} /> <Route exact path='/assessments/intro-extro' render={() => <Assessments testType={"introvert-extrovert"} />} /> <Route exact path='/assessments/heroes' render={() => <Assessments testType={"super-hero"} />} /> <Route exact path='/assessments/movies' render={() => <Assessments testType={"movies"} />} /> <Route exact path='/assessments/persuasion' render={() => <Assessments testType={"persuasion"} />} /> <Route exact path='/results' component={Results} /> </div> ) } export default App;
define(function() { var pastTime = new Date(); var slowTime = null; var pastY = 0; var speedLimit = 1; var waitForSlow = 500; var slowClassToAdd = "slow-scroll"; var fastClassToAdd = "fast-scroll"; var body = document.body; var slow = false var switchToSlow = false; var autoShowElements = []; function scroll(e) { var presentTime = new Date(); var presentY = document.documentElement.scrollTop; var deltaY = presentY - pastY; var deltaTime = presentTime.getTime() - pastTime.getTime(); var speed = deltaY / deltaTime; var currentClasses = document.body.getAttribute("class"); if (!currentClasses) { currentClasses = ""; } if (speed < 0 && slow || presentY < 50) { if (currentClasses.indexOf(fastClassToAdd) == -1) { currentClasses = currentClasses.replace(slowClassToAdd, "").replace(/\s\s/g, ""); currentClasses = currentClasses.replace(/(^\s+|\s+$)/, ""); document.body.setAttribute('class', currentClasses); } slow = false; slowTime = null; } else if (speed >= 0 && !slow) { if (!slowTime) { slowTime = new Date(); } if (!switchToSlow && presentTime.getTime() - slowTime.getTime() > waitForSlow) { switchToSlow = true; } } if (switchToSlow) { switchToSlow = false; slow = true; currentClasses = currentClasses.replace(fastClassToAdd, "").replace(/\s\s/g, ""); currentClasses += " " + slowClassToAdd; currentClasses = currentClasses.replace(/(^\s+|\s+$)/, ""); document.body.setAttribute('class', currentClasses); } pastTime = presentTime; pastY = presentY; } function init(options) { options = options || {}; speedLimit = options.speedLimit || speedLimit; slowClassToAdd = options.slowClassToAdd || slowClassToAdd; fastClassToAdd = options.fastClassToAdd || fastClassToAdd; waitForSlow = options.waitForSlow || waitForSlow; autoShowElements = options.autoShowElements || autoShowElements; for(var i = 0, ii = autoShowElements.length; i < ii; i++){ var element = autoShowElements[i]; element.addEventListener('mouseenter', function() { var currentClasses = document.body.getAttribute("class"); if (!currentClasses) { currentClasses = ""; } currentClasses = currentClasses.replace(slowClassToAdd, "").replace(/\s\s/g, ""); currentClasses = currentClasses.replace(/(^\s+|\s+$)/, ""); document.body.setAttribute('class', currentClasses); slow = false; slowTime = null; }, false); } window.addEventListener("scroll", scroll, false); } return { init: init }; });
/** * @author Robert */ var bsa; var toggleDetailedView = false; var birdImgPosition = 1; var number; function grabID(e) { number = 1; var birdSelector = e.getAttribute("data-id"); birdInformation.some(function(entry, i) { if (entry.birdSerialnumber == birdSelector) { bsa = i; return true; } }); /** BIRD GALLERY **/ var bip = birdInformation[bsa].birdImgPath; var bip1 = birdInformation[bsa].birdImgPath1; var bip2 = birdInformation[bsa].birdImgPath2; var bip3 = birdInformation[bsa].birdImgPath3; var bip4 = birdInformation[bsa].birdImgPath4; var bip5 = birdInformation[bsa].birdImgPath5; var bip6 = birdInformation[bsa].birdImgPath6; if (bip1 != 0) { $('<img />').attr('src', pathImg + bip1).appendTo('body').css('display','none'); number++; if (bip2 != 0) { $('<img />').attr('src', pathImg + bip2).appendTo('body').css('display','none'); number++; if (bip3 != 0) { $('<img />').attr('src', pathImg + bip3).appendTo('body').css('display','none'); number++; if (bip4 != 0) { $('<img />').attr('src', pathImg + bip4).appendTo('body').css('display','none'); number++; if (bip5 != 0) { $('<img />').attr('src', pathImg + bip5).appendTo('body').css('display','none'); number++; if (bip6 != 0) { $('<img />').attr('src', pathImg + bip6).appendTo('body').css('display','none'); number++; } } } } } } setTimeout(copyRighter, 1); } // Mobile Hover var clicker = false; $('#detailedShower').on('click', '#nImage', function() { if (isTouchDevice == true) { if(clicker == true) { nextImg(); clicker = false; return; } clicker = true; } else { nextImg(); } }); $('#detailedShower').on('click', '#pImage', function() { if (isTouchDevice == true) { if(clicker == true) { prevImg(); clicker = false; return; } clicker = true; } else { prevImg(); } }); // Mobile Hover $('#detailedShower').on('click', '#bullet1', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 1; copyRighter(); $("#bullet2, #bullet3, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet1").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet2', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath1).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 2; copyRighter(); $("#bullet1, #bullet3, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet2").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet3', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath2).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 3; copyRighter(); $("#bullet1, #bullet2, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet3").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet4', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath3).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 4; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet4").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet5', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath4).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 5; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet5").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet6', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath5).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 6; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet5, #bullet7").css("background-size", "20%"); $("#bullet6").css("background-size", "50%"); }); $('#detailedShower').on('click', '#bullet7', function() { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath6).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 7; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet5, #bullet6").css("background-size", "20%"); $("#bullet7").css("background-size", "50%"); }); function nextImg() { if (birdImgPosition == 1 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath1).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 2; copyRighter(); $("#bullet1, #bullet3, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet2").css("background-size", "50%"); } else if (birdImgPosition == 2 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath2).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 3; copyRighter(); $("#bullet1, #bullet2, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet3").css("background-size", "50%"); } else if (birdImgPosition == 3 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath3).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 4; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet4").css("background-size", "50%"); } else if (birdImgPosition == 4 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath4).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 5; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet5").css("background-size", "50%"); } else if (birdImgPosition == 5 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath5).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 6; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet5, #bullet7").css("background-size", "20%"); $("#bullet6").css("background-size", "50%"); } else if (birdImgPosition == 6 && birdImgPosition < number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath6).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 7; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet5, #bullet6").css("background-size", "20%"); $("#bullet7").css("background-size", "50%"); } }; function prevImg() { if (birdImgPosition == 2 && birdImgPosition <= number) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 1; copyRighter(); $("#bullet2, #bullet3, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet1").css("background-size", "50%"); } else if (birdImgPosition == 3) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath1).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 2; copyRighter(); $("#bullet1, #bullet3, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet2").css("background-size", "50%"); } else if (birdImgPosition == 4) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath2).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 3; copyRighter(); $("#bullet1, #bullet2, #bullet4, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet3").css("background-size", "50%"); } else if (birdImgPosition == 5) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath3).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 4; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet5, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet4").css("background-size", "50%"); } else if (birdImgPosition == 6) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath4).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 5; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet6, #bullet7").css("background-size", "20%"); $("#bullet5").css("background-size", "50%"); } else if (birdImgPosition == 7) { $('#img1').fadeOut(300, function() { $(this).attr('src', pathImg + birdInformation[bsa].birdImgPath5).bind('onreadystatechange load', function() { if (this.complete) $(this).fadeIn(300); }); }); birdImgPosition = 6; copyRighter(); $("#bullet1, #bullet2, #bullet3, #bullet4, #bullet5, #bullet7").css("background-size", "20%"); $("#bullet6").css("background-size", "50%"); } }; function copyRighter() { copyName = birdImgPosition -1; document.getElementById("copyRightPicContainer").innerHTML = birdInformation[bsa].birdCopyRight[copyName]; setTimeout(testa, 320); } function testa() { var width = $('#img1').width(); var imgPos = $('#img1').position().left; width -= 30; imgPos += 4; $('#copyRightPicCenter').css({ 'width': width, 'left' : imgPos }); } /** BIRD GALLERY **/ var tempScrollTop; var templateDetailedPage = $.trim($('#templateDetailedPage').html()); $('#birdFrame').on('click', '.birdBox', function() { tempScrollTop = $(document).scrollTop(); $('#detailedShower').show(); $('.siteWrapper').addClass('noScroller'); $("#detailedShower").css("z-index", "50"); if (lang == true) { var tempdet = templateDetailedPage.replace(/{{birdImgPath}}/ig,pathImg + birdInformation[bsa].birdImgPath).replace(/{{birdTitel}}/ig, birdInformation[bsa].birdTitelViet).replace(/{{audioPath}}/ig, "audio/" + birdInformation[bsa].birdSerialnumber + ".mp3").replace(/{{Description}}/ig, "Mô tả").replace(/{{DescriptionText}}/ig, birdInformation[bsa].birdDescriptionViet).replace(/{{Habitat}}/ig, "Sinh cảnh sống").replace(/{{HabitatText}}/ig, birdInformation[bsa].birdHabitatViet).replace(/{{Observation}}/ig, "Quan sát").replace(/{{ObservationText}}/ig, birdInformation[bsa].birdObservationViet).replace(/{{Conversation}}/ig, "Tình trạng").replace(/{{ConversationText}}/ig, birdInformation[bsa].birdConversationViet); } else { var tempdet = templateDetailedPage.replace(/{{birdImgPath}}/ig,pathImg + birdInformation[bsa].birdImgPath).replace(/{{birdTitel}}/ig, birdInformation[bsa].birdTitel).replace(/{{audioPath}}/ig, "audio/" + birdInformation[bsa].birdSerialnumber + ".mp3").replace(/{{Description}}/ig, "Description").replace(/{{DescriptionText}}/ig, birdInformation[bsa].birdDescription).replace(/{{Habitat}}/ig, "Habitat").replace(/{{HabitatText}}/ig, birdInformation[bsa].birdHabitat).replace(/{{Observation}}/ig, "Observation").replace(/{{ObservationText}}/ig, birdInformation[bsa].birdObservation).replace(/{{Conversation}}/ig, "Conservation").replace(/{{ConversationText}}/ig, birdInformation[bsa].birdConversation); } $('#detailedShower').html(tempdet); $("#mainSiteWrap").animate({ opacity : 0.3 }, 250); setTimeout(detailedAnimate, 1); var k = 1; $(document).ready(function() { for (var i = number; i > 0; i--) { var bulletADD = ""; bulletADD += '<a href="#"><div id="bullet' + k + '"></div></a>'; $('#bulletContainer').append(bulletADD); k++; }; }); }); function detailedAnimate() { $(".birdDetailedTextWindow").toggleClass("birdDetailedTextWindow-change"); $(".detailLine").toggleClass("detailLine-change"); toggleDetailedView = true; } // close Details // $('#detailedShower').on('click', '#backDetailed, #backDetailed2', function() { if (toggleDetailedView == true) { $('.clickPlateDetail').hide(); $("#mainSiteWrap").animate({ opacity : 1 }, 50); birdImgPosition = 1; setTimeout(detailedAnimateDelay, 10); } clicker = false; }); $('#detailedShower').click(function(e) { if (e.target == this) { if (toggleDetailedView == true) { $("#mainSiteWrap").animate({ opacity : 1 }, 50); birdImgPosition = 1; setTimeout(detailedAnimateDelay, 10); } } }); $('#detailedShower').on('click', '#birdImgContainer, #textContainer', function(e) { if (e.target == this) { if (toggleDetailedView == true) { $('.clickPlateDetail').hide(); $("#mainSiteWrap").animate({ opacity : 1 }, 50); birdImgPosition = 1; setTimeout(detailedAnimateDelay, 10); } } }); function detailedAnimateDelay() { $("#detailedShower").css("z-index", "0"); $('.siteWrapper').removeClass('noScroller'); $('#detailedShower').empty(); $('#detailedShower').hide(); $(document).scrollTop(tempScrollTop); toggleDetailedView = false; } // Detailed Page //
"use strict"; import {scale} from './Config'; import Renderer from './Renderer'; export default class Canvas2DRenderer extends Renderer { constructor(canvas) { super(); this.ctx = canvas.getContext('2d'); this._rot = 10.0; this._next_rot = 1.0; this._zoom = 10.0; this._next_zoom = 1.0; this._center = [-320.0, -320.0]; this._next_center = [0.0, 0.0]; } _setDrawStyle(styles) { Object.keys(styles).forEach((sn) => { this.ctx[sn] = styles[sn]; }); } get Zoom() { return this._zoom; } set Zoom(z) { this._next_zoom = z; } get Rotation() { return this._rot; } set Rotation(z) { this._next_rot = z; } set Center(c) { this._next_center = c; } get Center() { return this._center; } beginUpdate(x,y) { let xx = (x)*scale+this._center[0]; let yy = (y)*scale+this._center[1]; this._updating = [xx,yy]; // Reset transform this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Translate to top left of square this.ctx.translate(xx, yy); // this.ctx.scale(this._zoom, this._zoom); // Wipe out rect where we are going to draw // Using alpha 0.5 will give a "blur" effect on all objects this.ctx.beginPath(); this.ctx.fillStyle='rgba(0, 0, 0, 0.5)'; this.ctx.rect(0, 0, scale, scale); this.ctx.fill(); this.ctx.translate(-xx, -yy); // this.ctx.scale(-this._zoom, -this._zoom); } endUpdate() { // Reset transform this.ctx.translate(-this._updating[0], -this._updating[1]); this._updating = false; } beginFrame() { // Reset transform this.ctx.setTransform(1, 0, 0, 1, 0, 0); // let cx = this._center[0]; // let cy = this._center[1]; // this.ctx.translate(cx, cy); // this.ctx.scale(this._zoom, this._zoom); // Step zoom, center and rot this._zoom = (this._next_zoom + this._zoom*3) / 4.0; this._center[0] = (this._next_center[0] + this._center[0]*7) / 8.0; this._center[1] = (this._next_center[1] + this._center[1]*7) / 8.0; this._rot = (this._next_rot + this._rot*3) / 4.0; } endFrame() { } // a GameObject has attr.primitives renderGameObject(go) { if(!this.updating) { console.warn("beginUpdate not called!"); } let xx = (go.x*scale)+this._center[0]; let yy = (go.y*scale)+this._center[1]; //console.log('draw %d', go.id, go.pos); go.attr.styles = go.attr.styles || {}; this.ctx.translate(xx, yy); go.attr.primitives.forEach((prim) => { prim.styles = prim.styles || {}; let strokeWidth = parseInt(go.attr.styles.strokeWidth || prim.styles.strokeWidth, 10); // Center offset to top left of primitive let co = prim.center ? (prim.size ? (scale / 2) - (prim.size / 2) : scale / 2) : 0; let xoffs = co; let yoffs = co; this.ctx.translate(co, co); this.ctx.rotate(go.rot || 0); this.ctx.beginPath(); switch(prim.type) { case 'triangle': let p = prim.points; this.ctx.moveTo(p[0][0], p[0][1]); this.ctx.lineTo(p[1][0], p[1][1]); this.ctx.lineTo(p[2][0], p[2][1]); this.ctx.moveTo(p[0][0], p[0][1]); break; case 'sphere': // treated as a circle in 2d this.ctx.arc(0, 0, prim.radius-2, prim.start_angle || 0, prim.end_angle || (Math.PI * 2) ); break; case 'box': // rectangle in 2d this.ctx.rect(0, 0, Math.floor(prim.size-1), Math.floor(prim.size-1) ); break; default: throw new Error('Unknown primitive ' + prim.type); } this._setDrawStyle(go.attr.styles||{}); this._setDrawStyle(prim.styles||{}); if(go.attr.styles.fillStyle) { this.ctx.fill(); } if(go.attr.styles.strokeStyle) { this.ctx.stroke(); } this.ctx.rotate(-(go.rot || 0)); this.ctx.translate(-co, -co); }); this.ctx.translate(-xx, -yy); // this.ctx.beginPath(); // if(go.hasAttr("radius")) { // var r = go.attr.radius; // this.ctx.arc(xx * scale + scale / 2, yy * scale + scale / 2, r-1, 0, 2 * Math.PI); // } else if(go.hasAttr("size")) { // this.ctx.rect(Math.floor(xx * scale + (scale / 2) - (go.attr.size / 2)), // Math.floor(yy * scale + (scale / 2) - (go.attr.size / 2)), // Math.floor(go.attr.size-1), // Math.floor(go.attr.size-1)); // } } }
import './helpers/helpers.js'; import './app-drawer/app-drawer.js'; import './app-drawer-layout/app-drawer-layout.js'; import './app-grid/app-grid-style.js'; import './app-header/app-header.js'; import './app-header-layout/app-header-layout.js'; import './app-toolbar/app-toolbar.js'; import './app-box/app-box.js'; /** @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /* FIXME(polymer-modulizer): the above comments were extracted from HTML and may be out of place here. Review them and then delete this comment! */ ;
import moment from 'moment'; const CacheTTL = moment.duration(5, 'minutes'); function getTimestamp() { return moment.utc(); } function hasExpired(timestamp, ttl = CacheTTL) { return getTimestamp().subtract(ttl) > timestamp; } export default { getTimestamp, hasExpired, };
angular.module('classMarker').directive('classMarker', ['$window', function($window) { classGrammar = $window.classGrammar return { restrict: 'E', template: '<input ng-class="{invalid : isInvalid}" ng-model="classText"></input>', link: function($scope, el, attrs) { console.log(classGrammar) $scope.classText = ""; $scope.isInvalid = false; $scope.$watch('classText', function(){ try { classGrammar.parse($scope.classText); $scope.isInvalid = false; }catch(err){ $scope.isInvalid = true; } }); } } }]);
var DelayNode = BaseNode.extend({ init: function(index, config){ this._super(index, config); this.shortName = "deln"; this.thingy = context.createDelay(); this.name = "Delay"; this.icon = "icon-pause"; this.tooltip = "Delays the incoming audio signal by a certain amount"; var el = this.createMainEl(true, true, true, 78); var delayN = this.thingy; var thisNode = this; if(!config) { this.c = { d: 0.8 }; } var setDelayFnc = function(el, v) { thisNode.c.d = v.value; delayN.delayTime.value = v.value; delayLabel.html('Delay ' + v.value + ' s'); }; var delayRange = $('<div>'); var delayLabel = $('<a href="#" rel="tooltip" title="Delay time in seconds">').tooltip(); delayRange.slider({ min: 0, max: 0.99, step: 0.01, value: this.c.d, slide: setDelayFnc }); el.append(delayLabel); el.append(delayRange); setDelayFnc(null, {value:this.c.d}); } });
const devpunx = require('./index') // dataStoreObject let store = devpunx.dataStoreObject store.user = {name: "Jon", age:23} console.log('Store: ', store) // Helpers let utils = devpunx.helpers // todayReadable utils.todayReadable console.log('Today readable: ', utils.todayReadable) // now (readable) utils.now.seperator = " -- " utils.now console.log('Today: ', utils.now.get)
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function(require) { 'use strict'; require('../coord/polar/polarCreator'); require('./angleAxis'); require('./radiusAxis'); // Polar view require('../echarts').extendComponentView({ type: 'polar' }); });
function addSearchResponseToPage(responseText){ $('#searchMovie-results').html(responseText); } function searchForMovieByInputString(inputString) { $.ajax({ url: "/movies", data: {q : inputString}, success: addSearchResponseToPage }); } function extractMovieName(){ var searchMovieInput = $('#searchMovie-input').val(); searchForMovieByInputString(searchMovieInput); console.log(searchMovieInput); } function initApp() { $('#searchMovie-btn').on('click', extractMovieName); }
"use strict"; // Use applicaion configuration module to register a new module ApplicationConfiguration.registerModule('carzen-devs');
import { RiotMapsMixin, GoogleMapMixin, MarkerMixin, SearchBoxMixin, DirectionsRendererMixin, InfoWindowMixin, StateMixin } from './mixins'; riot.mixin('RiotMapsMixin', new RiotMapsMixin()); riot.mixin('GoogleMapMixin', new GoogleMapMixin()); riot.mixin('MarkerMixin', new MarkerMixin()); riot.mixin('SearchBoxMixin', new SearchBoxMixin()); riot.mixin('DirectionsRendererMixin', new DirectionsRendererMixin()); riot.mixin('InfoWindowMixin', new InfoWindowMixin()); riot.mixin('StateMixin', new StateMixin()); export { default as GoogleMapTag } from './tags/GoogleMap.tag'; export { default as MarkerTag } from './tags/Marker.tag'; export { default as SearchBoxTag } from './tags/SearchBox.tag'; export { default as InfoWindowTag } from './tags/InfoWindow.tag'; if(!window.google && !!window.console) { console.warn('could not find google maps.'); }
import openDevToolsWindow from './openWindow'; export function createMenu() { const menus = [ { id: 'devtools-left', title: 'To left' }, { id: 'devtools-right', title: 'To right' }, { id: 'devtools-bottom', title: 'To bottom' }, { id: 'devtools-panel', title: 'Open in a panel (enable in browser settings)' }, { id: 'devtools-remote', title: 'Open Remote DevTools' } ]; let shortcuts = {}; chrome.commands.getAll(commands => { commands.forEach(({ name, shortcut }) => { shortcuts[name] = shortcut; }); menus.forEach(({ id, title }) => { chrome.contextMenus.create({ id: id, title: title + (shortcuts[id] ? ' (' + shortcuts[id] + ')' : ''), contexts: ['all'] }); }); }); } export function removeMenu() { chrome.contextMenus.removeAll(); } chrome.contextMenus.onClicked.addListener(({ menuItemId }) => { openDevToolsWindow(menuItemId); });
var postcss = require('postcss'); module.exports = postcss.plugin('postcss-generate-preset', generatePreset); function generatePreset(opts) { opts = opts || {}; return function(css) { css.walkAtRules(function (atRule) { if (atRule.name !== 'generate-preset') { return; } /** * Parse: `.u-mf margin font-size 5px 10px 15px` * Return: `['.u-mf', 'margin font-size', '5px 10px 15px']` */ var matches = /(^\.[a-z-_.]+)\s([a-z-\s]+)\s([a-z0-9\s\.]+)/ig.exec(atRule.params); if (!matches) { return; } var root = atRule.parent; var selector = matches[1]; var properties = postcss.list.space(matches[2]); var values = postcss.list.space(matches[3]); values.forEach(function(value) { var numeric = parseFloat(value, 10); // Reassign 0 with zeroValue if specified // Used for selectors like .u-mZ instead of .u-m0 if (numeric === 0 && opts.zeroValue) { numeric = opts.zeroValue; } // Can't have decimal values in the selector, // so replace dots with dashes if (isFloat(numeric)) { numeric = (numeric + '').replace('.', '-'); } var rule = postcss.rule({ selector: selector + numeric }); if (opts.useImportant) { value += ' !important'; } properties.forEach(function(prop) { rule.append(postcss.decl({ prop: prop, value: value })); }); root.insertBefore(atRule, rule); }); atRule.remove(); }); }; } function isFloat(n) { return n === +n && n !== (n | 0); }
quail.imgHasLongDesc = function (quail, test, Case) { test.get('$scope').find('img[longdesc]').each(function () { var _case = Case({ element: this }); test.add(_case); if ($(this).attr('longdesc') === $(this).attr('alt') || !quail.validURL($(this).attr('longdesc'))) { _case.set({ status: 'failed' }); } else { _case.set({ status: 'passed' }); } }); };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery.min.js //= require jquery_ujs //= require bootstrap.min.js //= require_tree .
function createThink(w, h) { var dir = 'right' return function(game) { if(dir === 'right') { dir = 'down'; return dir; } else { dir = 'right'; return dir; } } }
import React from 'react' import PropTypes from 'prop-types' import Link from 'gatsby-link' import styled from 'emotion/react' import cx from 'classnames' import { sansfont, selectorList, breakpoint1 } from '../layouts/emotion-base' import { workTagLink, capitalize } from '../util' const Container = styled.div` padding: 0; z-index: 1; @media (${breakpoint1}) { display: none; } ` const CategoryHeader = styled.div` composes: ${sansfont}; font-size: 16px; font-weight: 700; margin-top: 5px; ` const TagList = styled.ul` composes: ${selectorList}, ${sansfont}; display: block; font-size: 16px; font-weight: 100; & li { margin: 0; padding: 2px; } ` const TagSelector = ({ allTags , currentTag }) => ( <Container> <TagList> {allTags.map(tag => ( <li key={tag} className={cx({ active: tag === currentTag, })} > <Link to={workTagLink(tag)}>{capitalize(tag)}</Link> </li> ))} </TagList> </Container> ) TagSelector.propTypes = { allTags: PropTypes.array.isRequired, currentTag: PropTypes.string, } export default TagSelector
'use strict'; var gulp = require('gulp'); var config = require('../gulp.config')(); var libs = require('../gulp.libs'); var $ = require('gulp-load-plugins')(); var util = require('util'); var browserSync = require('browser-sync'); var paths = gulp.paths; var port = process.env.PORT || config.defaultPort; gulp.task('serve-dev', ['inject'], function() { libs.log('serve-dev'); var isDev = true; var nodeOptions = { script: config.nodeServer, delayTime: 1, env: { PORT: port, NODE_ENV: isDev ? 'dev' : 'build', }, watch: [config.server], }; return $.nodemon(nodeOptions) .on('restart', function(event) { libs.log('*** nodemon restarted'); libs.log('files changed:\n' + event); setTimeout(function() { }, config.browserReloadDelay); }) .on('start', function() { libs.log('*** nodemon started'); startBrowserSync(); }) .on('crash', function() { libs.log('*** nodemon crashed'); }) .on('exit', function() { libs.log('*** nodemon exited'); }); }); function startBrowserSync() { if (browserSync.active) { return; } libs.log('Starting browser-sync on port: ' + port); gulp.watch([config.less], ['styles']) .on('change', function(event) { libs.log('File ' + event.path + ' ' + event.type); }); var options = { proxy: 'localhost:' + port, port: 3000, files: [ config.client + '**/*.*', '!' + config.less, config.temp + '**/*.css', ], ghostMode: { clicks: true, location: false, forms: true, scroll: true, }, injectChanges: true, logFileChanges: true, /* logLevel: 'debug', */ logPrefix: 'gulp-patterns', notify: true, reloadDelay: 1000, open: false, }; browserSync(options); }
import React from 'react'; import { connect } from 'react-redux' import { StyleSheet, Text, View, ActivityIndicator, StatusBar, Button } from 'react-native'; import { authorizeUser, fetchDestination, clearError, makeSelection } from '../store/actions' import Logo from '../components/Logo' import ErrorMessage from '../components/ErrorMessage' import Footer from '../components/Footer' import Content from '../components/Content' class Home extends React.Component { render() { const { token, fetchDestination, isLoading, quote, destination, error, clearError, makeSelection, user } = this.props const { navigate } = this.props.navigation return ( <View style={styles.container}> <StatusBar barStyle="light-content" /> <View style={styles.contentContainer}> <Logo /> <ErrorMessage message={error} onClose={clearError} /> <ActivityIndicator animating={isLoading} style={styles.loadingIndicator} /> <Content onButtonPress={() => fetchDestination(token)} onResultPress={() => makeSelection(user, token, destination)} destination={destination} /> <Button onPress={() => navigate('Settings')} title="Settings" color="#fff" /> </View> <Footer quote={quote} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#05224B', alignItems: 'center', justifyContent: 'space-between', paddingTop: 15 }, contentContainer: { marginTop: 50, height: 500, flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start' }, loadingIndicator: { marginTop: 10, marginBottom: 10 } }); const mapStateToProps = (state) => { console.log(state) return { token: state.auth.token, isLoading: state.isLoading, user: state.user, quote: state.quote, destination: state.destination, error: state.error } } const mapDispatchToProps = (dispatch) => { return { fetchDestination: (token) => dispatch(fetchDestination(token)), clearError: () => dispatch(clearError()), makeSelection: (user, token, destination) => dispatch(makeSelection(user, token, destination)) } } export default connect( mapStateToProps, mapDispatchToProps )(Home);
'use strict'; angular.module('myApp.setting', []) .config([function() { }]).controller('SettingCtrl', ['dataService',function(dataService) { var model = this; model.userid=dataService.userId; model.updateDataService = function(id){ dataService.userId = model.userid; } }]);
var fs = require('fs'); var PANEL_FILE = 'panelTrim.csv'; var OUTCOME_FILE = 'outcome.txt'; var PANEL_LTINV_COL = 32; var PANEL_SYMBOL_COL = 3; var PANEL_QUARTER_COL = 0; var PANEL_AVG_COL = 6; var PANEL_TREAT_COL = 4; var PANEL_AT_COL = 38; var items = []; var records = []; var outcomes = []; var loadPanel = function() { console.log('Loading Panel'); fs.readFile(PANEL_FILE, 'utf-8', function(err, res) { res = res.split('\r\n'); items = res[0].split('\t'); // console.log(items); for(var i = 1; i < res.length; i++) { records.push(res[i].split('\t')); } calcOutput(); }); }; var calcOutput = function() { console.log('Calculating Output'); for(var i = 0; i < records.length; i++) { var treatRecord = records[i]; if(treatRecord[PANEL_QUARTER_COL] != '3') continue; var treatSymbol = treatRecord[PANEL_SYMBOL_COL]; // console.log(treatSymbol); var lastQuarter = -1; for(var j = 0; j < records.length; j++) { var matchRecord = records[j]; if(matchRecord[PANEL_SYMBOL_COL] != treatSymbol) continue; if(j == i) continue; var matchQuarter = parseInt(matchRecord[PANEL_QUARTER_COL]); if(matchQuarter > lastQuarter) { lastQuarter = matchQuarter; var treatLevel = parseFloat(treatRecord[PANEL_LTINV_COL]) / parseFloat(treatRecord[PANEL_AT_COL]); var matchLevel = parseFloat(matchRecord[PANEL_LTINV_COL]) / parseFloat(treatRecord[PANEL_AT_COL]); var curOutcome = treatLevel - matchLevel; if(isNaN(curOutcome)) { console.log('ERROR: ' + [treatRecord[PANEL_AT_COL], matchRecord[PANEL_AT_COL]].join('\t')); break; } outcomes[treatSymbol] = [treatSymbol, treatRecord[PANEL_AVG_COL], curOutcome, treatRecord[PANEL_TREAT_COL]]; } } } // console.log(outcomes); outStr = [['sym', 'avg', 'outcome', 'treat'].join('\t')]; for(var outcome in outcomes) { outStr.push(outcomes[outcome].join('\t')); } fs.writeFile(OUTCOME_FILE, outStr.join('\r\n'), function(err) { console.log('Data saved to ' + OUTCOME_FILE); }); }; loadPanel();
const Promise = require('bluebird'); const {expect} = require('chai'); const sinon = require('sinon'); const CMD = 'PBSZ'; describe(CMD, function () { let sandbox; const mockClient = { reply: () => Promise.resolve(), server: {} }; const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient); beforeEach(() => { sandbox = sinon.sandbox.create().usingPromise(Promise); sandbox.spy(mockClient, 'reply'); }); afterEach(() => { sandbox.restore(); }); it('// unsuccessful', () => { return cmdFn() .then(() => { expect(mockClient.reply.args[0][0]).to.equal(202); }); }); it('// successful', () => { mockClient.secure = true; mockClient.server._tls = {}; return cmdFn({command: {arg: '0'}}) .then(() => { expect(mockClient.reply.args[0][0]).to.equal(200); expect(mockClient.bufferSize).to.equal(0); }); }); it('// successful', () => { mockClient.secure = true; mockClient.server._tls = {}; return cmdFn({command: {arg: '10'}}) .then(() => { expect(mockClient.reply.args[0][0]).to.equal(200); expect(mockClient.bufferSize).to.equal(10); }); }); });
var Method = require('../Method'); module.exports = function(name, type) { var role = { className: null, classPK: 0, name: name, titleMap: JSON.stringify({ "en_US": name }), descriptionMap: JSON.stringify({ "en_US": "Generated by LWS." }), type: type, subtype: null }; var method = new Method('/role/add-role', role); return method.invoke(); };
(function() { QUnit.module('fabric.Shadow'); var REFERENCE_SHADOW_OBJECT = { 'color': 'rgb(0,255,0)', 'blur': 10, 'offsetX': 20, 'offsetY': 5 }; test('constructor', function() { ok(fabric.Shadow); var shadow = new fabric.Shadow(); ok(shadow instanceof fabric.Shadow, 'should inherit from fabric.Shadow'); }); test('initializing with object', function() { ok(fabric.Shadow); var shadow = new fabric.Shadow(REFERENCE_SHADOW_OBJECT); equal(shadow.color, 'rgb(0,255,0)'); equal(shadow.offsetX, 20); equal(shadow.offsetY, 5); equal(shadow.blur, 10); }); test('initializing with string', function() { ok(fabric.Shadow); // old text-shadow definition - color offsetX offsetY blur var shadow1 = new fabric.Shadow('rgba(0,0,255,0.5) 10px 20px 5px'); equal(shadow1.color, 'rgba(0,0,255,0.5)'); equal(shadow1.offsetX, 10); equal(shadow1.offsetY, 20); equal(shadow1.blur, 5); var shadow2 = new fabric.Shadow('rgb(0,0,255) 10px 20px '); equal(shadow2.color, 'rgb(0,0,255)'); equal(shadow2.offsetX, 10); equal(shadow2.offsetY, 20); equal(shadow2.blur, 0); var shadow3 = new fabric.Shadow('#00FF00 30 10 '); equal(shadow3.color, '#00FF00'); equal(shadow3.offsetX, 30); equal(shadow3.offsetY, 10); equal(shadow3.blur, 0); var shadow4 = new fabric.Shadow(' #FF0000 10px'); equal(shadow4.color, '#FF0000'); equal(shadow4.offsetX, 10); equal(shadow4.offsetY, 0); equal(shadow4.blur, 0); var shadow5 = new fabric.Shadow('#000000'); equal(shadow5.color, '#000000'); equal(shadow5.offsetX, 0); equal(shadow5.offsetY, 0); equal(shadow5.blur, 0); // new text-shadow definition - offsetX offsetY blur color var shadow6 = new fabric.Shadow('10px 20px 5px rgba(0,0,255,0.5)'); equal(shadow6.color, 'rgba(0,0,255,0.5)'); equal(shadow6.offsetX, 10); equal(shadow6.offsetY, 20); equal(shadow6.blur, 5); var shadow7 = new fabric.Shadow('10 20 5px #00FF00'); equal(shadow7.color, '#00FF00'); equal(shadow7.offsetX, 10); equal(shadow7.offsetY, 20); equal(shadow7.blur, 5); var shadow8 = new fabric.Shadow('10px 20px rgb(0,0,255)'); equal(shadow8.color, 'rgb(0,0,255)'); equal(shadow8.offsetX, 10); equal(shadow8.offsetY, 20); equal(shadow8.blur, 0); var shadow9 = new fabric.Shadow(' 10px #FF0000 '); equal(shadow9.color, '#FF0000'); equal(shadow9.offsetX, 10); equal(shadow9.offsetY, 0); equal(shadow9.blur, 0); var shadow10 = new fabric.Shadow(' #FF0000 '); equal(shadow10.color, '#FF0000'); equal(shadow10.offsetX, 0); equal(shadow10.offsetY, 0); equal(shadow10.blur, 0); var shadow11 = new fabric.Shadow(''); equal(shadow11.color, 'rgb(0,0,0)'); equal(shadow11.offsetX, 0); equal(shadow11.offsetY, 0); equal(shadow11.blur, 0); }); test('properties', function() { var shadow = new fabric.Shadow(); equal(shadow.blur, 0); equal(shadow.color, 'rgb(0,0,0)'); equal(shadow.offsetX, 0); equal(shadow.offsetY, 0); }); test('toString', function() { var shadow = new fabric.Shadow(); ok(typeof shadow.toString == 'function'); equal(shadow.toString(), '0px 0px 0px rgb(0,0,0)'); }); test('toObject', function() { var shadow = new fabric.Shadow(); ok(typeof shadow.toObject == 'function'); var object = shadow.toObject(); equal(JSON.stringify(object), '{"color":"rgb(0,0,0)","blur":0,"offsetX":0,"offsetY":0,"affectStroke":false}'); }); test('clone with affectStroke', function() { var shadow = new fabric.Shadow({affectStroke: true, blur: 5}); ok(typeof shadow.toObject == 'function'); var object = shadow.toObject(), shadow2 = new fabric.Shadow(object), object2 = shadow2.toObject(); equal(shadow.affectStroke, shadow2.affectStroke) deepEqual(object, object2); }); test('toObject without default value', function() { var shadow = new fabric.Shadow(); shadow.includeDefaultValues = false; equal(JSON.stringify(shadow.toObject()), '{}'); shadow.color = 'red'; equal(JSON.stringify(shadow.toObject()), '{"color":"red"}'); shadow.offsetX = 15; equal(JSON.stringify(shadow.toObject()), '{"color":"red","offsetX":15}'); }); test('toSVG', function() { // reset uid fabric.Object.__uid = 0; var shadow = new fabric.Shadow({color: '#FF0000', offsetX: 10, offsetY: -10, blur: 2}); var object = new fabric.Object({fill: '#FF0000'}); equal(shadow.toSVG(object), '<filter id="SVGID_0" y="-40%" height="180%" x="-40%" width="180%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="1"></feGaussianBlur>\n\t<feOffset dx="10" dy="-10" result="oBlur" ></feOffset>\n\t<feFlood flood-color="#FF0000"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n'); shadow.color = '#000000'; equal(shadow.toSVG(object), '<filter id="SVGID_0" y="-40%" height="180%" x="-40%" width="180%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="1"></feGaussianBlur>\n\t<feOffset dx="10" dy="-10" result="oBlur" ></feOffset>\n\t<feFlood flood-color="#000000"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n'); }); test('toSVG with rotated object', function() { // reset uid fabric.Object.__uid = 0; var shadow = new fabric.Shadow({color: '#FF0000', offsetX: 10, offsetY: 10, blur: 2}); var object = new fabric.Object({fill: '#FF0000', angle: 45}); equal(shadow.toSVG(object), '<filter id="SVGID_0" y="-40%" height="180%" x="-40%" width="180%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="1"></feGaussianBlur>\n\t<feOffset dx="14.14" dy="0" result="oBlur" ></feOffset>\n\t<feFlood flood-color="#FF0000"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n'); }); })();
const functions = require('firebase-functions') const axios = require('axios') const admin = require('firebase-admin') const db = admin.database() const stringSimilarity = require('string-similarity') const TOKEN = functions.config().api_ai.dev_token module.exports = (data, userId) => { const { result: { parameters: { task, person } }, sessionId } = data if (task && person) db.ref('users').once('value') .then(snapshot => { const keys = Object.keys(snapshot.val()) const userNames = keys.map(key => snapshot.val()[key].name) // array of user's name const similarityScore = userNames.map(name => stringSimilarity.compareTwoStrings(person, name)) const bestMatch = similarityScore.reduce((prev, next) => next > prev ? next : prev) if (bestMatch > 0.6) { const index = similarityScore.indexOf(bestMatch) // if userId exist and match with assignedTo (keys[index]) OR no userId provided if ((userId && (userId == keys[index])) || !userId) { if (userId) axios.delete(`https://api.dialogflow.com/v1/contexts/pre-todo-assigntoperson-followup?sessionId=${sessionId}`, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${TOKEN}` } }) return db.ref(`rooms/${sessionId}/minnie/todo`).push({ task, userId: keys[index], userName: userNames[index], timestamp: Date.now() }) } else { return Promise.resolve(null) } } else { return Promise.resolve({ userUndefined: true, name: person }) } }) .catch(err => Promise.reject(err)) else return Promise.resolve(null) }
/** * Basic Vector Class Object * WIP - pjkarlik@gmail.com **/ export default class Vector { constructor(config) { this.x = config.x; this.y = config.y; this.z = config.z; } add = (v) => { return { x: v.x ? this.x + v.x : this.x, y: v.y ? this.y + v.y : this.y, z: v.z ? this.z + v.z : this.z, }; } subtract = (v) => { return { x: v.x ? this.x - v.x : this.x, y: v.y ? this.y - v.y : this.y, z: v.z ? this.z - v.z : this.z, }; } scale = (v) => { return { x: v.x ? this.x * v.x : this.x, y: v.y ? this.y * v.y : this.y, z: v.z ? this.z * v.z : this.z, }; } divide = (v) => { return { x: v.x ? this.x / v.x : this.x, y: v.y ? this.y / v.y : this.y, z: v.z ? this.z / v.z : this.z, }; } square = () => { return { x: this.x * this.x, y: this.y * this.y, z: this.z * this.z, }; } normalize = () => { const sqrt = 1 / this.square(); return new Vector(this.x * sqrt, this.y * sqrt, this.z * sqrt); } mix = (v, amount) => { const amt = amount || 0.5; const mixX = v.x ? (1 - amt) * this.x + amt * v.x : this.x; const mixY = v.y ? (1 - amt) * this.y + amt * v.y : this.y; const mixZ = v.z ? (1 - amt) * this.y + amt * v.z : this.z; return { x: mixX, y: mixY, z: mixZ, }; } }
(function($){ 'use strict'; $.savantForm = function(el, options){ var base = this; base.$el = $(el); base.el = el; base.$el.data("savantForm", base); base.init = function(){ base.options = $.extend({},$.savantForm.defaultOptions, options); $('form.savant-form').submit(function() { document.cookie = "savant=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; document.cookie = "savantchecksandradios=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; }); var savant = base.getCookie("savant"); var savantchecksandradios = base.getCookie("savantchecksandradios"); if(savant !== "") base.restoreFields(savant); if(savantchecksandradios !== "") base.restoreChecksAndRadios(savantchecksandradios); $('.savant-form input, .savant-form textarea').focus(function(){ base.persistFields(); base.persistChecksAndRadios(); }); $('.savant-form input, .savant-form textarea').focusout(function(){ base.persistFields(); base.persistChecksAndRadios(); }); $('.savant-form input, .savant-form textarea, .savant-form select').change(function(){ base.persistFields(); base.persistChecksAndRadios(); }); $('.savant-form input').keyup(function(){ base.persistFields(); base.persistChecksAndRadios(); }); }; base.setCookie = function(name, cvalue) { var d = new Date(); d.setTime(d.getTime() + (base.options.expiresin * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = name + "=" + cvalue + "; " + expires; }; base.getCookie = function(name) { var name = 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); if (c.indexOf(name) === 0) return c.substring(name.length,c.length); } return ""; }; base.persistFields = function() { var values = JSON.stringify($(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").map(function(){return $(this).val(); }).get()); base.setCookie("savant", values); }; base.restoreFields = function(data){ var json = $.parseJSON(data); var textfields = $(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").toArray(); for(var x = 0; x < json.length; x++){ if(json[x] && !$(textfields[x]).hasClass('savant-skip')){ $(textfields[x]).val(json[x]); } } }; base.persistChecksAndRadios = function() { var values = JSON.stringify($(".savant-form input[type='checkbox'], .savant-form input[type='radio']").map(function(){return this.checked;}).get()); base.setCookie("savantchecksandradios", values); }; base.restoreChecksAndRadios = function(data){ var json = $.parseJSON(data); var checkboxes = $('.savant-form input[type="checkbox"], .savant-form input[type="radio"]').toArray(); for(var x = 0; x < json.length; x++){ if(json[x] && !$(checkboxes[x]).hasClass('savant-skip')){ $(checkboxes[x]).attr('checked', true); } } }; base.init(); }; $.savantForm.defaultOptions = { expiresin: 300 }; $.fn.savantForm = function(options){ return this.each(function(){ (new $.savantForm(this, options)); }); }; })(jQuery);
'use strict'; const BaseAgent = require('../base'); const consoleTracker = require('./tracker'); consoleTracker.enable(); class ConsoleAgent extends BaseAgent { constructor() { super(); this._enabled = false; this._forwardMessage = (message) => { this.emit('messageAdded', { message }); }; } /** * Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification. */ enable() { if (this._enabled) return; this._enabled = true; // Make sure we don't add the listener twice consoleTracker.removeListener('message', this._forwardMessage); consoleTracker.on('message', this._forwardMessage); for (const message of consoleTracker.buffer) { this._forwardMessage(message); } } /** * Disables console domain, prevents further console messages from being reported to the client. */ disable() { this._enabled = false; consoleTracker.removeListener('message', this._forwardMessage); } /** * Clears console messages collected in the browser. */ clearMessages() { consoleTracker.clearMessages(); } } module.exports = ConsoleAgent;
define([ 'angular-ui-router', '@shared/auth' ], function() { /* @ngInject */ function authController($scope, $rootScope, $location, Auth) { $scope.login = function() { Auth.login({ username: $scope.username, password: $scope.password }).then(function(result) { $scope.errorMessage = null; $rootScope.$broadcast('login.success', result); $location.path('/'); }, function(result) { console.log(result); $scope.errorMessage = result.message || 'Login failed'; $rootScope.$broadcast('login.failed', result); }); }; } return authController; });
/*! * Star Rating Ukrainian Translations * * This file must be loaded after 'star-rating.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * NOTE: this file must be saved in UTF-8 encoding. * * @see http://github.com/kartik-v/bootstrap-star-rating * @author Kartik Visweswaran <kartikv2@gmail.com> * @author https://github.com/wowkin2 */ (function ($) { "use strict"; $.fn.ratingLocales['ua'] = { defaultCaption: '{rating} Зірки', starCaptions: { 0.5: 'Пів зірки', 1: 'Одна зірка', 1.5: 'Півтори зірки', 2: 'Дві зірки', 2.5: 'Дві з половиною зірки', 3: 'Три зірки', 3.5: 'Три з половиною зірки', 4: 'Чотири зірки', 4.5: 'Чотири з половиною зірки', 5: 'П\'ять зірок' }, clearButtonTitle: 'Очистити', clearCaption: 'Без рейтингу' }; })(window.jQuery);
var app_prod = angular.module('App_prod',[]);
/** * PepipostLib * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ 'use strict'; const _request = require('../Http/Client/RequestClient'); const _configuration = require('../configuration'); const _apiHelper = require('../APIHelper'); const _baseController = require('./BaseController'); class SuppressionController { /** * This API allows you to suppress an email address and block any future email delivery * attempts on this email address. * * @param {AddemailordomaintoSuppressionlist} body add email or domain to suppression list * * @callback The callback function that returns response from the API call * * @returns {Promise} */ static adddomainoremailtosuppressionlist(body, callback) { // create empty callback if absent const _callback = typeof callback === 'function' ? callback : () => undefined; // prepare query string for API call const _baseUri = _configuration.BASEURI; const _pathUrl = '/suppression'; const _queryBuilder = `${_baseUri}${_pathUrl}`; // validate and preprocess url const _queryUrl = _apiHelper.cleanUrl(_queryBuilder); // prepare headers const _headers = { 'content-type': 'application/json; charset=utf-8', api_key: _configuration.apiKey, 'user-agent': 'APIMATIC 2.0', }; // construct the request const _options = { queryUrl: _queryUrl, method: 'POST', headers: _headers, body: _apiHelper.jsonSerialize(body), }; // build the response processing. return new Promise((_fulfill, _reject) => { _request(_options, (_error, _response, _context) => { let errorResponse; if (_error) { errorResponse = _baseController.validateResponse(_context); _callback(errorResponse.error, errorResponse.response, errorResponse.context); _reject(errorResponse.error); } else if (_response.statusCode >= 200 && _response.statusCode <= 206) { const _strResult = _response.body; const _result = JSON.parse(_strResult); _callback(null, _result, _context); _fulfill(_result); } else if (_response.statusCode === 400) { const _err = { errorMessage: 'API Response', errorCode: 400, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 401) { const _err = { errorMessage: 'API Response', errorCode: 401, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 403) { const _err = { errorMessage: 'API Response', errorCode: 403, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 405) { const _err = { errorMessage: 'Invalid input', errorCode: 405, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else { errorResponse = _baseController.validateResponse(_context); _callback(errorResponse.error, errorResponse.response, errorResponse.context); _reject(errorResponse.error); } }); }); } /** * Use this API to remove an email address or a recipient domain from the suppression list. * You can remove multiple email addresses and recipient domains together by passing them as * values & separating them using commas as shown below. * * @param {RemoveemailordomaintoSuppressionlist} body remove email or domain to suppression * list * * @callback The callback function that returns response from the API call * * @returns {Promise} */ static removedomainoremailtosuppressionlist(body, callback) { // create empty callback if absent const _callback = typeof callback === 'function' ? callback : () => undefined; // prepare query string for API call const _baseUri = _configuration.BASEURI; const _pathUrl = '/suppression'; const _queryBuilder = `${_baseUri}${_pathUrl}`; // validate and preprocess url const _queryUrl = _apiHelper.cleanUrl(_queryBuilder); // prepare headers const _headers = { 'content-type': 'application/json; charset=utf-8', api_key: _configuration.apiKey, 'user-agent': 'APIMATIC 2.0', }; // construct the request const _options = { queryUrl: _queryUrl, method: 'DELETE', headers: _headers, body: _apiHelper.jsonSerialize(body), }; // build the response processing. return new Promise((_fulfill, _reject) => { _request(_options, (_error, _response, _context) => { let errorResponse; if (_error) { errorResponse = _baseController.validateResponse(_context); _callback(errorResponse.error, errorResponse.response, errorResponse.context); _reject(errorResponse.error); } else if (_response.statusCode >= 200 && _response.statusCode <= 206) { const _strResult = _response.body; const _result = JSON.parse(_strResult); _callback(null, _result, _context); _fulfill(_result); } else if (_response.statusCode === 400) { const _err = { errorMessage: 'API Response', errorCode: 400, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 401) { const _err = { errorMessage: 'API Response', errorCode: 401, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 403) { const _err = { errorMessage: 'API Response', errorCode: 403, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else if (_response.statusCode === 405) { const _err = { errorMessage: 'Invalid input', errorCode: 405, errorResponse: _response.body }; _callback(_err, null, _context); _reject(_err); } else { errorResponse = _baseController.validateResponse(_context); _callback(errorResponse.error, errorResponse.response, errorResponse.context); _reject(errorResponse.error); } }); }); } } module.exports = SuppressionController;
(function(){ var tags = document.getElementsByTagName('PRE'); for (var i=0; i<tags.length; i++) { if (tags[i].className && tags[i].className.indexOf('highlight') == -1 && tags[i].className.indexOf('code') > -1) { high_light(tags[i]); } } function loopArr(arr, regexp, color){ for (var i in arr) { var pattern2 = new RegExp(regexp, "gi"), result2; while((result2 = pattern2.exec(arr[i])) != null){ arr[i] = arr[i].replace(pattern2, "<font color="+color+">$&"+"</font>"); } } } function escapeStr(str){ return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); } function highlightQuotes(html, char){ var newline = '', flag = 0; for (var x=0, y=html.length; x<y; x++ ) { if (html.charAt(x) == char) { if(flag == 0){ newline += '<font color="blue">'; newline += html.charAt(x); flag = 1; }else if(flag == 1 && html.charAt(x-1) != '\\') { newline += html.charAt(x); newline += '</font>'; flag = 0; }else { newline += html.charAt(x); } }else { newline += html.charAt(x); } } return newline; }; function hasSingleQuotation (html){ return html.indexOf("'") != -1; } function hasDoubleQuotation (html){ return html.indexOf('"') != -1; } function hasEscapeCharacter (html){ return html.indexOf('\\') != -1; } function high_light(tag){ var arr = tag.innerHTML.split("\n") , div = document.createElement('PRE') , ldiv = document.createElement('DIV') , rdiv = document.createElement('DIV') , arr_len = arr.length , str_len = arr_len + ''; div.appendChild(ldiv); div.appendChild(rdiv); if (arr[arr_len - 1] == '') { arr.pop(); arr_len --; } var keywords = { "red":['function', 'var', 'instanceof', 'if', 'else', 'return', 'array'], "#fb0495":['(', ')', '[', ']', '{', '}'], "#f94304":['+', '-', ',', '*', '/', '=', '!'] }; var regexps = { "green":['\\$[a-zA-Z_][a-zA-Z0-9_]*'], "gray":['\/\/[^<>]*?$'] }; for (var i in arr) { var hasSingle = hasSingleQuotation(arr[i]); var hasDouble = hasDoubleQuotation(arr[i]); if (hasSingle && hasDouble) { } else if(hasSingle){ arr[i] = highlightQuotes(arr[i], "'"); } else if(hasDouble){ arr[i] = highlightQuotes(arr[i], '"'); } } for (var j in regexps) { for (var x in regexps[j]) { loopArr(arr, '(?!<font>*|<[^<>]*)'+regexps[j][x]+'(?![^<>]*<\/font>|<\/[^<>]*|[^<>]*>)', j); } } for (var j in keywords) { for (var x in keywords[j]) { loopArr(arr, '(?!<font>*|<[^<>]*)'+escapeStr(keywords[j][x])+'(?![^<>]*<\/font>|<\/[^<>]*|[^<>]*>)', j); } } var width = str_len.length * 10; ldiv.style.width = width + 'px'; ldiv.style.float = 'left'; ldiv.style.padding = "0 4px 0 0"; ldiv.style.margin = "0 6px 0 0"; ldiv.style.position = 'absolute'; ldiv.style.borderRight = "1px dotted #CCC"; ldiv.style.textAlign = "right"; rdiv.style.paddingLeft = (width + 11) + 'px'; div.style.position = 'relative'; div.className = "code highlight wbreak"; for (var i in arr) { ldiv.innerHTML += '<span style="display:block;">'+i+'</span>'; } for (var i in arr) { var div_style = 'style="display:block;"'; if (arr[i].replace(/\s/, '') == '') { div_style = 'style="height:26px;display:block;"'; } rdiv.innerHTML += '<span '+div_style+'>'+ arr[i] +"</span>"; } tag.parentNode.insertBefore(div, tag.nextSibling); tag.style.display = 'none'; function adjust_height(){ var ldiv_child = ldiv.getElementsByTagName('SPAN'); var rdiv_child = rdiv.getElementsByTagName('SPAN'); for (var i in ldiv.getElementsByTagName('SPAN')) { if(ldiv_child[i].tagName){ ldiv_child[i].style.height = rdiv_child[i].offsetHeight + 'px'; } } } this.adjust_height = adjust_height; adjust_height(); if(window.addEventListener){ window.addEventListener( 'resize', adjust_height, false ); }else if(window.attachEvent){ window.attachEvent("onresize", adjust_height); } } })();
"use strict"; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Dependencies //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var path = require("path"); var helper = require("./../../helper"); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Module //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ exports.get = function (req, res) { helper.isLoggedIn(req, res) .then(function () { res.sendFile(path.join(__dirname, "../../public/pages/newGame.html")); }) .catch(function () { helper.route(res, "/login"); }); };
// es6 promise polyfill is only required // when using karma-phantomjs-launcher require('es6-promise').polyfill(); require('isomorphic-fetch'); // see https://github.com/webpack/karma-webpack#alternative-usage // require all files in ~/src const src = require.context('../src', true, /^.+\.jsx?$/); src.keys().forEach(src); const tests = require.context('.', true, /.+\.test\.jsx?$/); tests.keys().forEach(tests);
/* * jQuery Reveal Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function($) { /*--------------------------- Defaults for Reveal ----------------------------*/ /*--------------------------- Listener for data-reveal-id attributes ----------------------------*/ $('a[data-reveal-id]').click(function(e) { e.preventDefault(); var modalLocation = $(this).attr('data-reveal-id'); $('#'+modalLocation).reveal($(this).data()); }); /*--------------------------- Extend and Execute ----------------------------*/ $.fn.reveal = function(options) { var defaults = { animation: 'fadeAndPop', //fade, fadeAndPop, none animationspeed: 300, //how fast animtions are closeonbackgroundclick: true, //if you click background will modal close? dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal }; //Extend dem' options var options = $.extend({}, defaults, options); return this.each(function() { /*--------------------------- Global Variables ----------------------------*/ var modal = $(this), topMeasure = parseInt(modal.css('top')), topOffset = modal.height() + topMeasure, locked = false, modalBG = $('.reveal-modal-bg'); /*--------------------------- Create Modal BG ----------------------------*/ if(modalBG.length == 0) { modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal); } /*--------------------------- Open & Close Animations ----------------------------*/ //Entrance Animations modal.bind('reveal:open', function () { modalBG.unbind('click.modalEvent'); $('.' + options.dismissmodalclass).unbind('click.modalEvent'); if(!locked) { lockModal(); if(options.animation == "fadeAndPop") { modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'}); modalBG.fadeIn(options.animationspeed/2); modal.delay(options.animationspeed/2).animate({ "top": $(document).scrollTop()+topMeasure + 'px', "opacity" : 1 }, options.animationspeed,unlockModal()); } if(options.animation == "fade") { modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure}); modalBG.fadeIn(options.animationspeed/2); modal.delay(options.animationspeed/2).animate({ "opacity" : 1 }, options.animationspeed,unlockModal()); } if(options.animation == "none") { modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure}); modalBG.css({"display":"block"}); unlockModal() } } modal.unbind('reveal:open'); }); //Closing Animation modal.bind('reveal:close', function () { if(!locked) { lockModal(); if(options.animation == "fadeAndPop") { modalBG.delay(options.animationspeed).fadeOut(options.animationspeed); modal.animate({ "top": $(document).scrollTop()-topOffset + 'px', "opacity" : 0 }, options.animationspeed/2, function() { modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'}); unlockModal(); }); } if(options.animation == "fade") { modalBG.delay(options.animationspeed).fadeOut(options.animationspeed); modal.animate({ "opacity" : 0 }, options.animationspeed, function() { modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure}); unlockModal(); }); } if(options.animation == "none") { modal.css({'visibility' : 'hidden', 'top' : topMeasure}); modalBG.css({'display' : 'none'}); } } modal.unbind('reveal:close'); }); /*--------------------------- Open and add Closing Listeners ----------------------------*/ //Open Modal Immediately modal.trigger('reveal:open') //Close Modal Listeners var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () { modal.trigger('reveal:close') }); if(options.closeonbackgroundclick) { modalBG.css({"cursor":"pointer"}) modalBG.bind('click.modalEvent', function () { modal.trigger('reveal:close') }); } $('body').keyup(function(e) { if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key }); /*--------------------------- Animations Locks ----------------------------*/ function unlockModal() { locked = false; } function lockModal() { locked = true; } });//each call }//orbit plugin call })(jQuery);
export default from './Stylus'
var keystone = require('keystone'); exports = module.exports = function (req, res) { var view = new keystone.View(req, res); var locals = res.locals; // locals.section is used to set the currently selected // item in the header navigation. locals.section = 'home'; // Render the view view.render('index'); // return res.status(200).json({'success': true}) };
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.data.ServiceStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.data.ServiceStore"] = true; dojo.provide("dojox.data.ServiceStore"); // note that dojox.rpc.Service is not required, you can create your own services // A ServiceStore is a readonly data store that provides a data.data interface to an RPC service. // var myServices = new dojox.rpc.Service(dojo.moduleUrl("dojox.rpc.tests.resources", "test.smd")); // var serviceStore = new dojox.data.ServiceStore({service:myServices.ServiceStore}); // // The ServiceStore also supports lazy loading. References can be made to objects that have not been loaded. // For example if a service returned: // {"name":"Example","lazyLoadedObject":{"$ref":"obj2"}} // // And this object has accessed using the dojo.data API: // var obj = serviceStore.getValue(myObject,"lazyLoadedObject"); // The object would automatically be requested from the server (with an object id of "obj2"). // dojo.declare("dojox.data.ServiceStore", // ClientFilter is intentionally not required, ServiceStore does not need it, and is more // lightweight without it, but if it is provided, the ServiceStore will use it. dojox.data.ClientFilter||null,{ service: null, constructor: function(options){ //summary: // ServiceStore constructor, instantiate a new ServiceStore // A ServiceStore can be configured from a JSON Schema. Queries are just // passed through to the underlying services // // options: // Keyword arguments // The *schema* parameter // This is a schema object for this store. This should be JSON Schema format. // // The *service* parameter // This is the service object that is used to retrieve lazy data and save results // The function should be directly callable with a single parameter of an object id to be loaded // // The *idAttribute* parameter // Defaults to 'id'. The name of the attribute that holds an objects id. // This can be a preexisting id provided by the server. // If an ID isn't already provided when an object // is fetched or added to the store, the autoIdentity system // will generate an id for it and add it to the index. // // The *estimateCountFactor* parameter // This parameter is used by the ServiceStore to estimate the total count. When // paging is indicated in a fetch and the response includes the full number of items // requested by the fetch's count parameter, then the total count will be estimated // to be estimateCountFactor multiplied by the provided count. If this is 1, then it is assumed that the server // does not support paging, and the response is the full set of items, where the // total count is equal to the numer of items returned. If the server does support // paging, an estimateCountFactor of 2 is a good value for estimating the total count // It is also possible to override _processResults if the server can provide an exact // total count. // // The *syncMode* parameter // Setting this to true will set the store to using synchronous calls by default. // Sync calls return their data immediately from the calling function, so // callbacks are unnecessary. This will only work with a synchronous capable service. // // description: // ServiceStore can do client side caching and result set updating if // dojox.data.ClientFilter is loaded. Do this add: // | dojo.require("dojox.data.ClientFilter") // prior to loading the ServiceStore (ClientFilter must be loaded before ServiceStore). // To utilize client side filtering with a subclass, you can break queries into // client side and server side components by putting client side actions in // clientFilter property in fetch calls. For example you could override fetch: // | fetch: function(args){ // | // do the sorting and paging on the client side // | args.clientFilter = {start:args.start, count: args.count, sort: args.sort}; // | // args.query will be passed to the service object for the server side handling // | return this.inherited(arguments); // | } // When extending this class, if you would like to create lazy objects, you can follow // the example from dojox.data.tests.stores.ServiceStore: // | var lazyItem = { // | _loadObject: function(callback){ // | this.name="loaded"; // | delete this._loadObject; // | callback(this); // | } // | }; //setup a byId alias to the api call this.byId=this.fetchItemByIdentity; this._index = {}; // if the advanced json parser is enabled, we can pass through object updates as onSet events if(options){ dojo.mixin(this,options); } // We supply a default idAttribute for parser driven construction, but if no id attribute // is supplied, it should be null so that auto identification takes place properly this.idAttribute = (options && options.idAttribute) || (this.schema && this.schema._idAttr); }, schema: null, idAttribute: "id", labelAttribute: "label", syncMode: false, estimateCountFactor: 1, getSchema: function(){ return this.schema; }, loadLazyValues:true, getValue: function(/*Object*/ item, /*String*/property, /*value?*/defaultValue){ // summary: // Gets the value of an item's 'property' // // item: // The item to get the value from // property: // property to look up value for // defaultValue: // the default value var value = item[property]; return value || // return the plain value since it was found; (property in item ? // a truthy value was not found, see if we actually have it value : // we do, so we can return it item._loadObject ? // property was not found, maybe because the item is not loaded, we will try to load it synchronously so we can get the property (dojox.rpc._sync = true) && arguments.callee.call(this,dojox.data.ServiceStore.prototype.loadItem({item:item}) || {}, property, defaultValue) : // load the item and run getValue again defaultValue);// not in item -> return default value }, getValues: function(item, property){ // summary: // Gets the value of an item's 'property' and returns // it. If this value is an array it is just returned, // if not, the value is added to an array and that is returned. // // item: /* object */ // property: /* string */ // property to look up value for var val = this.getValue(item,property); if(val instanceof Array){ return val; } if(!this.isItemLoaded(val)){ dojox.rpc._sync = true; val = this.loadItem({item:val}); } return val instanceof Array ? val : val === undefined ? [] : [val]; }, getAttributes: function(item){ // summary: // Gets the available attributes of an item's 'property' and returns // it as an array. // // item: /* object */ var res = []; for(var i in item){ if(item.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_')){ res.push(i); } } return res; }, hasAttribute: function(item,attribute){ // summary: // Checks to see if item has attribute // // item: /* object */ // attribute: /* string */ return attribute in item; }, containsValue: function(item, attribute, value){ // summary: // Checks to see if 'item' has 'value' at 'attribute' // // item: /* object */ // attribute: /* string */ // value: /* anything */ return dojo.indexOf(this.getValues(item,attribute),value) > -1; }, isItem: function(item){ // summary: // Checks to see if the argument is an item // // item: /* object */ // attribute: /* string */ // we have no way of determining if it belongs, we just have object returned from // service queries return (typeof item == 'object') && item && !(item instanceof Date); }, isItemLoaded: function(item){ // summary: // Checks to see if the item is loaded. // // item: /* object */ return item && !item._loadObject; }, loadItem: function(args){ // summary: // Loads an item and calls the callback handler. Note, that this will call the callback // handler even if the item is loaded. Consequently, you can use loadItem to ensure // that an item is loaded is situations when the item may or may not be loaded yet. // If you access a value directly through property access, you can use this to load // a lazy value as well (doesn't need to be an item). // // example: // store.loadItem({ // item: item, // this item may or may not be loaded // onItem: function(item){ // // do something with the item // } // }); var item; if(args.item._loadObject){ args.item._loadObject(function(result){ item = result; // in synchronous mode this can allow loadItem to return the value delete item._loadObject; var func = result instanceof Error ? args.onError : args.onItem; if(func){ func.call(args.scope, result); } }); }else if(args.onItem){ // even if it is already loaded, we will use call the callback, this makes it easier to // use when it is not known if the item is loaded (you can always safely call loadItem). args.onItem.call(args.scope, args.item); } return item; }, _currentId : 0, _processResults : function(results, deferred){ // this should return an object with the items as an array and the total count of // items (maybe more than currently in the result set). // for example: // | {totalCount:10, items: [{id:1},{id:2}]} // index the results, assigning ids as necessary if(results && typeof results == 'object'){ var id = results.__id; if(!id){// if it hasn't been assigned yet if(this.idAttribute){ // use the defined id if available id = results[this.idAttribute]; }else{ id = this._currentId++; } if(id !== undefined){ var existingObj = this._index[id]; if(existingObj){ for(var j in existingObj){ delete existingObj[j]; // clear it so we can mixin } results = dojo.mixin(existingObj,results); } results.__id = id; this._index[id] = results; } } for(var i in results){ results[i] = this._processResults(results[i], deferred).items; } var count = results.length; } return {totalCount: deferred.request.count == count ? (deferred.request.start || 0) + count * this.estimateCountFactor : count, items: results}; }, close: function(request){ return request && request.abort && request.abort(); }, fetch: function(args){ // summary: // See dojo.data.api.Read.fetch // // The *queryOptions.cache* parameter // If true, indicates that the query result should be cached for future use. This is only available // if dojox.data.ClientFilter has been loaded before the ServiceStore // // The *syncMode* parameter // Indicates that the call should be fetch synchronously if possible (this is not always possible) // // The *clientFetch* parameter // This is a fetch keyword argument for explicitly doing client side filtering, querying, and paging args = args || {}; if("syncMode" in args ? args.syncMode : this.syncMode){ dojox.rpc._sync = true; } var self = this; var scope = args.scope || self; var defResult = this.cachingFetch ? this.cachingFetch(args) : this._doQuery(args); defResult.request = args; defResult.addCallback(function(results){ if(args.clientFetch){ results = self.clientSideFetch({query:args.clientFetch,sort:args.sort,start:args.start,count:args.count},results); } var resultSet = self._processResults(results, defResult); results = args.results = resultSet.items; if(args.onBegin){ args.onBegin.call(scope, resultSet.totalCount, args); } if(args.onItem){ for(var i=0; i<results.length;i++){ args.onItem.call(scope, results[i], args); } } if(args.onComplete){ args.onComplete.call(scope, args.onItem ? null : results, args); } return results; }); defResult.addErrback(args.onError && function(err){ return args.onError.call(scope, err, args); }); args.abort = function(){ // abort the request defResult.cancel(); }; args.store = this; return args; }, _doQuery: function(args){ var query= typeof args.queryStr == 'string' ? args.queryStr : args.query; return this.service(query); }, getFeatures: function(){ // summary: // return the store feature set return { "dojo.data.api.Read": true, "dojo.data.api.Identity": true, "dojo.data.api.Schema": this.schema }; }, getLabel: function(item){ // summary // returns the label for an item. Just gets the "label" attribute. // return this.getValue(item,this.labelAttribute); }, getLabelAttributes: function(item){ // summary: // returns an array of attributes that are used to create the label of an item return [this.labelAttribute]; }, //Identity API Support getIdentity: function(item){ return item.__id; }, getIdentityAttributes: function(item){ // summary: // returns the attributes which are used to make up the // identity of an item. Basically returns this.idAttribute return [this.idAttribute]; }, fetchItemByIdentity: function(args){ // summary: // fetch an item by its identity, by looking in our index of what we have loaded var item = this._index[(args._prefix || '') + args.identity]; if(item){ // the item exists in the index if(item._loadObject){ // we have a handle on the item, but it isn't loaded yet, so we need to load it args.item = item; return this.loadItem(args); }else if(args.onItem){ // it's already loaded, so we can immediately callback args.onItem.call(args.scope, item); } }else{ // convert the different spellings return this.fetch({ query: args.identity, onComplete: args.onItem, onError: args.onError, scope: args.scope }).results; } return item; } } ); }
'use strict'; //For production type: gulp --type production var gutil = require('gulp-util'), minify = require('gulp-uglify'), htmlmin = require('gulp-htmlmin'), prod = gutil.env.type === 'production'; var GulpConfig = (function () { function gulpConfig() { //Got tired of scrolling through all the comments so removed them //Don't hurt me AC :-) this.source = './src/'; // this.source = './src/'; //TypeScript this.sourceApp = this.source + 'ts'; this.tsOutputPath = this.source + 'js/'; this.jsSources = this.source; // this.allJavaScript = [this.source + '/js/**/*.js']; this.allTypeScript = this.sourceApp + '/**/*.ts'; //Development and production this.devSource = './builds/development/'; // this.devSource = './builds/development/'; this.prodSource = './builds/production/'; this.outputSource = prod ? this.prodSource : this.devSource; // this.prodSource = './builds/production/'; // JS this.devJS = this.devSource + 'js/'; this.prodJS = this.prodSource + 'js/'; this.jsOutput = prod ? this.prodJS : this.devJS; this.devJsName = 'jquery.frodo.js'; this.prodJsName = 'jquery.frodo.min.js'; this.jsFileName = prod ? this.prodJsName : this.devJsName; //Sass this.sassSources = 'src/sass/'; this.sassOptions = { errLogToConsole: true, outputStyle: prod ? 'compressed' : 'compact' }; // CSS this.devCss = this.devSource + '/css'; this.prodCss = this.prodSource + '/css'; this.cssOutput = prod ? this.prodCss : this.devCss; this.outputCssName = prod ? this.prodCssName : this.devCssName; this.devCssName = 'jquery.frodo.css'; this.prodCssName = 'jquery.frodo.min.css'; this.cssFileName = prod ? this.prodCssName : this.devCssName; // HTML this.htmlSources = this.source + '*.html'; this.htmlOptions = { collapseWhitespace: true, removeComments: true, collapseInlineTagWhitespace: true, useShortDoctype: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, minifyJS: true, minifyCSS: true }; this.devHtml = this.devSource; // this.devHtml = this.devSource + '*.html'; this.prodHtml = this.prodSource; this.htmlOutput = prod ? this.prodHtml : this.devHtml; // IMAGES this.imgSources = this.source + 'images/**/*'; this.devImg = this.devSource + 'images'; this.prodImg = this.prodSource + 'images'; this.imgOutput = prod ? this.prodImg : this.devImg; this.prodMinify = prod ? minify() : gutil.noop(); this.prodHtmlMin = prod ? htmlmin(this.htmlOptions) : gutil.noop(); this.typings = './tools/typings/'; this.libraryTypeScriptDefinitions = './tools/typings/**/*.ts'; } return gulpConfig; })(); module.exports = GulpConfig;
define("ace/snippets/ocaml",["require","exports","module"],function(e,i,n){"use strict";i.snippetText=undefined,i.scope="ocaml"}); //# sourceMappingURL=node_modules/ace-builds/src-min/snippets/ocaml.js.map
import ShapeLine from './graph.shape.line.js'; /** * Shows a horizontal line with three little vertical bars. Very useful to demonstrate a peak start, end and middle value * @extends ShapeLine */ class ShapePeakBoundaries extends ShapeLine { constructor( graph ) { super( graph ); this.lineHeight = 6; } createDom() { this._dom = document.createElementNS( this.graph.ns, 'line' ); this.line1 = document.createElementNS( this.graph.ns, 'line' ); this.line2 = document.createElementNS( this.graph.ns, 'line' ); this.line3 = document.createElementNS( this.graph.ns, 'line' ); this.rectBoundary = document.createElementNS( this.graph.ns, 'path' ); this.rectBoundary.setAttribute( 'fill', 'transparent' ); this.rectBoundary.setAttribute( 'stroke', 'none' ); this.rectBoundary.setAttribute( 'pointer-events', 'fill' ); this.rectBoundary.jsGraphIsShape = true; this.group.appendChild( this.rectBoundary ); this.group.appendChild( this.line1 ); this.group.appendChild( this.line2 ); this.group.appendChild( this.line3 ); this._dom.element = this; } createHandles() { this._createHandles( 3, 'rect', { transform: 'translate(-3 -3)', width: 6, height: 6, stroke: 'black', fill: 'white', cursor: 'nwse-resize' } ); } redrawImpl() { this.line1.setAttribute( 'stroke', this.getStrokeColor() ); this.line2.setAttribute( 'stroke', this.getStrokeColor() ); this.line3.setAttribute( 'stroke', this.getStrokeColor() ); this.line1.setAttribute( 'stroke-width', this.getStrokeWidth() ); this.line2.setAttribute( 'stroke-width', this.getStrokeWidth() ); this.line3.setAttribute( 'stroke-width', this.getStrokeWidth() ); this.setHandles(); this.redrawLines(); } /** * @memberof ShapePeakBoundaries * Redraws the vertical lines according to the positions. * Position 0 is the left line, position 1 is the right line and position 2 is the center line * @returns {ShapePeakBoundaries} The shape instance */ redrawLines() { var posLeft = this.computePosition( 0 ); var posRight = this.computePosition( 1 ); var posCenter = this.computePosition( 2 ); if ( posLeft.x && posRight.x && posCenter.x && this.posYPx ) { var height = this.lineHeight; this.rectBoundary.setAttribute( 'd', `M ${ posLeft.x } ${ this.posYPx - height } v ${ 2 * height } H ${ posRight.x } v ${ -2 * height }z` ); this.line1.setAttribute( 'x1', posLeft.x ); this.line1.setAttribute( 'x2', posLeft.x ); this.line2.setAttribute( 'x1', posRight.x ); this.line2.setAttribute( 'x2', posRight.x ); this.line3.setAttribute( 'x1', posCenter.x ); this.line3.setAttribute( 'x2', posCenter.x ); this._dom.setAttribute( 'x1', posLeft.x ); this._dom.setAttribute( 'x2', posRight.x ); this.redrawY( height ); } return this; } /** * @memberof ShapePeakBoundaries * Redraws the vertical positions of the shape * @returns {ShapePeakBoundaries} The shape instance */ redrawY() { if ( !this.posYPx ) { return this; } var height = this.lineHeight; this.line1.setAttribute( 'y1', this.posYPx - height ); this.line1.setAttribute( 'y2', this.posYPx + height ); this.line2.setAttribute( 'y1', this.posYPx - height ); this.line2.setAttribute( 'y2', this.posYPx + height ); this.line3.setAttribute( 'y1', this.posYPx - height ); this.line3.setAttribute( 'y2', this.posYPx + height ); this._dom.setAttribute( 'y1', this.posYPx ); this._dom.setAttribute( 'y2', this.posYPx ); return this; } setHandles() { if ( !this.posYPx ) { return; } var posLeft = this.computePosition( 0 ); var posRight = this.computePosition( 1 ); var posCenter = this.computePosition( 2 ); if ( posLeft.x && posRight.x && posCenter.x ) { this.handles[ 1 ].setAttribute( 'x', posLeft.x ); this.handles[ 1 ].setAttribute( 'y', this.posYPx ); this.handles[ 2 ].setAttribute( 'x', posRight.x ); this.handles[ 2 ].setAttribute( 'y', this.posYPx ); this.handles[ 3 ].setAttribute( 'x', posCenter.x ); this.handles[ 3 ].setAttribute( 'y', this.posYPx ); } } /** * @memberof ShapePeakBoundaries * Sets the y position of the shape * @param {Number} y - The y position in px * @returns {ShapePeakBoundaries} The shape instance */ setY( y ) { this.posYPx = y; return this; } /** * @memberof ShapePeakBoundaries * Sets the height of the peak lines * @param {Number} height - The height of the lines in px * @returns {ShapePeakBoundaries} The shape instance */ setLineHeight( height ) { this.lineHeihgt = height; } handleMouseMoveImpl( e, deltaX, deltaY ) { if ( this.isLocked() ) { return; } var posLeft = this.getPosition( 0 ); var posRight = this.getPosition( 1 ); var posCenter = this.getPosition( 2 ); switch ( this.handleSelected ) { case 1: // left posLeft.deltaPosition( 'x', deltaX, this.getXAxis() ); if ( Math.abs( posCenter.x - posRight.x ) > Math.abs( posRight.x - posLeft.x ) || Math.abs( posCenter.x - posLeft.x ) > Math.abs( posRight.x - posLeft.x ) ) { posCenter.x = posLeft.x + ( posRight.x - posLeft.x ) * 0.1; } break; case 2: // left posRight.deltaPosition( 'x', deltaX, this.getXAxis() ); if ( Math.abs( posCenter.x - posRight.x ) > Math.abs( posRight.x - posLeft.x ) || Math.abs( posCenter.x - posLeft.x ) > Math.abs( posRight.x - posLeft.x ) ) { posCenter.x = posRight.x + ( posLeft.x - posRight.x ) * 0.1; } break; case 3: // left posCenter.deltaPosition( 'x', deltaX, this.getXAxis() ); if ( Math.abs( posCenter.x - posRight.x ) > Math.abs( posRight.x - posLeft.x ) || Math.abs( posCenter.x - posLeft.x ) > Math.abs( posRight.x - posLeft.x ) ) { return; } break; } this.setLabelPosition( { y: this.getLabelPosition( 0 ).y, x: posCenter.x } ); this.updateLabels(); this.redrawLines(); this.setHandles(); } applyPosition() { this.redrawLines(); return true; } } export default ShapePeakBoundaries;
/** * Auth actions */ 'use strict'; var jwt = require('jwt-simple'); var secret = require('../config').secret; // var validateUser = require('../routes/auth').validateUser; module.exports = function(req, res, next) { // When performing a cross domain request, you will recieve // a preflighted request first. This is to check if our the app // is safe. // We skip the token outh for [OPTIONS] requests. // if(req.method == 'OPTIONS') next(); var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token']; // var key = (req.body && req.body.x_key) || (req.query && req.query.x_key) || req.headers['x-key']; // if (token || key) { if (token) { try { var decoded = jwt.decode(token, secret); if (decoded.expires <= Date.now()) { res.status(401); res.json({ status: 401, message: 'Token Expired' }); return; } next(); // // Authorize the user to see if s/he can access our resources // var dbUser = validateUser(key); // The key would be the logged in user's username // if (dbUser) { // if ((req.url.indexOf('admin') >= 0 && dbUser.role == 'admin') || (req.url.indexOf('admin') < 0 && req.url.indexOf('/api/v1/') >= 0)) { // next(); // To move to next middleware // } else { // res.status(403); // res.json({ // "status": 403, // "message": "Not Authorized" // }); // return; // } // } else { // // No user with this name exists, respond back with a 401 // res.status(401); // res.json({ // "status": 401, // "message": "Invalid User" // }); // return; // } } catch (err) { // If token is invalid, respond back with 401 res.status(401); res.json({ status: 401, message: 'Authentication failed', error: err }); } } else { // If no token or key is sent, respond back with 401 res.status(401); res.json({ status: 401, message: 'Authentication failed' }); return; } };
require(['require', 'requireConfig'], function(require) { 'use strict'; require([ 'jQuery', 'Angular', 'bbtk' ], function(jQuery, angular){ angular.element(document).ready(function() { angular.bootstrap(document, ['bbToolkit']); }); }); });
// Gulp plugins: var gulp = require('gulp') var pug = require('gulp-pug') var stylus = require('gulp-stylus') var nib = require('nib') var changed = require('gulp-changed') var prefix = require('gulp-autoprefixer') var uglify = require('gulp-uglify') var concat = require('gulp-concat') var plumber = require('gulp-plumber') var browserSync = require('browser-sync') var gulpIf = require('gulp-if') var argv = require('yargs').argv // Useful globs in handy variables: var markupSrc = [ 'source/markup/**/*.pug', '!source/markup/_layout.pug', '!source/markup/partials{,/**}', '!source/markup/sections{,/**}', '!source/markup/features{,/**}' ] var stylesSrc = [ 'source/stylesheets/**/*.styl', '!source/stylesheets/partials{,/**}', '!source/stylesheets/modules{,/**}' ] var jsSrc = [ 'source/javascript/**/*.js', '!source/javascript/vendor{,/**}' ] var imagesSrc = 'source/images/**/*.*' // Aaaand we start taskin’ // By default, we build, serve, and watch for changes: gulp.task('watch', ['build', 'browser-sync'], function () { gulp.watch(markupSrc[0], ['markup']) gulp.watch(stylesSrc[0], ['styles']) gulp.watch(jsSrc[0], ['javascript', 'javascript_vendors']) gulp.watch(imagesSrc, ['images']) }) // Build the site: gulp.task('build', [ 'markup', 'styles', 'javascript', 'javascript_vendors', 'images' ] ) // Generate markup: gulp.task('markup', function () { gulp.src(markupSrc) .pipe(plumber()) .pipe(pug({ pretty: (argv.production ? false : true) })) .pipe(gulp.dest('build/')) }) // Generate styles, add prefixes: gulp.task('styles', function () { gulp.src(stylesSrc) .pipe(plumber()) .pipe(stylus({ use: [nib()], compress: (argv.production ? true : false) })) .pipe(prefix('last 2 versions', '> 1%')) .pipe(gulp.dest('build/stylesheets')) }) // Copy javascript: gulp.task('javascript', function () { gulp.src(jsSrc) .pipe(plumber()) .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('build/javascript')) }) // TO-DO: Implement hinting & collation. gulp.task('javascript_vendors', function () { gulp.src('source/javascript/vendor/*') .pipe(plumber()) .pipe(gulp.dest('build/javascript/vendor')) }) // Copy images to build dir: gulp.task('images', function () { gulp.src(imagesSrc) .pipe(plumber()) .pipe(gulp.dest('build/images')) }) // Init browser-sync & watch generated files: gulp.task('browser-sync', function () { browserSync.init(null, { server: { baseDir: './build' }, files: [ 'build/**/*.html', 'build/**/*.css', 'build/**/*.js' ] }) })
import { extend } from 'flarum/extend'; import app from 'flarum/app'; import HeaderSecondary from 'flarum/components/HeaderSecondary'; import FlagsDropdown from './components/FlagsDropdown'; export default function () { extend(HeaderSecondary.prototype, 'items', function (items) { if (app.forum.attribute('canViewFlags')) { items.add('flags', <FlagsDropdown state={app.flags} />, 15); } }); }
// @flow import axios from 'axios' import { keyBy } from 'lodash-es' import { api } from '@cityofzion/neon-js' // import { wallet } from '@cityofzion/neon-js' import { getNode, getRPCEndpoint } from '../actions/nodeStorageActions' import { addPendingTransaction } from '../actions/pendingTransactionActions' import { getAddress, getAssetBalances, getIsHardwareLogin, getSigningFunction, getTokenBalances, getWIF, getPublicKey, } from '../core/deprecated' import { showErrorNotification, showInfoNotification, showSuccessNotification, } from './notifications' import { getTokenBalancesMap } from '../core/wallet' import { toBigNumber } from '../core/math' import { buildTransferScript } from './transactions' const N2 = require('@cityofzion/neon-js-legacy-latest') const N3 = require('@cityofzion/neon-js-next') export const performMigration = ({ sendEntries, migrationAddress, }: { sendEntries: Array<SendEntryType>, migrationAddress?: string, }) => (dispatch: DispatchType, getState: GetStateType): Promise<*> => // TODO: will need to be dynamic based on network // eslint-disable-next-line // const provider = new N2.api.neoCli.instance('https://testnet1.neo2.coz.io') new Promise(async (resolve, reject) => { try { const state = getState() const wif = getWIF(state) const tokenBalances = getTokenBalances(state) const balances = { ...getAssetBalances(state), ...getTokenBalancesMap(tokenBalances), } const tokensBalanceMap = keyBy(tokenBalances, 'symbol') const fromAddress = getAddress(state) const entry = sendEntries[0] const signingFunction = getSigningFunction(state) const isHardwareSend = getIsHardwareLogin(state) const publicKey = getPublicKey(state) const TO_ACCOUNT = new N3.wallet.Account( isHardwareSend ? migrationAddress : wif, ) const FROM_ACCOUNT = new N2.wallet.Account( isHardwareSend ? fromAddress : wif, ) // eslint-disable-next-line const net = state.spunky.network.data == 1 ? 'MainNet' : 'TestNet' let endpoint = await getNode(net) if (!endpoint) { endpoint = await getRPCEndpoint(net) } // eslint-disable-next-line const provider = new N2.api.neoCli.instance(endpoint) const { symbol, amount, address } = entry let intent let script = '' if (symbol === 'GAS' || symbol === 'NEO') { intent = N2.api.makeIntent({ [symbol]: Number(amount) }, address) } else { script = buildTransferScript( net, sendEntries, FROM_ACCOUNT.address, // $FlowFixMe tokensBalanceMap, ) } if (symbol === 'nNEO' && Number(amount) < 1) { return dispatch( showErrorNotification({ message: 'Oops... you cannot migrate less than 1 nNEO.', }), ) } const hexRemark = N2.u.str2hexstring(TO_ACCOUNT.address) const hexTagRemark = N2.u.str2hexstring('Neon Desktop Migration') const hasBalanceForRequiredFee = (MIN_FEE = 1) => { if ( !balances.GAS || (balances.GAS && toBigNumber(balances.GAS).lt(MIN_FEE)) ) { return false } return true } const feeIsRequired = () => { const userMustPayFee = (symbol === 'NEO' && Number(amount) < 10) || (symbol === 'GAS' && Number(amount) < 20) || (symbol === 'CGAS' && Number(amount) < 20) || (symbol === 'nNEO' && Number(amount) < 10) return userMustPayFee } if (!hasBalanceForRequiredFee() && feeIsRequired()) { const generateMinRequirementString = () => { const requirementMap = { GAS: ' OR migrate at least 20 GAS.', NEO: ' OR migrate at least 10 NEO.', nNEO: '.', CGAS: '.', OTHER: '.', } if (requirementMap[symbol]) { return requirementMap[symbol] } return requirementMap.OTHER } const message = `Account does not have enough to cover the 1 GAS fee... Please transfer at least 1 GAS to ${ FROM_ACCOUNT.address } to proceed${generateMinRequirementString()}` const error = new Error(message) dispatch( showErrorNotification({ message, autoDismiss: 10000, }), ) return reject(error) } const CONFIG = { api: provider, account: FROM_ACCOUNT, intents: intent, fees: feeIsRequired() ? 1.0 : null, script, signingFunction: null, publicKey, error: false, } dispatch( showInfoNotification({ message: 'Broadcasting transaction to network...', autoDismiss: 0, }), ) if (isHardwareSend) { dispatch( showInfoNotification({ message: 'Please sign the transaction on your hardware device', autoDismiss: 0, }), ) CONFIG.signingFunction = signingFunction } let c = await N2.api.fillSigningFunction(CONFIG) c = await N2.api.fillUrl(c) // if (net !== 'TestNet') { c = await N2.api.fillBalance(c) if (symbol === 'GAS' || symbol === 'NEO') { const { balance } = c if ( balance.assets[symbol].unspent.length && balance.assets[symbol].unspent.length > 15 ) { dispatch( showErrorNotification({ message: 'This migration transaction has an excessive number of UTXO inputs and will require extra GAS in fees. Consider sending all your (GAS|NEO) to yourself first in order to consolidate your UTXOs into a single input before migrating, in order to avoid the extra fee.', }), ) return reject() } } c = script ? await N2.api.createInvocationTx(c) : await N2.api.createContractTx(c) c.tx.attributes.push( new N2.tx.TransactionAttribute({ usage: N2.tx.TxAttrUsage.Remark14, data: hexRemark, }), new N2.tx.TransactionAttribute({ usage: N2.tx.TxAttrUsage.Remark15, data: hexTagRemark, }), ) if (isHardwareSend) { if (script === '') { c = await api.sendAsset(c, api.neoscan).catch(e => { console.error({ e }) if (e.message === 'this.str.substr is not a function') { return null } CONFIG.error = true if (e.message === 'Navigate to the NEO app on your Ledger device') { dispatch( showInfoNotification({ message: `Please open the legacy Neo app to sign the migration transaction.`, }), ) return reject() } dispatch( showErrorNotification({ message: e.message, }), ) return reject() }) } else { c = await api.doInvoke(c, api.neoscan).catch(e => { console.error({ e }) if (e.message === 'this.str.substr is not a function') { return null } CONFIG.error = true if (e.message === 'Navigate to the NEO app on your Ledger device') { dispatch( showInfoNotification({ message: `Please open the legacy Neo app to sign the migration transaction.`, }), ) CONFIG.error = true return reject() } dispatch( showErrorNotification({ message: e.message, }), ) return reject() }) } } else { c = await N2.api.signTx(c) c = await N2.api.sendTx(c) } // eslint-disable-next-line if ((c && c.response.hasOwnProperty('txid')) || !CONFIG.error) { dispatch( showSuccessNotification({ message: 'Transaction pending! Your balance will automatically update when the blockchain has processed it.', }), ) // $FlowFixMe if (CONFIG.tx.hash) { dispatch( addPendingTransaction.call({ address: CONFIG.account.address, tx: { hash: CONFIG.tx.hash, sendEntries, }, net, }), ) } else { dispatch( addPendingTransaction.call({ address: c.account.address, tx: { hash: c.response.txid, sendEntries, }, net, }), ) } return resolve() } } catch (e) { console.error(e) dispatch( showErrorNotification({ message: `Oops... Something went wrong please try again. ${ e.message }`, }), ) return reject(e) } })
'use strict'; describe('angucomplete-alt', function() { var $compile, $scope, $timeout; var KEY_DW = 40, KEY_UP = 38, KEY_ES = 27, KEY_EN = 13, KEY_DEL = 46, KEY_TAB = 9, KEY_BS = 8; beforeEach(module('angucomplete-alt')); beforeEach(inject(function(_$compile_, $rootScope, _$timeout_) { $compile = _$compile_; $scope = $rootScope.$new(); $timeout = _$timeout_; })); describe('Render', function() { it('should render input element with given id plus _value', function() { var element = angular.element('<div angucomplete-alt id="ex1" selected-object="selectedCountry" title-field="name"></div>'); $scope.selectedCountry = null; $compile(element)($scope); $scope.$digest(); expect(element.find('#ex1_value').length).toBe(1); }); it('should render planceholder string', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name"/>'); $scope.selectedCountry = null; $compile(element)($scope); $scope.$digest(); expect(element.find('#ex1_value').attr('placeholder')).toEqual('Search countries'); }); it('should render maxlength string', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" maxlength="25" />'); $scope.selectedCountry = null; $compile(element)($scope); $scope.$digest(); expect(element.find('#ex1_value').attr('maxlength')).toEqual('25'); }); it('should render default type attribute for input element if not explicitly specified', function() { var element = angular.element('<div angucomplete-alt id="ex1" selected-object="selectedCountry" title-field="name"></div>'); $scope.selectedCountry = null; $compile(element)($scope); $scope.$digest(); expect(element.find('#ex1_value').attr('type')).toEqual('text'); }); }); describe('Local data', function() { it('should show search results after 3 letter is entered', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); expect(element.find('.angucomplete-row').length).toBe(0); e.which = 108; // letter: l inputField.val('al'); inputField.trigger('input'); inputField.trigger(e); expect(element.find('.angucomplete-row').length).toBe(0); e.which = 98; // letter: b inputField.val('alb'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBeGreaterThan(0); }); it('should show search results after 1 letter is entered with minlength being set to 1', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBeGreaterThan(0); }); it('should show search results after 2 letters are entered and hide results when a letter is deleted', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="2"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); expect(element.find('.angucomplete-row').length).toBe(0); e.which = 108; // letter: l inputField.val('al'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBe(2); // delete a char e.which = KEY_DEL; inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); expect(element.find('.angucomplete-row').length).toBe(0); }); it('should reset selectedObject to undefined when input changes', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_DW; inputField.trigger(eKeydown); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect($scope.selectedCountry.originalObject).toEqual({name: 'Afghanistan', code: 'AF'}); inputField.focus(); inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect($scope.selectedCountry).toBeUndefined(); }); describe('incomplete local data', function() { it('should not throw errors', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.countrySelected = null; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {code: 'AX'}, {name: 'Albania'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); expect(function() { $timeout.flush(); }).not.toThrow(); }); }); }); describe('Set results', function() { it('should set scope.results[0].title', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name" title-field="name" minlength="1"/>'); $scope.names = [ {name: 'John'}, {name: 'Tim'}, {name: 'Wanda'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].title).toBe('John'); }); it('should set scope.results[0].title for two title fields', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="firstName" title-field="firstName,lastName" minlength="1"/>'); var lastName = 'Doe', firstName = 'John'; $scope.names = [ {firstName: 'John', lastName: 'Doe'}, {firstName: 'Tim', lastName: 'Doe'}, {firstName: 'Wanda', lastName: 'Doe'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].title).toBe(firstName + ' ' + lastName); }); it('should set scope.results[0].title to dotted attribute', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name.first" title-field="name.first,name.last" minlength="1"/>'); var first = 'John'; var last = 'Doe'; $scope.names = [ { name: { first: first, last: last } } ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].title).toBe(first + ' ' + last); }); it('should set scope.results[0].description', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name" title-field="name" description-field="desc" minlength="1"/>'); var description = 'blah blah blah'; $scope.names = [ {name: 'John', desc: description} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].description).toBe(description); }); it('should set scope.results[0].description to dotted attribute', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name" title-field="name" description-field="desc.short" minlength="1"/>'); var desc = 'short desc...'; $scope.names = [ { name: 'John', desc: { long: 'very very long description...', short: desc } } ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].description).toBe(desc); }); it('should set scope.results[0].image', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name" title-field="name" image-field="pic" minlength="1"/>'); var image = 'some pic'; $scope.names = [ {name: 'John', pic: image} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].image).toBe(image); }); it('should set scope.results[0].image to dotted attribute', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" local-data="names" search-fields="name" title-field="name" image-field="pic.small" minlength="1"/>'); var image = 'small pic'; $scope.names = [ { name: 'John', pic: { large: 'large pic', mid: 'medium pic', small: image } } ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'j'.charCodeAt(0); inputField.val('j'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.isolateScope().results[0].image).toBe(image); }); }); describe('Local Data', function() { it('should set $scope.searching to false', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'a'.charCodeAt(0); inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); expect(element.isolateScope().searching).toBe(false); }); }); describe('Remote API', function() { var $httpBackend; beforeEach(inject(function(_$httpBackend_) { $httpBackend = _$httpBackend_; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should process via custom handler', inject(function($http) { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-api-handler="postFn" search-fields="name" title-field="name" remote-url-data-field="data" minlength="1"/>'); var url = '/api'; $scope.postFn = function(str, timeout) { return $http.post(url, {q: str}, {timeout: timeout}); }; $compile(element)($scope); $scope.$digest(); var queryTerm = 'j'; var results = {data: [{name: 'john'}]}; $httpBackend.expectPOST('/api', {q: queryTerm}).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = queryTerm.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); $httpBackend.flush(); expect(element.find('.angucomplete-row').length).toBe(1); })); it('should url encode input string', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" remote-url-error-callback="errorCB" minlength="1"/>'); $scope.errorCB = jasmine.createSpy('errorCB'); $compile(element)($scope); $scope.$digest(); var queryTerm = '//'; var results = {data: [{name: 'john'}]}; var encodedQueryTerm = encodeURIComponent(queryTerm); $httpBackend.expectGET('names?q=' + encodedQueryTerm).respond(0); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = '/'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); $httpBackend.flush(); }); it('should not do anything when request is canceled', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" remote-url-error-callback="errorCB" minlength="1"/>'); $scope.errorCB = jasmine.createSpy('errorCB'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{name: 'john'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(0); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); $httpBackend.flush(); expect($scope.errorCB).not.toHaveBeenCalled(); }); it('should call $http with given url and param', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" minlength="1"/>'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{name: 'john'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); $httpBackend.flush(); }); it('should set $scope.searching to false after success', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" minlength="1"/>'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{name: 'john'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.isolateScope().searching).toBe(true); $timeout.flush(); $httpBackend.flush(); expect(element.isolateScope().searching).toBe(false); }); it('should process dotted data attribute', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="search.data" title-field="name" minlength="1"/>'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = { meta: { offset: 0, total: 1 }, search: { seq_id: 1234567890, data: [ {name: 'john'} ] } }; $httpBackend.expectGET('names?q=' + queryTerm).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); $httpBackend.flush(); expect(element.isolateScope().results[0].originalObject).toEqual(results.search.data[0]); }); it('should not throw an exception when match-class is set and remote api returns bogus results (issue #2)', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" description="type" minlength="1" match-class="highlight"/>'); $compile(element)($scope); $scope.$digest(); var results = {data: [{name: 'tim', type: 'A'}]}; $httpBackend.expectGET('names?q=a').respond(200, results); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); $httpBackend.flush(); expect(element.isolateScope().searching).toBe(false); }); it('should call error callback when it is given', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="name" remote-url-data-field="data" remote-url-error-callback="errorCallback" title-field="name" minlength="1"/>'); $scope.errorCallback = jasmine.createSpy('errorCallback'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{name: 'john'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(500, 'Internal server error'); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); $httpBackend.flush(); expect($scope.errorCallback).toHaveBeenCalled(); }); }); describe('request formatter function for ajax request', function() { it('should process the request with the given function', inject(function($httpBackend) { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names" search-fields="name" remote-url-data-field="data" remote-url-request-formatter="dataFormatFn" title-field="name" minlength="1"/>'); var sequenceNum = 1234567890; $scope.dataFormatFn = function(str) { return {q: str, sequence: sequenceNum}; }; $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{name: 'john'}]}; $httpBackend.expectGET('names?q=' + queryTerm + '&sequence=' + sequenceNum).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); $httpBackend.flush(); $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); })); }); describe('custom data formatter function for ajax response', function() { var $httpBackend; beforeEach(inject(function(_$httpBackend_) { $httpBackend = _$httpBackend_; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should process normarlly if not given', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url="names?q=" search-fields="first" remote-url-data-field="data" title-field="name" minlength="1"/>'); $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{first: 'John', last: 'Doe'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); $httpBackend.flush(); expect(element.isolateScope().results[0].originalObject).toEqual(results.data[0]); }); it('should run response data through formatter if given', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search names" selected-object="selected" remote-url-response-formatter="dataConverter" remote-url="names?q=" search-fields="name" remote-url-data-field="data" title-field="name" minlength="1"/>'); $scope.dataConverter = function(rawData) { var data = rawData.data; for (var i = 0; i < data.length; i++) { data[i].name = data[i].last + ', ' + data[i].first; } return rawData; }; $compile(element)($scope); $scope.$digest(); var queryTerm = 'john'; var results = {data: [{first: 'John', last: 'Doe'}]}; $httpBackend.expectGET('names?q=' + queryTerm).respond(200, results); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 'n'.charCodeAt(0); inputField.val(queryTerm); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); $httpBackend.flush(); expect(element.isolateScope().results[0].originalObject).toEqual({first: 'John', last: 'Doe', name: 'Doe, John'}); }); }); describe('clear result', function() { it('should clear input when clear-selected is true', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" clear-selected="true"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_DW; inputField.trigger(eKeydown); expect(element.isolateScope().currentIndex).toBe(0); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect($scope.selectedCountry.originalObject).toEqual({name: 'Afghanistan', code: 'AF'}); expect(element.isolateScope().searchStr).toBe(null); }); }); describe('blur', function() { it('should hide dropdown when focus is lost', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" clear-selected="true"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); inputField.blur(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeTruthy(); }); it('should cancel hiding the dropdown if it happens within pause period', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" clear-selected="true"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); inputField.blur(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); inputField.focus(); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeTruthy(); }); }); describe('TAB for selecting', function() { it('should select the selected suggestion when TAB is pressed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_DW; inputField.trigger(eKeydown); expect(element.isolateScope().currentIndex).toBe(0); eKeydown.which = KEY_TAB; inputField.trigger(eKeydown); $scope.$digest(); expect($scope.selectedCountry.originalObject).toEqual($scope.countries[0]); }); it('should select the first suggestion when TAB is pressed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_TAB; inputField.trigger(eKeydown); $scope.$digest(); expect($scope.selectedCountry.originalObject).toEqual($scope.countries[0]); }); it('should take the input field value when TAB is pressed when there is no selection', function() { var element = angular.element('<form><div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" override-suggestions="true"/></form>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('z'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBe(0); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_TAB; inputField.trigger(eKeydown); inputField.blur(); expect($scope.selectedCountry.originalObject).toEqual('z'); }); it('should not select the first suggestion when TAB is pressed when override-suggestions is set', function() { var element = angular.element('<form><div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" override-suggestions="true"/></form>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_TAB; inputField.trigger(eKeydown); inputField.blur(); expect($scope.selectedCountry.originalObject).toEqual('a'); }); }); describe('override suggestions', function() { it('should override suggestions when enter is pressed but no suggestion is selected', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" override-suggestions="true"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('abc'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect($scope.selectedCountry.originalObject).toEqual('abc'); inputField.blur(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeTruthy(); }); it('should override suggestions when enter is pressed but no suggestion is selected also incorporate with clear-selected if it is set', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" override-suggestions="true" clear-selected="true"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('abc'); inputField.trigger('input'); inputField.trigger(e); $timeout.flush(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeFalsy(); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect($scope.selectedCountry.originalObject).toEqual('abc'); inputField.blur(); expect(element.find('#ex1_dropdown').hasClass('ng-hide')).toBeTruthy(); expect(element.isolateScope().searchStr).toBe(null); }); }); describe('selectedObject callback', function() { it('should call selectedObject callback if given', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); var selected = false; $scope.countrySelected = function(value) { selected = true; }; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); expect(selected).toBe(false); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('#ex1_dropdown').length).toBe(1); var eKeydown = $.Event('keydown'); eKeydown.which = KEY_DW; inputField.trigger(eKeydown); expect(element.isolateScope().currentIndex).toBe(0); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect(selected).toBe(true); }); }); describe('initial value', function() { it('should set initial value from string', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1" initial-value="initialValue"/>'); $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); $scope.initialValue = 'Japan'; $scope.$digest(); expect(element.isolateScope().searchStr).toBe('Japan'); }); it('should set initial value from object', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="grabCountryCode" local-data="countries" search-fields="name" title-field="name" minlength="1" initial-value="initialValue"/>'); $scope.countryCode = null; $scope.grabCountryCode = function(value) { $scope.countryCode = value.originalObject.code; }; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); $scope.initialValue = {name: 'Aland Islands', code: 'AX'}; $scope.$digest(); expect(element.isolateScope().searchStr).toBe('Aland Islands'); expect($scope.countryCode).toBe('AX'); }); it('should set validity to true', function() { var element = angular.element('<form name="form"><div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1" initial-value="initialValue" field-required="true"/></form>'); $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); $scope.initialValue = 'Japan'; $scope.$digest(); expect(element.find('#ex1').isolateScope().searchStr).toBe('Japan'); expect(element.hasClass('ng-valid')).toBe(true); }); }); describe('require field', function() { it('should add a class ng-invalid-autocomplete-required when initialized', function() { var element = angular.element('<form name="form"><div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1" field-required="true"/></form>'); $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(true); }); it('should add a class ng-invalid-autocomplete-required when selection is made', function() { var element = angular.element('<form name="form"><div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1" field-required="true"/></form>'); $scope.countrySelected = null; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(true); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBe(3); // make a selection var eKeydown = $.Event('keydown'); eKeydown.which = KEY_DW; inputField.trigger(eKeydown); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(false); expect($scope.countrySelected).toBeDefined(); // delete a char inputField.focus(); eKeyup.which = KEY_DEL; inputField.val('Afghanista'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(true); expect(element.find('.angucomplete-row').length).toBe(1); expect($scope.countrySelected).toBeUndefined(); // make a selection again eKeydown.which = KEY_DW; inputField.trigger(eKeydown); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(false); expect($scope.countrySelected).toBeDefined(); }); }); describe('Input changed callback', function() { it('should call input changed callback when input is changed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="selectedCountry" local-data="countries" search-fields="name" title-field="name" minlength="1" input-changed="inputChanged"/>'); $scope.selectedCountry = undefined; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $scope.inputChanged = jasmine.createSpy('inputChanged'); $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var e = $.Event('keyup'); e.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(e); expect($scope.inputChanged).toHaveBeenCalledWith('a'); }); }); describe('Auto Selecting', function() { it('should select the first suggestion when the search text fully matches any of the attributes', function() { var element = angular.element('<div angucomplete-alt auto-match="true" id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="name" title-field="name" minlength="2"/>'); $scope.selectedPerson = undefined; $scope.people = [ {name: 'Jim Beam', email: 'jbeam@aol.com'}, {name: 'Elvis Presly', email: 'theking@gmail.com'}, {name: 'John Elway', email: 'elway@nfl.com'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var y = $.Event('keyup'); y.which = 121; inputField.val('john elway'); inputField.trigger('input'); inputField.trigger(y); $timeout.flush(); expect($scope.selectedPerson.originalObject).toEqual($scope.people[2]); }); it('should not throw an error when description is not defined', function() { var element = angular.element('<div angucomplete-alt auto-match="true" id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="name,email" title-field="name" description-field="email" minlength="1"/>'); $scope.selectedPerson = undefined; $scope.people = [ {name: 'Jim Beam', email: 'jbeam@aol.com'}, {name: 'Elvis Presly'}, {name: 'John Elway', email: 'elway@nfl.com'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var y = $.Event('keyup'); y.which = 121; inputField.val('e'); inputField.trigger('input'); inputField.trigger(y); expect(function() { $timeout.flush(); }).not.toThrow(); }); }); describe('key event handling', function() { it('should query again when down arrow key is pressed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="1"/>'); $scope.countrySelected = null; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.trigger('input'); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBe(3); // ESC once eKeyup.which = KEY_ES; inputField.trigger(eKeyup); expect(element.find('.angucomplete-row').length).toBe(0); // Down arrow inputField.focus(); eKeyup.which = KEY_DW; inputField.trigger('input'); inputField.trigger(eKeyup); expect(element.find('.angucomplete-row').length).toBe(3); }); }); describe('Clear input', function() { it('should clear input fields', function() { var element = angular.element( '<form name="name">' + ' <div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson1" local-data="people" search-fields="firstName" title-field="firstName" minlength="1"/>' + ' <div angucomplete-alt id="ex2" placeholder="Search people" selected-object="selectedPerson2" local-data="people" search-fields="firstName" title-field="firstName" minlength="1"/>' + '</form>' ); $scope.clearInput = function(id) { $scope.$broadcast('angucomplete-alt:clearInput', id); }; $scope.selectedPerson1 = undefined; $scope.selectedPerson2 = undefined; $scope.people = [ {firstName: 'Emma'}, {firstName: 'Elvis'}, {firstName: 'John'} ]; $compile(element)($scope); $scope.$digest(); var inputField1 = element.find('#ex1_value'); var inputField2 = element.find('#ex2_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField1.val('e'); inputField1.trigger('input'); eKeyup.which = 'e'.charCodeAt(0); inputField1.trigger(eKeyup); $timeout.flush(); inputField2.val('j'); inputField2.trigger('input'); eKeyup.which = 'j'.charCodeAt(0); inputField2.trigger(eKeyup); $timeout.flush(); expect(inputField1.val()).toEqual('e'); expect(inputField2.val()).toEqual('j'); $scope.clearInput('ex1'); $scope.$digest(); // should only clear #ex1 expect(inputField1.val()).toBe(''); expect(inputField2.val()).toBe('j'); inputField1.val('e'); inputField1.trigger('input'); eKeyup.which = 'e'.charCodeAt(0); inputField1.trigger(eKeyup); $timeout.flush(); expect(inputField1.val()).toEqual('e'); expect(inputField2.val()).toEqual('j'); $scope.clearInput(); $scope.$digest(); // should clear both expect(inputField1.val()).toBe(''); expect(inputField2.val()).toBe(''); }); it('should clear input fields', function() { var element = angular.element( '<form name="name">' + ' <div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="firstName" title-field="firstName" minlength="1" field-required="true"/>' + '</form>' ); $scope.clearInput = function(id) { $scope.$broadcast('angucomplete-alt:clearInput', id); }; $scope.selectedPerson = undefined; $scope.people = [ {firstName: 'Emma'}, {firstName: 'Elvis'}, {firstName: 'John'} ]; $compile(element)($scope); $scope.$digest(); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(true); var inputField = element.find('#ex1_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField.val('e'); inputField.trigger('input'); eKeyup.which = 'e'.charCodeAt(0); inputField.trigger(eKeyup); $timeout.flush(); expect(element.find('.angucomplete-row').length).toBe(2); // make a selection eKeydown.which = KEY_DW; inputField.trigger(eKeydown); eKeydown.which = KEY_EN; inputField.trigger(eKeydown); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(false); expect($scope.selectedPerson).toBeDefined(); $scope.clearInput('ex1'); $scope.$digest(); expect(inputField.val()).toBe(''); expect(element.hasClass('ng-invalid-autocomplete-required')).toBe(true); }); }); describe('Update input field text', function() { it('should update input field when up/down arrow key is pressed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="firstName,middleName,surname" title-field="firstName,surname" minlength="1"/>'); $scope.selectedPerson = undefined; $scope.people = [ {firstName: 'Emma', middleName: 'C.D.', surname: 'Watson'}, {firstName: 'Elvis', middleName: 'A.', surname: 'Presly'}, {firstName: 'John', middleName: 'A.', surname: 'Elway'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField.val('e'); inputField.trigger('input'); eKeyup.which = 101;// letter e inputField.trigger(eKeyup); $timeout.flush(); // Down arrow 2 times eKeydown.which = KEY_DW; inputField.trigger(eKeydown); inputField.trigger(eKeydown); expect(inputField.val()).toEqual('Elvis Presly'); // Up arrow 1 time eKeydown.which = KEY_UP; inputField.trigger(eKeydown); expect(inputField.val()).toEqual('Emma Watson'); }); it('should update input field when up/down arrow key is pressed with match class on', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="firstName,middleName,surname" title-field="firstName,surname" minlength="1" match-class="highlight"/>'); $scope.selectedPerson = undefined; $scope.people = [ {firstName: 'Emma', middleName: 'C.D.', surname: 'Watson'}, {firstName: 'Elvis', middleName: 'A.', surname: 'Presly'}, {firstName: 'John', middleName: 'A.', surname: 'Elway'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField.val('e'); inputField.trigger('input'); eKeyup.which = 101;// letter e inputField.trigger(eKeyup); $timeout.flush(); // Down arrow 2 times eKeydown.which = KEY_DW; inputField.trigger(eKeydown); inputField.trigger(eKeydown); expect(inputField.val()).toEqual('Elvis Presly'); // Up arrow 1 time eKeydown.which = KEY_UP; inputField.trigger(eKeydown); expect(inputField.val()).toEqual('Emma Watson'); }); it('should change back to original when it goes up to input field', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="firstName,middleName,surname" title-field="firstName,surname" minlength="1"/>'); $scope.selectedPerson = undefined; $scope.people = [ {firstName: 'Emma', middleName: 'C.D.', surname: 'Watson'}, {firstName: 'Elvis', middleName: 'A.', surname: 'Presly'}, {firstName: 'John', middleName: 'A.', surname: 'Elway'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField.val('e'); inputField.trigger('input'); eKeyup.which = 101;// letter e inputField.trigger(eKeyup); $timeout.flush(); // Down arrow 2 times eKeydown.which = KEY_DW; inputField.trigger(eKeydown); inputField.trigger(eKeydown); expect(inputField.val()).toEqual('Elvis Presly'); // Up arrow 2 time and go back to original input eKeydown.which = KEY_UP; inputField.trigger(eKeydown); inputField.trigger(eKeydown); expect(inputField.val()).toEqual('e'); }); it('should reset input field when ESC key is pressed after up/down arrow key is pressed', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search people" selected-object="selectedPerson" local-data="people" search-fields="firstName,middleName,surname" title-field="firstName,surname" minlength="1"/>'); $scope.selectedPerson = undefined; $scope.people = [ {firstName: 'Emma', middleName: 'C.D.', surname: 'Watson'}, {firstName: 'Elvis', middleName: 'A.', surname: 'Presly'}, {firstName: 'John', middleName: 'A.', surname: 'Elway'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); var eKeydown = $.Event('keydown'); var eKeyup = $.Event('keyup'); inputField.val('e'); inputField.trigger('input'); eKeyup.which = 101;// letter e inputField.trigger(eKeyup); $timeout.flush(); // Down arrow 2 times eKeydown.which = KEY_DW; inputField.trigger(eKeydown); inputField.trigger(eKeydown); // Hit ESC eKeyup.which = KEY_ES; inputField.trigger(eKeyup); expect(inputField.val()).toEqual('e'); }); }); describe('set minlenght to 0', function() { it('should show all items when focused', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="0"/>'); $scope.countrySelected = null; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); expect(element.find('.angucomplete-row').length).toBe(0); // TODO: should replace all triggers with this triggerHandler // http://sravi-kiran.blogspot.co.nz/2013/12/TriggeringEventsInAngularJsDirectiveTests.html inputField.triggerHandler('focus'); $scope.$digest(); expect(element.find('.angucomplete-row').length).toBe(3); }); it('should remove highlight when input becomes empty', function() { var element = angular.element('<div angucomplete-alt id="ex1" placeholder="Search countries" selected-object="countrySelected" local-data="countries" search-fields="name" title-field="name" minlength="0" match-class="highlight"/>'); $scope.countrySelected = null; $scope.countries = [ {name: 'Afghanistan', code: 'AF'}, {name: 'Aland Islands', code: 'AX'}, {name: 'Albania', code: 'AL'} ]; $compile(element)($scope); $scope.$digest(); var inputField = element.find('#ex1_value'); inputField.triggerHandler('focus'); $scope.$digest(); expect(element.find('.angucomplete-row').length).toBe(3); element.find('.angucomplete-row .highlight').each(function() { expect($(this).text().length).toBe(0); }); var eKeyup = $.Event('keyup'); eKeyup.which = 97; // letter: a inputField.val('a'); inputField.triggerHandler('input'); inputField.trigger(eKeyup); $timeout.flush(); element.find('.angucomplete-row .highlight').each(function() { expect($(this).text().length).toBeGreaterThan(0); }); eKeyup.which = KEY_DEL; inputField.val(''); inputField.triggerHandler('input'); inputField.trigger(eKeyup); $scope.$digest(); element.find('.angucomplete-row .highlight').each(function() { expect($(this).text().length).toBe(0); }); expect(element.find('.angucomplete-row').length).toBe(3); }); }); });
/*global App, _, $fh*/ /* Backbone View */ App.View.WeatherSampleView = App.View.BaseView.extend({ templateId: 'weather', model: App.models.weatherPage, events: { 'click .get-geo-btn': 'getLocation', 'click .get-weather-btn': 'getWeatherData' }, initialize: function(){ _.bindAll(this, 'getLocation', 'gotLocation', 'getWeatherData', 'gotWeatherData'); }, getLocation: function(){ var self = this; self.dataReset(); if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(pos){ self.gotLocation(pos); }, function(err){ self.dataError('Failed to get location : ' + err.message); }, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }); } }, gotLocation: function(pos){ this.coords = pos.coords; this.$el.find('#locationField').val('lat = ' + this.coords.latitude + '; lon = ' + this.coords.longitude); this.$el.find('.hidden').removeClass('hidden'); }, getWeatherData: function(){ var self = this; self.dataReset(); var lat = this.coords.latitude; var lon = this.coords.longitude; $fh.cloud({ path:'getWeather', data: { lat: lat, lon: lon } }, function(res){ self.gotWeatherData(res); }, function(msg){ self.dataError(msg); }); }, gotWeatherData: function(data){ this.$el.find('.response_content').removeClass('alert-error').removeClass('alert').html(App.Templates['weather-data'](data)); } });
Oskari.registerLocalization({ "lang": "th", "key": "DivManazer", "value": { "LanguageSelect": { "title": "ภาษา", "tooltip": "NOT TRANSLATED", "languages": { "af": "แอฟริกานส์", "ak": "อาคัน", "am": "อัมฮารา", "ar": "อาหรับ", "az": "อาเซอร์ไบจาน", "be": "เบลารุส", "bg": "บัลแกเรีย", "bm": "บัมบารา", "bn": "เบงกาลี", "bo": "ทิเบต", "br": "เบรตัน", "bs": "บอสเนีย", "ca": "กาตาลัง", "cs": "เช็ก", "cy": "เวลส์", "da": "เดนมาร์ก", "de": "เยอรมัน", "dz": "ซองคา", "ee": "เอเว", "el": "กรีก", "en": "อังกฤษ", "eo": "เอสเปอรันโต", "es": "สเปน", "et": "เอสโตเนีย", "eu": "บัสเก", "fa": "เปอร์เซีย", "ff": "ฟูลาฮ์", "fi": "ฟินแลนด์", "fo": "แฟโร", "fr": "ฝรั่งเศส", "fy": "ฟริเซียนตะวันตก", "ga": "ไอริช", "gd": "สกอตส์กาลิก", "gl": "กาลิเซีย", "gu": "คุชราต", "ha": "เฮาชา", "he": "ฮิบรู", "hi": "ฮินดี", "hr": "โครเอเชีย", "hu": "ฮังการี", "hy": "อาร์เมเนีย", "ia": "อินเตอร์ลิงกัว", "id": "อินโดนีเชีย", "ig": "อิกโบ", "is": "ไอซ์แลนด์", "it": "อิตาลี", "ja": "ญี่ปุ่น", "ka": "จอร์เจีย", "ki": "กีกูยู", "kk": "คาซัค", "kl": "กรีนแลนด์", "km": "เขมร", "kn": "กันนาดา", "ko": "เกาหลี", "ks": "กัศมีร์", "kw": "คอร์นิช", "ky": "คีร์กีซ", "lb": "ลักเซมเบิร์ก", "lg": "ยูกันดา", "ln": "ลิงกาลา", "lo": "ลาว", "lt": "ลิทัวเนีย", "lu": "ลูบา-กาตองกา", "lv": "ลัตเวีย", "mg": "มาลากาซี", "mk": "มาซิโดเนีย", "ml": "มาลายาลัม", "mn": "มองโกเลีย", "mr": "มราฐี", "ms": "มาเลย์", "mt": "มอลตา", "my": "พม่า", "nb": "นอร์เวย์บุคมอล", "nd": "เอ็นเดเบเลเหนือ", "ne": "เนปาล", "nl": "ดัตช์", "nn": "นอร์เวย์นีนอสก์", "om": "โอโรโม", "or": "โอริยา", "os": "ออสเซเตีย", "pa": "ปัญจาบ", "pl": "โปแลนด์", "ps": "พาชตู", "pt": "โปรตุเกส", "qu": "ควิชัว", "rm": "โรแมนซ์", "rn": "บุรุนดี", "ro": "โรมาเนีย", "ru": "รัสเซีย", "rw": "รวันดา", "se": "ซามิเหนือ", "sg": "แซงโก", "si": "สิงหล", "sk": "สโลวัก", "sl": "สโลวีเนีย", "sn": "โชนา", "so": "โซมาลี", "sq": "แอลเบเนีย", "sr": "เซอร์เบีย", "sv": "สวีเดน", "sw": "สวาฮีลี", "ta": "ทมิฬ", "te": "เตลูกู", "th": "ไทย", "ti": "ติกริญญา", "tn": "บอตสวานา", "to": "ตองกา", "tr": "ตุรกี", "ts": "ซิิตซองกา", "ug": "อุยกัว", "uk": "ยูเครน", "ur": "อูรดู", "uz": "อุซเบก", "vi": "เวียดนาม", "yi": "ยิว", "yo": "โยรูบา", "zh": "จีน", "zu": "ซูลู" } } } });
import {combineReducers} from 'redux'; import * as learnLifeCycleReduces from './learn/life-cycle'; const appReducers = combineReducers({ ...learnLifeCycleReduces, }); export default appReducers;
module.exports = function(config) { 'use strict'; config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js', 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-mocks.js', 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-resource.js', 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.compat.js', 'src/*.js', 'test/*.js' ], reporters: ['mocha'], port: 9876, runnerPort: 9100, colors: true, autoWatch: true, browsers: ['PhantomJS'], singleRun: false }); };
var everyauth = require('everyauth') , util = require('util') , siteConf = require('./getConfig') , users = require('./Models/connectFacebook').fbUser; users = new users(); var https = require('https'); module.exports = function Server(expressInstance, siteConf) { everyauth.debug = siteConf.debug; everyauth.everymodule.handleLogout( function (req, res) { delete req.session.user; if(typeof req.session.doc != 'undefined' || req.session.doc != undefined) { delete req.session.doc; } req.logout(); res.writeHead(303, { 'Location': this.logoutRedirectPath() }); res.end(); }); // Facebook if(siteConf.external && siteConf.external.facebook) { everyauth.facebook .appId(siteConf.external.facebook.appId) .appSecret(siteConf.external.facebook.appSecret) .findOrCreateUser(function(session, accessToken, accessTokenExtra, fbUser) { if(siteConf.debug) { //console.log('fbUser: ' + util.inspect(fbUser)); //console.log('Session: ' + util.inspect(session)); //console.log('accessToken: ' + util.inspect(accessToken)); //console.log('accessTokenExtra: ' + util.inspect(accessTokenExtra)); } users.findOrCreateUserByFacebookData(session, accessToken, accessTokenExtra, fbUser); return true; }) .redirectPath('/'); } // Twitter if (siteConf.external && siteConf.external.twitter) { everyauth.twitter .myHostname(siteConf.uri) .consumerKey(siteConf.external.twitter.consumerKey) .consumerSecret(siteConf.external.twitter.consumerSecret) .findOrCreateUser(function (session, accessToken, accessSecret, twitterUser) {return true;}).redirectPath('/'); } everyauth.helpExpress(expressInstance, { userAlias: '__user__' }); // Fetch and format data so we have an easy object with user data to work with. function normalizeUserData() { function handler(req, res, next) { if (req.session && !req.session.user && req.session.auth && req.session.auth.loggedIn) { if(siteConf.debug) { //console.log(util.inspect(req, true, null)); //console.log(util.inspect(res, true, null)); //console.log(next); } var user = {}; if (req.session.auth.twitter) { user.image = req.session.auth.twitter.user.profile_image_url; user.name = req.session.auth.twitter.user.name; user.id = 'twitter-'+req.session.auth.twitter.user.id_str; } if (req.session.auth.facebook) { user.image = req.session.auth.facebook.user.picture; user.name = req.session.auth.facebook.user.name; user.id = 'facebook-'+req.session.auth.facebook.user.id; // Need to fetch the users image... https.get({ 'host': 'graph.facebook.com' , 'path': '/me/picture?access_token='+req.session.auth.facebook.accessToken }, function(response) { user.image = response.headers.location; req.session.user = user; next(); }).on('error', function(e) { req.session.user = user; next(); }); return; } req.session.user = user; if(siteConf.debug) { console.log(user); console.log(req.session.user); } } next(); } return handler; } return { 'middleware': { 'auth': everyauth.middleware , 'normalizeUserData': normalizeUserData } }; };
/** * Templates */ Router.onBeforeAction('loading'); Router.configure({ loadingTemplate: 'loading' }); Router.map(function(){ this.route('match', { path: 'match/:id', waitOn: function() { match = Matchs.findOne({country: 'brazil'}); console.log(match); return [ Meteor.subscribe('tweets', this.params.id), Meteor.subscribe('messages', this.params.id)]; }, data: function (){ templateData = { messages: Messages.find({}, { sort: { time: -1 }}), countBrazil: Tweets.find({ country: 'brazil' }).count(), countFrance: Tweets.find({ country: 'france' }).count() }; return templateData; } }); });
/*global define*/ /*global describe, it, expect*/ /*global jasmine*/ /*global beforeEach, afterEach*/ /*jslint white: true*/ define([ 'jquery', 'GenomeCategorizer', 'testUtil', 'common/runtime', 'base/js/namespace', 'kbaseNarrative' ], ( $, GenomeCategorizer, TestUtil, Runtime, Jupyter, Narrative ) => { 'use strict'; describe('Test the GenomeCategorizer widget', () => { let $div = null; beforeEach(() => { jasmine.Ajax.install(); $div = $('<div>'); Jupyter.narrative = new Narrative(); Jupyter.narrative.getAuthToken = () => { return 'NotARealToken!' }; }); afterEach(() => { jasmine.Ajax.uninstall(); $div.remove(); }); it('Should properly render data', (done) => { let genomecatgorizerdata = { "attribute_data":["EamA family transporter RarD","hydrogenase nickel incorporation protein HypA"], "attribute_type":"functional_roles", "class_list_mapping":{"N":1,"P":0}, "classifier_description":"this is my description", "classifier_handle_ref":"c061a832-1d64-4119-a2fb-75a360fa1f53", "classifier_id":"", "classifier_name":"DTCFL_DecisionTreeClassifier_entropy", "classifier_type":"DecisionTreeClassifier", "lib_name":"sklearn", "number_of_attributes":3320, "number_of_genomes":2, "training_set_ref":"35279/17/1" }; let trainingsetdata = { "classes":["P","N"], "classification_data":[ { "evidence_types":["another","some","list"], "genome_classification":"N","genome_id": "my_genome_id", "genome_name":"Acetivibrio_ethanolgignens", "genome_ref":"35279/3/1", "references":["some","list"] },{ "evidence_types":["another","some","list"], "genome_classification":"P", "genome_id":"my_genome_id", "genome_name":"Aggregatibacter_actinomycetemcomitans_serotype_b_str._SCC4092", "genome_ref":"35279/4/1", "references":["some","list"] },{ "evidence_types":["another","some","list"], "genome_classification":"N", "genome_id":"my_genome_id", "genome_name":"Afipia_felis_ATCC_53690", "genome_ref":"35279/5/1", "references":["some","list"] }], "classification_type":"my_classification_type", "description":"my_description", "name":"my_name", "number_of_classes":2, "number_of_genomes":3 }; // this code is more of less ignored, because two WS calls are made both can't be stubbed jasmine.Ajax.stubRequest('https://ci.kbase.us/services/ws').andReturn({ status: 200, statusText: 'success', contentType: 'application/json', responseHeaders: '', responseText: JSON.stringify({ version: '1.1', result: [{ data: [{data: trainingsetdata}] }] }) }); let w = new GenomeCategorizer($div, {upas: {upas: ['fake']}}); w.objData = genomecatgorizerdata; w.trainingSetData = trainingsetdata; w.render(); [ 'Overview', 'Training Set' ].forEach((str) => { expect($div.html()).toContain(str); }); // more complex structure matching let tabs = $div.find('.tabbable'); expect(tabs).not.toBeNull(); let tabsContent = $div.find('.tab-pane'); expect(tabsContent.length).toEqual(2); [ 'Classifier Name', 'DTCFL_DecisionTreeClassifier_entropy', 'Number of genomes', '3', ].forEach((str) => { expect($(tabsContent[0]).html()).toContain(str); }); expect($(tabsContent[1]).html()).toContain('Acetivibrio_ethanolgignens'); expect($(tabsContent[1]).html()).not.toContain('<table>'); done(); }); }) })
window.onload = terrainGeneration; var mapCanvas = document.getElementById('canvas'), imgSave = document.getElementById('imgSave'), settings = { roughness : 8, mapDimension : 256, unitSize : 1, mapType : 1, smoothness : 0.1, smoothIterations : 0, genShadows : false, sunX : -100, sunY : -100, sunZ : 4, render : function(){ terrainGeneration(); } }; function terrainGeneration(){ "use strict"; // Set these variables to adjust how the map is generated var mapDimension, unitSize = 0, // Power of 2 roughness = 0, genPerspective = 0, genShadows = 0, sunX = settings.sunX, sunY = settings.sunY, sunZ = settings.sunZ, mapType = 0, map = 0, mapCanvas = document.getElementById('canvas'), mapCtx = mapCanvas.getContext("2d"), voxCanvas = document.getElementById('voxelview'); // init roughness = parseInt(settings.roughness, 10); mapDimension = parseInt(settings.mapDimension, 10); unitSize = parseInt(settings.unitSize, 10); mapType = parseInt(settings.mapType, 10); genShadows = settings.genShadows; if(genShadows){ sunX = parseInt(settings.sunX, 10); sunY = parseInt(settings.sunY, 10); sunZ = parseInt(settings.sunZ, 10); } mapCanvas.width = mapDimension; mapCanvas.height = mapDimension; map = generateTerrainMap(mapDimension, unitSize, roughness); // Smooth terrain for(var i = 0; i < settings.smoothIterations; i++){ map = smooth(map, mapDimension, settings.smoothness); } // Draw everything after the terrain vals are generated drawMap(mapDimension, "canvas", map, mapType); if(genShadows){ drawShadowMap(mapDimension, sunX, sunY, sunZ); } // Round to nearest pixel function round(n) { if (n-(parseInt(n, 10)) >= 0.5){ return parseInt(n, 10) + 1; }else{ return parseInt(n, 10); } } // smooth function function smooth(data, size, amt) { /* Rows, left to right */ for (var x = 1; x < size; x++){ for (var z = 0; z < size; z++){ data[x][z] = data[x - 1][z] * (1 - amt) + data[x][z] * amt; } } /* Rows, right to left*/ for (x = size - 2; x < -1; x--){ for (z = 0; z < size; z++){ data[x][z] = data[x + 1][z] * (1 - amt) + data[x][z] * amt; } } /* Columns, bottom to top */ for (x = 0; x < size; x++){ for (z = 1; z < size; z++){ data[x][z] = data[x][z - 1] * (1 - amt) + data[x][z] * amt; } } /* Columns, top to bottom */ for (x = 0; x < size; x++){ for (z = size; z < -1; z--){ data[x][z] = data[x][z + 1] * (1 - amt) + data[x][z] * amt; } } return data; } //Create Shadowmap function drawShadowMap(size, sunPosX, sunPosY, sunHeight){ var shadowCanvas = document.createElement("canvas"), sCtx = shadowCanvas.getContext("2d"), x = 0, y = 0, idx, colorFill = {r : 0, g : 0, b : 0, a : 0}, sunX, sunY, sunZ, pX, pY, pZ, mag, dX, dY, dZ; shadowCanvas.width = shadowCanvas.height = mapDimension; var img = sCtx.createImageData(shadowCanvas.width, shadowCanvas.height), imgData = img.data; // Suns position sunX = sunPosX; sunY = sunPosY; sunZ = sunHeight; for(x = 0; x < mapDimension; x += unitSize){ for(y = 0; y < mapDimension; y += unitSize){ dX = sunX - x; dY = sunY - y; dZ = sunZ - map[x][y]; mag = Math.sqrt(dX * dX + dY * dY + dZ * dZ); dX = (dX / mag); dY = (dY / mag); dZ = (dZ / mag); pX = x; pY = y; pZ = map[x][y]; while(pX > 0 && pX < mapDimension && pY > 0 && pY < mapDimension && pZ < sunZ){ if((map[~~(pX)][~~(pY)]) > pZ){ colorFill = {r : 0, g : 0, b : 0, a : 200}; for (var w = 0; w < unitSize; w++) { for (var h = 0; h < unitSize; h++) { var pData = (~~ (x + w) + (~~ (y + h) * canvas.width)) * 4; imgData[pData] = colorFill.r; imgData[pData + 1] = colorFill.g; imgData[pData + 2] = colorFill.b; imgData[pData + 3] += colorFill.a; } } break; } pX += (dX * unitSize); pY += (dY * unitSize); pZ += (dZ * unitSize); } } } sCtx.putImageData(img, 0, 0); mapCtx.drawImage(shadowCanvas, 0, 0); var strDataURI = mapCanvas.toDataURL(); imgSave.src = strDataURI; } // Draw the map function drawMap(size, canvasId, mapData, mapType){ var canvas = document.getElementById(canvasId), ctx = canvas.getContext("2d"), x = 0, y = 0, r = 0, g = 0, b = 0, gamma = 500, colorFill = 0, img = ctx.createImageData(canvas.height, canvas.width), imgData = img.data; // colormap colors var waterStart={r:10,g:20,b:40}, waterEnd={r:39,g:50,b:63}, grassStart={r:22,g:38,b:3}, grassEnd={r:67,g:100,b:18}, mtnEnd={r:60,g:56,b:31}, mtnStart={r:67,g:80,b:18}, rocamtStart={r:90,g:90,b:90}, rocamtEnd={r:130,g:130,b:130}, snowStart={r:255,g:255,b:255}, snowEnd={r:200,g:200,b:200}; for(x = 0; x <= size; x += unitSize){ for(y = 0; y <= size; y += unitSize){ colorFill = {r : 0, g : 0, b : 0}; switch(mapType){ case 1: // Color map var data = mapData[x][y]; if (data >= 0 && data <= 0.3) { colorFill = fade(waterStart, waterEnd, 30, parseInt(data * 100, 10)); } else if (data > 0.3 && data <= 0.7) { colorFill = fade(grassStart, grassEnd, 45, parseInt(data * 100, 10) - 30); } else if (data > 0.7 && data <= 0.95) { colorFill = fade(mtnStart, mtnEnd, 15, parseInt(data * 100, 10) - 70); } else if (data > 0.95 && data <= 1) { colorFill = fade(rocamtStart, rocamtEnd, 5, parseInt(data * 100, 10) - 95); } break; case 2: // Standard var standardShade = Math.floor(map[x][y] * 250); colorFill = {r : standardShade, g : standardShade, b : standardShade}; break; case 3: // 10 shades var greyShade = Math.round(~~(mapData[x][y]*100) / 25) * 25; colorFill = {r : greyShade, g : greyShade, b : greyShade}; break; case 4: // 2 shades if(mapData[x][y] <= 0.5) { mapData[x][y] = 0; }else if(mapData[x][y] > 0.5) { mapData[x][y] = 220; } var grey = mapData[x][y]; colorFill = { r : grey, g : grey, b : grey}; break; case 5: // Section of code modified from http://www.hyper-metrix.com/processing-js/docs/index.php?page=Plasma%20Fractals if (mapData[x][y] < 0.5) { r = mapData[x][y] * gamma; } else { r = (1.0 - mapData[x][y]) * gamma; } if (mapData[x][y] >= 0.3 && mapData[x][y] < 0.8) { g = (mapData[x][y] - 0.3) * gamma; } else if (mapData[x][y] < 0.3) { g = (0.3 - mapData[x][y]) * gamma; } else { g = (1.3 - mapData[x][y]) * gamma; } if (mapData[x][y] >= 0.5) { b = (mapData[x][y] - 0.5) * gamma; } else { b = (0.5 - mapData[x][y]) * gamma; } colorFill = { r : ~~r, g : ~~g, b : ~~b}; break; } for (var w = 0; w <= unitSize; w++) { for (var h = 0; h <= unitSize; h++) { var pData = ( ~~(x + w) + ( ~~(y + h) * canvas.width)) * 4; imgData[pData] = colorFill.r; imgData[pData + 1] = colorFill.g; imgData[pData + 2] = colorFill.b; imgData[pData + 3] = 255; } } } } ctx.putImageData(img, 0, 0); // Add to an image so its easier to save var strDataURI = mapCanvas.toDataURL(); imgSave.src = strDataURI; function fade(startColor, endColor, steps, step){ var scale = step / steps, r = startColor.r + scale * (endColor.r - startColor.r), b = startColor.b + scale * (endColor.b - startColor.b), g = startColor.g + scale * (endColor.g - startColor.g); return { r: r, g: g, b: b } }; } } var gui = new dat.GUI(); gui.add(settings, 'roughness'); gui.add(settings, 'mapDimension', [64,128,256,512,1024]); gui.add(settings, 'unitSize', [1,2,4] ); gui.add(settings, 'mapType', {'Color Map' : 1, 'Gray Scale' : 2, '10 Shades' : 3, '2 Shades' : 4, 'Plasma' : 5}); gui.add(settings, 'smoothness', 0, 0.99); gui.add(settings, 'smoothIterations'); var shadowSection = gui.addFolder('Shadow Map'); shadowSection.add(settings, 'genShadows'); shadowSection.add(settings, 'sunX'); shadowSection.add(settings, 'sunY'); shadowSection.add(settings, 'sunZ'); gui.add(settings, 'render');
import 'pixi' import 'p2' import Phaser from 'phaser' import BootState from './states/Boot' import SplashState from './states/Splash' import GameState from './states/Game' import OverState from './states/Over' import config from './config' class Game extends Phaser.Game { constructor () { const docElement = document.documentElement const width = docElement.clientWidth > config.gameWidth ? config.gameWidth : docElement.clientWidth const height = docElement.clientHeight > config.gameHeight ? config.gameHeight : docElement.clientHeight super(width, height, Phaser.CANVAS, 'content', null) this.state.add('Boot', BootState, false) this.state.add('Splash', SplashState, false) this.state.add('Game', GameState, false) this.state.add('Over', OverState, false) // with Cordova with need to wait that the device is ready so we will call the Boot state in another file if (!window.cordova) { this.state.start('Boot') } } } window.game = new Game() if (window.cordova) { var app = { initialize: function () { document.addEventListener( 'deviceready', this.onDeviceReady.bind(this), false ) }, // deviceready Event Handler // onDeviceReady: function () { this.receivedEvent('deviceready') // When the device is ready, start Phaser Boot state. window.game.state.start('Boot') }, receivedEvent: function (id) { console.log('Received Event: ' + id) } } app.initialize() }