code
stringlengths
2
1.05M
// New Spotify object function Spotify(tab){ this.tab = tab; } // search for a song // open spotify if theres a match Spotify.prototype.search = function(title, artist, album){ var query = 'title:"' + title + '"'; query += 'artist:"' + artist + '"'; if(album){ query += 'album:"' + album + '"'; } $.ajax( { 'url': constants.SPOTIFY.SEARCH, 'type': 'GET', 'data': { 'q': query } } ).then( this.determineSearch.bind(this), function(){ this.tab.sendServiceAction( false, 'Error searching for song on Spotify', 'open', 'Spotify' ); }.bind(this) ) } // does the search result match what we provided it? // If so open Spotify app Spotify.prototype.determineSearch = function(json){ if(json.tracks.length > 0){ this.tab.openThenClose(json.tracks[0].href); this.tab.sendServiceAction( true, 'Song opened on Spotify', 'open', 'Spotify' ); } else{ this.tab.sendServiceAction( false, 'Song not found on Spotify', 'open', 'Spotify' ); } }
(function($){ $.fn.extend({ inputNumberFormat: function(options) { this.defaultOptions = { 'decimal': 2, 'decimalAuto': 2, 'separator': '.', 'separatorAuthorized': ['.', ','], 'allowNegative': false }; var settings = $.extend({}, this.defaultOptions, options); var matchValue = function(value, options) { var found = []; var regexp = "^[0-9]+"; if (options.allowNegative){ regexp = "^-{0,1}[0-9]*"; } if(options.decimal) { regexp += "["+options.separatorAuthorized.join("")+"]?[0-9]{0," + options.decimal + "}"; regexp = new RegExp(regexp + "$"); found = value.match(regexp); if(!found){ regexp = "^["+options.separatorAuthorized.join("")+"][0-9]{0," + options.decimal + "}"; regexp = new RegExp(regexp + "$"); found = value.match(regexp); } }else{ regexp = new RegExp(regexp + "$"); found = value.match(regexp); } return found; } var formatValue = function(value, options) { var formatedValue = value; if(!formatedValue) { return formatedValue; } if(formatedValue == "-") { return ""; } formatedValue = formatedValue.replace(",", options.separator); if(options.decimal && options.decimalAuto) { formatedValue = Math.round(formatedValue*Math.pow(10,options.decimal))/(Math.pow(10,options.decimal))+""; if(formatedValue.indexOf(options.separator) === -1) { formatedValue += options.separator; } var nbDecimalToAdd = options.decimalAuto - formatedValue.split(options.separator)[1].length; for(var i=1; i <= nbDecimalToAdd; i++) { formatedValue += "0"; } } return formatedValue; } return this.each(function() { var $this = $(this); $this.on('keypress', function(e) { if(e.ctrlKey) { return; } if(e.key.length > 1) { return; } var options = $.extend({}, settings, $(this).data()); var beginVal = $(this).val().substr(0, e.target.selectionStart); var endVal = $(this).val().substr(e.target.selectionEnd, $(this).val().length - 1); var val = beginVal + e.key + endVal; if(!matchValue(val, options)) { e.preventDefault(); return; } }); $this.on('blur', function(e) { var options = $.extend({}, settings, $(this).data()); $(this).val(formatValue($(this).val(), options)); }); $this.on('change', function(e) { var options = $.extend({}, settings, $(this).data()); $(this).val(formatValue($(this).val(), options)); }); }); } }); })(jQuery);
describe("Image", function() { beforeEach(function() { $("body").append($('<div id="sandbox"></div>')); }); afterEach(function() { $('#sandbox').remove(); $('.ui-dialog').remove(); }); it("add image into item content by factory", function() { $('#sandbox').wikimate({}); $('#sandbox').wikimate('newItem', {type: 'factory'}); $('.new-image').click(); var image = "data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"; $('.image_url_input').val(image); var done = $('.ui-button').filter(function(i, button) { return $(button).text() == "Done"; }); done.click(); expect($('#sandbox .item').prop('class')).toEqual('item image'); expect($('#sandbox .item img').length).toEqual(1); expect($('#sandbox .item img').prop('src')).toEqual(image); expect($('#sandbox .item').story_item('data').type).toEqual('image'); expect($('#sandbox .item').story_item('data').text).toEqual(image); }); it("should not add image when image url is blank", function() { $('#sandbox').wikimate({}); $('#sandbox').wikimate('newItem', {type: 'factory'}); $('.new-image').click(); var done = $('.ui-button').filter(function(i, button) { return $(button).text() == "Done"; }); done.click(); expect($('#sandbox .item').length).toEqual(0); }); });
var dogVideos = [ "http://media.giphy.com/media/l2JHZ7CDZa6jp1rAQ/giphy.mp4", "http://media.giphy.com/media/26tnmOjq7uQ98qxZC/giphy.mp4", "http://media.giphy.com/media/26tnazn9Fm4V3VUMU/giphy.mp4", "http://media.giphy.com/media/26tnhrpR1B6iOnUgo/giphy.mp4", "http://media.giphy.com/media/26tn2A11Cgd3xvIqc/giphy.mp4", "http://media.giphy.com/media/l2JHTMc51UdCYCn2o/giphy.mp4", "http://media.giphy.com/media/l2JI9XQlqkRLYIWCA/giphy.mp4", "http://media.giphy.com/media/26tn4dAvXHkHcHncQ/giphy.mp4", "http://media.giphy.com/media/26tn956W5qLmbO9YQ/giphy.mp4", "http://media.giphy.com/media/l2JHQGY0SoanXpvck/giphy.mp4", "http://media.giphy.com/media/l2JIcb3CvvjMZ9akU/giphy.mp4", "http://media.giphy.com/media/26tmZGflCf82PGbjq/giphy.mp4", "http://media.giphy.com/media/26tn5ZBO276MhXjiw/giphy.mp4", "http://media.giphy.com/media/26tncxLvZXWff0FlS/giphy.mp4", "http://media.giphy.com/media/l2JHSUA0chBuwY63e/giphy.mp4", "http://media.giphy.com/media/l2JIkLzS2M9c5XD0I/giphy.mp4" ]; function displayRandomVideo() { var randomIndex = Math.floor((Math.random() * dogVideos.length)); $("#dog-video").attr("src", dogVideos[randomIndex]); $("#video")[0].load(); } $(document).ready(function(){ displayRandomVideo(); });
// 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 //= require jquery_ujs //= require jquery.serializejson //= require jquery.transit //= require underscore //= require moment //= require backbone //= require_tree ./utils //= require maildog //= require_tree ../templates //= require_tree ./mixins //= require_tree ./models //= require_tree ./collections //= require_tree ./views //= require_tree ./routers //= require_tree .
angular.module('resource.magacinska', ['ngResource']) .factory('Kartica', function ($resource) { return $resource('http://localhost:8080/xws/api/magacinska-karticaK/:idMagacinskaKartica', { idMagacinskaKartica: '@idMagacinskaKartica' }, { 'update': { method:'PUT' } }); })
/* --- name: Element.Data.Specs description: n/a requires: [Behavior/Element.Data] provides: [Element.Data.Specs] ... */ (function(){ var target = new Element('div', { 'data-filters': 'Test1 Test2', 'data-json':'{"foo": "bar", "nine": 9, "arr": [1, 2, 3]}' }); describe('Element.Data', function(){ it('should get a data property from an element', function(){ expect(target.getData('filters')).toBe('Test1 Test2'); }); it('should set a data property on an element', function(){ target.setData('foo', 'bar'); expect(target.getData('foo')).toBe('bar'); }); it('should read a property as JSON', function(){ var json = target.getJSONData('json'); expect(json.foo).toBe('bar'); expect(json.nine).toBe(9); expect(json.arr).toEqual([1,2,3]); }); it('should set a property as JSON', function(){ target.setJSONData('json2', { foo: 'bar', nine: 9, arr: [1,2,3] }); var json = target.getJSONData('json2'); expect(json.foo).toBe('bar'); expect(json.nine).toBe(9); expect(json.arr).toEqual([1,2,3]); }); it('should return null for a non-defined property', function(){ expect(target.getData('baz')).toBeNull(); }); }); })();
/* * * apiView * */ import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { connect } from 'react-redux' import ReadMargin from 'components/ReadMargin' import View from 'components/View' import P from 'components/P' import messages from './messages' class WorldView extends PureComponent { componentDidMount() { } render() { return ( <div> <View left={true}> <ReadMargin> <P><FormattedMessage {...messages.arasaacInWorld} /></P> </ReadMargin> </View> <iframe src="https://www.google.com/maps/d/u/0/embed?mid=1EBR3psLxK-G_WujU93NMWkfisTYK4HwY" width="100%" height="800"></iframe> </div> ) } } WorldView.propTypes = { theme: PropTypes.string.isRequired } const mapStateToProps = (state) => ({ theme: state.get('theme') }) export default connect(mapStateToProps)(WorldView)
module.exports = function(RED) { "use strict"; var reconnect = RED.settings.ibmdbReconnectTime || 30000; var db2 = require('ibm_db'); var Promise = require('promise'); function IbmDBNode(n) { RED.nodes.createNode(this,n); this.host = n.host; this.port = n.port; this.connected = false; this.connecting = false; this.dbname = n.db; var node = this; function doConnect(conncb) { node.connecting = true; node.conn = {}; node.connection = { connect: (cb) => { var conStr = "DRIVER={DB2};DATABASE="+node.dbname +";HOSTNAME="+node.host +";UID="+node.credentials.user +";PWD="+node.credentials.password +";PORT="+node.port+";PROTOCOL=TCPIP"; db2.open(conStr, function (err,conn) { if (err) { cb(err, null); } else { console.log('connection to ' + node.dbname); conn.connName = node.dbname; cb(null, conn); } }); }, end: (conn) => { conn.close(() => { console.log('connection closed'); }); } }; node.connection.connect(function(err, conn) { node.connecting = false; if (err) { node.error(err); console.log("connection error " + err); } else { node.conn = conn; node.connected = true; } conncb(err); }); } this.connect = function() { return new Promise((resolve, reject) => { if (!this.connected && !this.connecting) { doConnect((err)=>{ if(err) reject(err); else resolve(); }); } else{ resolve(); } }); } this.on('close', function (done) { if (this.connection) { node.connection.end(this.conn); } done(); }); } RED.nodes.registerType("IbmDBdatabase", IbmDBNode, { credentials: { user: {type: "text"}, password: {type: "password"} } }); function IbmDBNodeIn(n) { RED.nodes.createNode(this,n); this.mydb = n.mydb; var node = this; node.query = function(node, db, msg){ if ( msg.payload !== null && typeof msg.payload === 'string' && msg.payload !== '') { db.conn.query(msg.payload, function(err, rows) { if (err) { console.log("QUERY ERROR "+ err); node.error(err,msg); } else { rows.forEach(function(row) { node.send({ topic: msg.topic, payload: row }); }) node.send([ null, { topic: msg.topic, control: 'end' }]); } }); } else { if (msg.payload === null) { node.error("msg.payload : the query is not defined"); } if (typeof msg.payload !== 'string') { node.error("msg.payload : the query is not defined as a string"); } if (typeof msg.payload === 'string' && msg.payload === '') { node.error("msg.payload : the query string is empty"); } } } node.on("input", (msg) => { if ( msg.database !== null && typeof msg.database === 'string' && msg.database !== '') { node.mydbNode = RED.nodes.getNode(n.mydb); if (node.mydbNode) { node.send([ null, { control: 'start', query: msg.payload, database: n.mydb } ]); if(node.mydbNode.conn && node.mydbNode.conn.connName === msg.database){ console.log("already connected"); node.query(node, node.mydbNode, msg); } else{ var findNode; RED.nodes.eachNode((node)=>{ if(node.db && node.db === msg.database){ findNode = RED.nodes.getNode(node.id); node.mydb = node.id; } }) findNode.connect() .then(()=>{ node.query(node, findNode, msg); }); } } else { this.error("database not configured"); } } else{ this.error("database not specified"); } }); } RED.nodes.registerType("ibmdb", IbmDBNodeIn); }
import { linkTo } from '@storybook/addon-links'; export default { title: 'Addon/Links', }; export const GoToWelcome = () => ({ template: '<my-button :rounded="true" @click="click" >This buttons links to Welcome</my-button>', methods: { click: linkTo('Welcome'), }, }); GoToWelcome.story = { name: 'Go to welcome', };
jQuery(document).ready(function($){ var is_firefox = navigator.userAgent.indexOf('Firefox') > -1; //open team-member bio $('#cd-team').find('ul a').on('click', function(event){ event.preventDefault(); var selected_member = $(this).data('type'); $('.cd-member-bio.'+selected_member+'').addClass('slide-in'); $('#mainNav').hide(); $('.cd-member-bio-close').addClass('is-visible'); // firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden if( is_firefox ) { $('main').addClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){ $('body').addClass('overflow-hidden'); }); } else { $('main').addClass('slide-out'); $('body').addClass('overflow-hidden'); } }); //close team-member bio $(document).on('click', '.cd-overlay, .cd-member-bio-close', function(event){ event.preventDefault(); $('.cd-member-bio').removeClass('slide-in'); $('#mainNav').show(); $('.cd-member-bio-close').removeClass('is-visible'); if( is_firefox ) { $('main').removeClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){ $('body').removeClass('overflow-hidden'); }); } else { $('main').removeClass('slide-out'); $('body').removeClass('overflow-hidden'); } }); });
(function($) { }) (JQuery);
'use strict'; describe('Service: ScreenSpySrv', function () { // load the service's module beforeEach(module('brandonMcgregorApp')); // instantiate service var ScreenSpySrv; beforeEach(inject(function (_ScreenSpySrv_) { ScreenSpySrv = _ScreenSpySrv_; })); it('should do something', function () { expect(!!ScreenSpySrv).toBe(true); }); });
'use strict'; angular.module('baka') .controller('NavbarCtrl', function ($scope, AuthenticationService) { $scope.logout = function () { AuthenticationService.logout(); }; });
/** * Created by Adrian on 2016-05-08. */ import angular from "angular"; import angularMeteor from "angular-meteor"; import uiRouter from "angular-ui-router"; import "./mobile.html"; import {Tasks} from "../../../api/tasks/index"; import {name as TaskItem} from "../taskItem/taskItem"; class TasksList { constructor($scope, $reactive) { 'ngInject'; $reactive(this).attach($scope); this.subscribe('tasks'); this.helpers({ tasks() { return Tasks.find(); } }); } } const template = 'mobile'; const name = 'tasksList'; export default angular.module(name, [ angularMeteor, uiRouter, TaskItem ]).component(name, { templateUrl: `imports/ui/components/${name}/${template}.html`, controllerAs: name, controller: TasksList });
// colors and line weights var NOTHING = 0; var EVERYTHING = 255; var MOSTLY = 200; var THICK_WEIGHT = 4; var THIN_WEIGHT = 1; // background var CANVAS_WIDTH = 1000; var CANVAS_HEIGHT = 750; // touchpad var BOX_SIZE = 50; var X_MIN = CANVAS_WIDTH - (2 * BOX_SIZE); var X_MAX = X_MIN + BOX_SIZE; var Y_MIN = BOX_SIZE; var Y_MAX = Y_MIN + BOX_SIZE; // the circle var DIAMETER = 20; var EASING = 0.1; var x_now = 0; var y_now = 0; var remap_cursor = function(sketch){ sketch.setup = function(){ sketch.createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT); sketch.background(NOTHING, NOTHING, EVERYTHING); sketch.stroke(EVERYTHING); sketch.strokeWeight(THIN_WEIGHT); sketch.fill(NOTHING, NOTHING, EVERYTHING); sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE); }// end sketch.setup sketch.draw = function(){ // refresh the background sketch.background(NOTHING, NOTHING, EVERYTHING, MOSTLY); sketch.strokeWeight(THIN_WEIGHT); sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE); // map the mouse position in the box to the larger image mx = sketch.map(sketch.mouseX, X_MIN, X_MAX, 0, CANVAS_WIDTH); my = sketch.map(sketch.mouseY, Y_MIN, Y_MAX, 0, CANVAS_HEIGHT); // add easing x_now = x_now + (mx - x_now) * EASING; y_now = y_now + (my - y_now) * EASING; // draw the circle sketch.strokeWeight(THICK_WEIGHT); sketch.ellipse(x_now, y_now, DIAMETER, DIAMETER); }// end sketch.draw }// end remap_cursor
/*! * VisualEditor DataModel TransactionProcessor tests. * * @copyright 2011-2014 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ QUnit.module( 've.dm.TransactionProcessor' ); /* Tests */ QUnit.test( 'commit', function ( assert ) { var i, originalData, originalDoc, msg, testDoc, tx, expectedData, expectedDoc, n = 0, store = ve.dm.example.createExampleDocument().getStore(), bold = ve.dm.example.createAnnotation( ve.dm.example.bold ), italic = ve.dm.example.createAnnotation( ve.dm.example.italic ), underline = ve.dm.example.createAnnotation( ve.dm.example.underline ), metaElementInsert = { type: 'alienMeta', attributes: { style: 'comment', text: ' inline ' } }, metaElementInsertClose = { type: '/alienMeta' }, metadataExample = [ { type: 'paragraph' }, 'a', 'b', { type: 'alienMeta', attributes: { domElements: $( '<!-- comment -->' ).toArray() } }, { type: '/alienMeta' }, 'c', 'd', { type: 'alienMeta', attributes: { domElements: $( '<!-- comment -->' ).toArray() } }, { type: '/alienMeta' }, 'e', 'f', { type: 'alienMeta', attributes: { domElements: $( '<!-- comment -->' ).toArray() } }, { type: '/alienMeta' }, 'g', 'h', { type: '/paragraph' } ], cases = { 'no operations': { calls: [], expected: function () {} }, retaining: { calls: [['pushRetain', 38]], expected: function () {} }, 'annotating content': { calls: [ ['pushRetain', 1], ['pushStartAnnotating', 'set', bold], ['pushRetain', 1], ['pushStopAnnotating', 'set', bold], ['pushRetain', 1], ['pushStartAnnotating', 'clear', italic], ['pushStartAnnotating', 'set', bold], ['pushStartAnnotating', 'set', underline], ['pushRetain', 1], ['pushStopAnnotating', 'clear', italic], ['pushStopAnnotating', 'set', bold], ['pushStopAnnotating', 'set', underline] ], expected: function ( data ) { data[1] = ['a', store.indexes( [ bold ] )]; data[2] = ['b', store.indexes( [ bold ] )]; data[3] = ['c', store.indexes( [ bold, underline ] )]; } }, 'annotating content and leaf elements': { calls: [ ['pushRetain', 38], ['pushStartAnnotating', 'set', bold], ['pushRetain', 4], ['pushStopAnnotating', 'set', bold] ], expected: function ( data ) { data[38] = ['h', store.indexes( [ bold ] )]; data[39].annotations = store.indexes( [ bold ] ); data[41] = ['i', store.indexes( [ bold ] )]; } }, 'annotating across metadata': { data: metadataExample, calls: [ ['pushRetain', 2], ['pushStartAnnotating', 'set', bold], ['pushRetain', 2], ['pushStopAnnotating', 'set', bold], ['pushRetain', 6] ], expected: function ( data ) { data[2] = ['b', store.indexes( [ bold ] )]; data[3].annotations = store.indexes( [ bold ] ); data[5] = ['c', store.indexes( [ bold ] )]; } }, 'annotating with metadata at edges': { data: metadataExample, calls: [ ['pushRetain', 3], ['pushStartAnnotating', 'set', bold], ['pushRetain', 4], ['pushStopAnnotating', 'set', bold], ['pushRetain', 3] ], expected: function ( data ) { data[7].annotations = store.indexes( [ bold ] ); data[5] = ['c', store.indexes( [ bold ] )]; data[6] = ['d', store.indexes( [ bold ] )]; data[9] = ['e', store.indexes( [ bold ] )]; data[10] = ['f', store.indexes( [ bold ] )]; } }, 'unannotating metadata': { data: [ { type: 'paragraph' }, 'a', ['b', store.indexes( [ bold ] )], { type: 'alienMeta', attributes: { domElements: $( '<!-- comment -->' ).toArray() }, annotations: store.indexes( [ bold ] ) }, { type: '/alienMeta' }, ['c', store.indexes( [ bold ] )], 'd', { type: '/paragraph' } ], calls: [ ['pushRetain', 2], ['pushStartAnnotating', 'clear', bold], ['pushRetain', 2], ['pushStopAnnotating', 'clear', bold], ['pushRetain', 6] ], expected: function ( data ) { data[2] = 'b'; data[5] = 'c'; delete data[3].annotations; } }, 'using an annotation method other than set or clear throws an exception': { calls: [ ['pushStartAnnotating', 'invalid-method', bold], ['pushRetain', 1], ['pushStopAnnotating', 'invalid-method', bold] ], exception: Error }, 'annotating branch opening element throws an exception': { calls: [ ['pushStartAnnotating', 'set', bold], ['pushRetain', 1], ['pushStopAnnotating', 'set', bold] ], exception: Error }, 'annotating branch closing element throws an exception': { calls: [ ['pushRetain', 4], ['pushStartAnnotating', 'set', bold], ['pushRetain', 1], ['pushStopAnnotating', 'set', bold] ], exception: Error }, 'setting duplicate annotations throws an exception': { calls: [ ['pushRetain', 2], ['pushStartAnnotating', 'set', bold], ['pushRetain', 1], ['pushStopAnnotating', 'set', bold] ], exception: Error }, 'removing non-existent annotations throws an exception': { calls: [ ['pushRetain', 1], ['pushStartAnnotating', 'clear', bold], ['pushRetain', 1], ['pushStopAnnotating', 'clear', bold] ], exception: Error }, 'changing, removing and adding attributes': { calls: [ ['pushReplaceElementAttribute', 'level', 1, 2], ['pushRetain', 12], ['pushReplaceElementAttribute', 'style', 'bullet', 'number'], ['pushReplaceElementAttribute', 'test', undefined, 'abcd'], ['pushRetain', 27], ['pushReplaceElementAttribute', 'src', ve.dm.example.imgSrc, undefined] ], expected: function ( data ) { data[0].attributes.level = 2; data[12].attributes.style = 'number'; data[12].attributes.test = 'abcd'; delete data[39].attributes.src; } }, 'changing attributes on non-element data throws an exception': { calls: [ ['pushRetain', 1], ['pushReplaceElementAttribute', 'foo', 23, 42] ], exception: Error }, 'inserting text': { calls: [ ['pushRetain', 1], ['pushReplace', 1, 0, ['F', 'O', 'O']] ], expected: function ( data ) { data.splice( 1, 0, 'F', 'O', 'O' ); } }, 'removing text': { calls: [ ['pushRetain', 1], ['pushReplace', 1, 1, []] ], expected: function ( data ) { data.splice( 1, 1 ); } }, 'replacing text': { calls: [ ['pushRetain', 1], ['pushReplace', 1, 1, ['F', 'O', 'O']] ], expected: function ( data ) { data.splice( 1, 1, 'F', 'O', 'O' ); } }, 'emptying text': { calls: [ ['pushRetain', 10], ['pushReplace', 10, 1, []] ], expected: function ( data ) { data.splice( 10, 1 ); } }, 'inserting mixed content': { calls: [ ['pushRetain', 1], ['pushReplace', 1, 1, ['F', 'O', 'O', { type: 'image' }, { type: '/image' }, 'B', 'A', 'R']] ], expected: function ( data ) { data.splice( 1, 1, 'F', 'O', 'O', { type: 'image' }, { type: '/image' }, 'B', 'A', 'R' ); } }, 'converting an element': { calls: [ ['pushReplace', 0, 1, [{ type: 'paragraph' }]], ['pushRetain', 3], ['pushReplace', 4, 1, [{ type: '/paragraph' }]] ], expected: function ( data ) { data[0].type = 'paragraph'; delete data[0].attributes; data[4].type = '/paragraph'; } }, 'splitting an element': { calls: [ ['pushRetain', 2], [ 'pushReplace', 2, 0, [{ type: '/heading' }, { type: 'heading', attributes: { level: 1 } }] ] ], expected: function ( data ) { data.splice( 2, 0, { type: '/heading' }, { type: 'heading', attributes: { level: 1 } } ); } }, 'merging an element': { calls: [ ['pushRetain', 57], ['pushReplace', 57, 2, []] ], expected: function ( data ) { data.splice( 57, 2 ); } }, 'stripping elements': { calls: [ ['pushRetain', 3], ['pushReplace', 3, 1, []], ['pushRetain', 6], ['pushReplace', 10, 1, []] ], expected: function ( data ) { data.splice( 10, 1 ); data.splice( 3, 1 ); } }, 'inserting text after alien node at the end': { data: [ { type: 'paragraph' }, 'a', { type: 'alienInline' }, { type: '/alienInline' }, { type: '/paragraph' } ], calls: [ ['pushRetain', 4], ['pushReplace', 4, 0, ['b']] ], expected: function ( data ) { data.splice( 4, 0, 'b' ); } }, 'inserting metadata element into existing element list': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 11 ], ['pushRetainMetadata', 2 ], ['pushReplaceMetadata', [], [ metaElementInsert ] ], ['pushRetainMetadata', 2 ], ['pushRetain', 1 ] ], expected: function ( data ) { data.splice( 25, 0, metaElementInsert, metaElementInsertClose ); } }, 'inserting metadata element into empty list': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 3 ], ['pushReplaceMetadata', [], [ metaElementInsert ] ], ['pushRetain', 9 ] ], expected: function ( data ) { data.splice( 7, 0, metaElementInsert, metaElementInsertClose ); } }, 'removing all metadata elements from a metadata list': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 11 ], ['pushReplaceMetadata', ve.dm.example.withMetaMetaData[11], [] ], ['pushRetain', 1 ] ], expected: function ( data ) { data.splice( 21, 8 ); } }, 'removing some metadata elements from metadata list': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 11 ], ['pushRetainMetadata', 1 ], ['pushReplaceMetadata', ve.dm.example.withMetaMetaData[11].slice( 1, 3 ), [] ], ['pushRetainMetadata', 1 ], ['pushRetain', 1 ] ], expected: function ( data ) { data.splice( 23, 4 ); } }, 'replacing metadata at end of list': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 11 ], ['pushRetainMetadata', 3 ], ['pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][3] ], [ metaElementInsert ] ], ['pushRetain', 1 ] ], expected: function ( data ) { data.splice( 27, 2, metaElementInsert, metaElementInsertClose ); } }, 'replacing metadata twice at the same offset': { data: ve.dm.example.withMeta, calls: [ [ 'pushRetain', 11 ], [ 'pushRetainMetadata', 1 ], [ 'pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][1] ], [ metaElementInsert ] ], [ 'pushRetainMetadata', 1 ], [ 'pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][3] ], [ metaElementInsert ] ], [ 'pushRetain', 1 ] ], expected: function ( data ) { data.splice( 23, 2, metaElementInsert, metaElementInsertClose ); data.splice( 27, 2, metaElementInsert, metaElementInsertClose ); } }, 'removing data from between metadata merges metadata': { data: ve.dm.example.withMeta, calls: [ ['pushRetain', 7 ], ['pushReplace', 7, 2, []], ['pushRetain', 2 ] ], expected: function ( data ) { data.splice( 15, 2 ); } }, 'structural replacement starting at an offset without metadata': { data: [ { type: 'paragraph' }, 'F', { type: 'alienMeta', attributes: { domElements: $( '<!-- foo -->' ).toArray() } }, { type: '/alienMeta' }, 'o', 'o', { type: '/paragraph' } ], calls: [ ['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]] ], expected: function ( data ) { data.splice( 0, 2 ); data.splice( 2, 3, { type: 'table' }, { type: '/table' } ); } }, 'structural replacement starting at an offset with metadata': { data: [ { type: 'alienMeta', attributes: { domElements: $( '<!-- foo -->' ).toArray() } }, { type: '/alienMeta' }, { type: 'paragraph' }, 'F', { type: 'alienMeta', attributes: { style: 'comment', text: ' inline ' } }, { type: '/alienMeta' }, 'o', 'o', { type: '/paragraph' } ], calls: [ ['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]] ], expected: function ( data ) { // metadata is merged. data.splice( 2, 2 ); data.splice( 4, 3, { type: 'table' }, { type: '/table' } ); } }, 'structural replacement ending at an offset with metadata': { data: [ { type: 'alienMeta', attributes: { domElements: $( '<!-- foo -->' ).toArray() } }, { type: '/alienMeta' }, { type: 'paragraph' }, 'F', { type: 'alienMeta', attributes: { style: 'comment', text: ' inline ' } }, { type: '/alienMeta' }, 'o', 'o', { type: '/paragraph' }, { type: 'alienMeta', attributes: { domElements: $( '<!-- bar -->' ).toArray() } }, { type: '/alienMeta' }, { type: 'paragraph' }, 'B', 'a', 'r', { type: '/paragraph' } ], calls: [ ['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]], ['pushRetain', 5 ] ], expected: function ( data ) { // metadata is merged. data.splice( 2, 2 ); data.splice( 4, 3, { type: 'table' }, { type: '/table' } ); } }, 'structural deletion ending at an offset with metadata': { data: [ { type: 'alienMeta', attributes: { domElements: $( '<!-- foo -->' ).toArray() } }, { type: '/alienMeta' }, { type: 'paragraph' }, 'F', { type: 'alienMeta', attributes: { style: 'comment', text: ' inline ' } }, { type: '/alienMeta' }, 'o', 'o', { type: '/paragraph' }, { type: 'alienMeta', attributes: { domElements: $( '<!-- bar -->' ).toArray() } }, { type: '/alienMeta' }, { type: 'paragraph' }, 'B', 'a', 'r', { type: '/paragraph' } ], calls: [ ['pushReplace', 0, 5, [] ], ['pushRetain', 5 ] ], expected: function ( data ) { // metadata is merged. data.splice( 2, 2 ); data.splice( 4, 3 ); } }, 'preserves metadata on unwrap': { data: ve.dm.example.listWithMeta, calls: [ [ 'newFromWrap', new ve.Range( 1, 11 ), [ { type: 'list' } ], [], [ { type: 'listItem', attributes: { styles: ['bullet'] } } ], [] ] ], expected: function ( data ) { data.splice( 35, 1 ); // remove '/list' data.splice( 32, 1 ); // remove '/listItem' data.splice( 20, 1 ); // remove 'listItem' data.splice( 17, 1 ); // remove '/listItem' data.splice( 5, 1 ); // remove 'listItem' data.splice( 2, 1 ); // remove 'list' } }, 'inserting trailing metadata (1)': { data: ve.dm.example.listWithMeta, calls: [ [ 'newFromMetadataInsertion', 12, 0, [ { type: 'alienMeta', attributes: { domElements: $( '<meta property="fourteen" />' ).toArray() } } ] ] ], expected: function ( data ) { ve.batchSplice( data, data.length - 2, 0, [ { type: 'alienMeta', attributes: { domElements: $( '<meta property="fourteen" />' ).toArray() } }, { type: '/alienMeta' } ] ); } }, 'inserting trailing metadata (2)': { data: ve.dm.example.listWithMeta, calls: [ [ 'newFromMetadataInsertion', 12, 1, [ { type: 'alienMeta', attributes: { domElements: $( '<meta property="fourteen" />' ).toArray() } } ] ] ], expected: function ( data ) { ve.batchSplice( data, data.length, 0, [ { type: 'alienMeta', attributes: { domElements: $( '<meta property="fourteen" />' ).toArray() } }, { type: '/alienMeta' } ] ); } }, 'removing trailing metadata': { data: ve.dm.example.listWithMeta, calls: [ [ 'newFromMetadataRemoval', 12, new ve.Range( 0, 1 ) ] ], expected: function ( data ) { ve.batchSplice( data, data.length - 2, 2, [] ); } }, 'preserves trailing metadata': { data: ve.dm.example.listWithMeta, calls: [ [ 'newFromInsertion', 4, [ 'b' ] ] ], expected: function ( data ) { ve.batchSplice( data, 12, 0, [ 'b' ] ); } } }; for ( msg in cases ) { n += ( 'expected' in cases[msg] ) ? 4 : 1; } QUnit.expect( n ); // Run tests for ( msg in cases ) { // Generate original document originalData = cases[msg].data || ve.dm.example.data; originalDoc = new ve.dm.Document( ve.dm.example.preprocessAnnotations( ve.copy( originalData ), store ) ); originalDoc.buildNodeTree(); testDoc = new ve.dm.Document( ve.dm.example.preprocessAnnotations( ve.copy( originalData ), store ) ); testDoc.buildNodeTree(); tx = new ve.dm.Transaction(); for ( i = 0; i < cases[msg].calls.length; i++ ) { // some calls need the document as its first argument if ( /^(pushReplace$|new)/.test( cases[msg].calls[i][0] ) ) { cases[msg].calls[i].splice( 1, 0, testDoc ); } // special case static methods of Transaction if ( /^new/.test( cases[msg].calls[i][0] ) ) { tx = ve.dm.Transaction[cases[msg].calls[i][0]].apply( null, cases[msg].calls[i].slice( 1 ) ); break; } tx[cases[msg].calls[i][0]].apply( tx, cases[msg].calls[i].slice( 1 ) ); } if ( 'expected' in cases[msg] ) { // Generate expected document expectedData = ve.copy( originalData ); cases[msg].expected( expectedData ); expectedDoc = new ve.dm.Document( ve.dm.example.preprocessAnnotations( expectedData, store ) ); expectedDoc.buildNodeTree(); // Commit testDoc.commit( tx ); assert.deepEqualWithDomElements( testDoc.getFullData(), expectedDoc.getFullData(), 'commit (data): ' + msg ); assert.equalNodeTree( testDoc.getDocumentNode(), expectedDoc.getDocumentNode(), 'commit (tree): ' + msg ); // Rollback testDoc.commit( tx.reversed() ); assert.deepEqualWithDomElements( testDoc.getFullData(), originalDoc.getFullData(), 'rollback (data): ' + msg ); assert.equalNodeTree( testDoc.getDocumentNode(), originalDoc.getDocumentNode(), 'rollback (tree): ' + msg ); } else if ( 'exception' in cases[msg] ) { /*jshint loopfunc:true */ assert.throws( function () { testDoc.commit( tx ); }, cases[msg].exception, 'commit: ' + msg ); } } } );
/** * Takes an array of strings that represent functional dependencies and returns * them as an array of objects containing functionaldependency objects. */ var parseInput = function(lines) { lines = lines.split('\n'); var functionalDependencies = new DependencySet(); for(var i = 0; i < lines.length; ++i) { var line = lines[i]; var arrowIndex = line.indexOf('->'); if(arrowIndex >= 0) { var lhs = line.substring(0, arrowIndex).trim().split(','); var rhs = line.substring(arrowIndex + 2, line.length).trim().split(','); /* Trim all the individual attributes */ for(var j=0;j<lhs.length;++j) lhs[j] = lhs[j].trim(); for(var k=0;k<rhs.length;++k) rhs[k] = rhs[k].trim(); /* Make sure they're nonzero and add them to the list */ if(lhs.length > 0 && rhs.length > 0) { var functionalDependency = new FunctionalDependency(lhs, rhs); functionalDependencies.add(functionalDependency); } } } return functionalDependencies; };
var test = require('tape'); var url = require('url'); var curli = require('../'); var testServer = require('./server.js'); var buildUAString = require('../lib/util').buildUAString; test('Default user agent being set', function(t) { var server = testServer.createServer(); var ua = buildUAString(); server.listen(0, function() { var port = server.address().port; var host = '//localhost:' + port; var href = 'http:' + host + '/'; server.on('/', function(req, res) { t.equal(req.headers['user-agent'], ua, 'Default user agent set to "' + ua + '"'); res.writeHead(200); res.end(); }); curli(href, function(err, headers) { t.ok(headers, 'Headers sent'); t.error(err, 'Shouldn\'t error'); server.close(); t.end(); }); }); }); test('Custom user agent', function(t) { var server = testServer.createServer(); server.listen(0, function() { var port = server.address().port; var host = '//localhost:' + port; var href = 'http:' + host + '/'; var options = url.parse(href); options.headers = { 'User-Agent': 'Node' }; var ua = options.headers['User-Agent']; server.on('/', function(req, res) { t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"'); res.writeHead(200); res.end(); }); curli(options, function(err, headers) { t.ok(headers, 'Headers sent'); t.error(err, 'Shouldn\'t error'); server.close(); t.end(); }); }); }); test('Custom user agent, funky header', function(t) { var server = testServer.createServer(); server.listen(0, function() { var port = server.address().port; var host = '//localhost:' + port; var href = 'http:' + host + '/'; var options = url.parse(href); options.headers = { 'UsER-AgeNt': 'kNode' }; var ua = options.headers['UsER-AgeNt']; server.on('/', function(req, res) { t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"'); res.writeHead(200); res.end(); }); curli(options, function(err, headers) { t.ok(headers, 'Headers sent'); t.error(err, 'Shouldn\'t error'); server.close(); t.end(); }); }); });
var path = require('path'), config; config = { production: { url: 'http://localhost:2368', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '../node_modules/ghost/content/data/ghost-dev.db') }, debug: false }, server: { host: '127.0.0.1', port: '2368' }, paths: { contentPath: path.join(__dirname, '../node_modules/ghost/content/') } } }; // Export config module.exports = config;
// All symbols in the Phoenician block as per Unicode v6.1.0: [ '\uD802\uDD00', '\uD802\uDD01', '\uD802\uDD02', '\uD802\uDD03', '\uD802\uDD04', '\uD802\uDD05', '\uD802\uDD06', '\uD802\uDD07', '\uD802\uDD08', '\uD802\uDD09', '\uD802\uDD0A', '\uD802\uDD0B', '\uD802\uDD0C', '\uD802\uDD0D', '\uD802\uDD0E', '\uD802\uDD0F', '\uD802\uDD10', '\uD802\uDD11', '\uD802\uDD12', '\uD802\uDD13', '\uD802\uDD14', '\uD802\uDD15', '\uD802\uDD16', '\uD802\uDD17', '\uD802\uDD18', '\uD802\uDD19', '\uD802\uDD1A', '\uD802\uDD1B', '\uD802\uDD1C', '\uD802\uDD1D', '\uD802\uDD1E', '\uD802\uDD1F' ];
import React, {PropTypes} from "react"; import {Provider} from "react-redux"; import {Router} from "react-router"; import {getRoutes} from "./routes"; export default function Root({history, store}) { return ( <Provider store={store}> <Router history={history} routes={getRoutes(store.getState)}/> </Provider> ); } Root.propTypes = { history: PropTypes.object.isRequired, store: PropTypes.object.isRequired };
/********************************************************************************* * File Name : loader.js * Created By : Jone Casper([email protected]) * Creation Date : [2014-03-25 22:14] * Last Modified : [2014-04-06 05:17] * Description : A loader for loading module **********************************************************************************/ (function(root, name, factory) { "use strict"; if (typeof define === 'function' && define.amd) { define(function(){ return factory(); }); }else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){ module.exports = factory(); }else{ var namespaces = name.split("."), scope = root || this; for (var i=0; i<namespaces.length; i++) { var p = namespaces[i], ex = scope[p]; scope = scope[p] = (i === namespaces.length - 1) ? factory(): (ex || {}); } } }(this, "backchart.base.loader",function(){ var root = this; var exports = function(name, callback){ var args = []; if (typeof define === 'function' && define.amd) { require(name instanceof Array ? name : [name], callback); }else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){ if (name instanceof Array){ for (var i=0; i<name.length ; i++){ args.push(require(name[i])); } callback.apply(this, args); }else{ callback.call(this, require(name)); } }else{ if (typeof name === "string" || name instanceof String){ name = [name]; } for (var n=0; n<name.length; n++){ var namespaces = name[n], scope = root; namespaces = namespaces.replace("/",".").split("."); for (var j=0; j<namespaces.length; j++) { var p = namespaces[j], ex = scope[p]; if (!ex) { args.push(null); break; //callback.call(this, null); } if (j === namespaces.length -1){ args.push(ex); //callback.call(this, ex); } scope = ex; } } callback.apply(this, args); } }; return exports; }));
/*jshint esversion: 6 */ (function () { let locationPromise = new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition((position) => { resolve(position); }); }); locationPromise .then(displayLocation) .catch((error) => { // var errMessage = document.getElementById("main"); let errMessage = $("#main"); errMessage.html("Can not get location"); }); function displayLocation(position) { let imgSrc = `http://maps.googleapis.com/maps/api/staticmap?center=${position.coords.latitude},${position.coords.longitude}&zoom=18&size=600x600&sensor=true`; $("#locationMap").attr("src", imgSrc); } }());
"use strict"; System.register([], function (_export, _context) { "use strict"; var ClickCounter; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } return { setters: [], execute: function () { _export("ClickCounter", ClickCounter = function () { function ClickCounter() { _classCallCheck(this, ClickCounter); this.count = 0; } ClickCounter.prototype.increment = function increment() { this.count++; }; return ClickCounter; }()); _export("ClickCounter", ClickCounter); } }; });
/*! * Jade - Lexer * Copyright(c) 2010 TJ Holowaychuk <[email protected]> * MIT Licensed */ /** * Initialize `Lexer` with the given `str`. * * Options: * * - `colons` allow colons for attr delimiters * * @param {String} str * @param {Object} options * @api private */ var Lexer = module.exports = function Lexer(str, options) { options = options || {}; this.input = str.replace(/\r\n|\r/g, '\n'); this.colons = options.colons; this.deferredTokens = []; this.lastIndents = 0; this.lineno = 1; this.stash = []; this.indentStack = []; this.indentRe = null; this.pipeless = false; }; /** * Lexer prototype. */ Lexer.prototype = { /** * Construct a token with the given `type` and `val`. * * @param {String} type * @param {String} val * @return {Object} * @api private */ tok: function(type, val){ return { type: type , line: this.lineno , val: val } }, /** * Consume the given `len` of input. * * @param {Number} len * @api private */ consume: function(len){ this.input = this.input.substr(len); }, /** * Scan for `type` with the given `regexp`. * * @param {String} type * @param {RegExp} regexp * @return {Object} * @api private */ scan: function(regexp, type){ var captures; if (captures = regexp.exec(this.input)) { this.consume(captures[0].length); return this.tok(type, captures[1]); } }, /** * Defer the given `tok`. * * @param {Object} tok * @api private */ defer: function(tok){ this.deferredTokens.push(tok); }, /** * Lookahead `n` tokens. * * @param {Number} n * @return {Object} * @api private */ lookahead: function(n){ var fetch = n - this.stash.length; while (fetch-- > 0) this.stash.push(this.next()); return this.stash[--n]; }, /** * Return the indexOf `start` / `end` delimiters. * * @param {String} start * @param {String} end * @return {Number} * @api private */ indexOfDelimiters: function(start, end){ var str = this.input , nstart = 0 , nend = 0 , pos = 0; for (var i = 0, len = str.length; i < len; ++i) { if (start == str.charAt(i)) { ++nstart; } else if (end == str.charAt(i)) { if (++nend == nstart) { pos = i; break; } } } return pos; }, /** * Stashed token. */ stashed: function() { return this.stash.length && this.stash.shift(); }, /** * Deferred token. */ deferred: function() { return this.deferredTokens.length && this.deferredTokens.shift(); }, /** * end-of-source. */ eos: function() { if (this.input.length) return; if (this.indentStack.length) { this.indentStack.shift(); return this.tok('outdent'); } else { return this.tok('eos'); } }, /** * Comment. */ comment: function() { var captures; if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { this.consume(captures[0].length); var tok = this.tok('comment', captures[2]); tok.buffer = '-' != captures[1]; return tok; } }, /** * Tag. */ tag: function() { var captures; if (captures = /^(\w[-:\w]*)/.exec(this.input)) { this.consume(captures[0].length); var tok, name = captures[1]; if (':' == name[name.length - 1]) { name = name.slice(0, -1); tok = this.tok('tag', name); this.defer(this.tok(':')); while (' ' == this.input[0]) this.input = this.input.substr(1); } else { tok = this.tok('tag', name); } return tok; } }, /** * Filter. */ filter: function() { return this.scan(/^:(\w+)/, 'filter'); }, /** * Doctype. */ doctype: function() { return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); }, /** * Id. */ id: function() { return this.scan(/^#([\w-]+)/, 'id'); }, /** * Class. */ className: function() { return this.scan(/^\.([\w-]+)/, 'class'); }, /** * Text. */ text: function() { return this.scan(/^(?:\| ?)?([^\n]+)/, 'text'); }, /** * Extends. */ "extends": function() { return this.scan(/^extends +([^\n]+)/, 'extends'); }, /** * Block prepend. */ prepend: function() { var captures; if (captures = /^prepend +([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); var mode = 'prepend' , name = captures[1] , tok = this.tok('block', name); tok.mode = mode; return tok; } }, /** * Block append. */ append: function() { var captures; if (captures = /^append +([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); var mode = 'append' , name = captures[1] , tok = this.tok('block', name); tok.mode = mode; return tok; } }, /** * Block. */ block: function() { var captures; if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); var mode = captures[1] || 'replace' , name = captures[2] , tok = this.tok('block', name); tok.mode = mode; return tok; } }, /** * Yield. */ yield: function() { return this.scan(/^yield */, 'yield'); }, /** * Include. */ include: function() { return this.scan(/^include +([^\n]+)/, 'include'); }, /** * Case. */ "case": function() { return this.scan(/^case +([^\n]+)/, 'case'); }, /** * When. */ when: function() { return this.scan(/^when +([^:\n]+)/, 'when'); }, /** * Default. */ "default": function() { return this.scan(/^default */, 'default'); }, /** * Assignment. */ assignment: function() { var captures; if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { this.consume(captures[0].length); var name = captures[1] , val = captures[2]; return this.tok('code', 'var ' + name + ' = (' + val + ');'); } }, /** * Mixin. */ mixin: function(){ var captures; if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { this.consume(captures[0].length); var tok = this.tok('mixin', captures[1]); tok.args = captures[2]; return tok; } }, /** * Conditional. */ conditional: function() { var captures; if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { this.consume(captures[0].length); var type = captures[1] , js = captures[2]; switch (type) { case 'if': js = 'if (' + js + ')'; break; case 'unless': js = 'if (!(' + js + '))'; break; case 'else if': js = 'else if (' + js + ')'; break; case 'else': js = 'else'; break; } return this.tok('code', js); } }, /** * While. */ "while": function() { var captures; if (captures = /^while +([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); return this.tok('code', 'while (' + captures[1] + ')'); } }, /** * Each. */ each: function() { var captures; if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); var tok = this.tok('each', captures[1]); tok.key = captures[2] || '$index'; tok.code = captures[3]; return tok; } }, /** * Code. */ code: function() { var captures; if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { this.consume(captures[0].length); var flags = captures[1]; captures[1] = captures[2]; var tok = this.tok('code', captures[1]); tok.escape = flags[0] === '='; tok.buffer = flags[0] === '=' || flags[1] === '='; return tok; } }, /** * Attributes. */ attrs: function() { if ('(' == this.input.charAt(0)) { var index = this.indexOfDelimiters('(', ')') , str = this.input.substr(1, index-1) , tok = this.tok('attrs') , len = str.length , colons = this.colons , states = ['key'] , key = '' , val = '' , quote , c; function state(){ return states[states.length - 1]; } function interpolate(attr) { return attr.replace(/#\{([^}]+)\}/g, function(_, expr){ return quote + " + (" + expr + ") + " + quote; }); } this.consume(index + 1); tok.attrs = {}; function parse(c) { var real = c; // TODO: remove when people fix ":" if (colons && ':' == c) c = '='; switch (c) { case ',': case '\n': switch (state()) { case 'expr': case 'array': case 'string': case 'object': val += c; break; default: states.push('key'); val = val.trim(); key = key.trim(); if ('' == key) return; tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val ? true : interpolate(val); key = val = ''; } break; case '=': switch (state()) { case 'key char': key += real; break; case 'val': case 'expr': case 'array': case 'string': case 'object': val += real; break; default: states.push('val'); } break; case '(': if ('val' == state() || 'expr' == state()) states.push('expr'); val += c; break; case ')': if ('expr' == state() || 'val' == state()) states.pop(); val += c; break; case '{': if ('val' == state()) states.push('object'); val += c; break; case '}': if ('object' == state()) states.pop(); val += c; break; case '[': if ('val' == state()) states.push('array'); val += c; break; case ']': if ('array' == state()) states.pop(); val += c; break; case '"': case "'": switch (state()) { case 'key': states.push('key char'); break; case 'key char': states.pop(); break; case 'string': if (c == quote) states.pop(); val += c; break; default: states.push('string'); val += c; quote = c; } break; case '': break; default: switch (state()) { case 'key': case 'key char': key += c; break; default: val += c; } } } for (var i = 0; i < len; ++i) { parse(str.charAt(i)); } parse(','); return tok; } }, /** * Indent | Outdent | Newline. */ indent: function() { var captures, re; // established regexp if (this.indentRe) { captures = this.indentRe.exec(this.input); // determine regexp } else { // tabs re = /^\n(\t*) */; captures = re.exec(this.input); // spaces if (captures && !captures[1].length) { re = /^\n( *)/; captures = re.exec(this.input); } // established if (captures && captures[1].length) this.indentRe = re; } if (captures) { var tok , indents = captures[1].length; ++this.lineno; this.consume(indents + 1); if (' ' == this.input[0] || '\t' == this.input[0]) { throw new Error('Invalid indentation, you can use tabs or spaces but not both'); } // blank line if ('\n' == this.input[0]) return this.tok('newline'); // outdent if (this.indentStack.length && indents < this.indentStack[0]) { while (this.indentStack.length && this.indentStack[0] > indents) { this.stash.push(this.tok('outdent')); this.indentStack.shift(); } tok = this.stash.pop(); // indent } else if (indents && indents != this.indentStack[0]) { this.indentStack.unshift(indents); tok = this.tok('indent', indents); // newline } else { tok = this.tok('newline'); } return tok; } }, /** * Pipe-less text consumed only when * pipeless is true; */ pipelessText: function() { if (this.pipeless) { if ('\n' == this.input[0]) return; var i = this.input.indexOf('\n'); if (-1 == i) i = this.input.length; var str = this.input.substr(0, i); this.consume(str.length); return this.tok('text', str); } }, /** * ':' */ colon: function() { return this.scan(/^: */, ':'); }, /** * Return the next token object, or those * previously stashed by lookahead. * * @return {Object} * @api private */ advance: function(){ return this.stashed() || this.next(); }, /** * Return the next token object. * * @return {Object} * @api private */ next: function() { return this.deferred() || this.eos() || this.pipelessText() || this.yield() || this.doctype() || this["case"]() || this.when() || this["default"]() || this["extends"]() || this.append() || this.prepend() || this.block() || this.include() || this.mixin() || this.conditional() || this.each() || this["while"]() || this.assignment() || this.tag() || this.filter() || this.code() || this.id() || this.className() || this.attrs() || this.indent() || this.comment() || this.colon() || this.text(); } };
var express = require('express'); var request = require('request'); var rp = require('rp'); var config = require('../../config') var router = express.Router(); var twilio = require('twilio'); var mysql = require('mysql'); var connection = mysql.createConnection(config.mysqlConfig); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: '네이버 채용 알리미' }); }); router.post('/enlist', function(req, res, next) { if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) { return res.json({"response" : "Please complete recaptcha."}); } var regex = /^\d{3}-\d{4}-\d{4}$/; if(!req.body.phonenumber.match(regex)){ return res.json({"response" : "Please input a correct phone number. (000-0000-0000)"}); } request.post({url:"https://www.google.com/recaptcha/api/siteverify", form:{"secret" : config.captchasecret, "response" : req.body['g-recaptcha-response']}}, function(error, response, body){ body = JSON.parse(body); // Success will be true or false depending upon captcha validation. if(body.success !== undefined && !body.success) { return res.json({"response" : "Recaptcha validation failed, please try again."}) } //everything OK, now we add the phone number to the DB. connection.query('INSERT INTO `NotifyList`(phonenumber) VALUES("'+req.body.phonenumber+'");', function(error, cursor){ if(error==null){ var twclient = new twilio(config.twaccountSid, config.twaccountToken); twclient.messages.create({ body: "Welcome to Naver job opening notification service!"+" / 구독취소:gyuhyeonlee.com", to: '+82'+req.body.phonenumber, from: '+12568184331' }) .then((message) => console.log(message.sid)); return res.json({"response" : "Success! Please wait for confirmation SMS."}); } else{ return res.json({"response" : "We're sorry, but either our DB is not working, or you're already subscribed!"}); } }); //end of insert connection.query }); //end of request.post (sorry for callback hell!) }) //end of router post handling router.post('/unsubscribe', function(req, res, next) { if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) { return res.json({"response" : "Please complete recaptcha."}); } var regex = /^\d{3}-\d{4}-\d{4}$/; if(!req.body.phonenumber.match(regex)){ return res.json({"response" : "Please input a correct phone number. (000-0000-0000)"}); } request.post({url:"https://www.google.com/recaptcha/api/siteverify", form:{"secret" : config.captchasecret, "response" : req.body['g-recaptcha-response']}}, function(error, response, body){ body = JSON.parse(body); // Success will be true or false depending upon captcha validation. if(body.success !== undefined && !body.success) { return res.json({"response" : "Recaptcha validation failed, please try again."}) } //everything OK, now we add the phone number to the DB. connection.query('DELETE FROM `NaverJobs`.`NotifyList` WHERE `phonenumber`="'+req.body.phonenumber+'";', function(error, cursor){ if(error==null){ if(cursor.affectedRows>0){ return res.json({"response" : "Success! Your number has been deleted."}); } else{ return res.json({"response" : "Your number is not in the database!"}); } } else{ return res.json({"response" : "We're sorry, our DB seems to be down right now..."}); } }); //end of insert connection.query }); //end of request.post (sorry for callback hell!) }); // line webhook for receiving sub&unsub events. router.post('/lineevents', function(req, res, next) { let insertvalues = []; let removevalues = []; if(req.body.events!==null && req.body.events!==undefined){ for (let i = 0; i < req.body.events.length; ++i) { if (req.body.events[i].type == 'follow') { insertvalues.push(req.body.events[i].source.userId); } else if(req.body.events[i].type == 'unfollow') { removevalues.push(req.body.events[i].source.userId); } } if (insertvalues.length > 0) { // don't really care about data consistency. All we need make sure is that removing takes priority over adding. connection.query('INSERT INTO `NaverJobs`.`LineFriends`(id) VALUES (?);', insertvalues, function(error, cursor){ if(error == null){ let options = { method: "POST", uri: "https://api.line.me/v2/bot/message/multicast", headers: { 'Content-Type':'application/json', 'Authorization':'Bearer {'+config.linetoken+'}' }, body: { to: insertvalues, messages: [{"type":"text", "text": "구독 신청 감사합니다! 변경사항이 있을 경우 바로 알려드릴게요 :)"}] }, json: true // this encodes our body as json when SENDING POST request. // in GET requests, this means it will encode RESPONSE in json when we RECEIVE IT. // pretty confusing... }; rp(options).catch((e) => console.log(e)); // one way request, don't really need .then() promises. Send greetings to new users. } else{ console.log("DB error : "+error); } }); } if (removevalues.length > 0) { connection.query('DELETE FROM `NaverJobs`.`LineFriends` WHERE `id`=?;', removevalues, function(error){ if(error != null){ console.log("DB error : "+error); } }); } } res.set('Content-Type', 'text/plain'); res.send("Thanks LINE!"); }); module.exports = router;
/** * local_resize_img * by [email protected] * 2015-04-08 */ var MAX_SIZE = 600; var LIT_SIZE = 80; $.fn.local_resize_img = function(obj) { this.on('change', function() { var file_path = this.files[0]; load_image(file_path); }); function is_android() { var ua = navigator.userAgent.toLowerCase(); is_android_browser = ua.indexOf("android") > -1; return is_android_browser; } function is_ios() { var ua = navigator.userAgent.toLowerCase(); is_android_browser = ua.indexOf("iphone") > -1; return is_android_browser; } function load_image(file_path) { if (! file_path.type.match(/image.*/)) { if (window.console) { console.log("我说哥哥,只能选图片"); }else { window.confirm("我说哥哥,只能选图片啊"); } return ; } var reader = new FileReader() ; reader.onloadend = function(e) { //获取到图片内容,准备渲染 (内容是base64滴,还带header) render(e.target.result); }; reader.readAsDataURL(file_path); }; function render(img_data) { var img = new Image() ; img.src = img_data; //先把图啊,用个img对象装起来 img.onload = function () { var this_img = this; var w = this_img.width, lit_w, lit_h, h = this_img.height, scale = w/h; //宽高比 //计算缩放之后的宽高 if (Math.min(w,h) > MAX_SIZE) { if (w > h) { h=MAX_SIZE; w=h*scale; lit_h = LIT_SIZE; lit_w = lit_h * scale; } else { w=MAX_SIZE; h = w/scale; lit_w = LIT_SIZE ; lit_h = w/scale; } } //取exif.orientation EXIF.getData(this); var orientation = EXIF.getTag(this, "Orientation") || 1; var rotate_degree = 0; switch(orientation) { case 1: rotate_degree = 0; break; case 8: rotate_degree = -90; break; case 3: rotate_degree = 180; break; case 6: rotate_degree = 90; break; } var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); if (rotate_degree == 90 || rotate_degree == -90) { $(canvas).attr({width: h, height: w}); }else { $(canvas).attr({width: w, height: h}); } //draw on big resized canvas MAX_SIZE var canvas_width = $(canvas).attr("width"); var canvas_height = $(canvas).attr("height"); if (is_ios()) { var mp_img = new MegaPixImage(img); mp_img.render(canvas, {maxWidth:w, maxHeight:h, orientation:orientation}); }else { ctx.translate(canvas_width/2, canvas_height/2); ctx.rotate(rotate_degree * Math.PI/180); ctx.drawImage(this_img, -w/2,-h/2, w,h); } var base64 = canvas.toDataURL("image/jpeg", 0.8); if (base64.indexOf("image/jpeg") > 0) { } else { var encoder = new JPEGEncoder(80); var img_data = ctx.getImageData(0,0,canvas_width,canvas_height); base64 = encoder.encode(img_data); } var result = { base64: base64, }; obj.success(result); }; } };
'use strict'; angular.module("services") .factory('mapSVC', [ "colorsSVC", function(colorsSVC) { // Converts two coordinates to a GoogleLatLong var cnvLatLong = function (x) { return new google.maps.LatLng(x[0],x[1]); }; var setPathMode = function (mode) { if(mode == "driving"){ return google.maps.DirectionsTravelMode.DRIVING; } else if(mode == "walking"){ return google.maps.DirectionsTravelMode.WALKING; } else if(mode == "transit"){ return google.maps.DirectionsTravelMode.TRANSIT; } else if(mode == "bicycling"){ return google.maps.DirectionsTravelMode.BICYCLING; } } // Sets the colors of the chart, from RGB data to Hex var setColors = function (colors) { var util = []; for(var i=0;i<colors.length;i++){ var rgb = colors[i]; var color = colorsSVC.rgbToHex(rgb.red, rgb.green, rgb.blue); util.push(color); } return util; } var createPolyline = function (pathLine, color, map) { return new google.maps.Polyline({ path: pathLine , strokeColor: color , strokeOpacity: 1.0 , strokeWeight: 3 , map: map , visible: true }); }; var createMarker = function (point, map) { var marker = new MarkerWithLabel({ position: new google.maps.LatLng(point.latitude, point.longitude) , map: map , title: point.id.toString() , icon: { url: 'aps/res/markerBI_24.png' , size: new google.maps.Size(24,24) , anchor: new google.maps.Point(12,12) } , zIndex: 1 , labelContent: point.id < 100 ? (point.id < 10 ? "T0" + point.id.toString() : "T" + point.id.toString()) : point.id.toString() , labelAnchor: new google.maps.Point(8, 7) , labelClass: "mrkLa" , labelZIndex: 2 }); return marker; } var buildPath = function(path, color, map, polylines, method) { var pathline = []; var service = new google.maps.DirectionsService(); for(var i=0; i<path.length-1; i++) { service.route({ origin: cnvLatLong(path[i]) // Consumes a point from the path , destination: cnvLatLong(path[i+1]) // Recursively calls itself for the next points , travelMode: setPathMode(method) } , function(result, status) { // Async Callback, gets the response from Google Maps Directions if(status == google.maps.DirectionsStatus.OK) { var path = result.routes[0].overview_path; var legs = result.routes[0].legs; for (var i=0;i<legs.length;i++) { // Parses the subroutes between two points var steps = legs[i].steps; for (var j=0;j<steps.length;j++) { var nextSegment = steps[j].path; for (var k=0;k<nextSegment.length;k++) { // Pushes the segment on the path pathline.push(nextSegment[k]); } } } // Generates the Polyline of the calculated path polylines.push(createPolyline(pathline,color,map)); pathline = []; } }); } }; var resetMap = function (map, polylines, markers, id, position) { for(var line in polylines){ polylines[line].setMap(null); } for(var marker in markers){ markers[marker].setMap(null); } }; return { createPolyline : createPolyline , buildPath : buildPath , setColors : setColors , buildLegend : function (map, position, id) { var legend = document.getElementById('mapLegend'); if (position == "top-right"){ if(map.controls[google.maps.ControlPosition.TOP_RIGHT].length > 0){ map.controls[google.maps.ControlPosition.TOP_RIGHT].pop(); } map.controls[google.maps.ControlPosition.TOP_RIGHT].push(legend); } if (position == "top-left"){ if(map.controls[google.maps.ControlPosition.TOP_LEFT].length > 0){ map.controls[google.maps.ControlPosition.TOP_LEFT].pop(); } map.controls[google.maps.ControlPosition.TOP_LEFT].push(legend); } if (position == "bottom-right"){ if(map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].length > 0){ map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].pop(); } map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(legend); } if (position == "bottom-left"){ if(map.controls[google.maps.ControlPosition.BOTTOM_LEFT].length > 0){ map.controls[google.maps.ControlPosition.BOTTOM_LEFT].pop(); } map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(legend); } } , createMarker: createMarker , updateMovie : function (markers, newData, map) { for(var marker in markers) { var toBeRemoved = true; // It's always pending removal, except when it has to be updated! for(var i=0;i<newData.newPoints.length && toBeRemoved == true;i++) { // Then update it! if(markers[marker].title == newData.newPoints[i].id.toString() || markers[marker].title == newData.newPoints[i].id){ markers[marker].setPosition(new google.maps.LatLng(newData.newPoints[i].latitude, newData.newPoints[i].longitude)); newData.newPoints.splice(i,1); toBeRemoved = false; } } if(toBeRemoved) { // I guess its time has come markers[marker].setMap(); delete markers[marker]; } } // A new life is born! for(var obj in newData.newPoints) { markers[newData.newPoints[obj].id] = createMarker(newData.newPoints[obj], map); } } , resetMap: resetMap } }]);
module.exports = require('identity-obj-proxy');
Meteor.startup(function () { Meteor.defer(function () { Session.setDefault("checked", $("input[type=checkbox]").is(":checked")); }); if (Meteor.isCordova) { window.alert = navigator.notification.alert; } Push.addListener('message', function(notification) { // Called on every message console.log(JSON.stringify(notification)) function alertDismissed() { NotificationHistory.update({_id: notification.payload.historyId}, { $set: { "recievedAt": new Date() } }); } alert(notification.message, alertDismissed, notification.payload.title, "Ok"); }); });
// dependencies var AWS = require('aws-sdk'); //Provided by lambda (no need to install) var async = require('async'); var gm = require('gm') .subClass({ imageMagick: true }); // Enable ImageMagick integration. var util = require('util'); var fs = require("fs"); var path = require("path"); // get reference to S3 client var s3 = new AWS.S3(); exports.handler = function(event, context) { // Load config.json var configPath = path.resolve(__dirname, "config.json"); var config = JSON.parse(fs.readFileSync(configPath, { encoding: "utf8" })); // Read options from the event. console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); var srcBucket = event.Records[0].s3.bucket.name; var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); var dstBucket = config.dstBucket; //from config.json var dstKey = srcKey; // Sanity check: validate that source and destination are different buckets. if (srcBucket == dstBucket) { console.error("Destination bucket must not match source bucket."); return; } var thumbs = config.thumbs; // From config.json var thumbs2 = thumbs; // Take a copy to iterate, but leave original alone for (var i=0, tot=thumbs2.length; i < tot; i++) { async.waterfall( [ function download(next) { // Download the image from S3 into a buffer. s3.getObject( { Bucket: srcBucket, Key: srcKey }, next ); }, function getFormat(response, next) { gm(response.Body).format(function (err, format) { // console.log('Format: '+ format); next(null, format, response); }); }, function transform(imageType, response, next) { // console.log('imageType: '+ imageType); var current_thumb = thumbs.pop(); if(current_thumb.type=='thumbnail'){ if (typeof current_thumb.geometry == 'undefined') current_thumb.geometry = '960x540'; console.log('Thumbnail '+ current_thumb.geometry); gm(response.Body) .autoOrient() .noProfile() .command('convert') .out('-quality', 95) .out('-gravity', 'center') .out('-resize', current_thumb.geometry+'^') .out('-crop', current_thumb.geometry+'+0+0') .toBuffer(imageType, function(err, buffer) { if (err) { next(err); } else { next(null, response.ContentType, buffer, current_thumb.folder); } }); } else if(current_thumb.type=='resize'){ if (typeof current_thumb.width == 'undefined') current_thumb.width = null; if (typeof current_thumb.height == 'undefined') current_thumb.height = null; console.log('Resize '+ current_thumb.width + 'x' + current_thumb.height); gm(response.Body) .resize(current_thumb.width, current_thumb.height) .toBuffer(imageType, function(err, buffer) { if (err) { next(err); } else { next(null, response.ContentType, buffer, current_thumb.folder); } }); } }, function upload(contentType, data, folder, next) { // Stream the transformed image to a different S3 bucket. console.log('Uploading '+ folder + '/' + dstKey); s3.putObject( { Bucket: dstBucket, Key: folder + '/' + dstKey, Body: data, ContentType: contentType }, next ); } ], function (err) { if (err) { console.error( 'Unable to resize ' + srcBucket + '/' + srcKey + ' and upload to ' + dstBucket + '/' + dstKey + ' due to an error: ' + err ); } else { console.log( 'Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey ); } //callback(null, "message"); } ); } };
import Yoga from '@react-pdf/yoga'; import setJustifyContent from '../../src/node/setJustifyContent'; describe('node setJustifyContent', () => { const mock = jest.fn(); const node = { _yogaNode: { setJustifyContent: mock } }; beforeEach(() => { mock.mockReset(); }); test('should return node if no yoga node available', () => { const emptyNode = { box: { width: 10, height: 20 } }; const result = setJustifyContent(null)(emptyNode); expect(result).toBe(emptyNode); }); test('Should set center', () => { const result = setJustifyContent('center')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_CENTER); expect(result).toBe(node); }); test('Should set flex-end', () => { const result = setJustifyContent('flex-end')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_END); expect(result).toBe(node); }); test('Should set flex-start', () => { const result = setJustifyContent('flex-start')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_START); expect(result).toBe(node); }); test('Should set space-between', () => { const result = setJustifyContent('space-between')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_BETWEEN); expect(result).toBe(node); }); test('Should set space-around', () => { const result = setJustifyContent('space-around')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_AROUND); expect(result).toBe(node); }); test('Should set space-evenly', () => { const result = setJustifyContent('space-evenly')(node); expect(mock.mock.calls).toHaveLength(1); expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_EVENLY); expect(result).toBe(node); }); });
// Constants export const USERS_INCREMENT = 'USERS_INCREMENT' export const USERS_DOUBLE_ASYNC = 'USERS_DOUBLE_ASYNC' // Actions export function increment(value = 1) { return { type: USERS_INCREMENT, payload: value } } export const doubleAsync = () => { return (dispatch, getState) => { return new Promise((resolve) => { setTimeout(() => { dispatch({ type: USERS_DOUBLE_ASYNC, payload: getState().users }) resolve() }, 200) }) } } export const actions = { increment, doubleAsync } // Action Handlers const ACTION_HANDLERS = { [USERS_INCREMENT]: (state, action) => state + action.payload, [USERS_DOUBLE_ASYNC]: (state) => state * 2 } // Reducer const initialState = 0 export default function usersReducer(state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
import React from 'react'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './InputArea.scss'; const exclamation = () => <div className={styles.suffix + ' ' + styles.exclamation}> <SvgExclamation width={2} height={11}/> </div>; export default exclamation;
var TestTime = require('logux-core').TestTime var ServerSync = require('../server-sync') var TestPair = require('../test-pair') var sync function createTest () { var test = new TestPair() sync = new ServerSync('server', TestTime.getLog(), test.left) test.leftSync = sync return test.left.connect().then(function () { return test }) } afterEach(function () { sync.destroy() }) it('sends debug messages', function () { return createTest().then(function (test) { test.leftSync.sendDebug('testType', 'testData') return test.wait('right') }).then(function (test) { expect(test.leftSent).toEqual([['debug', 'testType', 'testData']]) }) }) it('emits a debug on debug error messages', function () { var pair = new TestPair() sync = new ServerSync('server', TestTime.getLog(), pair.left) sync.authenticated = true var debugs = [] sync.on('debug', function (type, data) { debugs.push(type, data) }) sync.onMessage(['debug', 'error', 'testData']) expect(debugs).toEqual(['error', 'testData']) }) it('checks types', function () { var wrongs = [ ['debug'], ['debug', 0], ['debug', []], ['debug', {}, 'abc'], ['debug', 'error', 0], ['debug', 'error', []], ['debug', 'error', {}] ] return Promise.all(wrongs.map(function (command) { return createTest().then(function (test) { test.right.send(command) return test.wait('right') }).then(function (test) { expect(test.leftSync.connected).toBeFalsy() expect(test.leftSent).toEqual([ ['error', 'wrong-format', JSON.stringify(command)] ]) }) })) })
'use strict'; var util = require('util'), Transform = require('stream').Transform, Response = require('../response'); function ResponseStream (multiline) { this.multiline = multiline || false; var response; this._transform = function (chunk, encoding, callback) { if (undefined === response) { response = Response.createFromString(encoding === 'buffer' ? chunk.toString() : chunk); if (false === this.multiline) { this.push(response); this.end(); } } else { response.lines.push(chunk); } callback(); }; this._flush = function (callback) { this.push(response); callback(); }; Transform.call(this, { objectMode: true }); } util.inherits(ResponseStream, Transform); module.exports = ResponseStream;
/* eslint-env browser */ /** * Module dependencies. */ var Base = require('./base'); var utils = require('../utils'); var Progress = require('../browser/progress'); var escapeRe = require('escape-string-regexp'); var escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ /* eslint-disable no-unused-vars, no-native-reassign */ var Date = global.Date; var setTimeout = global.setTimeout; var setInterval = global.setInterval; var clearTimeout = global.clearTimeout; var clearInterval = global.clearInterval; /* eslint-enable no-unused-vars, no-native-reassign */ /** * Expose `HTML`. */ exports = module.exports = HTML; /** * Stats template. */ var statsTemplate = '<ul id="mocha-stats">' + '<li class="progress"><canvas width="40" height="40"></canvas></li>' + '<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' + '<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>' + '<li class="duration">duration: <em>0</em>s</li>' + '</ul>'; /** * Initialize a new `HTML` reporter. * * @api public * @param {Runner} runner */ function HTML(runner) { Base.call(this, runner); var self = this; var stats = this.stats; var stat = fragment(statsTemplate); var items = stat.getElementsByTagName('li'); var passes = items[1].getElementsByTagName('em')[0]; var passesLink = items[1].getElementsByTagName('a')[0]; var failures = items[2].getElementsByTagName('em')[0]; var failuresLink = items[2].getElementsByTagName('a')[0]; var duration = items[3].getElementsByTagName('em')[0]; var canvas = stat.getElementsByTagName('canvas')[0]; var report = fragment('<ul id="mocha-report"></ul>'); var stack = [report]; var progress; var ctx; var root = document.getElementById('mocha'); if (canvas.getContext) { var ratio = window.devicePixelRatio || 1; canvas.style.width = canvas.width; canvas.style.height = canvas.height; canvas.width *= ratio; canvas.height *= ratio; ctx = canvas.getContext('2d'); ctx.scale(ratio, ratio); progress = new Progress(); } if (!root) { return error('#mocha div missing, add it to your document'); } // pass toggle on(passesLink, 'click', function() { unhide(); var name = (/pass/).test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) { hideSuitesWithout('test pass'); } }); // failure toggle on(failuresLink, 'click', function() { unhide(); var name = (/fail/).test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) { hideSuitesWithout('test fail'); } }); root.appendChild(stat); root.appendChild(report); if (progress) { progress.size(40); } runner.on('suite', function(suite) { if (suite.root) { return; } // suite var url = self.suiteURL(suite); var el = fragment('<li class="suite"><h1><a href="%e">%e</a></h1></li>', url, suite.title); // container stack[0].appendChild(el); stack.unshift(document.createElement('ul')); el.appendChild(stack[0]); }); runner.on('suite end', function(suite) { if (suite.root) { return; } stack.shift(); }); runner.on('fail', function(test) { if (test.type === 'hook') { runner.emit('test end', test); } }); runner.on('test end', function(test) { // TODO: add to stats var percent = stats.tests / this.total * 100 | 0; if (progress) { progress.update(percent).draw(ctx); } // update stats var ms = new Date() - stats.start; text(passes, stats.passes); text(failures, stats.failures); text(duration, (ms / 1000).toFixed(2)); // test var el; if (test.state === 'passed') { var url = self.testURL(test); el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url); } else if (test.pending) { el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title); } else { el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay">‣</a></h2></li>', test.title, self.testURL(test)); var stackString; // Note: Includes leading newline var message = test.err.toString(); // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we // check for the result of the stringifying. if (message === '[object Error]') { message = test.err.message; } if (test.err.stack) { var indexOfMessage = test.err.stack.indexOf(test.err.message); if (indexOfMessage === -1) { stackString = test.err.stack; } else { stackString = test.err.stack.substr(test.err.message.length + indexOfMessage); } } else if (test.err.sourceURL && test.err.line !== undefined) { // Safari doesn't give you a stack. Let's at least provide a source line. stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; } stackString = stackString || ''; if (test.err.htmlMessage && stackString) { el.appendChild(fragment('<div class="html-error">%s\n<pre class="error">%e</pre></div>', test.err.htmlMessage, stackString)); } else if (test.err.htmlMessage) { el.appendChild(fragment('<div class="html-error">%s</div>', test.err.htmlMessage)); } else { el.appendChild(fragment('<pre class="error">%e%e</pre>', message, stackString)); } } // toggle code // TODO: defer if (!test.pending) { var h2 = el.getElementsByTagName('h2')[0]; on(h2, 'click', function() { pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; }); var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString())); el.appendChild(pre); pre.style.display = 'none'; } // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. if (stack[0]) { stack[0].appendChild(el); } }); } /** * Makes a URL, preserving querystring ("search") parameters. * * @param {string} s * @return {string} A new URL. */ function makeUrl(s) { var search = window.location.search; // Remove previous grep query parameter if present if (search) { search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); } return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s)); } /** * Provide suite URL. * * @param {Object} [suite] */ HTML.prototype.suiteURL = function(suite) { return makeUrl(suite.fullTitle()); }; /** * Provide test URL. * * @param {Object} [test] */ HTML.prototype.testURL = function(test) { return makeUrl(test.fullTitle()); }; /** * Display error `msg`. * * @param {string} msg */ function error(msg) { document.body.appendChild(fragment('<div id="mocha-error">%e</div>', msg)); } /** * Return a DOM fragment from `html`. * * @param {string} html */ function fragment(html) { var args = arguments; var div = document.createElement('div'); var i = 1; div.innerHTML = html.replace(/%([se])/g, function(_, type) { switch (type) { case 's': return String(args[i++]); case 'e': return escape(args[i++]); // no default } }); return div.firstChild; } /** * Check for suites that do not have elements * with `classname`, and hide them. * * @param {text} classname */ function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); if (!els.length) { suites[i].className += ' hidden'; } } } /** * Unhide .hidden suites. */ function unhide() { var els = document.getElementsByClassName('suite hidden'); while (els.length > 0) { els[0].className = els[0].className.replace('suite hidden', 'suite'); } } /** * Set an element's text contents. * * @param {HTMLElement} el * @param {string} contents */ function text(el, contents) { if (el.textContent) { el.textContent = contents; } else { el.innerText = contents; } } /** * Listen on `event` with callback `fn`. */ function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); } else { el.attachEvent('on' + event, fn); } }
// Regular expression that matches all symbols with the `Pattern_White_Space` property as per Unicode v6.3.0: /[\x09-\x0D\x20\x85\u200E\u200F\u2028\u2029]/;
$(function() { // When we're using HTTPS, use WSS too. $('#all_messages').scrollTop($('#all_messages')[0].scrollHeight); var to_focus = $("#message"); var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/ws/"); chatsock.onmessage = function(message) { if($("#no_messages").length){ $("#no_messages").remove(); } var data = JSON.parse(message.data); if(data.type == "presence"){ //update lurkers count lurkers = data.payload.lurkers; lurkers_ele = document.getElementById("lurkers-count"); lurkers_ele.innerText = lurkers; //update logged in users list user_list = data.payload.members; document.getElementById("loggedin-users-count").innerText = user_list.length; user_list_obj = document.getElementById("user-list"); user_list_obj.innerText = ""; //alert(user_list); for(var i = 0; i < user_list.length; i++ ){ var user_ele = document.createElement('li'); user_ele.setAttribute('class', 'list-group-item'); user_ele.innerText = user_list[i]; user_list_obj.append(user_ele); } return; } var chat = $("#chat") var ele = $('<li class="list-group-item"></li>') ele.append( '<strong>'+data.user+'</strong> : ') ele.append( data.message) chat.append(ele) $('#all_messages').scrollTop($('#all_messages')[0].scrollHeight); }; $("#chatform").on("submit", function(event) { var message = { message: $('#message').val() } chatsock.send(JSON.stringify(message)); $("#message").val('').focus(); return false; }); setInterval(function() { chatsock.send(JSON.stringify("heartbeat")); }, 10000); });
"use strict"; /** @module router * A module that defines a class for routing * http requests to handler functions */ module.exports = { Router: Router }; var url = require('url'); function Router(db) { this.db = db; this.routeMap = { get: [], post: [] } } /** @function route * Routes an incoming request to the proper registered * request handler, or sends a 404 error if no match * is found. Modifies the request object to contain a * params associative array of tokens parsed from the * reqeust object. * @param {http.incomingRequest} req - the reqeust object * @param {http.serverResponse} res - the response object */ Router.prototype.route = function(req, res) { console.log("Routing!"); // The method is used to determine which routeMap // to search for the route in var routeMap = this.routeMap[req.method.toLowerCase()]; // The resource string from the request url will // be matched against the routeMap regular expressions var resource = url.parse(req.url).pathname; // Find the correct route for the requested resource // INVARIANT: route has not yet been found. for(var i = 0; i < routeMap.length; i++){ var match = routeMap[i].regexp.exec(resource); if(match) { // Store the parameters as an object // on the request req.params = {} routeMap[i].tokens.forEach(function(token, j){ // Each token corresponds to a capture group // from the regular expression match. These are // offset by 1, as the first entry in the match // array is the full matching string. req.params[token] = match[j+1]; }); // Trigger the handler and return, stopping execution return routeMap[i].handler(req, res); } } console.log("Resource Not Mapped"); // If we reach this point, the resource was not mapped // to a route, so send a 404 error res.statusCode = 404; res.statusMessage = "Resource not found"; res.end("Resource not found"); } /** @function get * Adds a GET route with associated handler to * the get routemap. * @param {string} route - the route to add * @param {function} handler - the function to * call when a match is found */ Router.prototype.get = function(route, handler) { addRoute(this.routeMap.get, route, handler); } /** @function post * Adds a POST route with associated handler to * the get routemap. * @param {string} route - the route to add * @param {function} handler - the function to * call when a match is found */ Router.prototype.post = function(route, handler) { addRoute(this.routeMap.post, route, handler); } /** @function resource * This is a shorthand method for generating restful * routes for a resource, i.e.: * GET route/ -> resource.list() * POST route/ -> resource.add() * GET route/:id -> resource.show() * POST route/:id -> resource.update() * GET route/:id/edit -> resource.edit() * POST route/:id/destroy -> resource.destroy() * @param {string} route - the resource route * @param {object} resource - an object implementing the * above methods */ Router.prototype.resource = function(route, resource) { var db = this.db; console.log("Route: "+route); if(resource.list) this.get(route, function(req, res) {resource.list(req, res, db)}); if(resource.create) this.post(route, function(req, res) {resource.create(req, res, db)}); if(resource.read) this.get(route + '/:id', function(req, res) {resource.read(req, res, db)}); if(resource.edit) this.get(route + '/:id/edit', function(req, res) {resource.read(req, res, db)}); if(resource.update) this.post(route + '/:id', function(req, res) {resource.update(req, res, db)}); if(resource.destroy) this.get(route + '/:id/destroy', function(req, res) {resource.destroy(req, res, db)}); } /** @function addRoute * This helper function adds a route to a routeMap * associative array * @param {object} routeMap - the routemap to add the route to * @param {string} route - the route to add * @param {function} handler - the handler to add */ function addRoute(routeMap, route, handler) { var tokens = []; // Convert the route into a regular expression var parts = route.split('/').map(function(part) { if(part.charAt(0) == ':') { // This is a token, so store the token and // add a regexp capture group to our parts array tokens.push(part.slice(1)); return '(\\w+)'; } else { // This is a static sequence of characters, // so leave it as-is return part; } }); var regexp = new RegExp('^' + parts.join('/') + '/?$'); // Store the route in the routemap routeMap.push({ regexp: regexp, tokens: tokens, handler: handler }); }
function almostPerfect() { console.log("Hello, world!"); }; for(var i = 0; i < 10; i++) almostPerfect();
'use strict'; var _ = require( 'lodash' ); /* RESPONSE DATA STRUCTURE ========================================================================== data = [ ..., { // Day Object stop_id: '2681', stop_name: 'Highland Ave @ Benton Rd', mode: [ ..., { // Mode Object mode_name: 'Bus', route_type: '3', route: [ ..., { // Route Object route_id: '88', route_name: '88', direction: [ ..., { // Direction Object direction_id: '1', direction_name: 'Inbound', trip: [ ..., { // Trip Object sch_arr_dt: '1434278820', sch_dep_dt: '1434278820', trip_id: '26616679', trip_name: '6:40 am from Clarendon Hill Busway to Lechmere' }] }] }] }] }] */ /** * Convert from a Day Object to a flat array of data objects representing trips * @param {Number} dayIndex A numeric index for a weekday, from 0 to 6 * @param {Object} route A route object from the API response * @return {Array} A flat array of trip data objects */ function convertRouteToTripsArray( dayIndex, route ) { /* jshint camelcase: false */ var routeId = route.route_id; var routeName = route.route_name; return _.map( route.direction, function( direction ) { return _.map( direction.trip, function( trip ) { return { day: +dayIndex, name: trip.trip_name, route: routeName, routeId: routeId, time: +trip.sch_arr_dt, // Trip ID is NOT UNIQUE: avoid collection issues by avoiding 'id' tripId: +trip.trip_id }; }); }); } /** * Convert the raw API responses into a flat array of trips * @param {Array} data The API response object * @return {Array} A flat array of object literals describing trips */ function parseData( data ) { return _.chain( data ) .reduce(function( memo, day, dayIndex ) { var trips = _.chain( day.mode ) .pluck( 'route' ) .flatten() // Create the mapper method for the relevant day .map( _.partial( convertRouteToTripsArray, dayIndex ) ) .flattenDeep() // Deep flatten .value(); // Concatenate with the prior results return memo.concat( trips ); }, []) .sortBy(function( trip ) { return trip.time; }) .value(); } module.exports = parseData;
'use strict'; var extend = require('../utils/extend'); var LoginTask = require('./login'); var IonicAppLib = require('ionic-app-lib'); var IonicProject = IonicAppLib.project; var Share = IonicAppLib.share; var log = IonicAppLib.logging.logger; var Login = IonicAppLib.login; var appLibUtils = IonicAppLib.utils; var settings = { title: 'share', name: 'share', summary: 'Share an app with a client, co-worker, friend, or customer', args: { '<EMAIL>': 'The email to share the app with' }, isProjectTask: true }; function run(ionic, argv) { var project; if (argv._.length < 2) { return appLibUtils.fail('Invalid command', 'share'); } try { project = IonicProject.load(); } catch (ex) { appLibUtils.fail(ex.message); return; } if (project.get('app_id') === '') { return appLibUtils.fail('You must first upload the app to share it'); } var email = argv._[1]; if (email.indexOf('@') < 0) { return appLibUtils.fail('Invalid email address', 'share'); } log.info(['Sharing app ', project.get('name'), ' (', project.get('app_id'), ') with ', email, '.'].join('').green); return Login.retrieveLogin() .then(function(jar) { if (!jar) { log.info('No previous login existed. Attempting to log in now.'); return LoginTask.login(argv); } return jar; }) .then(function(jar) { return Share.shareApp(process.cwd(), jar, email); }) .catch(function(ex) { return appLibUtils.fail(ex); }); } module.exports = extend(settings, { run: run });
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true, white:true */ /*global X:true */ (function () { "use strict"; var _ = X._; /** Defines the data route. @extends X.Route @class */ X.dataRoute = X.Route.create({ handle: function (xtr) { var path, handler, session; path = xtr.get("requestType"); handler = this.find(path); if (!handler) { xtr.error("Could not handle %@".f(path)); } else { if (handler.needsSession) session = X.Session.create(xtr.get("data")); handler.handle(xtr, session); } }, find: function (path) { var ret = X.functorMap[path]; //console.log("find(): ", Object.keys(X.functorMap)); return ret; }, handles: "data /data".w() }); }());
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License (function (require, exports) { /** * @module */ /*whatsupdoc*/ var Q = require("q"); var has = Object.prototype.hasOwnProperty; var update = function (_object, object) { for (var key in object) { if (has.call(object, key)) { _object[key] = object[key]; } } }; var copy = function (object) { var _object = {}; update(_object, object); return _object; } var enquote = typeof JSON !== "undefined" && JSON.stringify || function (text) { return text; }; /** * Creates a `require` function, and arranges for modules * to be executed and their exports memoized, in a lexical * scope that includes: * * * `require(id)` with support for identifiers relative to * the calling module. * * `require.loader` for direct access to the module * loader, which can be used in nested requirers. * * `require.force(id)` * * `require.once(id, scope)` to execute but not memoize * a module, with an optional object that owns additional * free variables to inject into the module's lexical * scope. * * `module` * * `id` * * `path` * * `exports` * * @param {{loader, modules, debug}} options * @constructor * @returns {require(id)} */ exports.Require = function (options) { options = options || {}; var loader = options.loader; var factories = options.factories || {}; var modules = options.modules || {}; var apis = options.exports || {}; var supportDefine = options.supportDefine; var sharedScope = options.scope || {}; for (var id in apis) if (has.call(apis, id)) modules[id] = {"exports": apis[id]}; var load = function (id) { if (!factories[id]) { if (!loader) { return Q.reject("require: Can't load " + enquote(id)); } else { factories[id] = loader.load(id); } } return factories[id]; }; var require = function (id, baseId, options) { var module, factory, exports, completed, require; options = options || {}; id = resolve(id, baseId); if (has.call(modules, id)) { module = modules[id]; } else if (has.call(factories, id)) { factory = factories[id]; module = Module(id, factory.path); modules[id] = module; exports = modules[id].exports; require = Require(id); scope = {}; update(scope, sharedScope); update(scope, options.scope || {}); update(scope, { "require": require, "exports": exports, "module": module }); if (supportDefine) scope.define = Define(require, exports, module); try { var returned = factory(scope); completed = true; } finally { if (!completed) { delete modules[id]; } } if (typeof returned !== "undefined") { module.exports = returned; } } else { throw new Error("require: Can't load " + enquote(id)); } return module.exports; }; // curries require for a module, so its baseId can be assumed var Require = function (baseId) { var _require = function (id) { return require(id, baseId); }; _require.async = function (id) { return require.async(id, baseId) }; _require.loader = loader; _require.main = modules[options.main]; return _require; }; var Define = function (require, exports, module) { return function () { var callback = arguments[arguments.length - 1]; var returned; if (typeof callback === "function") { returned = callback(require, exports, module); } else { returned = callback; } if (typeof returned !== "undefined") module.exports = returned; return returned; }; }; // creates a module object var Module = function (baseId, path) { var module = {}; module.exports = {}; module.id = baseId; module.path = path; return module; }; // asynchronously adds module factories to a factory list var advanceFactories = function (id, factories) { return Q.when(load(id), function (factory) { return (factory.requirements || []).reduce(function (factories, requirement) { requirement = resolve(requirement, id); return Q.when(factories, function (factories) { if (has.call(modules, requirement) || has.call(factories, requirement)) return factories; return advanceFactories(requirement, factories); }); }, factories); }); }; require.reload = function (id) { return Q.when(advanceFactories(id, {}), function (factories) { return exports.Require({ "loader": loader, "factories": factories }); }); }; require.ensure = function (ids, callback) { var _modules = copy(modules); var _factories = ids.reduce(function (factories, id) { return Q.when(factories, function (factories) { return advanceFactories(id, factories); }); }, copy(factories)); return Q.when(_factories, function (factories) { callback(exports.Require({ "loader": loader, "factories": factories, "modules": _modules })); }, function (reason) { throw new Error(reason.message || reason); }); }; require.async = function (id, baseId) { var _factories = copy(factories); var _modules = copy(modules); return Q.when(advanceFactories(id, _factories), function (factories) { var _require = exports.Require({ "loader": loader, "factories": factories, "modules": _modules }); return _require(id, baseId); }); }; require.exec = function (id, scope) { var _factories = copy(factories); var _modules = copy(modules); return Q.when(advanceFactories(id, _factories), function (factories) { var _require = exports.Require({ "loader": loader, "factories": factories, "modules": _modules, "main": id, "scope": sharedScope, "supportDefine": supportDefine }); return _require(id, undefined, { "scope": scope }); }); }; require.loader = loader; return require; }; exports.resolve = resolve; function resolve(id, baseId) { id = String(id); var ids = id.split("/"); // assert ids.length >= 1 since "".split("") == [""] var first = ids[0]; if (first === ".." || first === ".") { var baseIds = baseId.split("/"); baseIds.pop(); ids.unshift.apply(ids, baseIds); } var parts = []; while (ids.length) { var part = ids.shift(); if (part === ".") { } else if (part === "..") { parts.pop(); } else { parts.push(part); } } return parts.join("/"); } }).apply({}, typeof exports !== "undefined" ? [ require, exports ] : [ (function (global) { return function (id) { return global["/" + id]; } })(this), this["/require"] = {} ] );
require([ "gaslib/Node" ], function(Node){ QUnit.test( "Node - initialize", function( assert ) { var node = new Node(); assert.equal( node.getCaption(), "Node", "Nieprawidłowa nazwa węzła" ); }); });
var requireDir = require('require-dir') requireDir('./gulp/tasks')
'use strict'; angular.module('myApp.setting') .factory('SettingServices', ['$http', '$q', '$timeout', function ($http, $q, $timeout) { var obj = {}; obj.getMyCfg = function() { var srvUrl; if (location.hostname === "localhost" || location.hostname === "127.0.0.1") { srvUrl = 'localhost:8090'; } else { srvUrl = 'exploit.courses'; } var cfg = { srvurl: srvUrl, } return cfg; } obj.setMyCfg = function(config) { localStorage.setItem('lxdcfg', JSON.stringify(config)); } obj.getSrvUrl = function() { return '//' + obj.getMyCfg().srvurl; } obj.getSrvApiUrl = function() { return '//' + obj.getMyCfg().srvurl + '/1.0'; } return obj; }]) ;
//#include 'debug.js' //#include 'Image.js' //#include 'path/Ellipse.js' //#include 'path/Path.js' //#include 'path/Point.js' //#include 'path/Rect.js' //#include 'Tokenizer.js' var CanvizEntity = exports.CanvizEntity = function(defaultAttrHashName, name, canviz, rootGraph, parentGraph, immediateGraph) { this.defaultAttrHashName = defaultAttrHashName; this.name = name; this.canviz = canviz; this.rootGraph = rootGraph; this.parentGraph = parentGraph; this.immediateGraph = immediateGraph; this.attrs = {}; this.drawAttrs = {}; }; CanvizEntity.prototype = { initBB: function() { var matches = this.getAttr('pos').match(/([0-9.]+),([0-9.]+)/); var x = Math.round(matches[1]); var y = Math.round(this.canviz.height - matches[2]); this.bbRect = new Rect(x, y, x, y); }, getAttr: function(attrName, escString) { if ('undefined' === typeof escString) escString = false; var attrValue = this.attrs[attrName]; if ('undefined' === typeof attrValue) { var graph = this.parentGraph; while ('undefined' !== typeof graph) { attrValue = graph[this.defaultAttrHashName][attrName]; if ('undefined' === typeof attrValue) { graph = graph.parentGraph; } else { break; } } } if (attrValue && escString) { attrValue = attrValue.replace(this.escStringMatchRe, _.bind(function(match, p1) { switch (p1) { case 'N': // fall through case 'E': return this.name; case 'T': return this.tailNode; case 'H': return this.headNode; case 'G': return this.immediateGraph.name; case 'L': return this.getAttr('label', true); } return match; }, this)); } return attrValue; }, draw: function(ctx, ctxScale, redrawCanvasOnly) { var i, tokens, fillColor, strokeColor; if (!redrawCanvasOnly) { this.initBB(); var bbDiv = $('<div>'); bbDiv.addClass('entity'); this.canviz.elements.append(bbDiv); var tooltip = this.getAttr('tooltip'); if (tooltip) bbDiv.attr({title: tooltip}); } _.each(this.drawAttrs, _.bind(function(command) { // debug(command); var tokenizer = new CanvizTokenizer(command); var token = tokenizer.takeChars(); if (token) { var dashStyle = 'solid'; ctx.save(); while (token) { // debug('processing token ' + token); switch (token) { case 'E': // filled ellipse case 'e': // unfilled ellipse var filled = ('E' == token); var cx = tokenizer.takeNumber(); var cy = this.canviz.height - tokenizer.takeNumber(); var rx = tokenizer.takeNumber(); var ry = tokenizer.takeNumber(); var path = new Ellipse(cx, cy, rx, ry); break; case 'P': // filled polygon case 'p': // unfilled polygon case 'L': // polyline var filled = ('P' == token); var closed = ('L' != token); var numPoints = tokenizer.takeNumber(); tokens = tokenizer.takeNumber(2 * numPoints); // points var path = new Path(); for (i = 2; i < 2 * numPoints; i += 2) { path.addBezier([ new Point(tokens[i - 2], this.canviz.height - tokens[i - 1]), new Point(tokens[i], this.canviz.height - tokens[i + 1]) ]); } if (closed) { path.addBezier([ new Point(tokens[2 * numPoints - 2], this.canviz.height - tokens[2 * numPoints - 1]), new Point(tokens[0], this.canviz.height - tokens[1]) ]); } break; case 'B': // unfilled b-spline case 'b': // filled b-spline var filled = ('b' == token); var numPoints = tokenizer.takeNumber(); tokens = tokenizer.takeNumber(2 * numPoints); // points var path = new Path(); for (i = 2; i < 2 * numPoints; i += 6) { path.addBezier([ new Point(tokens[i - 2], this.canviz.height - tokens[i - 1]), new Point(tokens[i], this.canviz.height - tokens[i + 1]), new Point(tokens[i + 2], this.canviz.height - tokens[i + 3]), new Point(tokens[i + 4], this.canviz.height - tokens[i + 5]) ]); } break; case 'I': // image var l = tokenizer.takeNumber(); var b = this.canviz.height - tokenizer.takeNumber(); var w = tokenizer.takeNumber(); var h = tokenizer.takeNumber(); var src = tokenizer.takeString(); if (!this.canviz.images[src]) { this.canviz.images[src] = new CanvizImage(this.canviz, src); } this.canviz.images[src].draw(ctx, l, b - h, w, h); break; case 'T': // text var l = Math.round(ctxScale * tokenizer.takeNumber() + this.canviz.padding); var t = Math.round(ctxScale * this.canviz.height + 2 * this.canviz.padding - (ctxScale * (tokenizer.takeNumber() + this.canviz.bbScale * fontSize) + this.canviz.padding)); var textAlign = tokenizer.takeNumber(); var textWidth = Math.round(ctxScale * tokenizer.takeNumber()); var str = tokenizer.takeString(); if (!redrawCanvasOnly && !/^\s*$/.test(str)) { // debug('draw text ' + str + ' ' + l + ' ' + t + ' ' + textAlign + ' ' + textWidth); str = _.str.escapeHTML(str); do { matches = str.match(/ ( +)/); if (matches) { var spaces = ' '; _(matches[1].length).times(function() { spaces += '&nbsp;'; }); str = str.replace(/ +/, spaces); } } while (matches); var text; var href = this.getAttr('URL', true) || this.getAttr('href', true); if (href) { var target = this.getAttr('target', true) || '_self'; var tooltip = this.getAttr('tooltip', true) || this.getAttr('label', true); // debug(this.name + ', href ' + href + ', target ' + target + ', tooltip ' + tooltip); text = $('<a>').attrs({href: href, target: target, title: tooltip}); _.each(['onclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout'], _.bind(function(attrName) { var attrValue = this.getAttr(attrName, true); if (attrValue) { text.writeAttribute(attrName, attrValue); } }, this)); text.css({ textDecoration: 'none' }); } else { text = $('<span>'); } text.html(str); text.css({ fontSize: Math.round(fontSize * ctxScale * this.canviz.bbScale) + 'px', fontFamily: fontFamily, color: strokeColor.textColor, position: 'absolute', textAlign: (-1 == textAlign) ? 'left' : (1 == textAlign) ? 'right' : 'center', left: (l - (1 + textAlign) * textWidth) + 'px', top: t + 'px', width: (2 * textWidth) + 'px' }); if (1 !== strokeColor.opacity) text.setOpacity(strokeColor.opacity); $(this.canviz.elements).append(text); } break; case 'C': // set fill color case 'c': // set pen color var fill = ('C' == token); var color = this.parseColor(tokenizer.takeString()); if (fill) { fillColor = color; ctx.fillStyle = color.canvasColor; } else { strokeColor = color; ctx.strokeStyle = color.canvasColor; } break; case 'F': // set font fontSize = tokenizer.takeNumber(); fontFamily = tokenizer.takeString(); switch (fontFamily) { case 'Times-Roman': fontFamily = 'Times New Roman'; break; case 'Courier': fontFamily = 'Courier New'; break; case 'Helvetica': fontFamily = 'Arial'; break; default: // nothing } // debug('set font ' + fontSize + 'pt ' + fontFamily); break; case 'S': // set style var style = tokenizer.takeString(); switch (style) { case 'solid': case 'filled': // nothing break; case 'dashed': case 'dotted': dashStyle = style; break; case 'bold': ctx.lineWidth = 2; break; default: matches = style.match(/^setlinewidth\((.*)\)$/); if (matches) { ctx.lineWidth = Number(matches[1]); } else { debug('unknown style ' + style); } } break; default: debug('unknown token ' + token); return; } if (path) { this.canviz.drawPath(ctx, path, filled, dashStyle, this); if (!redrawCanvasOnly) this.bbRect.expandToInclude(path.getBB()); path = undefined; } token = tokenizer.takeChars(); } if (!redrawCanvasOnly) { var xOff = 0, yOff = 0; bbDiv.css({ position: 'absolute', left: Math.round(ctxScale * (this.bbRect.l + xOff) + this.canviz.padding) + 'px', top: Math.round(ctxScale * (this.bbRect.t + yOff) + this.canviz.padding) + 'px', width: Math.round(ctxScale * this.bbRect.getWidth()) + 'px', height: Math.round(ctxScale * this.bbRect.getHeight()) + 'px' }); } ctx.restore(); } }, this)); }, parseColor: function(color) { var parsedColor = {opacity: 1}; // rgb/rgba if (/^#(?:[0-9a-f]{2}\s*){3,4}$/i.test(color)) { return this.canviz.parseHexColor(color); } // hsv var matches = color.match(/^(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)$/); if (matches) { parsedColor.canvasColor = parsedColor.textColor = this.canviz.hsvToRgbColor(matches[1], matches[2], matches[3]); return parsedColor; } // named color var colorScheme = this.getAttr('colorscheme') || 'X11'; var colorName = color; matches = color.match(/^\/(.*)\/(.*)$/); if (matches) { if (matches[1]) { colorScheme = matches[1]; } colorName = matches[2]; } else { matches = color.match(/^\/(.*)$/); if (matches) { colorScheme = 'X11'; colorName = matches[1]; } } colorName = colorName.toLowerCase(); var colorSchemeName = colorScheme.toLowerCase(); var colorSchemeData = Canviz.prototype.colors[colorSchemeName]; if (colorSchemeData) { var colorData = colorSchemeData[colorName]; if (colorData) { return this.canviz.parseHexColor('#' + colorData); } } colorData = Canviz.prototype.colors['fallback'][colorName]; if (colorData) { return this.canviz.parseHexColor('#' + colorData); } if (!colorSchemeData) { debug('unknown color scheme ' + colorScheme); } // unknown debug('unknown color ' + color + '; color scheme is ' + colorScheme); parsedColor.canvasColor = parsedColor.textColor = '#000000'; return parsedColor; } };
/* * sentinel * https://github.com/jaredhoyt/jquery-sentinel * * Copyright (c) 2015 Jared Hoyt * Licensed under the MIT license. */ (function($) { // Collection method. $.fn.sentinel = function() { return this.each(function(i) { // Do something awesome to each selected element. $(this).html('awesome' + i); }); }; // Static method. $.sentinel = function(options) { // Override default options with passed-in options. options = $.extend({}, $.sentinel.options, options); // Return something awesome. return 'awesome' + options.punctuation; }; // Static method default options. $.sentinel.options = { punctuation: '.' }; // Custom selector. $.expr[':'].sentinel = function(elem) { // Is this element awesome? return $(elem).text().indexOf('awesome') !== -1; }; }(jQuery));
import request from "./request"; export default function(defaultMimeType, response) { return function(url, callback) { var r = request(url).mimeType(defaultMimeType).response(response); return callback ? r.get(callback) : r; }; };
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './utils/registerServiceWorker'; import 'semantic-ui-css/semantic.min.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
$('.registerModalButton').on("click", function () { var courseId = $(this).data('id'), courseName = $(this).data('name'); $("#studentModal .registerOkButton").data('courseToRegisterId', courseId); $("#studentModal #courseNameModal").text(courseName); }); $(".registerOkButton").on("click", function () { var id = $("#studentModal .registerOkButton").data('courseToRegisterId'), token = $('input[name="__RequestVerificationToken"]').val(), data = { 'courseId': id, '__RequestVerificationToken': token }; $.ajax({ type: "POST", url: "/Home/AssignToCourse", data: data, datatype: "html", success: function (data) { $('[data-groupid=' + id + ']') .clone() .appendTo('.registerdSection') .find('button') .remove(); }, error: function (data) { $("#errorModal .modal-title").text(data.responseText); $('#errorModal').modal(); console.log('fail to register'); } }); });
import { ActionCreators } from 'redux-undo'; import * as types from './actionTypes'; export function setInitialState(options) { return { type: types.SET_INITIAL_STATE, options }; } export function changeDimensions(gridProperty, increment) { return { type: types.CHANGE_DIMENSIONS, gridProperty, increment }; } export function updateGridBoundaries(gridElement) { return { type: types.UPDATE_GRID_BOUNDARIES, gridElement }; } export function selectPaletteColor(position) { return { type: types.SELECT_PALETTE_COLOR, position }; } export function setCustomColor(customColor) { return { type: types.SET_CUSTOM_COLOR, customColor }; } export function cellAction({ id, drawingTool, color, paletteColor, columns, rows }) { return { type: `APPLY_${drawingTool}`, id, color, paletteColor, columns, rows }; } export function moveDrawing({ xDiff, yDiff, cellWidth }) { return { type: 'MOVE_DRAWING', moveDiff: { xDiff, yDiff, cellWidth } }; } export function setDrawing( frames, paletteGridData, cellSize, columns, rows, hoveredIndex ) { return { type: types.SET_DRAWING, frames, paletteGridData, cellSize, columns, rows, hoveredIndex }; } export function endDrag() { return { type: types.END_DRAG }; } export function switchTool(tool) { return { type: types.SWITCH_TOOL, tool }; } export function setCellSize(cellSize) { return { type: types.SET_CELL_SIZE, cellSize }; } export function resetGrid() { return { type: types.SET_RESET_GRID }; } export function showSpinner() { return { type: types.SHOW_SPINNER }; } export function hideSpinner() { return { type: types.HIDE_SPINNER }; } export function sendNotification(message) { return { type: types.SEND_NOTIFICATION, message }; } export function changeActiveFrame(frameIndex) { return { type: types.CHANGE_ACTIVE_FRAME, frameIndex }; } export function reorderFrame(selectedIndex, destinationIndex) { return { type: types.REORDER_FRAME, selectedIndex, destinationIndex }; } export function createNewFrame() { return { type: types.CREATE_NEW_FRAME }; } export function deleteFrame(frameId) { return { type: types.DELETE_FRAME, frameId }; } export function duplicateFrame(frameId) { return { type: types.DUPLICATE_FRAME, frameId }; } export function setDuration(duration) { return { type: types.SET_DURATION, duration }; } export function changeFrameInterval(frameIndex, interval) { return { type: types.CHANGE_FRAME_INTERVAL, frameIndex, interval }; } export function newProject() { return { type: types.NEW_PROJECT }; } export function changeHoveredCell(cell) { return { type: types.CHANGE_HOVERED_CELL, cell }; } export function undo() { return ActionCreators.undo(); } export function redo() { return ActionCreators.redo(); }
export const ic_battery_full_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"},"children":[]}]};
/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ Version: 1.5.0 Author: Ken Wheeler Website: http://kenwheeler.github.io Docs: http://kenwheeler.github.io/slick Repo: http://github.com/kenwheeler/slick Issues: http://github.com/kenwheeler/slick/issues */ /* global window, document, define, jQuery, setInterval, clearInterval */ (function(factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports !== 'undefined') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function($) { 'use strict'; var Slick = window.Slick || {}; Slick = (function() { var instanceUid = 0; function Slick(element, settings) { var _ = this, dataSettings, responsiveSettings, breakpoint; _.defaults = { accessibility: true, adaptiveHeight: false, appendArrows: $(element), appendDots: $(element), arrows: true, asNavFor: null, prevArrow: '<button type="button" data-role="none" class="carousel-control left" aria-label="previous"></button>', nextArrow: '<button type="button" data-role="none" class="carousel-control right" aria-label="next"></button>', autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', //customPaging: function(slider, i) { // return '<button type="button" data-role="none">' + (i + 1) + '</button>'; //}, customPaging: function(slider, i) { return '<button type="button" data-role="none"></button>'; }, dots: true, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: 'ondemand', mobileFirst: false, pauseOnHover: true, pauseOnDotsHover: false, respondTo: 'window', responsive: null, rows: 1, rtl: false, slide: '', slidesPerRow: 1, slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, verticalSwiping: false, waitForAnimate: true }; _.initials = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, $dots: null, listWidth: null, listHeight: null, loadIndex: 0, $nextArrow: null, $prevArrow: null, slideCount: null, slideWidth: null, $slideTrack: null, $slides: null, sliding: false, slideOffset: 0, swipeLeft: null, $list: null, touchObject: {}, transformsEnabled: false }; $.extend(_, _.initials); _.activeBreakpoint = null; _.animType = null; _.animProp = null; _.breakpoints = []; _.breakpointSettings = []; _.cssTransitions = false; _.hidden = 'hidden'; _.paused = false; _.positionProp = null; _.respondTo = null; _.rowCount = 1; _.shouldClick = true; _.$slider = $(element); _.$slidesCache = null; _.transformType = null; _.transitionType = null; _.visibilityChange = 'visibilitychange'; _.windowWidth = 0; _.windowTimer = null; dataSettings = $(element).data('slick') || {}; _.options = $.extend({}, _.defaults, dataSettings, settings); _.currentSlide = _.options.initialSlide; _.originalSettings = _.options; responsiveSettings = _.options.responsive || null; if (responsiveSettings && responsiveSettings.length > -1) { _.respondTo = _.options.respondTo || 'window'; for (breakpoint in responsiveSettings) { if (responsiveSettings.hasOwnProperty(breakpoint)) { _.breakpoints.push(responsiveSettings[ breakpoint].breakpoint); _.breakpointSettings[responsiveSettings[ breakpoint].breakpoint] = responsiveSettings[breakpoint].settings; } } _.breakpoints.sort(function(a, b) { if (_.options.mobileFirst === true) { return a - b; } else { return b - a; } }); } if (typeof document.mozHidden !== 'undefined') { _.hidden = 'mozHidden'; _.visibilityChange = 'mozvisibilitychange'; } else if (typeof document.msHidden !== 'undefined') { _.hidden = 'msHidden'; _.visibilityChange = 'msvisibilitychange'; } else if (typeof document.webkitHidden !== 'undefined') { _.hidden = 'webkitHidden'; _.visibilityChange = 'webkitvisibilitychange'; } _.autoPlay = $.proxy(_.autoPlay, _); _.autoPlayClear = $.proxy(_.autoPlayClear, _); _.changeSlide = $.proxy(_.changeSlide, _); _.clickHandler = $.proxy(_.clickHandler, _); _.selectHandler = $.proxy(_.selectHandler, _); _.setPosition = $.proxy(_.setPosition, _); _.swipeHandler = $.proxy(_.swipeHandler, _); _.dragHandler = $.proxy(_.dragHandler, _); _.keyHandler = $.proxy(_.keyHandler, _); _.autoPlayIterator = $.proxy(_.autoPlayIterator, _); _.instanceUid = instanceUid++; // A simple way to check for HTML strings // Strict HTML recognition (must start with <) // Extracted from jQuery v1.11 source _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/; _.init(); _.checkResponsive(true); } return Slick; }()); Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) { var _ = this; if (typeof(index) === 'boolean') { addBefore = index; index = null; } else if (index < 0 || (index >= _.slideCount)) { return false; } _.unload(); if (typeof(index) === 'number') { if (index === 0 && _.$slides.length === 0) { $(markup).appendTo(_.$slideTrack); } else if (addBefore) { $(markup).insertBefore(_.$slides.eq(index)); } else { $(markup).insertAfter(_.$slides.eq(index)); } } else { if (addBefore === true) { $(markup).prependTo(_.$slideTrack); } else { $(markup).appendTo(_.$slideTrack); } } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.animateHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.animate({ height: targetHeight }, _.options.speed); } }; Slick.prototype.animateSlide = function(targetLeft, callback) { var animProps = {}, _ = this; _.animateHeight(); if (_.options.rtl === true && _.options.vertical === false) { targetLeft = -targetLeft; } if (_.transformsEnabled === false) { if (_.options.vertical === false) { _.$slideTrack.animate({ left: targetLeft }, _.options.speed, _.options.easing, callback); } else { _.$slideTrack.animate({ top: targetLeft }, _.options.speed, _.options.easing, callback); } } else { if (_.cssTransitions === false) { if (_.options.rtl === true) { _.currentLeft = -(_.currentLeft); } $({ animStart: _.currentLeft }).animate({ animStart: targetLeft }, { duration: _.options.speed, easing: _.options.easing, step: function(now) { now = Math.ceil(now); if (_.options.vertical === false) { animProps[_.animType] = 'translate(' + now + 'px, 0px)'; _.$slideTrack.css(animProps); } else { animProps[_.animType] = 'translate(0px,' + now + 'px)'; _.$slideTrack.css(animProps); } }, complete: function() { if (callback) { callback.call(); } } }); } else { _.applyTransition(); targetLeft = Math.ceil(targetLeft); if (_.options.vertical === false) { animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)'; } else { animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)'; } _.$slideTrack.css(animProps); if (callback) { setTimeout(function() { _.disableTransition(); callback.call(); }, _.options.speed); } } } }; Slick.prototype.asNavFor = function(index) { var _ = this, asNavFor = _.options.asNavFor !== null ? $(_.options.asNavFor).slick('getSlick') : null; if (asNavFor !== null) asNavFor.slideHandler(index, true); }; Slick.prototype.applyTransition = function(slide) { var _ = this, transition = {}; if (_.options.fade === false) { transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase; } else { transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase; } if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.autoPlay = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } if (_.slideCount > _.options.slidesToShow && _.paused !== true) { _.autoPlayTimer = setInterval(_.autoPlayIterator, _.options.autoplaySpeed); } }; Slick.prototype.autoPlayClear = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } }; Slick.prototype.autoPlayIterator = function() { var _ = this; if (_.options.infinite === false) { if (_.direction === 1) { if ((_.currentSlide + 1) === _.slideCount - 1) { _.direction = 0; } _.slideHandler(_.currentSlide + _.options.slidesToScroll); } else { if ((_.currentSlide - 1 === 0)) { _.direction = 1; } _.slideHandler(_.currentSlide - _.options.slidesToScroll); } } else { _.slideHandler(_.currentSlide + _.options.slidesToScroll); } }; Slick.prototype.buildArrows = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow = $(_.options.prevArrow); _.$nextArrow = $(_.options.nextArrow); if (_.htmlExpr.test(_.options.prevArrow)) { _.$prevArrow.appendTo(_.options.appendArrows); } if (_.htmlExpr.test(_.options.nextArrow)) { _.$nextArrow.appendTo(_.options.appendArrows); } if (_.options.infinite !== true) { _.$prevArrow.addClass('slick-disabled'); } } }; Slick.prototype.buildDots = function() { var _ = this, i, dotString; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { dotString = '<ul class="' + _.options.dotsClass + '">'; for (i = 0; i <= _.getDotCount(); i += 1) { dotString += '<li>' + _.options.customPaging.call(this, _, i) + '</li>'; } dotString += '</ul>'; _.$dots = $(dotString).appendTo( _.options.appendDots); _.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false'); } }; Slick.prototype.buildOut = function() { var _ = this; _.$slides = _.$slider.children( ':not(.slick-cloned)').addClass( 'slick-slide'); _.slideCount = _.$slides.length; _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.$slider.addClass('slick-slider'); _.$slideTrack = (_.slideCount === 0) ? $('<div class="slick-track"/>').appendTo(_.$slider) : _.$slides.wrapAll('<div class="slick-track"/>').parent(); _.$list = _.$slideTrack.wrap( '<div aria-live="polite" class="slick-list"/>').parent(); _.$slideTrack.css('opacity', 0); if (_.options.centerMode === true || _.options.swipeToSlide === true) { _.options.slidesToScroll = 1; } $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading'); _.setupInfinite(); _.buildArrows(); _.buildDots(); _.updateDots(); if (_.options.accessibility === true) { _.$list.prop('tabIndex', 0); } _.setSlideClasses(typeof this.currentSlide === 'number' ? this.currentSlide : 0); if (_.options.draggable === true) { _.$list.addClass('draggable'); } }; Slick.prototype.buildRows = function() { var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection; newSlides = document.createDocumentFragment(); originalSlides = _.$slider.children(); if(_.options.rows > 1) { slidesPerSection = _.options.slidesPerRow * _.options.rows; numOfSlides = Math.ceil( originalSlides.length / slidesPerSection ); for(a = 0; a < numOfSlides; a++){ var slide = document.createElement('div'); for(b = 0; b < _.options.rows; b++) { var row = document.createElement('div'); for(c = 0; c < _.options.slidesPerRow; c++) { var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c)); if (originalSlides.get(target)) { row.appendChild(originalSlides.get(target)); } } slide.appendChild(row); } newSlides.appendChild(slide); } _.$slider.html(newSlides); _.$slider.children().children().children() .width((100 / _.options.slidesPerRow) + "%") .css({'display': 'inline-block'}); } }; Slick.prototype.checkResponsive = function(initial) { var _ = this, breakpoint, targetBreakpoint, respondToWidth; var sliderWidth = _.$slider.width(); var windowWidth = window.innerWidth || $(window).width(); if (_.respondTo === 'window') { respondToWidth = windowWidth; } else if (_.respondTo === 'slider') { respondToWidth = sliderWidth; } else if (_.respondTo === 'min') { respondToWidth = Math.min(windowWidth, sliderWidth); } if (_.originalSettings.responsive && _.originalSettings .responsive.length > -1 && _.originalSettings.responsive !== null) { targetBreakpoint = null; for (breakpoint in _.breakpoints) { if (_.breakpoints.hasOwnProperty(breakpoint)) { if (_.originalSettings.mobileFirst === false) { if (respondToWidth < _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } else { if (respondToWidth > _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } } } if (targetBreakpoint !== null) { if (_.activeBreakpoint !== null) { if (targetBreakpoint !== _.activeBreakpoint) { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { if (_.activeBreakpoint !== null) { _.activeBreakpoint = null; _.options = _.originalSettings; if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } }; Slick.prototype.changeSlide = function(event, dontAnimate) { var _ = this, $target = $(event.target), indexOffset, slideOffset, unevenOffset; // If target is a link, prevent default action. $target.is('a') && event.preventDefault(); unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0); indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll; switch (event.data.message) { case 'previous': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate); } break; case 'next': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate); } break; case 'index': var index = event.data.index === 0 ? 0 : event.data.index || $(event.target).parent().index() * _.options.slidesToScroll; _.slideHandler(_.checkNavigable(index), false, dontAnimate); break; default: return; } }; Slick.prototype.checkNavigable = function(index) { var _ = this, navigables, prevNavigable; navigables = _.getNavigableIndexes(); prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }; Slick.prototype.cleanUpEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).off('click.slick', _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .off('mouseenter.slick', _.setPaused.bind(_, true)) .off('mouseleave.slick', _.setPaused.bind(_, false)); } if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide); _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide); } _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler); _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler); _.$list.off('touchend.slick mouseup.slick', _.swipeHandler); _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler); _.$list.off('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).off(_.visibilityChange, _.visibility); } _.$list.off('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.off('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.off('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().off('click.slick', _.selectHandler); } $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange); $(window).off('resize.slick.slick-' + _.instanceUid, _.resize); $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault); $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.cleanUpRows = function() { var _ = this, originalSlides; if(_.options.rows > 1) { originalSlides = _.$slides.children().children(); originalSlides.removeAttr('style'); _.$slider.html(originalSlides); } }; Slick.prototype.clickHandler = function(event) { var _ = this; if (_.shouldClick === false) { event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); } }; Slick.prototype.destroy = function() { var _ = this; _.autoPlayClear(); _.touchObject = {}; _.cleanUpEvents(); $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } if (_.$slides) { _.$slides.removeClass('slick-slide slick-active slick-center slick-visible') .attr('aria-hidden', 'true') .removeAttr('data-slick-index') .css({ position: '', left: '', top: '', zIndex: '', opacity: '', width: '' }); _.$slider.html(_.$slides); } _.cleanUpRows(); _.$slider.removeClass('slick-slider'); _.$slider.removeClass('slick-initialized'); }; Slick.prototype.disableTransition = function(slide) { var _ = this, transition = {}; transition[_.transitionType] = ''; if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.fadeSlide = function(slideIndex, callback) { var _ = this; if (_.cssTransitions === false) { _.$slides.eq(slideIndex).css({ zIndex: 1000 }); _.$slides.eq(slideIndex).animate({ opacity: 1 }, _.options.speed, _.options.easing, callback); } else { _.applyTransition(slideIndex); _.$slides.eq(slideIndex).css({ opacity: 1, zIndex: 1000 }); if (callback) { setTimeout(function() { _.disableTransition(slideIndex); callback.call(); }, _.options.speed); } } }; Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) { var _ = this; if (filter !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.filter(filter).appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() { var _ = this; return _.currentSlide; }; Slick.prototype.getDotCount = function() { var _ = this; var breakPoint = 0; var counter = 0; var pagerQty = 0; if (_.options.infinite === true) { pagerQty = Math.ceil(_.slideCount / _.options.slidesToScroll); } else if (_.options.centerMode === true) { pagerQty = _.slideCount; } else { while (breakPoint < _.slideCount) { ++pagerQty; breakPoint = counter + _.options.slidesToShow; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } } return pagerQty - 1; }; Slick.prototype.getLeft = function(slideIndex) { var _ = this, targetLeft, verticalHeight, verticalOffset = 0, targetSlide; _.slideOffset = 0; verticalHeight = _.$slides.first().outerHeight(); if (_.options.infinite === true) { if (_.slideCount > _.options.slidesToShow) { _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1; verticalOffset = (verticalHeight * _.options.slidesToShow) * -1; } if (_.slideCount % _.options.slidesToScroll !== 0) { if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) { if (slideIndex > _.slideCount) { _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1; verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1; } else { _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1; verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1; } } } } else { if (slideIndex + _.options.slidesToShow > _.slideCount) { _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth; verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight; } } if (_.slideCount <= _.options.slidesToShow) { _.slideOffset = 0; verticalOffset = 0; } if (_.options.centerMode === true && _.options.infinite === true) { _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth; } else if (_.options.centerMode === true) { _.slideOffset = 0; _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2); } if (_.options.vertical === false) { targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset; } else { targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset; } if (_.options.variableWidth === true) { if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; if (_.options.centerMode === true) { if (_.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2; } } return targetLeft; }; Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) { var _ = this; return _.options[option]; }; Slick.prototype.getNavigableIndexes = function() { var _ = this, breakPoint = 0, counter = 0, indexes = [], max; if (_.options.infinite === false) { max = _.slideCount - _.options.slidesToShow + 1; if (_.options.centerMode === true) max = _.slideCount; } else { breakPoint = _.options.slidesToScroll * -1; counter = _.options.slidesToScroll * -1; max = _.slideCount * 2; } while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } return indexes; }; Slick.prototype.getSlick = function() { return this; }; Slick.prototype.getSlideCount = function() { var _ = this, slidesTraversed, swipedSlide, centerOffset; centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0; if (_.options.swipeToSlide === true) { _.$slideTrack.find('.slick-slide').each(function(index, slide) { if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) { swipedSlide = slide; return false; } }); slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1; return slidesTraversed; } else { return _.options.slidesToScroll; } }; Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) { var _ = this; _.changeSlide({ data: { message: 'index', index: parseInt(slide) } }, dontAnimate); }; Slick.prototype.init = function() { var _ = this; if (!$(_.$slider).hasClass('slick-initialized')) { $(_.$slider).addClass('slick-initialized'); _.buildRows(); _.buildOut(); _.setProps(); _.startLoad(); _.loadSlider(); _.initializeEvents(); _.updateArrows(); _.updateDots(); } _.$slider.trigger('init', [_]); }; Slick.prototype.initArrowEvents = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.on('click.slick', { message: 'previous' }, _.changeSlide); _.$nextArrow.on('click.slick', { message: 'next' }, _.changeSlide); } }; Slick.prototype.initDotEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).on('click.slick', { message: 'index' }, _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .on('mouseenter.slick', _.setPaused.bind(_, true)) .on('mouseleave.slick', _.setPaused.bind(_, false)); } }; Slick.prototype.initializeEvents = function() { var _ = this; _.initArrowEvents(); _.initDotEvents(); _.$list.on('touchstart.slick mousedown.slick', { action: 'start' }, _.swipeHandler); _.$list.on('touchmove.slick mousemove.slick', { action: 'move' }, _.swipeHandler); _.$list.on('touchend.slick mouseup.slick', { action: 'end' }, _.swipeHandler); _.$list.on('touchcancel.slick mouseleave.slick', { action: 'end' }, _.swipeHandler); _.$list.on('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).on(_.visibilityChange, _.visibility.bind(_)); } _.$list.on('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.on('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.on('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } $(window).on('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange.bind(_)); $(window).on('resize.slick.slick-' + _.instanceUid, _.resize.bind(_)); $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault); $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.initUI = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.show(); _.$nextArrow.show(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.show(); } if (_.options.autoplay === true) { _.autoPlay(); } }; Slick.prototype.keyHandler = function(event) { var _ = this; if (event.keyCode === 37 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'previous' } }); } else if (event.keyCode === 39 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'next' } }); } }; Slick.prototype.lazyLoad = function() { var _ = this, loadRange, cloneRange, rangeStart, rangeEnd; function loadImages(imagesScope) { $('img[data-lazy]', imagesScope).each(function() { var image = $(this), imageSource = $(this).attr('data-lazy'), imageToLoad = document.createElement('img'); imageToLoad.onload = function() { image.animate({ opacity: 1 }, 200); }; imageToLoad.src = imageSource; image .css({ opacity: 0 }) .attr('src', imageSource) .removeAttr('data-lazy') .removeClass('slick-loading'); }); } if (_.options.centerMode === true) { if (_.options.infinite === true) { rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1); rangeEnd = rangeStart + _.options.slidesToShow + 2; } else { rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1)); rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide; } } else { rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide; rangeEnd = rangeStart + _.options.slidesToShow; if (_.options.fade === true) { if (rangeStart > 0) rangeStart--; if (rangeEnd <= _.slideCount) rangeEnd++; } } loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd); loadImages(loadRange); if (_.slideCount <= _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-slide'); loadImages(cloneRange); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow); loadImages(cloneRange); } else if (_.currentSlide === 0) { cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1); loadImages(cloneRange); } }; Slick.prototype.loadSlider = function() { var _ = this; _.setPosition(); _.$slideTrack.css({ opacity: 1 }); _.$slider.removeClass('slick-loading'); _.initUI(); if (_.options.lazyLoad === 'progressive') { _.progressiveLazyLoad(); } }; Slick.prototype.next = Slick.prototype.slickNext = function() { var _ = this; _.changeSlide({ data: { message: 'next' } }); }; Slick.prototype.orientationChange = function() { var _ = this; _.checkResponsive(); _.setPosition(); }; Slick.prototype.pause = Slick.prototype.slickPause = function() { var _ = this; _.autoPlayClear(); _.paused = true; }; Slick.prototype.play = Slick.prototype.slickPlay = function() { var _ = this; _.paused = false; _.autoPlay(); }; Slick.prototype.postSlide = function(index) { var _ = this; _.$slider.trigger('afterChange', [_, index]); _.animating = false; _.setPosition(); _.swipeLeft = null; if (_.options.autoplay === true && _.paused === false) { _.autoPlay(); } }; Slick.prototype.prev = Slick.prototype.slickPrev = function() { var _ = this; _.changeSlide({ data: { message: 'previous' } }); }; Slick.prototype.preventDefault = function(e) { e.preventDefault(); }; Slick.prototype.progressiveLazyLoad = function() { var _ = this, imgCount, targetImage; imgCount = $('img[data-lazy]', _.$slider).length; if (imgCount > 0) { targetImage = $('img[data-lazy]', _.$slider).first(); targetImage.attr('src', targetImage.attr('data-lazy')).removeClass('slick-loading').load(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); if (_.options.adaptiveHeight === true) { _.setPosition(); } }) .error(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); }); } }; Slick.prototype.refresh = function() { var _ = this, currentSlide = _.currentSlide; _.destroy(); $.extend(_, _.initials); _.init(); _.changeSlide({ data: { message: 'index', index: currentSlide } }, false); }; Slick.prototype.reinit = function() { var _ = this; _.$slides = _.$slideTrack.children(_.options.slide).addClass( 'slick-slide'); _.slideCount = _.$slides.length; if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) { _.currentSlide = _.currentSlide - _.options.slidesToScroll; } if (_.slideCount <= _.options.slidesToShow) { _.currentSlide = 0; } _.setProps(); _.setupInfinite(); _.buildArrows(); _.updateArrows(); _.initArrowEvents(); _.buildDots(); _.updateDots(); _.initDotEvents(); if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } _.setSlideClasses(0); _.setPosition(); _.$slider.trigger('reInit', [_]); }; Slick.prototype.resize = function() { var _ = this; if ($(window).width() !== _.windowWidth) { clearTimeout(_.windowDelay); _.windowDelay = window.setTimeout(function() { _.windowWidth = $(window).width(); _.checkResponsive(); _.setPosition(); }, 50); } }; Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) { var _ = this; if (typeof(index) === 'boolean') { removeBefore = index; index = removeBefore === true ? 0 : _.slideCount - 1; } else { index = removeBefore === true ? --index : index; } if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) { return false; } _.unload(); if (removeAll === true) { _.$slideTrack.children().remove(); } else { _.$slideTrack.children(this.options.slide).eq(index).remove(); } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.setCSS = function(position) { var _ = this, positionProps = {}, x, y; if (_.options.rtl === true) { position = -position; } x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px'; y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px'; positionProps[_.positionProp] = position; if (_.transformsEnabled === false) { _.$slideTrack.css(positionProps); } else { positionProps = {}; if (_.cssTransitions === false) { positionProps[_.animType] = 'translate(' + x + ', ' + y + ')'; _.$slideTrack.css(positionProps); } else { positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)'; _.$slideTrack.css(positionProps); } } }; Slick.prototype.setDimensions = function() { var _ = this; if (_.options.vertical === false) { if (_.options.centerMode === true) { _.$list.css({ padding: ('0px ' + _.options.centerPadding) }); } } else { _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow); if (_.options.centerMode === true) { _.$list.css({ padding: (_.options.centerPadding + ' 0px') }); } } _.listWidth = _.$list.width(); _.listHeight = _.$list.height(); if (_.options.vertical === false && _.options.variableWidth === false) { _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow); _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length))); } else if (_.options.variableWidth === true) { _.$slideTrack.width(5000 * _.slideCount); } else { _.slideWidth = Math.ceil(_.listWidth); _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length))); } var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width(); if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset); }; Slick.prototype.setFade = function() { var _ = this, targetLeft; _.$slides.each(function(index, element) { targetLeft = (_.slideWidth * index) * -1; if (_.options.rtl === true) { $(element).css({ position: 'relative', right: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } else { $(element).css({ position: 'relative', left: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } }); _.$slides.eq(_.currentSlide).css({ zIndex: 900, opacity: 1 }); }; Slick.prototype.setHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.css('height', targetHeight); } }; Slick.prototype.setOption = Slick.prototype.slickSetOption = function(option, value, refresh) { var _ = this; _.options[option] = value; if (refresh === true) { _.unload(); _.reinit(); } }; Slick.prototype.setPosition = function() { var _ = this; _.setDimensions(); _.setHeight(); if (_.options.fade === false) { _.setCSS(_.getLeft(_.currentSlide)); } else { _.setFade(); } _.$slider.trigger('setPosition', [_]); }; Slick.prototype.setProps = function() { var _ = this, bodyStyle = document.body.style; _.positionProp = _.options.vertical === true ? 'top' : 'left'; if (_.positionProp === 'top') { _.$slider.addClass('slick-vertical'); } else { _.$slider.removeClass('slick-vertical'); } if (bodyStyle.WebkitTransition !== undefined || bodyStyle.MozTransition !== undefined || bodyStyle.msTransition !== undefined) { if (_.options.useCSS === true) { _.cssTransitions = true; } } if (bodyStyle.OTransform !== undefined) { _.animType = 'OTransform'; _.transformType = '-o-transform'; _.transitionType = 'OTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.MozTransform !== undefined) { _.animType = 'MozTransform'; _.transformType = '-moz-transform'; _.transitionType = 'MozTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false; } if (bodyStyle.webkitTransform !== undefined) { _.animType = 'webkitTransform'; _.transformType = '-webkit-transform'; _.transitionType = 'webkitTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.msTransform !== undefined) { _.animType = 'msTransform'; _.transformType = '-ms-transform'; _.transitionType = 'msTransition'; if (bodyStyle.msTransform === undefined) _.animType = false; } if (bodyStyle.transform !== undefined && _.animType !== false) { _.animType = 'transform'; _.transformType = 'transform'; _.transitionType = 'transition'; } _.transformsEnabled = (_.animType !== null && _.animType !== false); }; Slick.prototype.setSlideClasses = function(index) { var _ = this, centerOffset, allSlides, indexOffset, remainder; _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true').removeClass('slick-center'); allSlides = _.$slider.find('.slick-slide'); if (_.options.centerMode === true) { centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.infinite === true) { if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) { _.$slides.slice(index - centerOffset, index + centerOffset + 1).addClass('slick-active').attr('aria-hidden', 'false'); } else { indexOffset = _.options.slidesToShow + index; allSlides.slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2).addClass('slick-active').attr('aria-hidden', 'false'); } if (index === 0) { allSlides.eq(allSlides.length - 1 - _.options.slidesToShow).addClass('slick-center'); } else if (index === _.slideCount - 1) { allSlides.eq(_.options.slidesToShow).addClass('slick-center'); } } _.$slides.eq(index).addClass('slick-center'); } else { if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) { _.$slides.slice(index, index + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } else if (allSlides.length <= _.options.slidesToShow) { allSlides.addClass('slick-active').attr('aria-hidden', 'false'); } else { remainder = _.slideCount % _.options.slidesToShow; indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index; if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) { allSlides.slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder).addClass('slick-active').attr('aria-hidden', 'false'); } else { allSlides.slice(indexOffset, indexOffset + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } } } if (_.options.lazyLoad === 'ondemand') { _.lazyLoad(); } }; Slick.prototype.setupInfinite = function() { var _ = this, i, slideIndex, infiniteCount; if (_.options.fade === true) { _.options.centerMode = false; } if (_.options.infinite === true && _.options.fade === false) { slideIndex = null; if (_.slideCount > _.options.slidesToShow) { if (_.options.centerMode === true) { infiniteCount = _.options.slidesToShow + 1; } else { infiniteCount = _.options.slidesToShow; } for (i = _.slideCount; i > (_.slideCount - infiniteCount); i -= 1) { slideIndex = i - 1; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex - _.slideCount) .prependTo(_.$slideTrack).addClass('slick-cloned'); } for (i = 0; i < infiniteCount; i += 1) { slideIndex = i; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex + _.slideCount) .appendTo(_.$slideTrack).addClass('slick-cloned'); } _.$slideTrack.find('.slick-cloned').find('[id]').each(function() { $(this).attr('id', ''); }); } } }; Slick.prototype.setPaused = function(paused) { var _ = this; if (_.options.autoplay === true && _.options.pauseOnHover === true) { _.paused = paused; _.autoPlayClear(); } }; Slick.prototype.selectHandler = function(event) { var _ = this; var targetElement = $(event.target).is('.slick-slide') ? $(event.target) : $(event.target).parents('.slick-slide'); var index = parseInt(targetElement.attr('data-slick-index')); if (!index) index = 0; if (_.slideCount <= _.options.slidesToShow) { _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true'); _.$slides.eq(index).addClass('slick-active').attr("aria-hidden", "false"); if (_.options.centerMode === true) { _.$slider.find('.slick-slide').removeClass('slick-center'); _.$slides.eq(index).addClass('slick-center'); } _.asNavFor(index); return; } _.slideHandler(index); }; Slick.prototype.slideHandler = function(index, sync, dontAnimate) { var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null, _ = this; sync = sync || false; if (_.animating === true && _.options.waitForAnimate === true) { return; } if (_.options.fade === true && _.currentSlide === index) { return; } if (_.slideCount <= _.options.slidesToShow) { return; } if (sync === false) { _.asNavFor(index); } targetSlide = index; targetLeft = _.getLeft(targetSlide); slideLeft = _.getLeft(_.currentSlide); _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft; if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } if (_.options.autoplay === true) { clearInterval(_.autoPlayTimer); } if (targetSlide < 0) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll); } else { animSlide = _.slideCount + targetSlide; } } else if (targetSlide >= _.slideCount) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = 0; } else { animSlide = targetSlide - _.slideCount; } } else { animSlide = targetSlide; } _.animating = true; _.$slider.trigger("beforeChange", [_, _.currentSlide, animSlide]); oldSlide = _.currentSlide; _.currentSlide = animSlide; _.setSlideClasses(_.currentSlide); _.updateDots(); _.updateArrows(); if (_.options.fade === true) { if (dontAnimate !== true) { _.fadeSlide(animSlide, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } _.animateHeight(); return; } if (dontAnimate !== true) { _.animateSlide(targetLeft, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } }; Slick.prototype.startLoad = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.hide(); _.$nextArrow.hide(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.hide(); } _.$slider.addClass('slick-loading'); }; Slick.prototype.swipeDirection = function() { var xDist, yDist, r, swipeAngle, _ = this; xDist = _.touchObject.startX - _.touchObject.curX; yDist = _.touchObject.startY - _.touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle <= 360) && (swipeAngle >= 315)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (_.options.rtl === false ? 'right' : 'left'); } if (_.options.verticalSwiping === true) { if ((swipeAngle >= 35) && (swipeAngle <= 135)) { return 'left'; } else { return 'right'; } } return 'vertical'; }; Slick.prototype.swipeEnd = function(event) { var _ = this, slideCount; _.dragging = false; _.shouldClick = (_.touchObject.swipeLength > 10) ? false : true; if (_.touchObject.curX === undefined) { return false; } if (_.touchObject.edgeHit === true) { _.$slider.trigger("edge", [_, _.swipeDirection()]); } if (_.touchObject.swipeLength >= _.touchObject.minSwipe) { switch (_.swipeDirection()) { case 'left': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide + _.getSlideCount()) : _.currentSlide + _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 0; _.touchObject = {}; _.$slider.trigger("swipe", [_, "left"]); break; case 'right': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide - _.getSlideCount()) : _.currentSlide - _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 1; _.touchObject = {}; _.$slider.trigger("swipe", [_, "right"]); break; } } else { if (_.touchObject.startX !== _.touchObject.curX) { _.slideHandler(_.currentSlide); _.touchObject = {}; } } }; Slick.prototype.swipeHandler = function(event) { var _ = this; if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) { return; } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) { return; } _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ? event.originalEvent.touches.length : 1; _.touchObject.minSwipe = _.listWidth / _.options .touchThreshold; if (_.options.verticalSwiping === true) { _.touchObject.minSwipe = _.listHeight / _.options .touchThreshold; } switch (event.data.action) { case 'start': _.swipeStart(event); break; case 'move': _.swipeMove(event); break; case 'end': _.swipeEnd(event); break; } }; Slick.prototype.swipeMove = function(event) { var _ = this, edgeWasHit = false, curLeft, swipeDirection, swipeLength, positionOffset, touches; touches = event.originalEvent !== undefined ? event.originalEvent.touches : null; if (!_.dragging || touches && touches.length !== 1) { return false; } curLeft = _.getLeft(_.currentSlide); _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX; _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY; _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curX - _.touchObject.startX, 2))); if (_.options.verticalSwiping === true) { _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curY - _.touchObject.startY, 2))); } swipeDirection = _.swipeDirection(); if (swipeDirection === 'vertical') { return; } if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) { event.preventDefault(); } positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1); if (_.options.verticalSwiping === true) { positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1; } swipeLength = _.touchObject.swipeLength; _.touchObject.edgeHit = false; if (_.options.infinite === false) { if ((_.currentSlide === 0 && swipeDirection === "right") || (_.currentSlide >= _.getDotCount() && swipeDirection === "left")) { swipeLength = _.touchObject.swipeLength * _.options.edgeFriction; _.touchObject.edgeHit = true; } } if (_.options.vertical === false) { _.swipeLeft = curLeft + swipeLength * positionOffset; } else { _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset; } if (_.options.verticalSwiping === true) { _.swipeLeft = curLeft + swipeLength * positionOffset; } if (_.options.fade === true || _.options.touchMove === false) { return false; } if (_.animating === true) { _.swipeLeft = null; return false; } _.setCSS(_.swipeLeft); }; Slick.prototype.swipeStart = function(event) { var _ = this, touches; if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) { _.touchObject = {}; return false; } if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) { touches = event.originalEvent.touches[0]; } _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX; _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY; _.dragging = true; }; Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() { var _ = this; if (_.$slidesCache !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.unload = function() { var _ = this; $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } _.$slides.removeClass('slick-slide slick-active slick-visible').attr("aria-hidden", "true").css('width', ''); }; Slick.prototype.unslick = function() { var _ = this; _.destroy(); }; Slick.prototype.updateArrows = function() { var _ = this, centerOffset; centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.arrows === true && _.options.infinite !== true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.removeClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); if (_.currentSlide === 0) { _.$prevArrow.addClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } } }; Slick.prototype.updateDots = function() { var _ = this; if (_.$dots !== null) { _.$dots.find('li').removeClass('slick-active').attr("aria-hidden", "true"); _.$dots.find('li').eq(Math.floor(_.currentSlide / _.options.slidesToScroll)).addClass('slick-active').attr("aria-hidden", "false"); } }; Slick.prototype.visibility = function() { var _ = this; if (document[_.hidden]) { _.paused = true; _.autoPlayClear(); } else { _.paused = false; _.autoPlay(); } }; $.fn.slick = function() { var _ = this, opt = arguments[0], args = Array.prototype.slice.call(arguments, 1), l = _.length, i = 0, ret; for (i; i < l; i++) { if (typeof opt == 'object' || typeof opt == 'undefined') _[i].slick = new Slick(_[i], opt); else ret = _[i].slick[opt].apply(_[i].slick, args); if (typeof ret != 'undefined') return ret; } return _; }; }));
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // Annex E: Completion reform changes // https://bugs.ecmascript.org/show_bug.cgi?id=4337 // If-Statement completion value assertSame(undefined, eval(`0; if (false) ;`)); assertSame(undefined, eval(`0; if (true) ;`)); assertSame(undefined, eval(`0; if (false) ; else ;`)); assertSame(undefined, eval(`0; if (true) ; else ;`)); // Switch-Statement completion value assertSame(1, eval(`switch (0) { case 0: 1; case 1: }`)); assertSame(1, eval(`switch (0) { case 0: 1; default: }`)); // Try-Statement completion value assertSame(1, eval(`L: try { throw null } catch (e) { ; } finally { 1; break L; }`));
class upnp_upnpservice_1 { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_upnpservice_1;
/* global GazelleSchema :true */ // obj2 is merged into obj1, replacing duplicate keys. function merge (obj2, obj1) { for (var k in obj2) { try { if (obj2[k].constructor === Object) { obj1[k] = merge(obj1[k], obj2[k]); } else { obj1[k] = obj2[k]; } } catch (e) { obj1[k] = obj2[k]; } } return obj1; } var formatLabel = function (identifier, label) { return 'The ' + (identifier ? identifier + '\'s ' : ' ') + label; }; GazelleSchema = function (identifier) { this.identifier = identifier; }; GazelleSchema.prototype.formatLabel = function (label) { return formatLabel(this.identifier, label); }; GazelleSchema.prototype.id = function (extra) { return merge(extra, { type: String, label: this.formatLabel('id'), index: true, unique: true, autoValue: function () { if (this.isInsert) { return Random.id(); } else { this.unset(); } } }); }; GazelleSchema.prototype.foreignId = function (identifier, extra) { return merge(extra, { type: String, label: formatLabel(identifier, 'id'), index: true, unique: false, optional: false }); }; GazelleSchema.prototype.title = function (extra) { return merge(extra, { type: String, label: this.formatLabel('title'), index: true }); }; GazelleSchema.prototype.name = function (extra) { return merge(extra, this.title({ label: this.formatLabel('name') })); }; GazelleSchema.prototype.createdAt = function (extra) { return merge(extra, { type: Date, label: this.formatLabel('created at timestamp'), autoValue: function () { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return { $setOnInsert: new Date }; } else { this.unset(); } } }); }; GazelleSchema.prototype.updatedAt = function (extra) { return merge(extra, { type: Date, label: this.formatLabel('updated at timestamp'), autoValue: function () { if (this.isUpdate) { return new Date(); } }, denyInsert: true, optional: true }); }; GazelleSchema.prototype.createdBy = function (extra) { return merge(extra, { type: String, label: this.formatLabel('created by user id'), autoValue: function () { if (this.isInsert) { return this.userId; } else if (this.isUpsert) { return { $setOnInsert: this.userId }; } else { this.unset(); } } }); }; GazelleSchema.prototype.images = function (extra) { return merge(extra, { type: [new SimpleSchema({ title: this.images({ index: false }), url: { type: String, label: 'The url of the image' }, createdAt: this.createdAt('image'), createdBy: this.createdBy('image') })], label: 'The images', optional: true }); }; GazelleSchema.prototype.description = function (extra) { return merge(extra, { type: String, label: this.formatLabel('description'), optional: true }); }; GazelleSchema.prototype.body = function (extra) { return merge(extra, this.description({ label: this.formatLabel('body') })); }; GazelleSchema.prototype.tags = function (extra) { return merge(extra, { type: [new SimpleSchema({ id: this.id('tag'), createdAt: this.createdAt('tag'), createdBy: this.createdBy('tag') })], label: this.formatLabel('tag'), optional: true }); }; GazelleSchema.prototype.leechType = function (extra) { return merge(extra, { type: String, label: this.formatLabel('leech type'), defaultValue: function () { return 'Regular'; }, allowedValues: ['Regular', 'Free Leech', 'Neutral Leech'] }); }; GazelleSchema.year = function (extra) { return { type: Number, label: 'The ' + (entity ? entity + '\s ' : ' ') + 'year', optional: false }; };
/* * File: Options.AreaChart.js * */ /* Object: Options.AreaChart <AreaChart> options. Other options included in the AreaChart are <Options.Canvas>, <Options.Label>, <Options.Margin>, <Options.Tips> and <Options.Events>. Syntax: (start code js) Options.AreaChart = { animate: true, labelOffset: 3, type: 'stacked', selectOnHover: true, showAggregates: true, showLabels: true, filterOnClick: false, restoreOnRightClick: false }; (end code) Example: (start code js) var areaChart = new $jit.AreaChart({ animate: true, type: 'stacked:gradient', selectOnHover: true, filterOnClick: true, restoreOnRightClick: true }); (end code) Parameters: animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks. labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. type - (string) Default's *'stacked'*. Stack style. Posible values are 'stacked', 'stacked:gradient' to add gradients. selectOnHover - (boolean) Default's *true*. If true, it will add a mark to the hovered stack. showAggregates - (boolean) Default's *true*. Display the sum of the values of the different stacks. showLabels - (boolean) Default's *true*. Display the name of the slots. filterOnClick - (boolean) Default's *true*. Select the clicked stack by hiding all other stacks. restoreOnRightClick - (boolean) Default's *true*. Show all stacks by right clicking. */ Options.AreaChart = { $extend: true, animate: true, labelOffset: 3, // label offset type: 'stacked', // gradient Tips: { enable: false, onShow: $.empty, onHide: $.empty }, Events: { enable: false, onClick: $.empty }, selectOnHover: true, showAggregates: true, showLabels: true, filterOnClick: false, restoreOnRightClick: false };
import React, { createContext, useState } from 'react'; import PropTypes from 'prop-types'; const ErrorContext = createContext({ errors: [], }); const ErrorProvider = ({ children }) => { const [errors, setErrors] = useState([]); return ( <ErrorContext.Provider value={{ errors, setErrors, }} > {children} </ErrorContext.Provider> ); }; ErrorProvider.propTypes = { children: PropTypes.node, }; export { ErrorContext, ErrorProvider };
module.exports = { 'ar': require('../../i18n/ar.json'), 'da': require('../../i18n/da.json'), 'de': require('../../i18n/de.json'), 'en': require('../../i18n/en.json'), 'es': require('../../i18n/es.json'), 'fr': require('../../i18n/fr-FR.json'), 'fr-FR': require('../../i18n/fr-FR.json'), 'he': require('../../i18n/he.json'), 'it': require('../../i18n/it.json'), 'ja': require('../../i18n/ja.json'), 'ko': require('../../i18n/ko.json'), 'nb-NO': require('../../i18n/nb-NO.json'), 'nl': require('../../i18n/nl-NL.json'), 'nl-NL': require('../../i18n/nl-NL.json'), 'pt': require('../../i18n/pt.json'), 'pt-BR': require('../../i18n/pt-BR.json'), 'ru': require('../../i18n/ru.json'), 'sv': require('../../i18n/sv.json'), 'tlh': require('../../i18n/tlh.json'), 'tr': require('../../i18n/tr.json'), 'zh': require('../../i18n/zh.json'), 'zh-TW': require('../../i18n/zh-TW.json') }
/** * Created by GYX on 15/6/27. */ var nodeMailer = require('nodemailer'); var Imap = require("imap"); var MailParser = require("mailparser").MailParser; var imapconn =null; function mail(option) { this.smtp = option.smtp || ""; this.smtpPort = option.smtpPort || ""; this.imap = option.imap || ""; this.imapPort = option.imapPort || ""; this.mailAddress = option.mailAddress || ""; this.password = option.password || ""; this.transporter=null; this._mailbox=null; this._cb=null; this._onerror=null; } mail.prototype.setMailOption = function(otherOption){ this.smtp = otherOption.smtp || ""; this.smtpPort = otherOption.smtpPort || ""; this.imap = otherOption.imap || ""; this.imapPort = otherOption.imapPort || ""; this.mailAddress = otherOption.mailAddress || ""; this.password = otherOption.password || ""; }; //当然你也可以直接通过变量获取 mail.prototype.getMailOption = function(){ return {smtp:this.smtp,smtpPort:this.smtpPort, imap:this.imap,imapPort:this.imapPort, mailAddress:this.mailAddress,password:this.password}; }; /** * var mailOptions = { from: 'Fred Foo <[email protected]>', // sender address to: '[email protected], [email protected]', // list of receivers subject: 'Hello ', // Subject line text: 'Hello world ', // plaintext body html: '<b>Hello world </b>' // html body }; callback =function(error, info){ if(error){ console.log(error); }else{ console.log('Message sent: ' +info.message); }}; */ //发送邮件 mail.prototype.sendMail=function(mailOptions,callback){ if(!this.smtp||!this.smtpPort||!this.mailAddress||!this.password){ return {success:0,error:"Error,mail option is not enough"}; } this.transporter = nodeMailer.createTransport("SMTP",{ host:this.smtp, port:this.smtpPort, secureConnection:true, auth: { user: this.mailAddress, pass: this.password } }); this.transporter.sendMail(mailOptions,callback); }; //停止SMTP连接 mail.prototype.stopSMTPConnection = function(){ if(this.transporter==null) return {success:0,error:"please start smtp again"}; this.transporter.close(); }; /** searchFilter: * case 'ALL': case 'ANSWERED': case 'DELETED': case 'DRAFT': case 'FLAGGED': case 'NEW': case 'SEEN': case 'RECENT': case 'OLD': case 'UNANSWERED': case 'UNDELETED': case 'UNDRAFT': case 'UNFLAGGED': case 'UNSEEN': */ /** * 北航邮箱的文件夹 * { INBOX: { attribs: [], delimiter: '/', children: null, parent: null }, Drafts: { attribs: [ '\\Drafts' ], delimiter: '/', children: null, parent: null, special_use_attrib: '\\Drafts' }, 'Sent Items': { attribs: [ '\\Sent' ], delimiter: '/', children: null, parent: null, special_use_attrib: '\\Sent' }, Trash: { attribs: [ '\\Trash' ], delimiter: '/', children: null, parent: null, special_use_attrib: '\\Trash' }, 'Junk E-mail': { attribs: [ '\\Junk' ], delimiter: '/', children: null, parent: null, special_use_attrib: '\\Junk' }, 'Virus Items': { attribs: [], delimiter: '/', children: null, parent: null } } */ mail.prototype.openBox=function(mailbox,searchFilter,cb,onerror) { this._cb =cb; this._mailbox = mailbox; this._onerror = onerror; var self= this; if(!imapconn){ if(!this.imap||!this.imapPort||!this.mailAddress||!this.password){ return {success:0,error:"Error,mail option is not enough"}; } imapconn= new Imap({ user:this.mailAddress, password:this.password, host:this.imap, port:this.imapPort, tls: true, tlsOptions: { rejectUnauthorized: false }, attachments:false }); imapconn.once('error', this._onerror); imapconn.once('ready',function(){ self._openbox(searchFilter); }); imapconn.connect(); } else { self._openbox(searchFilter); } }; mail.prototype.getFullMail=function(mailbox,messageId,cb,onerror) { this._cb =cb; this._mailbox = mailbox; this._onerror = onerror; var self= this; if(!imapconn){ if(!this.imap||!this.imapPort||!this.mailAddress||!this.password){ return {success:0,error:"Error,mail option is not enough"}; } imapconn= new Imap({ user:this.mailAddress, password:this.password, host:this.imap, port:this.imapPort, tls: true, tlsOptions: { rejectUnauthorized: false }, attachments:false }); imapconn.once('error', this._onerror); imapconn.once('ready',function(){ self._getFullMail(messageId); }); imapconn.connect(); } else { self._getFullMail(messageId); } }; mail.prototype.killImap= function(){ imapconn.end(); imapconn=undefined; }; mail.prototype._openbox =function(searchFilter){ var self = this; imapconn.openBox(this._mailbox, false, function(err, box){ if (err) throw err; imapconn.search(searchFilter, function(err, results) { if (err) throw err; if(results.length>0) { var f = imapconn.fetch(results, {bodies: 'HEADER'}); f.on('message', function (msg) { var mailparser = new MailParser(); msg.on('body', function (stream, info) { stream.pipe(mailparser); mailparser.on("end", function (mail) { mail.messageId = mail.headers["message-id"]; delete mail.headers; self._cb(mail); }) }); }); f.once('error', function (err) { console.log('Fetch error: ' + err); }); } }); }); }; mail.prototype._getFullMail=function(messageId){ var self = this; imapconn.openBox(this._mailbox, false, function(err, box){ if (err) throw err; imapconn.search([["header","message-id",messageId]], function(err, results) { if (err) throw err; if(results.length>0){ var f = imapconn.fetch(results, { bodies: '' }); f.on('message', function(msg) { var mailparser = new MailParser(); msg.on('body', function(stream, info) { stream.pipe( mailparser ); mailparser.on("end",function( mail ){ mail.messageId=mail.headers["message-id"]; delete mail.headers; self._cb(mail); console.log(mail); }) }); }); f.once('error', function(err) { console.log('Fetch error: ' + err); }); } }); }); }; mail.prototype.imapTest =function(cb){ if(!this.imap||!this.imapPort||!this.mailAddress||!this.password){ return {success:0,error:"Error,mail option is not enough"}; } conn= new Imap({ user:this.mailAddress, password:this.password, host:this.imap, port:this.imapPort, tls: true, tlsOptions: { rejectUnauthorized: false }, connTimeout:1000 }); conn.once("error",function(){ cb(103,"无法连接到imap服务器"); }); conn.once('ready',function(){ cb(0,'success'); }); conn.connect(); }; mail.prototype.getAll=function(cb){ this.openBox("INBOX",["ALL"],cb); }; mail.prototype.getSince =function(time,cb){ this.openBox("INBOX",[["SINCE",time]],cb); }; mail.prototype.getUnseen=function(cb){ this.open("INBOX",["UNSEEN"],cb); }; module.exports = mail;
var request = require('request'); module.exports = function(args) { var opts = { API_URL:'http://en.wikipedia.org/w/api.php', RATE_LIMIT:false, RATE_LIMIT_MIN_WAIT:false, RATE_LIMIT_LAST_CALL:false, USER_AGENT:'wikipedia (https://github.com/meadowstream/wikipedia.js/)' }; for (var i in args) { opts[i] = args[i]; } return { // variables 'cache':new Cache(), // Functions 'opts':opts, 'search':search, 'set_caching':set_caching, 'suggest':suggest, 'page':page, 'geosearch':geosearch, 'languages':languages, 'set_lang':set_lang, 'set_rate_limiting':set_rate_limiting, 'random':random, // Classes 'WikipediaPage':WikipediaPage }; };
version https://git-lfs.github.com/spec/v1 oid sha256:a285e8981a5115bbdd913280943a1d1a0d498b079ace167d6e90a0cc9e2cdfba size 93324
var gulp = require('gulp'), config = require('../config.js'); require('./browserify.js'); require('./default.js'); require('./sass.js'); gulp.task('watch', ['default'], function() { gulp.watch(config.paths.sass.src, ['sass']); gulp.start('watch:js'); });
var path = require('path') var lib = require(path.join(__dirname, '/lib')) module.exports = lib
import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ survey_type: 'Biological Resources', duplicator_label: 'Observation(s)', fully_editable: true, name() { return faker.name.jobType(); }, status() { return faker.list.random('draft', 'active', 'inactive')(); } });
(function($) { "use strict"; // Start of use strict // jQuery for page scrolling feature - requires jQuery Easing plugin $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 50) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top', offset: 100 }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); // Offset for Main Navigation $('#mainNav').affix({ offset: { top: 50 } }) })(jQuery); // End of use strict ((window.gitter = {}).chat = {}).options = { room: 'FMeat/Lobby' };
var search = require('simple-object-query').search, CssSelectorParser = require('css-selector-parser').CssSelectorParser, cssParser = new CssSelectorParser(); cssParser .registerNestingOperators('>') .registerAttrEqualityMods('^', '$', '*', '~') ; module.exports = cssFind; function cssFind(root, rule) { if (typeof rule === 'string') { rule = cssParser.parse(rule); } if (rule.type === 'selectors') { for (var i = 0, len = rule.selectors.length; i < len; i++) { var res = cssFind(root, rule.selectors[i].rule); if (res) return res; } return; } else if (rule.type === 'ruleSet') { rule = rule.rule; } return search({ source: root, query: { type: 'tag' }, include: function (item) { if (rule.nestingOperator === '>' && item.parent && item.parent !== root) return false; return ( item.field === 'children' || item.path[item.path.length - 1] === 'children' ); }, callback: function (item) { if (item.target === root) return; var node = item.target; if (isCssValid(node, rule)) { if (!rule.rule) { return node; } return cssFind(node, rule.rule); } } }); } function isCssValid(node, rule) { var i, len; if (rule.tagName) { if (node.name !== rule.tagName) return false; } if (rule.classNames) { var classes = (node.attr['class'] || '').split(/\s+/); for (i = 0, len = rule.classNames.length; i < len; i++) { if (classes.indexOf(rule.classNames[i]) === -1) return false; } } if (rule.attrs) { for (i = 0, len = rule.attrs.length; i < len; i++) { var attr = rule.attrs[i]; if (!node.attr.hasOwnProperty(attr.name)) return false; switch (attr.operator) { case '=': if (node.attr[attr.name] !== attr.value) return false; break; case '^=': if (node.attr[attr.name].indexOf(attr.value) !== 0) return false; break; case '$=': if (node.attr[attr.name].slice(-attr.value.length) !== attr.value) return false; break; case '*=': if (node.attr[attr.name].indexOf(attr.value) === -1) return false; break; } } } if (rule.pseudos) { for (i = 0, len = rule.pseudos.length; i < len; i++) { var pseudo = rule.pseudos[i]; switch (pseudo.name) { case 'nth-child': case 'eq': if (getChildNodes(node.parent).indexOf(node) !== Number(pseudo.value) - 1) return false; break; } } } return true; } function getChildNodes(node) { var nodes = []; for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i].type === 'tag') { nodes.push(node.children[i]); } } return nodes; }
var Worker = require('./worker') /** * Tracks worker state across runs. */ function WorkerManager () { this._pollHandle = null this.workers = {} this.isPolling = false this.shouldShutdown = false } WorkerManager.prototype.registerWorker = function registerWorker (workerData) { if (this.workers[workerData.id]) { this.unregisterWorker(this.workers[workerData.id]) } var worker = new Worker(workerData) worker.emit('status', worker.status) this.workers[workerData.id] = worker return worker } WorkerManager.prototype.unregisterWorker = function unregisterWorker (worker) { worker.emit('delete', worker) worker.removeAllListeners() delete this.workers[worker.id] return worker } WorkerManager.prototype.updateWorker = function updateWorker (workerData) { var workers = this.workers if (workers[workerData.id]) { var worker = workers[workerData.id] var prevStatus = worker.status Object.keys(workerData).forEach(function (k) { worker[k] = workerData[k] }) if (worker.status !== prevStatus) { worker.emit('status', worker.status) } } } WorkerManager.prototype.startPolling = function startPolling (client, pollingTimeout, callback) { if (this.isPolling || this.shouldShutdown) { return } var self = this this.isPolling = true client.getWorkers(function (err, updatedWorkers) { if (err) { self.isPolling = false return (callback ? callback(err) : null) } var activeWorkers = (updatedWorkers || []).reduce(function (o, worker) { o[worker.id] = worker return o }, {}) Object.keys(self.workers).forEach(function (workerId) { if (activeWorkers[workerId]) { // process updates self.updateWorker(activeWorkers[workerId]) } else { // process deletions self.unregisterWorker(self.workers[workerId]) } }) self._pollHandle = setTimeout(function () { self.isPolling = false self.startPolling(client, pollingTimeout, callback) }, pollingTimeout) }) } WorkerManager.prototype.stopPolling = function stopPolling () { if (this._pollHandle) { clearTimeout(this._pollHandle) this._pollHandle = null } this.shouldShutdown = true } // expose a single, shared instance of WorkerManager module.exports = new WorkerManager()
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('frontender generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh) * Licensed under the MIT License (LICENSE.txt). * * Version: 3.1.11 * * Requires: jQuery 1.2.2+ */ ;define(function (require, exports, module) { //导入全局依赖模块 var $,jQuery; $ = jQuery = require('jquery'); var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; if ($.event.fixHooks) { for (var i = toFix.length; i;) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } var special = $.event.special.mousewheel = { version: '3.1.11', setup: function () { if (this.addEventListener) { for (var i = toBind.length; i;) { this.addEventListener(toBind[--i], handler, false); } } else { this.onmousewheel = handler; } // Store the line height and page height for this particular element $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); }, teardown: function () { if (this.removeEventListener) { for (var i = toBind.length; i;) { this.removeEventListener(toBind[--i], handler, false); } } else { this.onmousewheel = null; } // Clean up the data we added to the element $.removeData(this, 'mousewheel-line-height'); $.removeData(this, 'mousewheel-page-height'); }, getLineHeight: function (elem) { var $parent = $(elem)['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); if (!$parent.length) { $parent = $('body'); } return parseInt($parent.css('fontSize'), 10); }, getPageHeight: function (elem) { return $(elem).height(); }, settings: { adjustOldDeltas: true, // see shouldAdjustOldDeltas() below normalizeOffset: true // calls getBoundingClientRect for each event } }; $.fn.extend({ mousewheel: function (fn) { return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); }, unmousewheel: function (fn) { return this.unbind('mousewheel', fn); } }); function handler(event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); event.type = 'mousewheel'; // Old school scrollwheel delta if ('detail' in orgEvent) { deltaY = orgEvent.detail * -1; } if ('wheelDelta' in orgEvent) { deltaY = orgEvent.wheelDelta; } if ('wheelDeltaY' in orgEvent) { deltaY = orgEvent.wheelDeltaY; } if ('wheelDeltaX' in orgEvent) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ('axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ('deltaY' in orgEvent) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ('deltaX' in orgEvent) { deltaX = orgEvent.deltaX; if (deltaY === 0) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if (deltaY === 0 && deltaX === 0) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if (orgEvent.deltaMode === 1) { var lineHeight = $.data(this, 'mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if (orgEvent.deltaMode === 2) { var pageHeight = $.data(this, 'mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if (!lowestDelta || absDelta < lowestDelta) { lowestDelta = absDelta; // Adjust older deltas if necessary if (shouldAdjustOldDeltas(orgEvent, absDelta)) { lowestDelta /= 40; } } // Adjust older deltas if necessary if (shouldAdjustOldDeltas(orgEvent, absDelta)) { // Divide all the things by 40! delta /= 40; deltaX /= 40; deltaY /= 40; } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if (special.settings.normalizeOffset && this.getBoundingClientRect) { var boundingRect = this.getBoundingClientRect(); offsetX = event.clientX - boundingRect.left; offsetY = event.clientY - boundingRect.top; } // Add information to the event object event.deltaX = deltaX; event.deltaY = deltaY; event.deltaFactor = lowestDelta; event.offsetX = offsetX; event.offsetY = offsetY; // Go ahead and set deltaMode to 0 since we converted to pixels // Although this is a little odd since we overwrite the deltaX/Y // properties with normalized deltas. event.deltaMode = 0; // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); // Clearout lowestDelta after sometime to better // handle multiple device types that give different // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); return ($.event.dispatch || $.event.handle).apply(this, args); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } return $; });
var indexSectionsWithContent = { 0: "abcdefghilmnoprstuy~", 1: "abcdefghmnops", 2: "e", 3: "acdegilmnoprstu~", 4: "acefpsy", 5: "p", 6: "em" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "namespaces", 3: "functions", 4: "variables", 5: "typedefs", 6: "enums" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Namespaces", 3: "Functions", 4: "Variables", 5: "Typedefs", 6: "Enumerations" };
var mkdirp=require("../"),path=require("path"),fs=require("fs"),test=require("tap").test;test("return value",function(t){t.plan(2);var x=Math.floor(Math.random()*Math.pow(16,4)).toString(16),y=Math.floor(Math.random()*Math.pow(16,4)).toString(16),z=Math.floor(Math.random()*Math.pow(16,4)).toString(16),file="/tmp/"+[x,y,z].join("/"),made=mkdirp.sync(file);t.equal(made,"/tmp/"+x),made=mkdirp.sync(file),t.equal(made,null)});
const assert = require('assert'); const makeConfig = require('../../../core/util/makeConfig'); describe('make config', function () { it('should pass the filter arg correctly', function () { const actualConfig = makeConfig('init', { filter: true }); assert.strictEqual(actualConfig.args.filter, true); }); it('should work without an option param', function () { const actualConfig = makeConfig('init'); assert.deepStrictEqual(actualConfig.args, {}); }); });
game.TeamArcher = me.Entity.extend({ init: function(x, y, settings){ this._super(me.Entity, 'init', [x, y, { image: "archer", width: 64, height: 64, spritewidth: "64", spriteheight: "64", getShape: function(){ return (new me.Rect(0, 0, 64, 64)).toPolygon(); } }]); this.health = 10; this.alwaysUpdate = true; this.attacking = false; this.lastAttacking = new Date().getTime(); this.lastHit = new Date().getTime(); this.now = new Date().getTime(); this.body.setVelocity(3, 20); this.type = "TeamArcher"; this.renderable.addAnimation("attack", [260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272], 80); this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80); this.renderable.setCurrentAnimation("walk"); }, loseHealth: function(damage){ this.health = this.health - damage; }, update: function(delta){ if(this.health <= 0){ me.game.world.removeChild(this); } this.now = new Date().getTime(); this.body.vel.x += this.body.accel.x * me.timer.tick; me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ this.attacking=true; this.lastAttacking=this.now; this.body.vel.x = 0; this.pos.x = this.pos.x + 1; if((this.now-this.lastHit >=1000)){ this.lastHit = this.now; response.b.loseHealth(game.data.teamArcherAttack); } }else if (response.b.type==='EnemyCreep'){ var xdif = this.pos.x - response.b.pos.x; }else if(response.b.type==='EnemyWizard'){ var xdif = this.pos.x - response.b.pos.x; } this.attacking=true; if(xdif>0){ this.pos.x = this.pos.x + 1; this.body.vel.x = 0; } if((this.now-this.lastHit >=1000) && xdif>0){ this.lastHit = this.now; response.b.loseHealth(game.data.teamArcherAttack); } } } );
describe('Manual namespace managment', function() { describe('Namespace#addNamespace', function() { it('inserts a namespace for a given key', function() { nsr.addNamespace('users').should.eq('test:users'); }); }); describe('Namespace#removeNamespace', function() { it('removes a namespace for a given key', function() { nsr.removeNamespace('test:users').should.eq('users'); }); }); });
/* jshint node: true */ /* global require, module */ var EmberAddon = require( 'ember-cli/lib/broccoli/ember-addon' ); var packageConfig = require( './package.json' ); var replace = require( 'broccoli-string-replace' ); var env = require( './config/environment' ); var app = new EmberAddon(); var tree; // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. // Testing dependencies app.import( app.bowerDirectory + '/sinonjs/sinon.js', { type: 'test' }); app.import( app.bowerDirectory + '/sinon-qunit/lib/sinon-qunit.js', { type: 'test' }); tree = replace( app.toTree(), { files: [ 'index.html', 'assets/dummy.js' ], patterns: [ { match: /REPLACE_META_DESCRIPTION/g, replacement: packageConfig[ 'description' ] }, { match: /REPLACE_META_KEYWORDS/g, replacement: packageConfig[ 'keywords' ].join( ', ' ) + ', ember, ember cli' }, { match: /REPLACE_APPLICATION_VERSION/g, replacement: packageConfig[ 'version' ] } ] }); module.exports = tree;
function normalizeUrl(url){ // parseUri 1.2.2 // (c) Steven Levithan <stevenlevithan.com> // MIT License function parseUri (str) { var o = parseUri.options, m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), uri = {}, i = 14; while (i--) uri[o.key[i]] = m[i] || ""; uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) uri[o.q.name][$1] = $2; }); return uri; }; parseUri.options = { strictMode: false, key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], q: { name: "queryKey", parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; ////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////// // parse the url var uri = parseUri(url); //console.log("BEFORE uri.path", uri.path) var paths = uri.path.split('/'); //console.log("paths", JSON.stringify(paths)) // remove empty path '//' or null path '/./' paths = paths.filter(function(str, idx){ if( idx === 0 ) return true; if( str === '' ) return false; if( str === '.' ) return false; return true; }); //console.log("paths", JSON.stringify(paths)) // handle the parent path '..' for(var i = 0; i < paths.length; i++ ){ //console.log(i+"th", paths[i], "paths", JSON.stringify(paths)) if( i >= 1 && paths[i+1] === '..' ){ //console.log("BEFORE", i+"th", paths[i], "paths", JSON.stringify(paths)) paths.splice(i, 2); i -= 2; //console.log("AFTER", i+"th", paths[i], "paths", JSON.stringify(paths)) }else if( paths[i] === '..' ){ //console.log("BEFORE", i+"th", paths[i], "paths", JSON.stringify(paths)) paths.splice(i, 1); i -= 1; //console.log("AFTER", i+"th", paths[i], "paths", JSON.stringify(paths)) } } //console.log("paths", JSON.stringify(paths)) // reassemble uri.path uri.path = paths.join('/'); //console.log("AFTER uri.path", uri.path) // build the newUrl var newUrl = uri.protocol+"://"+uri.authority+uri.path + (uri.query ? '?'+uri.query :'') + (uri.anchor ? '#'+uri.anchor:''); // return the newUrl return newUrl; } // export in common js if( typeof module !== "undefined" && ('exports' in module)){ module.exports = normalizeUrl }
var User = require('../../models/user'); module.exports = function(req, res) { var result = User.find ({}) .where('loginName').ne('root') .select('id loginName name claims') .exec(function(err, users) { res.json(users); }); };
import { moduleForComponent, test } from 'ember-qunit'; //import hbs from 'htmlbars-inline-precompile'; moduleForComponent('fd-uml-diagram', 'Integration | Component | fd-uml-diagram', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.set('mockLinkFunction', function() {}); //this.render(hbs`{{fd-uml-diagram // enableEditLinks = mockLinkFunction // enableWrapBaseLinks = mockLinkFunction // disableEditLinks = mockLinkFunction //}}`); //assert.equal(this.$().text().trim(), ''); assert.equal('', ''); });
'use strict'; angular.module('cmaManagementApp') .constant('storageTypes', { VENDOR_UID: "VENDOR_UID", VENDOR_PASS: "VENDOR_PASS", CLIENT_UID: "CLIENT_UID", CLIENT_PASS: "CLIENT_PASS", MONITOR_UID: "MONITOR_UID", MONITOR_PASS: "MONITOR_PASS", ORCH_UID: "ORCH_UID", ORCH_PASS: "ORCH_PASS" });
// Ember.assert, Ember.deprecate, Ember.warn, Ember.TEMPLATES, // jQuery, Ember.lookup, // Ember.ContainerView circular dependency // Ember.ENV import Ember from 'ember-metal/core'; import create from 'ember-metal/platform/create'; import Evented from "ember-runtime/mixins/evented"; import EmberObject from "ember-runtime/system/object"; import EmberError from "ember-metal/error"; import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import setProperties from "ember-metal/set_properties"; import run from "ember-metal/run_loop"; import { addObserver, removeObserver } from "ember-metal/observer"; import { defineProperty } from "ember-metal/properties"; import { guidFor, typeOf } from "ember-metal/utils"; import { computed } from "ember-metal/computed"; import { Mixin, observer, beforeObserver } from "ember-metal/mixin"; import KeyStream from "ember-views/streams/key_stream"; import StreamBinding from "ember-metal/streams/stream_binding"; import ContextStream from "ember-views/streams/context_stream"; import isNone from 'ember-metal/is_none'; import { deprecateProperty } from "ember-metal/deprecate_property"; import { A as emberA } from "ember-runtime/system/native_array"; import { streamifyClassNameBinding } from "ember-views/streams/class_name_binding"; // ES6TODO: functions on EnumerableUtils should get their own export import { forEach, addObject, removeObject } from "ember-metal/enumerable_utils"; import { propertyWillChange, propertyDidChange } from "ember-metal/property_events"; import jQuery from "ember-views/system/jquery"; import "ember-views/system/ext"; // for the side effect of extending Ember.run.queues import CoreView from "ember-views/views/core_view"; import { subscribe, read, isStream } from "ember-metal/streams/utils"; import sanitizeAttributeValue from "ember-views/system/sanitize_attribute_value"; import { normalizeProperty } from "morph/dom-helper/prop"; function K() { return this; } // Circular dep var _renderView; function renderView(view, buffer, template) { if (_renderView === undefined) { _renderView = require('ember-htmlbars/system/render-view')['default']; } _renderView(view, buffer, template); } /** @module ember @submodule ember-views */ var childViewsProperty = computed(function() { var childViews = this._childViews; var ret = emberA(); forEach(childViews, function(view) { var currentChildViews; if (view.isVirtual) { if (currentChildViews = get(view, 'childViews')) { ret.pushObjects(currentChildViews); } } else { ret.push(view); } }); ret.replace = function (idx, removedCount, addedViews) { throw new EmberError("childViews is immutable"); }; return ret; }); Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionality can no longer be disabled.", Ember.ENV.VIEW_PRESERVES_CONTEXT !== false); /** Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. @property TEMPLATES @for Ember @type Hash */ Ember.TEMPLATES = {}; var EMPTY_ARRAY = []; var ViewStreamSupport = Mixin.create({ init: function() { this._baseContext = undefined; this._contextStream = undefined; this._streamBindings = undefined; this._super.apply(this, arguments); }, getStream: function(path) { var stream = this._getContextStream().get(path); stream._label = path; return stream; }, _getBindingForStream: function(pathOrStream) { if (this._streamBindings === undefined) { this._streamBindings = create(null); this.one('willDestroyElement', this, this._destroyStreamBindings); } var path = pathOrStream; if (isStream(pathOrStream)) { path = pathOrStream._label; if (!path) { // if no _label is present on the provided stream // it is likely a subexpr and cannot be set (so it // does not need a StreamBinding) return pathOrStream; } } if (this._streamBindings[path] !== undefined) { return this._streamBindings[path]; } else { var stream = this._getContextStream().get(path); var streamBinding = new StreamBinding(stream); streamBinding._label = path; return this._streamBindings[path] = streamBinding; } }, _destroyStreamBindings: function() { var streamBindings = this._streamBindings; for (var path in streamBindings) { streamBindings[path].destroy(); } this._streamBindings = undefined; }, _getContextStream: function() { if (this._contextStream === undefined) { this._baseContext = new KeyStream(this, 'context'); this._contextStream = new ContextStream(this); this.one('willDestroyElement', this, this._destroyContextStream); } return this._contextStream; }, _destroyContextStream: function() { this._baseContext.destroy(); this._baseContext = undefined; this._contextStream.destroy(); this._contextStream = undefined; }, _unsubscribeFromStreamBindings: function() { for (var key in this._streamBindingSubscriptions) { var streamBinding = this[key + 'Binding']; var callback = this._streamBindingSubscriptions[key]; streamBinding.unsubscribe(callback); } } }); var ViewKeywordSupport = Mixin.create({ init: function() { this._super.apply(this, arguments); if (!this._keywords) { this._keywords = create(null); } this._keywords._view = this; this._keywords.view = undefined; this._keywords.controller = new KeyStream(this, 'controller'); this._setupKeywords(); }, _setupKeywords: function() { var keywords = this._keywords; var contextView = this._contextView || this._parentView; if (contextView) { var parentKeywords = contextView._keywords; keywords.view = this.isVirtual ? parentKeywords.view : this; for (var name in parentKeywords) { if (keywords[name]) { continue; } keywords[name] = parentKeywords[name]; } } else { keywords.view = this.isVirtual ? null : this; } } }); var ViewContextSupport = Mixin.create({ /** The object from which templates should access properties. This object will be passed to the template function each time the render method is called, but it is up to the individual function to decide what to do with it. By default, this will be the view's controller. @property context @type Object */ context: computed(function(key, value) { if (arguments.length === 2) { set(this, '_context', value); return value; } else { return get(this, '_context'); } }).volatile(), /** Private copy of the view's template context. This can be set directly by Handlebars without triggering the observer that causes the view to be re-rendered. The context of a view is looked up as follows: 1. Supplied context (usually by Handlebars) 2. Specified controller 3. `parentView`'s context (for a child of a ContainerView) The code in Handlebars that overrides the `_context` property first checks to see whether the view has a specified controller. This is something of a hack and should be revisited. @property _context @private */ _context: computed(function(key, value) { if (arguments.length === 2) { return value; } var parentView, controller; if (controller = get(this, 'controller')) { return controller; } parentView = this._parentView; if (parentView) { return get(parentView, '_context'); } return null; }), _controller: null, /** The controller managing this view. If this property is set, it will be made available for use by the template. @property controller @type Object */ controller: computed(function(key, value) { if (arguments.length === 2) { this._controller = value; return value; } if (this._controller) { return this._controller; } var parentView = this._parentView; return parentView ? get(parentView, 'controller') : null; }) }); var ViewChildViewsSupport = Mixin.create({ /** Array of child views. You should never edit this array directly. Instead, use `appendChild` and `removeFromParent`. @property childViews @type Array @default [] @private */ childViews: childViewsProperty, _childViews: EMPTY_ARRAY, init: function() { // setup child views. be sure to clone the child views array first this._childViews = this._childViews.slice(); this._super.apply(this, arguments); }, appendChild: function(view, options) { return this.currentState.appendChild(this, view, options); }, /** Removes the child view from the parent view. @method removeChild @param {Ember.View} view @return {Ember.View} receiver */ removeChild: function(view) { // If we're destroying, the entire subtree will be // freed, and the DOM will be handled separately, // so no need to mess with childViews. if (this.isDestroying) { return; } // update parent node set(view, '_parentView', null); // remove view from childViews array. var childViews = this._childViews; removeObject(childViews, view); this.propertyDidChange('childViews'); // HUH?! what happened to will change? return this; }, /** Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. @method createChildView @param {Class|String} viewClass @param {Hash} [attrs] Attributes to add @return {Ember.View} new instance */ createChildView: function(maybeViewClass, _attrs) { if (!maybeViewClass) { throw new TypeError("createChildViews first argument must exist"); } if (maybeViewClass.isView && maybeViewClass._parentView === this && maybeViewClass.container === this.container) { return maybeViewClass; } var attrs = _attrs || {}; var view; attrs._parentView = this; attrs.renderer = this.renderer; if (CoreView.detect(maybeViewClass)) { attrs.container = this.container; view = maybeViewClass.create(attrs); // don't set the property on a virtual view, as they are invisible to // consumers of the view API if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); } } else if ('string' === typeof maybeViewClass) { var fullName = 'view:' + maybeViewClass; var ViewKlass = this.container.lookupFactory(fullName); Ember.assert("Could not find view: '" + fullName + "'", !!ViewKlass); view = ViewKlass.create(attrs); } else { view = maybeViewClass; Ember.assert('You must pass instance or subclass of View', view.isView); attrs.container = this.container; setProperties(view, attrs); } return view; } }); var ViewStateSupport = Mixin.create({ transitionTo: function(state, children) { Ember.deprecate("Ember.View#transitionTo has been deprecated, it is for internal use only"); this._transitionTo(state, children); }, _transitionTo: function(state, children) { var priorState = this.currentState; var currentState = this.currentState = this._states[state]; this._state = state; if (priorState && priorState.exit) { priorState.exit(this); } if (currentState.enter) { currentState.enter(this); } } }); var TemplateRenderingSupport = Mixin.create({ /** Called on your view when it should push strings of HTML into a `Ember.RenderBuffer`. Most users will want to override the `template` or `templateName` properties instead of this method. By default, `Ember.View` will look for a function in the `template` property and invoke it with the value of `context`. The value of `context` will be the view's controller unless you override it. @method render @param {Ember.RenderBuffer} buffer The render buffer */ render: function(buffer) { // If this view has a layout, it is the responsibility of the // the layout to render the view's template. Otherwise, render the template // directly. var template = get(this, 'layout') || get(this, 'template'); renderView(this, buffer, template); } }); /** `Ember.View` is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events. ## HTML Tag The default HTML tag name used for a view's DOM representation is `div`. This can be customized by setting the `tagName` property. The following view class: ```javascript ParagraphView = Ember.View.extend({ tagName: 'em' }); ``` Would result in instances with the following HTML: ```html <em id="ember1" class="ember-view"></em> ``` ## HTML `class` Attribute The HTML `class` attribute of a view's tag can be set by providing a `classNames` property that is set to an array of strings: ```javascript MyView = Ember.View.extend({ classNames: ['my-class', 'my-other-class'] }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view my-class my-other-class"></div> ``` `class` attribute values can also be set by providing a `classNameBindings` property set to an array of properties names for the view. The return value of these properties will be added as part of the value for the view's `class` attribute. These properties can be computed properties: ```javascript MyView = Ember.View.extend({ classNameBindings: ['propertyA', 'propertyB'], propertyA: 'from-a', propertyB: function() { if (someLogic) { return 'from-b'; } }.property() }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view from-a from-b"></div> ``` If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is `false` or `undefined`. ```javascript MyView = Ember.View.extend({ classNameBindings: ['hovered'], hovered: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view hovered"></div> ``` When using boolean class name bindings you can supply a string value other than the property name for use as the `class` HTML attribute by appending the preferred value after a ":" character when defining the binding: ```javascript MyView = Ember.View.extend({ classNameBindings: ['awesome:so-very-cool'], awesome: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view so-very-cool"></div> ``` Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format: ```javascript MyView = Ember.View.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view is-urgent"></div> ``` Class name bindings can also refer to object values that are found by traversing a path relative to the view itself: ```javascript MyView = Ember.View.extend({ classNameBindings: ['messages.empty'] messages: Ember.Object.create({ empty: true }) }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view empty"></div> ``` If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this: ```javascript // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false Ember.View.extend({ classNameBindings: ['isEnabled:enabled:disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view enabled"></div> ``` When isEnabled is `false`, the resulting HTML representation looks like this: ```html <div id="ember1" class="ember-view disabled"></div> ``` This syntax offers the convenience to add a class if a property is `false`: ```javascript // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false Ember.View.extend({ classNameBindings: ['isEnabled::disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"></div> ``` When the `isEnabled` property on the view is set to `false`, it will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view disabled"></div> ``` Updates to the the value of a class name binding will result in automatic update of the HTML `class` attribute in the view's rendered HTML representation. If the value becomes `false` or `undefined` the class name will be removed. Both `classNames` and `classNameBindings` are concatenated properties. See [Ember.Object](/api/classes/Ember.Object.html) documentation for more information about concatenated properties. ## HTML Attributes The HTML attribute section of a view's tag can be set by providing an `attributeBindings` property set to an array of property names on the view. The return value of these properties will be used as the value of the view's HTML associated attribute: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['href'], href: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` One property can be mapped on to another by placing a ":" between the source property and the destination property: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['url:href'], url: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` If the return value of an `attributeBindings` monitored property is a boolean the property will follow HTML's pattern of repeating the attribute's name as its value: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: true }); ``` Will result in view instances with an HTML representation of: ```html <input id="ember1" class="ember-view" disabled="disabled" /> ``` `attributeBindings` can refer to computed properties: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: function() { if (someLogic) { return true; } else { return false; } }.property() }); ``` Updates to the the property of an attribute binding will result in automatic update of the HTML attribute in the view's rendered HTML representation. `attributeBindings` is a concatenated property. See [Ember.Object](/api/classes/Ember.Object.html) documentation for more information about concatenated properties. ## Templates The HTML contents of a view's rendered representation are determined by its template. Templates can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted within the view's tag. Most typically in Ember this function will be a compiled `Ember.Handlebars` template. ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('I am the template') }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I am the template</div> ``` Within an Ember application is more common to define a Handlebars templates as part of a page: ```html <script type='text/x-handlebars' data-template-name='some-template'> Hello </script> ``` And associate it by name using a view's `templateName` property: ```javascript AView = Ember.View.extend({ templateName: 'some-template' }); ``` If you have nested resources, your Handlebars template will look like this: ```html <script type='text/x-handlebars' data-template-name='posts/new'> <h1>New Post</h1> </script> ``` And `templateName` property: ```javascript AView = Ember.View.extend({ templateName: 'posts/new' }); ``` Using a value for `templateName` that does not have a Handlebars template with a matching `data-template-name` attribute will throw an error. For views classes that may have a template later defined (e.g. as the block portion of a `{{view}}` Handlebars helper call in another template or in a subclass), you can provide a `defaultTemplate` property set to compiled template function. If a template is not later provided for the view instance the `defaultTemplate` value will be used: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default'), template: null, templateName: null }); ``` Will result in instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I was the default</div> ``` If a `template` or `templateName` is provided it will take precedence over `defaultTemplate`: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default') }); aView = AView.create({ template: Ember.Handlebars.compile('I was the template, not default') }); ``` Will result in the following HTML representation when rendered: ```html <div id="ember1" class="ember-view">I was the template, not default</div> ``` ## View Context The default context of the compiled template is the view's controller: ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('Hello {{excitedGreeting}}') }); aController = Ember.Object.create({ firstName: 'Barry', excitedGreeting: function() { return this.get("content.firstName") + "!!!" }.property() }); aView = AView.create({ controller: aController }); ``` Will result in an HTML representation of: ```html <div id="ember1" class="ember-view">Hello Barry!!!</div> ``` A context can also be explicitly supplied through the view's `context` property. If the view has neither `context` nor `controller` properties, the `parentView`'s context will be used. ## Layouts Views can have a secondary template that wraps their main template. Like primary templates, layouts can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML element is self closing (e.g. `<input />`) cannot have a layout and this property will be ignored. Most typically in Ember a layout will be a compiled `Ember.Handlebars` template. A view's layout can be set directly with the `layout` property or reference an existing Handlebars template by name with the `layoutName` property. A template used as a layout must contain a single use of the Handlebars `{{yield}}` helper. The HTML contents of a view's rendered `template` will be inserted at this location: ```javascript AViewWithLayout = Ember.View.extend({ layout: Ember.Handlebars.compile("<div class='my-decorative-class'>{{yield}}</div>"), template: Ember.Handlebars.compile("I got wrapped") }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"> <div class="my-decorative-class"> I got wrapped </div> </div> ``` See [Ember.Handlebars.helpers.yield](/api/classes/Ember.Handlebars.helpers.html#method_yield) for more information. ## Responding to Browser Events Views can respond to user-initiated events in one of three ways: method implementation, through an event manager, and through `{{action}}` helper use in their template or layout. ### Method Implementation Views can respond to user-initiated events by implementing a method that matches the event name. A `jQuery.Event` object will be passed as the argument to this method. ```javascript AView = Ember.View.extend({ click: function(event) { // will be called when when an instance's // rendered element is clicked } }); ``` ### Event Managers Views can define an object as their `eventManager` property. This object can then implement methods that match the desired event names. Matching events that occur on the view's rendered HTML or the rendered HTML of any of its DOM descendants will trigger this method. A `jQuery.Event` object will be passed as the first argument to the method and an `Ember.View` object as the second. The `Ember.View` will be the view whose rendered HTML was interacted with. This may be the view with the `eventManager` property or one of its descendant views. ```javascript AView = Ember.View.extend({ eventManager: Ember.Object.create({ doubleClick: function(event, view) { // will be called when when an instance's // rendered element or any rendering // of this view's descendant // elements is clicked } }) }); ``` An event defined for an event manager takes precedence over events of the same name handled through methods on the view. ```javascript AView = Ember.View.extend({ mouseEnter: function(event) { // will never trigger. }, eventManager: Ember.Object.create({ mouseEnter: function(event, view) { // takes precedence over AView#mouseEnter } }) }); ``` Similarly a view's event manager will take precedence for events of any views rendered as a descendant. A method name that matches an event name will not be called if the view instance was rendered inside the HTML representation of a view that has an `eventManager` property defined that handles events of the name. Events not handled by the event manager will still trigger method calls on the descendant. ```javascript var App = Ember.Application.create(); App.OuterView = Ember.View.extend({ template: Ember.Handlebars.compile("outer {{#view 'inner'}}inner{{/view}} outer"), eventManager: Ember.Object.create({ mouseEnter: function(event, view) { // view might be instance of either // OuterView or InnerView depending on // where on the page the user interaction occurred } }) }); App.InnerView = Ember.View.extend({ click: function(event) { // will be called if rendered inside // an OuterView because OuterView's // eventManager doesn't handle click events }, mouseEnter: function(event) { // will never be called if rendered inside // an OuterView. } }); ``` ### Handlebars `{{action}}` Helper See [Handlebars.helpers.action](/api/classes/Ember.Handlebars.helpers.html#method_action). ### Event Names All of the event handling approaches described above respond to the same set of events. The names of the built-in events are listed below. (The hash of built-in events exists in `Ember.EventDispatcher`.) Additional, custom events can be registered by using `Ember.Application.customEvents`. Touch events: * `touchStart` * `touchMove` * `touchEnd` * `touchCancel` Keyboard events * `keyDown` * `keyUp` * `keyPress` Mouse events * `mouseDown` * `mouseUp` * `contextMenu` * `click` * `doubleClick` * `mouseMove` * `focusIn` * `focusOut` * `mouseEnter` * `mouseLeave` Form events: * `submit` * `change` * `focusIn` * `focusOut` * `input` HTML5 drag and drop events: * `dragStart` * `drag` * `dragEnter` * `dragLeave` * `dragOver` * `dragEnd` * `drop` ## Handlebars `{{view}}` Helper Other `Ember.View` instances can be included as part of a view's template by using the `{{view}}` Handlebars helper. See [Ember.Handlebars.helpers.view](/api/classes/Ember.Handlebars.helpers.html#method_view) for additional information. @class View @namespace Ember @extends Ember.CoreView */ var View = CoreView.extend(ViewStreamSupport, ViewKeywordSupport, ViewContextSupport, ViewChildViewsSupport, ViewStateSupport, TemplateRenderingSupport, { concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'], /** @property isView @type Boolean @default true @static */ isView: true, // .......................................................... // TEMPLATE SUPPORT // /** The name of the template to lookup if no template is provided. By default `Ember.View` will lookup a template with this name in `Ember.TEMPLATES` (a shared global object). @property templateName @type String @default null */ templateName: null, /** The name of the layout to lookup if no layout is provided. By default `Ember.View` will lookup a template with this name in `Ember.TEMPLATES` (a shared global object). @property layoutName @type String @default null */ layoutName: null, /** Used to identify this view during debugging @property instrumentDisplay @type String */ instrumentDisplay: computed(function() { if (this.helperName) { return '{{' + this.helperName + '}}'; } }), /** The template used to render the view. This should be a function that accepts an optional context parameter and returns a string of HTML that will be inserted into the DOM relative to its parent view. In general, you should set the `templateName` property instead of setting the template yourself. @property template @type Function */ template: computed('templateName', function(key, value) { if (value !== undefined) { return value; } var templateName = get(this, 'templateName'); var template = this.templateForName(templateName, 'template'); Ember.assert("You specified the templateName " + templateName + " for " + this + ", but it did not exist.", !templateName || !!template); return template || get(this, 'defaultTemplate'); }), /** A view may contain a layout. A layout is a regular template but supersedes the `template` property during rendering. It is the responsibility of the layout template to retrieve the `template` property from the view (or alternatively, call `Handlebars.helpers.yield`, `{{yield}}`) to render it in the correct location. This is useful for a view that has a shared wrapper, but which delegates the rendering of the contents of the wrapper to the `template` property on a subclass. @property layout @type Function */ layout: computed(function(key) { var layoutName = get(this, 'layoutName'); var layout = this.templateForName(layoutName, 'layout'); Ember.assert("You specified the layoutName " + layoutName + " for " + this + ", but it did not exist.", !layoutName || !!layout); return layout || get(this, 'defaultLayout'); }).property('layoutName'), _yield: function(context, options, morph) { var template = get(this, 'template'); if (template) { var useHTMLBars = false; if (Ember.FEATURES.isEnabled('ember-htmlbars')) { useHTMLBars = template.isHTMLBars; } if (useHTMLBars) { return template.render(this, options, morph.contextualElement); } else { return template(context, options); } } }, _blockArguments: EMPTY_ARRAY, templateForName: function(name, type) { if (!name) { return; } Ember.assert("templateNames are not allowed to contain periods: "+name, name.indexOf('.') === -1); if (!this.container) { throw new EmberError('Container was not found when looking up a views template. ' + 'This is most likely due to manually instantiating an Ember.View. ' + 'See: http://git.io/EKPpnA'); } return this.container.lookup('template:' + name); }, /** If a value that affects template rendering changes, the view should be re-rendered to reflect the new value. @method _contextDidChange @private */ _contextDidChange: observer('context', function() { this.rerender(); }), /** If `false`, the view will appear hidden in DOM. @property isVisible @type Boolean @default null */ isVisible: true, // When it's a virtual view, we need to notify the parent that their // childViews will change. _childViewsWillChange: beforeObserver('childViews', function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { propertyWillChange(parentView, 'childViews'); } } }), // When it's a virtual view, we need to notify the parent that their // childViews did change. _childViewsDidChange: observer('childViews', function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { propertyDidChange(parentView, 'childViews'); } } }), /** Return the nearest ancestor that is an instance of the provided class. @method nearestInstanceOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated */ nearestInstanceOf: function(klass) { Ember.deprecate("nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType."); var view = get(this, 'parentView'); while (view) { if (view instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that is an instance of the provided class or mixin. @method nearestOfType @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), or an instance of Ember.Mixin. @return Ember.View */ nearestOfType: function(klass) { var view = get(this, 'parentView'); var isOfType = klass instanceof Mixin ? function(view) { return klass.detect(view); } : function(view) { return klass.detect(view.constructor); }; while (view) { if (isOfType(view)) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that has a given property. @method nearestWithProperty @param {String} property A property name @return Ember.View */ nearestWithProperty: function(property) { var view = get(this, 'parentView'); while (view) { if (property in view) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor whose parent is an instance of `klass`. @method nearestChildOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated */ nearestChildOf: function(klass) { Ember.deprecate("nearestChildOf has been deprecated."); var view = get(this, 'parentView'); while (view) { if (get(view, 'parentView') instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** When the parent view changes, recursively invalidate `controller` @method _parentViewDidChange @private */ _parentViewDidChange: observer('_parentView', function() { if (this.isDestroying) { return; } this._setupKeywords(); this.trigger('parentViewDidChange'); if (get(this, 'parentView.controller') && !get(this, 'controller')) { this.notifyPropertyChange('controller'); } }), _controllerDidChange: observer('controller', function() { if (this.isDestroying) { return; } this.rerender(); this.forEachChildView(function(view) { view.propertyDidChange('controller'); }); }), /** Renders the view again. This will work regardless of whether the view is already in the DOM or not. If the view is in the DOM, the rendering process will be deferred to give bindings a chance to synchronize. If children were added during the rendering process using `appendChild`, `rerender` will remove them, because they will be added again if needed by the next `render`. In general, if the display of your view changes, you should modify the DOM element directly instead of manually calling `rerender`, which can be slow. @method rerender */ rerender: function() { return this.currentState.rerender(this); }, /** Iterates over the view's `classNameBindings` array, inserts the value of the specified property into the `classNames` array, then creates an observer to update the view's element if the bound property ever changes in the future. @method _applyClassNameBindings @private */ _applyClassNameBindings: function(classBindings) { var classNames = this.classNames; var elem, newClass, dasherizedClass; // Loop through all of the configured bindings. These will be either // property names ('isUrgent') or property paths relative to the view // ('content.isUrgent') forEach(classBindings, function(binding) { var boundBinding; if (isStream(binding)) { boundBinding = binding; } else { boundBinding = streamifyClassNameBinding(this, binding, '_view.'); } // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; // Set up an observer on the context. If the property changes, toggle the // class name. var observer = this._wrapAsScheduled(function() { // Get the current value of the property elem = this.$(); newClass = read(boundBinding); // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames.removeObject(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } }); // Get the class name for the property at its current value dasherizedClass = read(boundBinding); if (dasherizedClass) { // Ensure that it gets into the classNames array // so it is displayed when we render. addObject(classNames, dasherizedClass); // Save a reference to the class name so we can remove it // if the observer fires. Remember that this variable has // been closed over by the observer. oldClass = dasherizedClass; } subscribe(boundBinding, observer, this); // Remove className so when the view is rerendered, // the className is added based on binding reevaluation this.one('willClearRender', function() { if (oldClass) { classNames.removeObject(oldClass); oldClass = null; } }); }, this); }, _unspecifiedAttributeBindings: null, /** Iterates through the view's attribute bindings, sets up observers for each, then applies the current value of the attributes to the passed render buffer. @method _applyAttributeBindings @param {Ember.RenderBuffer} buffer @private */ _applyAttributeBindings: function(buffer, attributeBindings) { var attributeValue; var unspecifiedAttributeBindings = this._unspecifiedAttributeBindings = this._unspecifiedAttributeBindings || {}; forEach(attributeBindings, function(binding) { var split = binding.split(':'); var property = split[0]; var attributeName = split[1] || property; Ember.assert('You cannot use class as an attributeBinding, use classNameBindings instead.', attributeName !== 'class'); if (property in this) { this._setupAttributeBindingObservation(property, attributeName); // Determine the current value and add it to the render buffer // if necessary. attributeValue = get(this, property); View.applyAttributeBindings(this.renderer._dom, buffer, attributeName, attributeValue); } else { unspecifiedAttributeBindings[property] = attributeName; } }, this); // Lazily setup setUnknownProperty after attributeBindings are initially applied this.setUnknownProperty = this._setUnknownProperty; }, _setupAttributeBindingObservation: function(property, attributeName) { var attributeValue, elem; // Create an observer to add/remove/change the attribute if the // JavaScript property changes. var observer = function() { elem = this.$(); attributeValue = get(this, property); var normalizedName = normalizeProperty(elem, attributeName.toLowerCase()) || attributeName; View.applyAttributeBindings(this.renderer._dom, elem, normalizedName, attributeValue); }; this.registerObserver(this, property, observer); }, /** We're using setUnknownProperty as a hook to setup attributeBinding observers for properties that aren't defined on a view at initialization time. Note: setUnknownProperty will only be called once for each property. @method setUnknownProperty @param key @param value @private */ setUnknownProperty: null, // Gets defined after initialization by _applyAttributeBindings _setUnknownProperty: function(key, value) { var attributeName = this._unspecifiedAttributeBindings && this._unspecifiedAttributeBindings[key]; if (attributeName) { this._setupAttributeBindingObservation(key, attributeName); } defineProperty(this, key); return set(this, key, value); }, /** Given a property name, returns a dasherized version of that property name if the property evaluates to a non-falsy value. For example, if the view has property `isUrgent` that evaluates to true, passing `isUrgent` to this method will return `"is-urgent"`. @method _classStringForProperty @param property @private */ _classStringForProperty: function(parsedPath) { return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); }, // .......................................................... // ELEMENT SUPPORT // /** Returns the current DOM element for the view. @property element @type DOMElement */ element: null, /** Returns a jQuery object for this view's element. If you pass in a selector string, this method will return a jQuery object, using the current element as its buffer. For example, calling `view.$('li')` will return a jQuery object containing all of the `li` elements inside the DOM element of this view. @method $ @param {String} [selector] a jQuery-compatible selector string @return {jQuery} the jQuery object for the DOM node */ $: function(sel) { return this.currentState.$(this, sel); }, mutateChildViews: function(callback) { var childViews = this._childViews; var idx = childViews.length; var view; while (--idx >= 0) { view = childViews[idx]; callback(this, view, idx); } return this; }, forEachChildView: function(callback) { var childViews = this._childViews; if (!childViews) { return this; } var len = childViews.length; var view, idx; for (idx = 0; idx < len; idx++) { view = childViews[idx]; callback(view); } return this; }, /** Appends the view's element to the specified parent element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing. This is not typically a function that you will need to call directly when building your application. You might consider using `Ember.ContainerView` instead. If you do need to use `appendTo`, be sure that the target element you are providing is associated with an `Ember.Application` and does not have an ancestor element that is associated with an Ember view. @method appendTo @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} receiver */ appendTo: function(selector) { var target = jQuery(selector); Ember.assert("You tried to append to (" + selector + ") but that isn't in the DOM", target.length > 0); Ember.assert("You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.", !target.is('.ember-view') && !target.parents().is('.ember-view')); this.renderer.appendTo(this, target[0]); return this; }, /** Replaces the content of the specified parent element with this view's element. If the view does not have an HTML representation yet, the element will be generated automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing @method replaceIn @param {String|DOMElement|jQuery} target A selector, element, HTML string, or jQuery object @return {Ember.View} received */ replaceIn: function(selector) { var target = jQuery(selector); Ember.assert("You tried to replace in (" + selector + ") but that isn't in the DOM", target.length > 0); Ember.assert("You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.", !target.is('.ember-view') && !target.parents().is('.ember-view')); this.renderer.replaceIn(this, target[0]); return this; }, /** Appends the view's element to the document body. If the view does not have an HTML representation yet the element will be generated automatically. If your application uses the `rootElement` property, you must append the view within that element. Rendering views outside of the `rootElement` is not supported. Note that this method just schedules the view to be appended; the DOM element will not be appended to the document body until all bindings have finished synchronizing. @method append @return {Ember.View} receiver */ append: function() { return this.appendTo(document.body); }, /** Removes the view's element from the element to which it is attached. @method remove @return {Ember.View} receiver */ remove: function() { // What we should really do here is wait until the end of the run loop // to determine if the element has been re-appended to a different // element. // In the interim, we will just re-render if that happens. It is more // important than elements get garbage collected. if (!this.removedFromDOM) { this.destroyElement(); } }, /** The HTML `id` of the view's element in the DOM. You can provide this value yourself but it must be unique (just as in HTML): ```handlebars {{my-component elementId="a-really-cool-id"}} ``` If not manually set a default value will be provided by the framework. Once rendered an element's `elementId` is considered immutable and you should never change it. @property elementId @type String */ elementId: null, /** Attempts to discover the element in the parent element. The default implementation looks for an element with an ID of `elementId` (or the view's guid if `elementId` is null). You can override this method to provide your own form of lookup. For example, if you want to discover your element using a CSS class name instead of an ID. @method findElementInParentElement @param {DOMElement} parentElement The parent's DOM element @return {DOMElement} The discovered element */ findElementInParentElement: function(parentElem) { var id = "#" + this.elementId; return jQuery(id)[0] || jQuery(id, parentElem)[0]; }, /** Creates a DOM representation of the view and all of its child views by recursively calling the `render()` method. After the element has been inserted into the DOM, `didInsertElement` will be called on this view and all of its child views. @method createElement @return {Ember.View} receiver */ createElement: function() { if (this.element) { return this; } this._didCreateElementWithoutMorph = true; this.renderer.renderTree(this); return this; }, /** Called when a view is going to insert an element into the DOM. @event willInsertElement */ willInsertElement: K, /** Called when the element of the view has been inserted into the DOM or after the view was re-rendered. Override this function to do any set up that requires an element in the document body. When a view has children, didInsertElement will be called on the child view(s) first, bubbling upwards through the hierarchy. @event didInsertElement */ didInsertElement: K, /** Called when the view is about to rerender, but before anything has been torn down. This is a good opportunity to tear down any manual observers you have installed based on the DOM state @event willClearRender */ willClearRender: K, /** Destroys any existing element along with the element for any child views as well. If the view does not currently have a element, then this method will do nothing. If you implement `willDestroyElement()` on your view, then this method will be invoked on your view before your element is destroyed to give you a chance to clean up any event handlers, etc. If you write a `willDestroyElement()` handler, you can assume that your `didInsertElement()` handler was called earlier for the same element. You should not call or override this method yourself, but you may want to implement the above callbacks. @method destroyElement @return {Ember.View} receiver */ destroyElement: function() { return this.currentState.destroyElement(this); }, /** Called when the element of the view is going to be destroyed. Override this function to do any teardown that requires an element, like removing event listeners. Please note: any property changes made during this event will have no effect on object observers. @event willDestroyElement */ willDestroyElement: K, /** Called when the parentView property has changed. @event parentViewDidChange */ parentViewDidChange: K, instrumentName: 'view', instrumentDetails: function(hash) { hash.template = get(this, 'templateName'); this._super(hash); }, beforeRender: function(buffer) {}, afterRender: function(buffer) {}, applyAttributesToBuffer: function(buffer) { // Creates observers for all registered class name and attribute bindings, // then adds them to the element. var classNameBindings = this.classNameBindings; if (classNameBindings.length) { this._applyClassNameBindings(classNameBindings); } // Pass the render buffer so the method can apply attributes directly. // This isn't needed for class name bindings because they use the // existing classNames infrastructure. var attributeBindings = this.attributeBindings; if (attributeBindings.length) { this._applyAttributeBindings(buffer, attributeBindings); } buffer.setClasses(this.classNames); buffer.id(this.elementId); var role = get(this, 'ariaRole'); if (role) { buffer.attr('role', role); } if (get(this, 'isVisible') === false) { buffer.style('display', 'none'); } }, // .......................................................... // STANDARD RENDER PROPERTIES // /** Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the `tagName` for an element, you must destroy and recreate the view element. By default, the render buffer will use a `<div>` tag for views. @property tagName @type String @default null */ // We leave this null by default so we can tell the difference between // the default case and a user-specified tag. tagName: null, /** The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. The full list of valid WAI-ARIA roles is available at: [http://www.w3.org/TR/wai-aria/roles#roles_categorization](http://www.w3.org/TR/wai-aria/roles#roles_categorization) @property ariaRole @type String @default null */ ariaRole: null, /** Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. @property classNames @type Array @default ['ember-view'] */ classNames: ['ember-view'], /** A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. ```javascript // Applies the 'high' class to the view element Ember.View.extend({ classNameBindings: ['priority'] priority: 'high' }); ``` If the value of the property is a Boolean, the name of that property is added as a dasherized class name. ```javascript // Applies the 'is-urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent'] isUrgent: true }); ``` If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this: ```javascript // Applies the 'urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent:urgent'] isUrgent: true }); ``` This list of properties is inherited from the view's superclasses as well. @property classNameBindings @type Array @default [] */ classNameBindings: EMPTY_ARRAY, /** A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the attribute. ```javascript // Applies the type attribute to the element // with the value "button", like <div type="button"> Ember.View.extend({ attributeBindings: ['type'], type: 'button' }); ``` If the value of the property is a Boolean, the name of that property is added as an attribute. ```javascript // Renders something like <div enabled="enabled"> Ember.View.extend({ attributeBindings: ['enabled'], enabled: true }); ``` @property attributeBindings */ attributeBindings: EMPTY_ARRAY, // ....................................................... // CORE DISPLAY METHODS // /** Setup a view, but do not finish waking it up. * configure `childViews` * register the view with the global views hash, which is used for event dispatch @method init @private */ init: function() { if (!this.isVirtual && !this.elementId) { this.elementId = guidFor(this); } this._super.apply(this, arguments); Ember.assert("Only arrays are allowed for 'classNameBindings'", typeOf(this.classNameBindings) === 'array'); this.classNameBindings = emberA(this.classNameBindings.slice()); Ember.assert("Only arrays of static class strings are allowed for 'classNames'. For dynamic classes, use 'classNameBindings'.", typeOf(this.classNames) === 'array'); this.classNames = emberA(this.classNames.slice()); }, __defineNonEnumerable: function(property) { this[property.name] = property.descriptor.value; }, /** Removes all children from the `parentView`. @method removeAllChildren @return {Ember.View} receiver */ removeAllChildren: function() { return this.mutateChildViews(function(parentView, view) { parentView.removeChild(view); }); }, destroyAllChildren: function() { return this.mutateChildViews(function(parentView, view) { view.destroy(); }); }, /** Removes the view from its `parentView`, if one is found. Otherwise does nothing. @method removeFromParent @return {Ember.View} receiver */ removeFromParent: function() { var parent = this._parentView; // Remove DOM element from parent this.remove(); if (parent) { parent.removeChild(this); } return this; }, /** You must call `destroy` on a view to destroy the view (and all of its child views). This will remove the view from any parent node, then make sure that the DOM element managed by the view can be released by the memory manager. @method destroy */ destroy: function() { // get parentView before calling super because it'll be destroyed var nonVirtualParentView = get(this, 'parentView'); var viewName = this.viewName; if (!this._super.apply(this, arguments)) { return; } // remove from non-virtual parent view if viewName was specified if (viewName && nonVirtualParentView) { nonVirtualParentView.set(viewName, null); } return this; }, becameVisible: K, becameHidden: K, /** When the view's `isVisible` property changes, toggle the visibility element of the actual DOM element. @method _isVisibleDidChange @private */ _isVisibleDidChange: observer('isVisible', function() { if (this._isVisible === get(this, 'isVisible')) { return ; } run.scheduleOnce('render', this, this._toggleVisibility); }), _toggleVisibility: function() { var $el = this.$(); var isVisible = get(this, 'isVisible'); if (this._isVisible === isVisible) { return ; } // It's important to keep these in sync, even if we don't yet have // an element in the DOM to manipulate: this._isVisible = isVisible; if (!$el) { return; } $el.toggle(isVisible); if (this._isAncestorHidden()) { return; } if (isVisible) { this._notifyBecameVisible(); } else { this._notifyBecameHidden(); } }, _notifyBecameVisible: function() { this.trigger('becameVisible'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameVisible(); } }); }, _notifyBecameHidden: function() { this.trigger('becameHidden'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameHidden(); } }); }, _isAncestorHidden: function() { var parent = get(this, 'parentView'); while (parent) { if (get(parent, 'isVisible') === false) { return true; } parent = get(parent, 'parentView'); } return false; }, // ....................................................... // EVENT HANDLING // /** Handle events from `Ember.EventDispatcher` @method handleEvent @param eventName {String} @param evt {Event} @private */ handleEvent: function(eventName, evt) { return this.currentState.handleEvent(this, eventName, evt); }, registerObserver: function(root, path, target, observer) { if (!observer && 'function' === typeof target) { observer = target; target = null; } if (!root || typeof root !== 'object') { return; } var scheduledObserver = this._wrapAsScheduled(observer); addObserver(root, path, target, scheduledObserver); this.one('willClearRender', function() { removeObserver(root, path, target, scheduledObserver); }); }, _wrapAsScheduled: function(fn) { var view = this; var stateCheckedFn = function() { view.currentState.invokeObserver(this, fn); }; var scheduledFn = function() { run.scheduleOnce('render', this, stateCheckedFn); }; return scheduledFn; } }); deprecateProperty(View.prototype, 'state', '_state'); deprecateProperty(View.prototype, 'states', '_states'); /* Describe how the specified actions should behave in the various states that a view can exist in. Possible states: * preRender: when a view is first instantiated, and after its element was destroyed, it is in the preRender state * inBuffer: once a view has been rendered, but before it has been inserted into the DOM, it is in the inBuffer state * hasElement: the DOM representation of the view is created, and is ready to be inserted * inDOM: once a view has been inserted into the DOM it is in the inDOM state. A view spends the vast majority of its existence in this state. * destroyed: once a view has been destroyed (using the destroy method), it is in this state. No further actions can be invoked on a destroyed view. */ // in the destroyed state, everything is illegal // before rendering has begun, all legal manipulations are noops. // inside the buffer, legal manipulations are done on the buffer // once the view has been inserted into the DOM, legal manipulations // are done on the DOM element. var mutation = EmberObject.extend(Evented).create(); // TODO MOVE TO RENDERER HOOKS View.addMutationListener = function(callback) { mutation.on('change', callback); }; View.removeMutationListener = function(callback) { mutation.off('change', callback); }; View.notifyMutationListeners = function() { mutation.trigger('change'); }; /** Global views hash @property views @static @type Hash */ View.views = {}; // If someone overrides the child views computed property when // defining their class, we want to be able to process the user's // supplied childViews and then restore the original computed property // at view initialization time. This happens in Ember.ContainerView's init // method. View.childViewsProperty = childViewsProperty; // Used by Handlebars helpers, view element attributes View.applyAttributeBindings = function(dom, elem, name, initialValue) { var value = sanitizeAttributeValue(dom, elem[0], name, initialValue); var type = typeOf(value); // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js if (name !== 'value' && (type === 'string' || (type === 'number' && !isNaN(value)))) { if (value !== elem.attr(name)) { elem.attr(name, value); } } else if (name === 'value' || type === 'boolean') { if (isNone(value) || value === false) { // `null`, `undefined` or `false` should remove attribute elem.removeAttr(name); // In IE8 `prop` couldn't remove attribute when name is `required`. if (name === 'required') { elem.removeProp(name); } else { elem.prop(name, ''); } } else if (value !== elem.prop(name)) { // value should always be properties elem.prop(name, value); } } else if (!value) { elem.removeAttr(name); } }; export default View; export { ViewKeywordSupport, ViewStreamSupport, ViewContextSupport, ViewChildViewsSupport, ViewStateSupport, TemplateRenderingSupport };
/** * No Coin - Stop coin miners in your browser ** * @author Rafael Keramidas <ker.af> * @license MIT * @source https://github.com/keraf/NoCoin */ // Config const defaultConfig = { toggle: true, whitelist: [{ domain: 'cnhv.co', expiration: 0, }], }; const localConfig = JSON.parse(localStorage.getItem('config')); let config = { ...defaultConfig, ...localConfig, }; /** * Functions */ const saveConfig = () => { localStorage.setItem('config', JSON.stringify(config)); }; const changeToggleIcon = (isEnabled) => { chrome.browserAction.setIcon({ path: `img/${isEnabled ? 'logo_enabled' : 'logo_disabled'}.png`, }); }; const getDomain = (url) => { const match = url.match(/:\/\/(.[^/]+)/); return match ? match[1] : ''; }; const getTimestamp = () => { return Math.floor(Date.now() / 1000); }; const isDomainWhitelisted = (domain) => { if (!domain) return false; const domainInfo = config.whitelist.find(w => w.domain === domain); if (domainInfo) { if (domainInfo.expiration !== 0 && domainInfo.expiration <= getTimestamp()) { removeDomainFromWhitelist(domain); return false; } return true; } return false; }; const addDomainToWhitelist = (domain, time) => { if (!domain) return; // Make sure the domain is not already whitelisted before adding it if (!isDomainWhitelisted(domain)) { config.whitelist = [ ...config.whitelist, { domain: domain, expiration: time === 0 ? 0 : getTimestamp() + (time * 60), }, ]; saveConfig(); } }; const removeDomainFromWhitelist = (domain) => { if (!domain) return; config.whitelist = config.whitelist.filter(w => w.domain !== domain); saveConfig(); }; const runBlocker = (blacklist) => { const blacklistedUrls = blacklist.split('\n'); chrome.webRequest.onBeforeRequest.addListener(details => { // Globally paused if (!config.toggle) { return { cancel: false }; } // Is domain white listed if (isDomainWhitelisted(domains[details.tabId])) { return { cancel: false }; } return { cancel: true }; }, { urls: blacklistedUrls }, ['blocking']); }; const runFallbackBlocker = () => { fetch(chrome.runtime.getURL('blacklist.txt')) .then(resp => { resp.text().then(text => runBlocker(text)); }); }; /** * Main */ let domains = []; // Updating domain for synchronous checking in onBeforeRequest chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { domains[tabId] = getDomain(tab.url); }); chrome.tabs.onRemoved.addListener((tabId) => { delete domains[tabId]; }); // Run with the right icon if (!config.toggle) { changeToggleIcon(false); } // Load the blacklist and run the blocker const blacklist = 'https://raw.githubusercontent.com/keraf/NoCoin/master/src/blacklist.txt'; fetch(blacklist) .then(resp => { if (resp.status === 200) { resp.text().then((text) => { if (text === '') { runFallbackBlocker(); } else { runBlocker(text); } }); } else { runFallbackBlocker(); } }) .catch(err => { runFallbackBlocker(); }); // Communication with the popup and content scripts chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { switch (message.type) { case 'GET_STATE': sendResponse({ whitelisted: isDomainWhitelisted(domains[message.tabId]), toggle: config.toggle, }); break; case 'TOGGLE': config.toggle = !config.toggle; saveConfig(); changeToggleIcon(config.toggle); sendResponse(config.toggle); break; case 'WHITELIST': { if (message.whitelisted) { removeDomainFromWhitelist(domains[message.tabId], message.time); } else { addDomainToWhitelist(domains[message.tabId], message.time); } sendResponse(!message.whitelisted); break; } } });
/** * @author mrdoob / http://mrdoob.com/ */ THREE.CSS2DObject = function ( element ) { THREE.Object3D.call( this ); this.element = element; this.element.style.position = 'absolute'; this.addEventListener( 'removed', function ( event ) { if ( this.element.parentNode !== null ) { this.element.parentNode.removeChild( this.element ); } } ); }; THREE.CSS2DObject.prototype = Object.create( THREE.Object3D.prototype ); THREE.CSS2DObject.prototype.constructor = THREE.CSS2DObject; // THREE.CSS2DRenderer = function () { console.log( 'THREE.CSS2DRenderer', THREE.REVISION ); var _width, _height; var _widthHalf, _heightHalf; var vector = new THREE.Vector3(); var viewMatrix = new THREE.Matrix4(); var viewProjectionMatrix = new THREE.Matrix4(); var domElement = document.createElement( 'div' ); domElement.style.overflow = 'hidden'; this.domElement = domElement; this.setSize = function ( width, height ) { _width = width; _height = height; _widthHalf = _width / 2; _heightHalf = _height / 2; domElement.style.width = width + 'px'; domElement.style.height = height + 'px'; }; var renderObject = function ( object, camera ) { if ( object instanceof THREE.CSS2DObject ) { vector.setFromMatrixPosition( object.matrixWorld ); vector.applyMatrix4( viewProjectionMatrix ); var element = object.element; var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)'; element.style.WebkitTransform = style; element.style.MozTransform = style; element.style.oTransform = style; element.style.transform = style; if ( element.parentNode !== domElement ) { domElement.appendChild( element ); } } for ( var i = 0, l = object.children.length; i < l; i ++ ) { renderObject( object.children[ i ], camera ); } }; this.render = function ( scene, camera ) { scene.updateMatrixWorld(); if ( camera.parent === null ) camera.updateMatrixWorld(); viewMatrix.copy( camera.matrixWorldInverse ); viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, viewMatrix ); renderObject( scene, camera ); }; };
/************************************************************* * * MathJax/localization/br/FontWarnings.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("br","FontWarnings",{ version: "2.7.3", isLoaded: true, strings: { webFont: "MathJax a implij ar fonto\u00F9 web evit diskwel ar jedado\u00F9 war ar bajenn-ma\u00F1. Pell eo ar re-se o pellgarga\u00F1 ha diskwelet e vefe buanoc'h ma stailhfec'h fonto\u00F9 jedoniezh war-eeun e teuliad fonto\u00F9 ho reizhiad.", noFonts: "N'hall ket MathJax lec'hia\u00F1 ur polis evit diskwel e jedado\u00F9, ha dihegerz eo ar fonto\u00F9 skeudenn. Ret eo implijout arouezenno\u00F9 Unicode neuze. Emicha\u00F1s e c'hallo ho merdeer diskwel anezho. Ne c'hallo ket arouezenno\u00F9 zo beza\u00F1 diskwelet mat, tamm ebet zoken.", webFonts: "GAnt an darn vrasa\u00F1 eus ar merdeerio\u00F9 arnevez e c'haller pellgarga\u00F1 fonto\u00F9 adalek ar web. Hizivaat ho merdeer (pe che\u00F1ch merdeer) a c'hallfe gwellaat kalite ar jedado\u00F9 war ar bajenn-ma\u00F1.", fonts: "Gallout a ra MathJax implijout pe ar fonto\u00F9 [STIX](%1) pe ar fonto\u00F9 [MathJax TeX](%2); Pellgargit ha stailhit unan eus fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.", STIXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [STIX ](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-penet gant MathJax.", TeXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [MathJax TeX](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.", imageFonts: "Ober a ra MathJax gant skeudenno\u00F9 font kentoc'h eget gant fonto\u00F9 web pe fonto\u00F9 lec'hel. Gant se e teu an trao\u00F9 gorrekoc'h war-wel ha marteze ne vo ket ar jedado\u00F9 evit beza\u00F1 moullet diouzh pizhder kloka\u00F1 ho moullerez." } }); MathJax.Ajax.loadComplete("[MathJax]/localization/br/FontWarnings.js");
'use strict'; describe('Controller: AdvisorCtrl', function () { // load the controller's module beforeEach(module('advisorLinkApp')); var AdvisorCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); AdvisorCtrl = $controller('AdvisorCtrl', { $scope: scope }); })); it('should ...', function () { expect(1).toEqual(1); }); });
var db= require('../../db'); var test = require('assert'); var create; var createEmbeded; var createOne; var createOneEmbeded; var find; var findEmbeded; var findOne; var findOneEmbeded; describe('core',function () { before(function (done) { db.connect(function () { create= require('../../core/create'); createEmbeded= require('../../core/createEmbeded'); createOne= require('../../core/createOne'); createOneEmbeded= require('../../core/createOneEmbeded'); find= require('../../core/find'); findEmbeded= require('../../core/findEmbeded'); findOne= require('../../core/findOne'); findOneEmbeded= require('../../core/findOneEmbeded'); done(); }); }); describe('find',function () { it('find',function (done) { var payload= new Date().getTime(); create('find',[{p1:payload}]) .then(function () { return find('find',{p1:payload}).toArray(); }) .then(function (r) { test.equal(1, r.length); done(); }) .catch(function (err) { done(err); }); }); it('findOne',function (done) { var payload= new Date().getTime(); create('findOne',[{p1:payload}]) .then(function () { return findOne('findOne',{p1:payload}); }) .then(function (r) { test.equal(payload, r.p1); done(); }) .catch(function (err) { done(err); }); }); it('Projection',function (done) { var payload= new Date().getTime(); create('findOne',[{p1:payload}]) .then(function () { return findOne('findOne',{p1:payload},{_id:0}); }) .then(function (r) { test.equal(false, r.hasOwnProperty('_id')); test.equal(payload, r.p1); done(); }) .catch(function (err) { done(err); }); }); it('findEmbeded',function (done) { var payload= new Date().getTime(); create('findEmbeded',[ { a:payload, embededProperty:[ { b:payload, c:1 }] }, { a:payload, embededProperty:[ { b:payload, c:2 }] } ]) .then(function () { return findEmbeded('embededProperty',{b:payload},{},'findEmbeded'); }) .then(function (r) { // console.log(r); test.equal( r.length,2); done(); }) .catch(function (err) { done(err); }); }); it('findOneEmbeded',function (done) { var payload= new Date().getTime(); create('findOneEmbeded',[ { a:payload, embededProperty:[ { b:payload }] }, { a:payload, embededProperty:[ { b:payload }] } ]) .then(function () { return findOneEmbeded('embededProperty',{b:payload},{},'findOneEmbeded'); }) .then(function (r) { test.equal(payload, r.b); done(); }) .catch(function (err) { console.log(err); done(err); }); }); }); });
/* * Kendo UI Web v2012.2.710 (http://kendoui.com) * Copyright 2012 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function($, undefined) { var kendo = window.kendo, ui = kendo.ui, proxy = $.proxy, extend = $.extend, grep = $.grep, map = $.map, inArray = $.inArray, ACTIVE = "k-state-selected", ASC = "asc", DESC = "desc", CLICK = "click", CHANGE = "change", POPUP = "kendoPopup", FILTERMENU = "kendoFilterMenu", MENU = "kendoMenu", Widget = ui.Widget; function trim(text) { if (!String.prototype.trim) { text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } else { text = text.trim(); } return text.replace(/&nbsp;/gi, ""); } var ColumnMenu = Widget.extend({ init: function(element, options) { var that = this, link; Widget.fn.init.call(that, element, options); element = that.element; options = that.options; that.owner = options.owner; that.field = element.attr(kendo.attr("field")); link = element.find(".k-header-column-menu"); if (!link[0]) { link = element.prepend('<a class="k-header-column-menu" href="#"><span class="k-icon k-i-arrowhead-s"/></a>').find(".k-header-column-menu"); } that._clickHandler = proxy(that._click, that); link.click(that._clickHandler); that.link = link; that.wrapper = $('<div class="k-column-menu"/>'); that.wrapper.html(kendo.template(template)({ ns: kendo.ns, messages: options.messages, sortable: options.sortable, filterable: options.filterable, columns: that._ownerColumns(), showColumns: options.columns })); that.popup = that.wrapper[POPUP]({ anchor: link, open: proxy(that._open, that) }).data(POPUP); that._menu(); that._sort(); that._columns(); that._filter(); }, options: { name: "ColumnMenu", messages: { sortAscending: "Sort Ascending", sortDescending: "Sort Descending", filter: "Filter", columns: "Columns" }, columns: true, sortable: true, filterable: true }, destroy: function() { var that = this; if (that.filterMenu) { that.filterMenu.destroy(); that.filterMenu = null; } that.wrapper.children().removeData(MENU); that.wrapper.removeData(POPUP).remove(); that.link.unbind(CLICK, that._clickHandler); that.element.removeData("kendoColumnMenu"); that.columns = null; }, close: function() { this.menu.close(); this.popup.close(); }, _click: function(e) { e.preventDefault(); e.stopPropagation(); this.popup.toggle(); }, _open: function() { $(".k-column-menu").not(this.wrapper).each(function() { $(this).data(POPUP).close(); }); }, _ownerColumns: function() { var columns = this.owner.columns, menuColumns = grep(columns, function(col) { var result = true, title = trim(col.title || ""); if (col.menu === false || (!col.field && !title.length)) { result = false; } return result; }); return map(menuColumns, function(col) { return { field: col.field, title: col.title || col.field, hidden: col.hidden, index: inArray(col, columns) }; }); }, _menu: function() { this.menu = this.wrapper.children()[MENU]({ orientation: "vertical", closeOnClick: false }).data(MENU); }, _sort: function() { var that = this; if (that.options.sortable) { that.refresh(); that.options.dataSource.bind(CHANGE, proxy(that.refresh, that)); that.menu.element.delegate(".k-sort-asc, .k-sort-desc", CLICK, function() { var item = $(this), dir = item.hasClass("k-sort-asc") ? ASC : DESC; item.parent().find(".k-sort-" + (dir == ASC ? DESC : ASC)).removeClass(ACTIVE); that._sortDataSource(item, dir); that.close(); }); } }, _sortDataSource: function(item, dir) { var that = this, sortable = that.options.sortable, dataSource = that.options.dataSource, idx, length, sort = dataSource.sort() || []; if (item.hasClass(ACTIVE) && sortable && sortable.allowUnsort !== false) { item.removeClass(ACTIVE); dir = undefined; } else { item.addClass(ACTIVE); } if (sortable === true || sortable.mode === "single") { sort = [ { field: that.field, dir: dir } ]; } else { for (idx = 0, length = sort.length; idx < length; idx++) { if (sort[idx].field === that.field) { sort.splice(idx, 1); break; } } sort.push({ field: that.field, dir: dir }); } dataSource.sort(sort); }, _columns: function() { var that = this; if (that.options.columns) { that._updateColumnsMenu(); that.owner.bind(["columnHide", "columnShow"], function() { that._updateColumnsMenu(); }); that.wrapper.delegate("[type=checkbox]", CHANGE , function(e) { var input = $(this), index = parseInt(input.attr(kendo.attr("index")), 10); if (input.is(":checked")) { that.owner.showColumn(index); } else { that.owner.hideColumn(index); } }); } }, _updateColumnsMenu: function() { var columns = this._ownerColumns(), allselector = map(columns, function(field) { return "[" + kendo.attr("index") + "=" + field.index+ "]"; }).join(","), visible = grep(columns, function(field) { return !field.hidden; }), selector = map(visible, function(field) { return "[" + kendo.attr("index") + "=" + field.index+ "]"; }).join(","); this.wrapper.find(allselector).attr("checked", false); this.wrapper.find(selector).attr("checked", true).attr("disabled", visible.length == 1); }, _filter: function() { var that = this, options = that.options; if (options.filterable !== false) { that.filterMenu = that.wrapper.find(".k-filterable")[FILTERMENU]( extend(true, {}, { appendToElement: true, dataSource: options.dataSource, values: options.values, field: that.field }, options.filterable) ).data(FILTERMENU); } }, refresh: function() { var that = this, sort = that.options.dataSource.sort() || [], descriptor, field = that.field, idx, length; that.wrapper.find(".k-sort-asc, .k-sort-desc").removeClass(ACTIVE); for (idx = 0, length = sort.length; idx < length; idx++) { descriptor = sort[idx]; if (field == descriptor.field) { that.wrapper.find(".k-sort-" + descriptor.dir).addClass(ACTIVE); } } } }); var template = '<ul>'+ '#if(sortable){#'+ '<li class="k-item k-sort-asc"><span class="k-link"><span class="k-sprite k-i-sort-asc"></span>${messages.sortAscending}</span></li>'+ '<li class="k-item k-sort-desc"><span class="k-link"><span class="k-sprite k-i-sort-desc"></span>${messages.sortDescending}</span></li>'+ '#if(showColumns || filterable){#'+ '<li class="k-separator"></li>'+ '#}#'+ '#}#'+ '#if(showColumns){#'+ '<li class="k-item k-columns-item"><span class="k-link"><span class="k-sprite k-i-columns"></span>${messages.columns}</span><ul>'+ '#for (var col in columns) {#'+ '<li><label><input type="checkbox" data-#=ns#field="#=columns[col].field#" data-#=ns#index="#=columns[col].index#"/>#=columns[col].title#</label></li>'+ '#}#'+ '</ul></li>'+ '#if(filterable){#'+ '<li class="k-separator"></li>'+ '#}#'+ '#}#'+ '#if(filterable){#'+ '<li class="k-item k-filter-item"><span class="k-link"><span class="k-sprite k-filter"></span>${messages.filter}</span><ul>'+ '<li><div class="k-filterable"></div></li>'+ '</ul></li>'+ '#}#'+ '</ul>'; ui.plugin(ColumnMenu); })(jQuery); ;
(function() { 'use strict'; angular .module('noctemApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('jhi-health', { parent: 'admin', url: '/health', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'health.title' }, views: { 'content@': { templateUrl: 'app/admin/health/health.html', controller: 'JhiHealthCheckController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('health'); return $translate.refresh(); }] } }); } })();
var Reflux = require('reflux'); var Firebase = require('firebase'); var GroupActions = require('../actions/GroupActions'); var DefaultStoreActions = require('../actions/DefaultStoreActions'); var _ = require('underscore'); var firebaseRef; function updateWithSnapshot(snapshot) { var val = snapshot.val(); var group = {id: snapshot.key() }; group = _.extend(group, val); GroupStore.setGroup(snapshot.key(), group); GroupStore.StoreActions.addSuccess(snapshot.key()); } function setupFirebase() { firebaseRef = new Firebase("http://glaring-heat-1654.firebaseio.com/groups"); firebaseRef.on('child_added', updateWithSnapshot); firebaseRef.on('child_changed', updateWithSnapshot); firebaseRef.on('child_removed', snapshot => { GroupStore.destroyGroup(snapshot.key()); }); } var GroupStore = Reflux.createStore({ _collections : {}, listenables: GroupActions, StoreActions: DefaultStoreActions(), init() { setupFirebase(); }, getGroups(userGroups) { if (!userGroups) return this._collections; var groups = []; userGroups.forEach(groupId => { groups.concat(this._collections[groupId] || []); }); return groups; }, setGroup(key, group) { this._collections[key] = group; this.trigger("setGroups", this._collections); }, destroyGroup(key) { delete this._collections[key]; this.trigger("setGroups", this._collections); }, addGroup(group) { firebaseRef.push(group); }, updateGroup(group) { var groupRef = firebaseRef.child(group.id); groupRef.update(group); }, removeGroup(group) { firebaseRef.child(group.id).remove(); } }); module.exports = GroupStore;
'use strict'; angular.module('myApp.view1') .directive('articolo', [function(){ return{ restrict: "EAC", scope: { articolo: "=news", searchKey: "=searchKey" }, templateUrl: 'app/components/view1/view1_articolo.html' } }]) ;
'use strict'; const { BasePage } = require('kakunin'); class SimpleForm extends BasePage { constructor() { super(); this.url = '/form/simple'; this.form = $('form'); this.nameInput = this.form.$('input[name="name"]'); this.descriptionTextarea = this.form.$('textarea[name="description"]'); this.optionCheckboxes = this.form.$$('input[type="checkbox"]'); this.optionRadios = this.form.$$('input[type="radio"]'); this.statusSelect = this.form.$('select[name="status"]'); this.submitButton = this.form.$('input[type="submit"]'); } } module.exports = SimpleForm;
var map; $(document).ready(function(){ var a=document.getElementById('map'); map = new GMaps({el: a, //el: '#map', lat: 55.763585, lng: 37.560883, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP, zoomControl : true, zoomControlOpt: { style : 'SMALL', position: 'TOP_LEFT' } }); var logo=$('#logo').attr('src'); //alert(logo); var icon = { url: '/bundles/realty/map_icon.png', // url scaledSize: new google.maps.Size(40, 40), // scaled size origin: new google.maps.Point(0,0), // origin anchor: new google.maps.Point(0, 0) // anchor }; //var icon='/bundles/realty/map_icon.png'; var markers=$('#PagesAllGoogleMap').val(); markers= JSON.parse(markers); var PagesAllGoogleMap_path=$('#PagesAllGoogleMap_path').val(); for (var i =0; i<markers.length;i++) { if (markers[i]['city'] && markers[i]['street'] ) { var address=markers[i]['city']+', '+markers[i]['street']+', '+markers[i]['house']; var image=''; if (markers[i]['image_path']) { image='<img src="/'+markers[i]['image_path']+'">'; } var price=''; if (markers[i]['price']) { price='<p>Price: '+markers[i]['price']+' USD</p>'; } var totalArea=''; if (markers[i]['totalArea']) { totalArea='<p>Total Area: '+markers[i]['totalArea']+'m2</p>'; } var floor=''; if (markers[i]['totalArea']) { floor='<p>Floor: '+markers[i]['numberOfFloors']+'/'+markers[i]['floor']+'</p>'; } var contentHtml='<div class="bubblewrap">' + '<a style="display:block;text-decoration:none" href="'+PagesAllGoogleMap_path+markers[i]['path']+'">' + '<div class="mapContainer">' + '<div class="mapPhoto">' + image + '</div>' + '<div class="mapDataC">' + '<p><i class="fa fa-map-marker" aria-hidden="true"></i>'+address+'</p>' + '<p>'+totalArea+'</p>' + '<p>'+floor+'</p>' + '<p>'+price+'</p>' + '</div>' + '<div class="view_div"><i class="info_window_arrow fa fa-5x fa-angle-right"></i></div>' + '</div>' + '</a>' + '</div>'; // ************************ // grnertae makers content theme hlml css // ************************ mapMake(address,icon,contentHtml); } } function mapMake(address, icon, contentHtml ) { GMaps.geocode({ address: address, callback: function(results, status, html1) { if (status == 'OK') { var latlng = results[0].geometry.location; map.setCenter(latlng.lat(), latlng.lng()); map.addMarker({ lat: latlng.lat(), lng: latlng.lng(), // title: 'Lima', icon: icon, infoWindow: { content: contentHtml } }); } } }); } });
//Init var CANVAS_WIDTH = 512; var CANVAS_HEIGHT = 512; var MOVABLE = "movable"; //jiglib body types in strings var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"]; //enums for indexing BODY_TYPES var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3}; var SCORE_LOC_X = 130; var SCORE_LOC_Y = 475; var SCORETEXT_LOC_X = 70; var SCORETEXT_LOC_Y = 478; var SCORE_TEXT_CONTENT = "score:"; //Factors for the ray xyz-values. Used in initStatusScene() var RAY_FACTOR_X = -5; var RAY_FACTOR_Y = 5; var RAY_FACTOR_Z = -5; //Start and end message constants var GAME_OVER_TEXT = "Game over!"; var START_GAME_TEXT = "Press 'enter' to start!"; var START_OFFSET_X = 0; var START_OFFSET_Y = 0; var START_OFFSET_Z = -5; var END_OFFSET_X = 0; var END_OFFSET_Y = 0; var END_OFFSET_Z = -5; var DEFAULT_FOG_COLOR = "#3F3F3F"; var EFFECT_FOG_COLOR = "#DCFCCC"; var SCORE_TEXT_COLOR = "#D0F0C0"; var SCORE_TEXT_SIZE = 10; var STATE_TEXT_COLOR = "#D0F0C0";//"#ffdd00"; var STATE_TEXT_SIZE = 17; var calculateSize = function(side1, side2){ if(side2 == side1){ return 0; } else if(side2 < 0.0 && side1 >= 0.0){ return(Math.abs(side2) + side1); } else if(side1 < 0.0 && side2 >= 0.0){ return(Math.abs(side1) + side2); } else if(side1 >= 0.0 && side2 >= 0.0 && side1 > side2){ return(side1-side2); } else if(side1 >= 0.0 && side2 >= 0.0 && side2 > side1){ return(side2-side1); } else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side1) > Math.abs(side2)){ return(Math.abs(side1)-Math.abs(side2)); } else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side2) > Math.abs(side1)){ return(Math.abs(side2)-Math.abs(side1)); } }
WAF.define('WakendoColorPicker', ['waf-core/widget', 'wakendoCore'], function(widget, $) { 'use strict'; var KendoColorPicker = widget.create('WakendoColorPicker', { value: widget.property({ type: 'string' }), flat: widget.property({ type: 'boolean', defaultValue: false }), init: function() { var self = this; self.valueChangeSubscriber = self.value.onChange(function(newValue) { self.kendoWidget.value(newValue); }); self.flat.onChange(self.render); self.render(); }, render: function() { var self = this; $(self.node).empty(); var options = { change: function(event) { self.valueChangeSubscriber.pause(); self.value(event.value); self.valueChangeSubscriber.resume(); } }; if (self.flat()) { var $el = $(self.node); $el.kendoFlatColorPicker(options); self.kendoWidget = $el.data("kendoFlatColorPicker"); } else { var $el = $('<input />').appendTo(self.node); $el.kendoColorPicker(options); self.kendoWidget = $el.data("kendoColorPicker"); } }, open: function() { this.kendoWidget.open(); }, close: function() { this.kendoWidget.close(); }, enable: function() { this.kendoWidget.enable(); }, disable: function() { this.kendoWidget.enable(false); } }); return KendoColorPicker; });
/* * The MIT License (MIT) * * Copyright (c) 2014 Marcel Mika, marcelmika.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Main Controller * * This controller creates instances of all controllers in the app and injects objects that are necessary for them. * It also holds instances of objects that are needed across the app. */ Y.namespace('LIMS.Controller'); Y.LIMS.Controller.MainController = Y.Base.create('mainController', Y.Base, [Y.LIMS.Controller.ControllerExtension], { /** * The initializer runs when a MainController instance is created, and gives * us an opportunity to set up all sub controllers */ initializer: function () { var buddyDetails = this.get('buddyDetails'), settingsModel = this.get('settingsModel'), notification = this.get('notification'), properties = this.get('properties'), serverTime = this.get('serverTimeModel'), poller = this.get('poller'), rootNode = this.getRootNode(); // Attach events this._attachEvents(); // Load the most fresh server time to count server time offset serverTime.load(function (err) { // Update to the optimal offset that we get from the server. // If there is an error properties contain offset read from the // html as a fallback. if (!err) { properties.set('offset', new Date().getTime() - serverTime.get('time')); } // Group new Y.LIMS.Controller.GroupViewController({ container: rootNode.one('.buddy-list'), properties: properties, poller: poller }); // Presence new Y.LIMS.Controller.PresenceViewController({ container: rootNode.one('.status-panel'), buddyDetails: buddyDetails }); // Settings new Y.LIMS.Controller.SettingsViewController({ container: rootNode.one('.chat-settings'), model: settingsModel }); // Conversation new Y.LIMS.Controller.ConversationsController({ container: rootNode.one('.lims-tabs'), buddyDetails: buddyDetails, settings: settingsModel, notification: notification, properties: properties, poller: poller }); }); }, /** * This is called whenever the user session expires */ sessionExpired: function () { // Fire an event so the other controllers know about the expiration Y.fire('userSessionExpired'); }, /** * Attach local functions to events * * @private */ _attachEvents: function () { // Global events Y.on('initializationFinished', this._onInitializationFinished, this); // Panel events Y.on('panelShown', this._onPanelShown, this); Y.on('panelHidden', this._onPanelHidden, this); Y.on('userSessionExpired', this._onSessionExpired, this); }, /** * Called when the initialization is finished * * @private */ _onInitializationFinished: function () { // We can now show the portlet this.showPortlet(); }, /** * Called when any panel is shown * * @param panel * @private */ _onPanelShown: function (panel) { var panelId = panel.get('panelId'); // Store current active panel id this.set('activePanelId', panelId); // Update settings this.get('settingsModel').updateActivePanel(panelId); }, /** * Called when any panel is hidden * * @param panel * @private */ _onPanelHidden: function (panel) { // If the hidden panel is currently active panel it means that no panel is currently active if (this.get('activePanelId') === panel.get('panelId')) { // Update settings this.get('settingsModel').updateActivePanel(null); } }, /** * Called when the user session expires * * @private */ _onSessionExpired: function () { // Hide the whole portlet Y.LIMS.Core.Util.hide(this.getRootNode()); } }, { // Add custom model attributes here. These attributes will contain your // model's data. See the docs for Y.Attribute to learn more about defining // attributes. ATTRS: { /** * Buddy details related of the currently logged user * * {Y.LIMS.Model.BuddyModelItem} */ buddyDetails: { valueFn: function () { // We need settings to determine user var properties = new Y.LIMS.Core.Properties(); // Get logged user return new Y.LIMS.Model.BuddyModelItem({ buddyId: properties.getCurrentUserId(), male: properties.getCurrentUserMale(), portraitId: properties.getCurrentUserPortraitId(), portraitImageToken: properties.getCurrentUserPortraitImageToken(), portraitToken: properties.getCurrentUserPortraitToken(), screenName: properties.getCurrentUserScreenName(), fullName: properties.getCurrentUserFullName() }); } }, /** * Settings of the currently logged user * * {Y.LIMS.Model.SettingsModel} */ settingsModel: { valueFn: function () { return new Y.LIMS.Model.SettingsModel({ buddy: this.get('buddyDetails') }); } }, /** * Current server time * * {Y.LIMS.Model.ServerTimeModel} */ serverTimeModel: { valueFn: function () { return new Y.LIMS.Model.ServerTimeModel(); } }, /** * Notification object responsible for the incoming message notification * * {Y.LIMS.Core.Notification} */ notification: { valueFn: function () { return new Y.LIMS.Core.Notification({ settings: this.get('settingsModel'), container: this.getRootNode().one('.lims-sound'), properties: this.get('properties') }); } }, /** * An instance of poller that periodically refreshes models that are subscribed * * {Y.LIMS.Core.Poller} */ poller: { valueFn: function () { return new Y.LIMS.Core.Poller(); } }, /** * Properties object that holds the global portlet properties * * {Y.LIMS.Core.Properties} */ properties: { valueFn: function () { return new Y.LIMS.Core.Properties(); } }, /** * ID of the current active panel * * {string} */ activePanelId: { value: null // default value } } });
let express = require('express'); let path = require('path'); let logger = require('morgan'); let bodyParser = require('body-parser'); let index = require('./routes/index'); let semanticui = require('./routes/semanticui'); let foundation = require('./routes/foundation'); let test = require('./routes/test-post'); let helmet = require('helmet'); let resourceMonitorMiddleware = require('express-watcher').resourceMonitorMiddleware; let app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(resourceMonitorMiddleware); app.use(helmet()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname + '/public'))); app.use(express.static(path.join(__dirname + '/dist'))); app.use('/', index); app.use('/semanticui', semanticui); app.use('/foundation', foundation); app.post('/test', function (req, res) { console.log('REQ.BODY: ' + req.body); res.send('click click'); }); // catch 404 and forward to error handler app.use(function(req, res, next) { console.log(res.statusCode); next(res.error); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;