code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/*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() }); }());
shackbarth/node-datasource
lib/routes/data.js
JavaScript
mit
896
// -- 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"] = {} ] );
kriskowal/lode
lib/require.js
JavaScript
mit
7,883
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" ); }); });
jeffreyjw/experimentA
testorial/tests/A beginner/1 getting started/Node/script.js
JavaScript
mit
236
var requireDir = require('require-dir') requireDir('./gulp/tasks')
tylingsoft/mermaid
gulpfile.js
JavaScript
mit
68
'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; }]) ;
dobin/yookiterm
app/modules/setting/SettingsServices.js
JavaScript
mit
989
//#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; } };
johndbritton/gitviz
canviz/src/Entity.js
JavaScript
mit
10,924
/* * 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));
jaredhoyt/jquery-sentinel
src/jquery.sentinel.js
JavaScript
mit
856
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; }; };
ibeerepoot/Programmeerproject
funda/node_modules/d3/node_modules/d3-request/src/requestType.js
JavaScript
mit
244
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();
scapp281/cliff-effects
src/index.js
JavaScript
mit
303
$('.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'); } }); });
primas23/UniversityCoursesRegistrationSystem
UCRS.WebClient/Scripts/modalStudent.js
JavaScript
mit
1,123
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(); }
jvalen/pixel-art-react
src/store/actions/actionCreators.js
JavaScript
mit
3,034
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":[]}]};
wmira/react-icons-kit
src/md/ic_battery_full_twotone.js
JavaScript
mit
330
/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ 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 _; }; }));
DellGDC/dell-ui-components
bower_components/slick-1.5.0/slick/slick.js
JavaScript
mit
70,367
/* * 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; }`));
jugglinmike/es6draft
src/test/scripts/suite/regress/bug4337.js
JavaScript
mit
812
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;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/UPnP.UPnPService.1.js
JavaScript
mit
573
/* 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 }; };
meteor-gazelle/meteor-gazelle
packages/meteor-gazelle-schema/gazelleSchema.js
JavaScript
mit
3,970
/* * 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 };
libbyh/jit
Source/Options/Options.AreaChart.js
JavaScript
mit
1,939
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 };
dreamyguy/gitinsight
frontend/src/contexts/ErrorProvider.js
JavaScript
mit
494
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') }
rpdiss/lock
lib/i18n/dicts.js
JavaScript
mit
916
/** * 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 <foo@blurdybloop.com>', // sender address to: 'bar@blurdybloop.com, baz@blurdybloop.com', // 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;
callmeharry/pelican
pelican/common/mail.js
JavaScript
mit
9,472
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 }; };
lengstrom/wikipedia.js
js/core.js
JavaScript
mit
682
version https://git-lfs.github.com/spec/v1 oid sha256:a285e8981a5115bbdd913280943a1d1a0d498b079ace167d6e90a0cc9e2cdfba size 93324
yogeshsaroya/new-cdnjs
ajax/libs/foundation/5.3.0/js/foundation.min.js
JavaScript
mit
130
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'); });
intensr/bachelorthesis
build/gulp/tasks/watch.js
JavaScript
mit
266
var path = require('path') var lib = require(path.join(__dirname, '/lib')) module.exports = lib
appology/resp-parser
index.js
JavaScript
mit
96
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')(); } });
kristenhazard/hanuman
frontend/mirage/factories/survey-template.js
JavaScript
mit
318
(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' };
FMeat/FMeat.github.io
js/new-age.js
JavaScript
mit
923
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; }
redexp/html-extend
src/css-find.js
JavaScript
mit
3,248
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()
karma-runner/karma-browserstack-launcher
worker-manager.js
JavaScript
mit
2,341
/*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); }); });
lancedikson/generator-frontender
test/test-load.js
JavaScript
mit
274
/*! 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 $; });
teal-front/teal-front.github.io
WEB/WEB_COMPONENT/iframe菜单_档住object_原趣玩游戏项目/chat/www/scripts/tools/jquery.mousewheel.js
JavaScript
mit
8,013
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" };
Zannark/CollegeProject_SurvivalGame
Docs/Documentation/html/search/searchdata.js
JavaScript
mit
453
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)});
lauren/open-in-spotify
node_modules/mocha/node_modules/mkdirp/test/return_sync.min.js
JavaScript
mit
425
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, {}); }); });
garris/BackstopJS
test/core/util/makeConfig_spec.js
JavaScript
mit
483
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); } } } );
mejiai14/Awsomenauts
js/entities/TeamArcher.js
JavaScript
mit
2,653
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'); }); }); });
vesln/nsredis
test/namespaces.test.js
JavaScript
mit
423
/* 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;
erangeles/sl-ember-test-helpers
Brocfile.js
JavaScript
mit
1,612
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 }
jeromeetienne/normalizeUrl.js
normalizeUrl.js
JavaScript
mit
2,727
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); }); };
TotalMace/lk-buddy
handlers/users/get-all-users.js
JavaScript
mit
272
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('', ''); });
Flexberry/ember-flexberry-designer
tests/integration/components/fd-uml-diagram-test.js
JavaScript
mit
686
'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" });
sanu82624/HealthApp
www/appjs/services/constant/storageTypes.js
JavaScript
mit
336
// 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 };
gdi2290/ember.js
packages/ember-views/lib/views/view.js
JavaScript
mit
64,713
/** * 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; } } });
suhail-sullad/NoCoin
src/js/background.js
JavaScript
mit
4,378
/** * @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 ); }; };
masterfish2015/my_project
math/libs/three/examples/js/renderers/CSS2DRenderer.js
JavaScript
mit
2,306
/************************************************************* * * 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");
wgertler/wgertler.github.io
MathJax-master/unpacked/localization/br/FontWarnings.js
JavaScript
mit
2,622
'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); }); });
prosperence/advisor-link
client/app/main/advisor/advisor.spec.js
JavaScript
mit
456
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); }); }); }); });
Utkarsh85/advaya-mongo
test/core/find.js
JavaScript
mit
2,838
/* * 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); ;
dbishoponline/superdashboard
kendo/source/js/kendo.columnmenu.js
JavaScript
mit
10,664
(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(); }] } }); } })();
gcorreageek/noctem
src/main/webapp/app/admin/health/health.state.js
JavaScript
mit
990
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;
mboperator/react-signal
lib/js/stores/GroupStore.js
JavaScript
mit
1,670
'use strict'; angular.module('myApp.view1') .directive('articolo', [function(){ return{ restrict: "EAC", scope: { articolo: "=news", searchKey: "=searchKey" }, templateUrl: 'app/components/view1/view1_articolo.html' } }]) ;
dennybiasiolli/angular-test
www/app/components/view1/directives.js
JavaScript
mit
328
'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;
TheSoftwareHouse/Kakunin
functional-tests/pages/simpleForm.js
JavaScript
mit
605
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 } }); } } }); } });
seinyan/NDM
src/RealtyBundle/Resources/public/realty_bundle_gmap.js
JavaScript
mit
3,420
//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)); } }
Pervasive/Lively3D
Dropbox/Lively3D/Resources/Tasohyppely/scripts/helpper.js
JavaScript
mit
1,667
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; });
acoudeyras/WakendoColorPicker
widget.js
JavaScript
mit
1,619
/* * 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 } } });
marcelmika/lims
docroot/js/src/lims/js/controller/MainController.js
JavaScript
mit
8,353
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;
Igelex/PP_2017-Voice-control
app.js
JavaScript
mit
1,500
import { emit } from "../../api"; import { setActiveRoom } from "../room/roomSlice.js"; export function presentChanged(present) { return { type: "localUser/present", present }; } export const ping = () => () => emit("/user/current/ping"); export const changeActiveRoom = roomId => dispatch => { dispatch(setActiveRoom(roomId)); return emit("/user/current/activity", { room: roomId }); }; export function changePresent(present) { return dispatch => { return emit("/user/current/present", { present }).then(() => dispatch(presentChanged(present))); }; }
bunkerchat/bunker
src/features/users/localUserActions.js
JavaScript
mit
563
(function(b,g,j,e,q,o){var i,d,c,f,h,l=function(){i=JSON.parse(e.getItem(b))||{};i=q?q({},i):i},k=function(m,a,n){m.addEventListener('click',function(){l();i[n]=a.value;e.setItem(b,JSON.stringify(i))})};l();o.querySelectorAll('.js-stream-item').forEach(function(a){if(!a.getAttribute(g)){d=a.getAttribute(j);c=a.querySelector('.ProfileCard-bio').parentNode;c.appendChild(f=o.createElement('textarea'),f.style.width='100%',f.style.height='150px',f.setAttribute('placeholder','メモ'),f.textContent=i[d]||'',f);c.appendChild(h=o.createElement('button'),h.className='btn',h.textContent='このアカウントのメモを保存',k(h,f,d),h);a.setAttribute(g,1)}})})('followmemo','data-applied','data-item-id',localStorage,Object.assign,document);
MarkerU/follow-memo
follow-memo.min.js
JavaScript
mit
744
/* * Returns Messages * * This contains all the text for the Returns component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.components.Returns.header', defaultMessage: 'returns', }, returnPolicy: { id: 'app.components.Returns.returnPolicy', defaultMessage: 'Return Policy', }, message: { id: 'app.components.Returns.message', defaultMessage: 'This item must be returned within 30 days of the ship date. See {policyLink} for details. Prices, promotions, styles and availability may vary by store and online.', }, });
outdooricon/my-retail-example
app/components/Returns/messages.js
JavaScript
mit
612
import React from 'react' import '../../styles/gkm-item.scss'; import ProductItem from './ProductItem' import Input from '../Common/Input' import SearchBar from '../SearchBar'; import _ from 'lodash' class EtsyProduct extends React.Component { constructor(props, context) { super(props, context); this.editables = { name: { max: 20, display: 'Name' }, shortDescription: { max: 100, display: 'Short Description' }, twitterTitle: { max: 100, display: 'Twitter Text' } }; } onUpdateField(update) { console.log(update) let product = this.props.product _.each(update, (v, k) => { product[k] = v; }) this.props.updateItem(product); } getListingById(id) { return _.find(this.props.listings, (l) => l.id === id) } editableFieldsHtml() { const { product } = this.props return ( <div> {_.map(this.editables, (v, fld) => ( <Input title={v.display} fld={fld} value={product[fld]} id={product.id} onUpdate={ (i, update) => this.onUpdateField(update) } />)) } </div> ) } onAddtoCategory(category) { const { product } = this.props; addItemtoCategory(product, category) } render() { const { product, listings, addListingToProduct } = this.props; const loader = (<div>loading...</div >) const productItems = product.populatedListings.map((listing) => (listing ? < ProductItem key={listing.id} product={listing} inProduct={true} /> : loader)) return ( <div className='gkm-etsy-product' id={product.id}> <h5>Etsy Product</h5> <div> Product Name: {product.name} <div>Categories:</div> {_.map(product.hashtags.all(), (hashtag) => (<div>{hashtag}</div>))} <Input title="add category" fld='category' resetOnClick={true} button={{ text: 'ADD!', action: this.onAddtoCategory }} /> {this.editableFieldsHtml()} </div> {productItems} <div> Add another listing: </div> <SearchBar products={listings} onSelect={ (listingId) => { addListingToProduct(product, this.getListingById(listingId)) } } /> </div> ) } } /* Item.propTypes = { }; */ export default EtsyProduct
oded-soffrin/gkm_viewer
.history/src/components/GKM/EtsyProduct_20170624130727.js
JavaScript
mit
2,453
/** * Main JS file for Jasper behaviours */ if (typeof jQuery == 'undefined') { document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></' + 'script>'); } (function ($) { "use strict"; // Header Parallax and Fade $(window).on('scroll', function() { var scroll_top = $(this).scrollTop(); var top_offset = 600; $('#site-head-content').css({ 'opacity' : (1-scroll_top/top_offset), 'top' : (scroll_top*-.2) }); /* // Background Image Parallax $('#site-head').css({ 'background-position' : 'center ' + (scroll_top*-.07) + 'px' }); */ }); // Shameless self-promotion console.log("Yo, fellow dev. Check out our homepage, and find out about our other goodies: http://www.farmsoftstudios.com") }(jQuery));
russianryebread/jasper
assets/js/index.js
JavaScript
mit
923
describe('dev-radiolist', function() { beforeEach(function() { browser().navigateTo(mainUrl); }); it('should show radio options and submit new value', function() { var s = '[ng-controller="DevRadiolistCtrl"] '; expect(element(s+'a.normal ').text()).toMatch('status1'); element(s+'a.normal ').click(); expect(element(s+'a.normal ').css('display')).toBe('none'); expect(element(s+'form[editable-form="$form"]').count()).toBe(1); expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2); expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true'); expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false'); // select status2 using(s+'label:eq(1)').input('$parent.$parent.$data').select('false'); element(s+'form button[type="submit"]').click(); expect(element(s+'a.normal ').css('display')).not().toBe('none'); expect(element(s+'a.normal ').text()).toMatch('status2'); expect(element(s+'form').count()).toBe(0); }); it('should show radio options and call on-change event', function() { var s = '[ng-controller="DevRadiolistCtrl"] '; expect(element(s+'a.nobuttons ').text()).toMatch('status1'); element(s+'a.nobuttons ').click(); expect(element(s+'a.nobuttons ').css('display')).toBe('none'); expect(element(s+'form[editable-form="$form"]').count()).toBe(1); expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2); expect(element(s+'form input[type="radio"]').attr('ng-change')).toBeDefined(); expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true'); expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false'); // select status2 using(s+'label:eq(1)').input('$parent.$parent.$data').select('false'); element(s).click(); expect(element(s+'a.nobuttons ').css('display')).not().toBe('none'); expect(element(s+'a.nobuttons ').text()).toMatch('status1'); expect(element(s+'form').count()).toBe(0); }); });
arielcr/angular-xeditable
docs/demos/dev-radiolist/test.js
JavaScript
mit
2,080
import React from 'react'; import styles from './App.less'; import withContext from '../../decorators/withContext'; import withStyles from '../../decorators/withStyles'; import Rankinglist from '../Rankinglist/Rankinglist'; @withContext @withStyles(styles) class App { render() { return ( <div id="app"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Norges Tour</h3> </div> <div id="main-wrapper"> <nav className="sidebar-left" id="left-menu"> <ul className="nav nav-pills nav-stacked"> <li role="presentation" className="active"><a href="#"> <span className="glyphicon glyphicon-stats" aria-hidden="true"></span> Rankinglister</a> </li> <li role="presentation" className="disabled"><a href="#"> <span className="glyphicon glyphicon-bullhorn" aria-hidden="true"></span> Resultater</a> </li> <li role="presentation" className="disabled"><a href="#"> <span className="glyphicon glyphicon-align-justify" aria-hidden="true"></span> Turneringer</a> </li> </ul> </nav> <main> <Rankinglist /> </main> </div> </div> </div> ); } } export default App;
SindreSvendby/beach-ranking-web
src/components/App/App.js
JavaScript
mit
1,431
/** * tiny-di * @module binding/lazy * @copyright Dennis Saenger <tiny-di-15@mail.ds82.de> */ 'use strict'; import { AbstractBinding } from './abstract'; export class LazyBinding extends AbstractBinding { constructor(injector, key, path, opts) { super(injector, key); this.path = path; this.opts = opts; } load() { return this.injector.load(this.key, this.path, this.opts); } $get() { return this.load(); } }
ds82/tiny-di
src/binding/lazy.js
JavaScript
mit
449
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fileEntry = { // Create the id for the file being uploaded as this will determine // the location of the uploaded file in our object store. id: await r.uuid(), name: fileToUpload.name, checksum: fileToUpload.hash, mediatype: mtype.mediaTypeDescriptionsFromMime(fileToUpload.type), size: fileToUpload.size, path: fileToUpload.path, owner: userId, parentId: '', }; let file = await getFileByNameInDirectory(fileToUpload.name, directoryId); if (!file) { // There is no existing file with this name in the directory. fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum); return await loadNewFileIntoDirectory(fileEntry, directoryId, projectId); } else if (file.checksum !== fileEntry.checksum) { // There is an existing file in the directory but it has a different // checksum, so we have to do a little book keeping to make this file // the current file, set its parent entry back to the existing, as well // as do the usual steps for uploading a file into the object store. fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum); return await loadExistingFileIntoDirectory(file, fileEntry, directoryId, projectId); } else { // If we are here then there is a file with the same name in the directory // and it has the same checksum. In that case there is nothing to load // into the database as the user is attempting to upload an existing // file (name and checksum match the existing file). removeFile(fileEntry.path); return file; } } // getFileByNameInDirectory will return the current file in the directory // that matches the filename. This is used to construct multiple versions // of a file, with only one version being the current one. async function getFileByNameInDirectory(fileName, directoryId) { let file = await r.table('datadir2datafile').getAll(directoryId, {index: 'datadir_id'}) .eqJoin('datafile_id', r.table('datafiles')).zip() .filter({name: fileName, current: true}); if (file) { return file[0]; // query returns an array of 1 entry. } return null; } async function loadNewFileIntoDirectory(fileEntry, directoryId, projectId) { await addToObjectStore(fileEntry); return await createFile(fileEntry, directoryId, projectId); } async function loadExistingFileIntoDirectory(parent, fileEntry, directoryId, projectId) { await addToObjectStore(fileEntry); fileEntry.parentId = parent.id; let created = await createFile(fileEntry, directoryId, projectId); // Parent is no longer the current file await r.table('datafiles').get(parent.id).update({current: false}); return created; } async function addToObjectStore(fileEntry) { if (fileEntry.usesid === '') { // This is a brand new file so move into the object store. await mcdir.moveIntoStore(fileEntry.path, fileEntry.id); } else { // There is already a file in the store with the same checksum // so delete uploaded file. removeFile(fileEntry.path); } } // findMatchingFileIdByChecksum will return the id of the file that // was uploaded with the name checksum or "" if there is no match. async function findMatchingFileIdByChecksum(checksum) { let matching = await r.table('datafiles').getAll(checksum, {index: 'checksum'}); if (matching.length) { // Multiple entries have been found that have the same checksum. In the database // a file has a usesid which points to the original entry that was first uploaded // with the matching checksum. So, we take the first entry in the list, it is // either this original upload, or a file with a usesid that points to the original // upload. We can determine this by checking if usesid === "". If it is return the // id, otherwise return the usesid. return matching[0].usesid === '' ? matching[0].id : matching[0].usesid; } // If we are here then there was no match found, so just return "" to signify no match. return ''; } function removeFile(path) { try { fs.unlinkSync(path); } catch (e) { return false; } } async function createFile(fileEntry, directoryId, projectId) { let file = new model.DataFile(fileEntry.name, fileEntry.owner); file.mediatype = fileEntry.mediatype; file.size = fileEntry.size; file.uploaded = file.size; file.checksum = fileEntry.checksum; file.usesid = fileEntry.usesid; file.id = fileEntry.id; file.parent = fileEntry.parentId ? fileEntry.parentId : ''; let created = await db.insert('datafiles', file); await addFileToDirectory(created.id, directoryId); await addFileToProject(created.id, projectId); return created; } async function addFileToDirectory(fileId, directoryId) { const dd2df = new model.DataDir2DataFile(directoryId, fileId); await r.table('datadir2datafile').insert(dd2df); } async function addFileToProject(fileId, projectId) { let p2df = new model.Project2DataFile(projectId, fileId); await r.table('project2datafile').insert(p2df); } return { addFileToDirectoryInProject, createFile, }; };
materials-commons/materialscommons.org
backend/servers/mcapid/lib/dal/dir-utils/file-upload.js
JavaScript
mit
6,105
'use strict'; import ResponseHandler from './response-handler'; import retrieve from './retrieve'; class ResultList { constructor(search, options, onSuccess, onFailure) { this._search = search; this._options = options; this._onSuccess = onSuccess; this._onFailure = onFailure; this._requestPromises = []; // first call of next will increment to desired page this._options.page -= 1; } next() { const nextPage = this._options.page += 1; if (this._requestPromises[nextPage]) { return this._requestPromises[nextPage]; } return this._get(); } previous() { if (this._options.page <= 1) { throw new Error('There is no previous page'); } const previousPage = this._options.page -= 1; if (this._requestPromises[previousPage]) { return this._requestPromises[previousPage]; } return this._get(); } _get() { const page = this._options.page; const perPage = this._options.per_page; const promise = retrieve(this._search, this._options) .then(this._success(page, perPage)) .catch(this._failure(page, perPage)); this._requestPromises[page] = promise; return promise; } _success(page, perPage) { return res => { const resHndlr = new ResponseHandler(res, page, perPage, this._onSuccess); return resHndlr.success(); }; } _failure(page, perPage) { return res => { const resHndlr = new ResponseHandler(res, page, perPage, this._onFailure); return resHndlr.failure(); }; } } export default ResultList;
yola/pixabayjs
src/result-list.js
JavaScript
mit
1,582
// ==UserScript== // @name GitHub Label Manager // @namespace http://github.com/senritsu // @version 0.1 // @description Enables importing/exporting of repository labels // @author senritsu // @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js // @match http*://github.com/*/*/labels* // ==/UserScript== /* jshint ignore:start */ var inline_src = (<><![CDATA[ /* jshint ignore:end */ /* jshint esnext: true */ /* jshint asi:true */ const find = (selector, context) => (context || document).querySelector(selector) const findAll = (selector, context) => (context || document).querySelectorAll(selector) const newLabelButton = find('.labels-list .subnav button.js-details-target') const importButton = document.createElement('button') importButton.id = 'import-labels' importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button') importButton.textContent = 'Import ' const exportButton = document.createElement('button') importButton.id = 'export-labels' exportButton.classList.add('btn', 'btn-default', 'right') exportButton.textContent = 'Export' const author = find('span.author a').textContent const repository = find('.repohead-details-container strong[itemprop=name] a').textContent const exportLink = document.createElement('a') exportLink.style.display = 'none' exportLink.download = `${author}-${repository}-labels.json` exportButton.appendChild(exportLink) const newLabelForm = find('form.new-label') const importForm = document.createElement('form') importForm.id = 'label-import-toolbar' importForm.classList.add('form') importForm.style.padding = '10px' importForm.style.marginBottom = '15px' importForm.style.backgroundColor = '#fafafa' importForm.style.border = '1px solid #e5e5e5' importForm.style.display = 'none' const importInput = document.createElement('input') importInput.id = 'label-import-file' importInput.classList.add('form-control', 'right') importInput.type = 'file' importForm.appendChild(importInput) const clearAllDiv = document.createElement('div') clearAllDiv.classList.add('checkbox', 'right') clearAllDiv.style.marginTop = '9px' clearAllDiv.style.marginRight = '15px' importForm.appendChild(clearAllDiv) const clearAllLabel = document.createElement('label') clearAllDiv.appendChild(clearAllLabel) const clearAllCheckbox = document.createElement('input') clearAllCheckbox.id = 'clear-labels-before-import' clearAllCheckbox.type = 'checkbox' clearAllLabel.appendChild(clearAllCheckbox) clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first')) const clearfix = document.createElement('div') clearfix.classList.add('clearfix') importForm.appendChild(clearfix) console.log($) if(newLabelButton) { setup() } function setup() { const parent = newLabelButton.parentNode parent.insertBefore(importButton, newLabelButton) parent.insertBefore(exportButton, newLabelButton) newLabelForm.parentNode.insertBefore(importForm, newLabelForm) let open = false importButton.addEventListener('click', (event) => { open = !open importForm.style.display = open ? 'block' : 'none' }) importInput.addEventListener('change', (event) => { const reader = new FileReader() reader.onload = (event) => { const labels = JSON.parse(reader.result) if(clearAllCheckbox.checked) { deleteAllLabels() } for(const label of labels) { addLabel(label) } } reader.readAsText(importInput.files[0]) }) exportButton.addEventListener('click', exportLabels) } function rgb2hex(rgb) { const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/) const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2) return "#" + hex(r) + hex(g) + hex(b) } function exportLabels() { const labels = Array.from(findAll('.labels-list-item .label-link')) .map((label) => ({ name: find('.label-name', label).textContent, color: rgb2hex(label.style.backgroundColor) })) const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2)); exportLink.href = data exportLink.click() } function findLabel(label) { return Array.from(findAll('.labels-list-item')) .filter((x) => find('.label-name', x).textContent === label.name)[0] } function updateLabel(label, element) { find('.js-edit-label', element).click() find('.label-edit-name', element).value = label.name find('.color-editor-input', element).value = label.color find('.new-label-actions .btn-primary', element).click() } function addLabel(label) { find('input.label-edit-name', newLabelForm).value = label.name find('input#edit-label-color-new', newLabelForm).value = label.color find('button[type=submit]', newLabelForm).click() } function deleteLabel(element) { find('.labels-list-actions button.js-details-target', element).click() find('.label-delete button[type=submit]', element).click() } function deleteAllLabels() { const labels = Array.from(findAll('.labels-list-item')) for(const label of labels) { deleteLabel(label) } } /* jshint ignore:start */ ]]></>).toString(); var c = babel.transform(inline_src); eval(c.code); /* jshint ignore:end */
senritsu/github-label-manager
github-label-manager.js
JavaScript
mit
5,483
// moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), longDateFormat : { LT: 'HH:mm [Uhr]', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY LT', LLLL : 'dddd, D. MMMM YYYY LT' }, calendar : { sameDay: '[Heute um] LT', sameElse: 'L', nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', m : processRelativeTime, mm : '%d Minuten', h : processRelativeTime, hh : '%d Stunden', d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); }));
sasedev/acf-expert
src/Acf/ResBundle/Resources/public/js/moment/locale/de.js
JavaScript
mit
2,293
//!Defines two helper functions. /* * c * https://github.com/rumpl/c * * Copyright (c) 2012 Djordje Lukic * Licensed under the MIT license. */ "use strict"; const helpers = module.exports; const colors = require("colors/safe"); //Despite looking unused, is not unused. const fs = require("fs"); const SPACING = 1; //Change this value if you want more or less space between file names and comments. const PADDING = " "; //Change this value for what character should present your padding. /**Prints a coloured node name, padding, and it's assigned comment. * @param {string} nodeName The name of the node. * @param {string} nodeComment The comment for the node. * @param {number} maxLine The length of the longest node name in the specified directory. * @param {string} dir the relative filepath to a directory, the contents of which will be listed. */ function print(nodeName, nodeComment, maxLine, dir) { nodeComment = nodeComment || ""; nodeComment = nodeComment.replace(/(\r\n|\n|\r)/gm, " "); //Removes any new lines with blank spaces. let pad; //The amount of spacing & the colouring changes depending on whether 'file' is a file or a directory. if (fs.statSync(dir + "/" + nodeName).isFile()) { pad = PADDING.repeat(maxLine - nodeName.length + 1 + SPACING); console.log( // @ts-ignore - TS compiler throws an unnecessary error. colors.brightGreen(nodeName) + pad + colors.yellow(nodeComment) ); } else { pad = PADDING.repeat(maxLine - nodeName.length + SPACING); console.log( // @ts-ignore - TS compiler throws an unnecessary error. colors.brightCyan(nodeName + "/") + pad + colors.yellow(nodeComment) ); } } //TODO: refactor printFileComments & printOnlyComments into one function - they're almost identical for the most part /**Prints all of the files and sub-directories of a specified directory, as well as their assigned comments. * @param {Array<string>} files An array of all of the file names in the specified directory. * @param {Array<string>} comments An array of all of the comments in the specified directory. * @param {string} dir the relative filepath to a directory, the content of which will be listed. */ helpers.printFileComments = function (files, comments, dir) { //Gets the length of the longest filename in the array - iterators through files. const maxLine = maxLength(files); //Prints the current file and it's comment print(".", comments["."], maxLine, dir); print("..", comments[".."], maxLine, dir); //For each file run the print function. files.forEach(function (file) { print(file, comments[file], maxLine, dir); }); }; /**Prints only the files and sub-directories of a specified directory which have comments, as well as their assigned comments. * @param {Array<string>} filesNames An array of all of the file names in the specified directory. * @param {Array<string>} comments An array of all of the comments in the specified directory. * @param {string} relativePathToTarget the relative filepath to a directory, the content of which will be listed. */ helpers.printOnlyComments = function ( filesNames, comments, relativePathToTarget ) { //Gets the length of the longest filename in the array - iterators through files. const maxLine = maxLength(filesNames); //Prints the current file and it's comment if (comments["."]) print(".", comments["."], maxLine, relativePathToTarget); if (comments[".."]) print("..", comments[".."], maxLine, relativePathToTarget); //For each file with a comment, run the print function. filesNames.forEach(function (file) { if (comments[file]) print(file, comments[file], maxLine, relativePathToTarget); }); }; /**Calculates the longest file name from all the returned files. * @param {Array<string>} files an array of all the file names in the specified directory. * @returns {number} Returns the length of the longest name in the array. */ function maxLength(files) { return files.reduce((a, b) => { return b.length > a ? b.length : a; }, 0); }
rumpl/c
src/helpers.js
JavaScript
mit
4,175
/** * shuji (周氏) * https://github.com/paazmaya/shuji * * Reverse engineering JavaScript and CSS sources from sourcemaps * * Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi) * Licensed under the MIT license */ const fs = require('fs'), path = require('path'); const MATCH_MAP = /\.map$/iu; const MATCH_CODE = /\.(js|css)$/iu; const FIND_SOURCE_FILE = /\/\/#\s*sourceMappingURL=([.\w]+map)/iu; const FIND_SOURCE_BASE64 = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]*)base64,([\w]+=)/iu; const FIND_SOURCE_UENC = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]+),([;:,.\-\w%]+)/iu; /** * Find the sourceMap and return its contents. * In case the given filepath is already the sourceMap file, not much is done. * In case the given filepath is a JavaScript file, then the matching sourceMap * is being search for. * * @param {string} filepath * @param {object} options Options object. If not defined, verbose=false * @param {boolean} options.verbose Shall there be more output * * @returns {string|boolean} soureMap contents or false when not found */ const findMap = (filepath, options) => { options = options || { verbose: false }; const input = fs.readFileSync(filepath, 'utf8'); if (filepath.match(MATCH_MAP)) { return input; } else if (filepath.match(MATCH_CODE)) { if (input.match(FIND_SOURCE_BASE64)) { const sourceMappingMatch = FIND_SOURCE_BASE64.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 2) { if (options.verbose) { console.log(`Input file "${filepath}" contains Base64 of ${sourceMappingMatch[2].length} length`); } const buf = Buffer.from(sourceMappingMatch[2], 'base64'); return buf.toString('utf8'); } } else if (input.match(FIND_SOURCE_UENC)) { const sourceMappingMatch = FIND_SOURCE_UENC.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 2) { if (options.verbose) { console.log(`Input file "${filepath}" contains URL encoded of ${sourceMappingMatch[2].length} length`); } const buf = Buffer.from(sourceMappingMatch[2], 'ascii'); return buf.toString('utf8'); } } else if (input.match(FIND_SOURCE_FILE)) { const sourceMappingMatch = FIND_SOURCE_FILE.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 1) { if (options.verbose) { console.log(`Input file "${filepath}" points to "${sourceMappingMatch[1]}"`); } } // Since the sourceMappingURL is relative, try to find it from the same folder const mapFile = path.join(path.dirname(filepath), sourceMappingMatch[1]); try { fs.accessSync(mapFile); } catch (error) { console.error(`Could not access "${mapFile}"`); console.error(error.message); return false; } return fs.readFileSync(mapFile, 'utf8'); } } else if (options.verbose) { console.error(`Input file "${filepath}" was not a map nor a code file`); } return false; }; module.exports = findMap;
paazmaya/shuji
lib/find-map.js
JavaScript
mit
3,110
var Vue = require('vue') function fixFilters() { // 动态 filter Vue.filter('apply', function(value, name) { var filter = this.$options.filters[name] || Vue.options.filters[name] var args = [value].concat( [].slice.call(arguments, 2) ) if (filter) return filter.apply(this, args) return value }) } module.exports = fixFilters
thx/brix-vue
src/brix/vue/decorator/filters.js
JavaScript
mit
392
/******************************* Release Config *******************************/ var requireDotFile = require('require-dot-file'), config, npmPackage, version ; /******************************* Derived Values *******************************/ try { config = requireDotFile('pegaMultiselect.json'); } catch(error) {} try { npmPackage = require('../../../package.json'); } catch(error) { // generate fake package npmPackage = { name: 'Unknown', version: 'x.x' }; } // looks for version in config or package.json (whichever is available) version = (npmPackage && npmPackage.version !== undefined && npmPackage.name == 'Multiselect-Pega') ? npmPackage.version : config.version ; /******************************* Export *******************************/ module.exports = { title : 'pegaMultiselect UI', repository : 'https://github.com/ghoshArnab/multiselect', url : 'https://github.com/ghoshArnab/multiselect', banner: '' + ' /*' + '\n' + ' * # <%= title %> - <%= version %>' + '\n' + ' * <%= repository %>' + '\n' + ' * <%= url %>' + '\n' + ' *' + '\n' + ' * Copyright 2014 Contributors' + '\n' + ' * Released under the MIT license' + '\n' + ' * http://opensource.org/licenses/MIT' + '\n' + ' *' + '\n' + ' */' + '\n', version : version };
ghoshArnab/multiselect
tasks/config/project/release.js
JavaScript
mit
1,375
/** * Placeholder test - checks that an attribute or the content of an * element itself is not a placeholder (i.e. 'click here' for links). */ 'use strict'; quail.components.placeholder = function (quail, test, Case, options) { var resolve = function resolve(element, resolution) { test.add(Case({ element: element, status: resolution })); }; test.get('$scope').find(options.selector).each(function () { var text = ''; if ($(this).css('display') === 'none' && !$(this).is('title')) { resolve(this, 'inapplicable'); return; } if (typeof options.attribute !== 'undefined') { if ((typeof $(this).attr(options.attribute) === 'undefined' || options.attribute === 'tabindex' && $(this).attr(options.attribute) <= 0) && !options.content) { resolve(this, 'failed'); return; } else { if ($(this).attr(options.attribute) && $(this).attr(options.attribute) !== 'undefined') { text += $(this).attr(options.attribute); } } } if (typeof options.attribute === 'undefined' || !options.attribute || options.content) { text += $(this).text(); $(this).find('img[alt]').each(function () { text += $(this).attr('alt'); }); } if (typeof text === 'string' && text.length > 0) { text = quail.cleanString(text); var regex = /^([0-9]*)(k|kb|mb|k bytes|k byte)$/g; var regexResults = regex.exec(text.toLowerCase()); if (regexResults && regexResults[0].length) { resolve(this, 'failed'); } else if (options.empty && quail.isUnreadable(text)) { resolve(this, 'failed'); } else if (quail.strings.placeholders.indexOf(text) > -1) { resolve(this, 'failed'); } // It passes. else { resolve(this, 'passed'); } } else { if (options.empty && typeof text !== 'number') { resolve(this, 'failed'); } } }); };
legendvijay/quail
lib/js/components/placeholder.js
JavaScript
mit
1,957
Parse.initialize("AQxY526I5fcCPVkniY6ONnaBqU5qh1qDMqcOCORz", "y0cZ5QAGDU1SN1o1DtsQA8mHAKL3TKetrRvGwv3Y"); calculateSteps(); function calculateSteps(){ var count = 0; var Trips = Parse.Object.extend("Trip"); var query = new Parse.Query(Trips); query.greaterThan("StepsCompleted", 0); query.find({ success: function(results) { for (var i = 0; i < results.length; i++) { var object = results[i]; var stepsTaken = object.get("StepsCompleted"); count += stepsTaken; document.getElementById('stepsContainer').innerHTML = count.toLocaleString(); var dollarsSaved = (count / 2000) * 2.5; document.getElementById('moneyContainer').innerHTML = dollarsSaved.toFixed(2); var co2Emissions = count * 0.0128; document.getElementById('co2EmissionsContainer').innerHTML = co2Emissions.toFixed(2); } }, error: function(error) { console.log("Error: " + error.code + " " + error.message); } }); //var timer = setInterval(refresh, 3000); } var myVar = setInterval(function(){ refresh() }, 1000); function refresh(){ calculateSteps(); }
totoromano/WalkingCity_Miami
Web/js/wc.js
JavaScript
mit
1,111
'use strict' // Module dependencies. var request = require('request') var querystring = require('querystring') var userAgent = require('random-useragent') // Root for all endpoints. var _baseUrl = 'http://data.europa.eu/euodp/data/api/action' // Infrastructure prevents requests from original user agent of requestee. var headers = { 'User-Agent': userAgent.getRandom(), 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } /** * Calls the service and return the data in a promise, but with POST. * @function * @private * @name _sendRequest * @param {object} options - The request set of options. * @param {string} options.endpoint - Resource endpoint, without any slashes. * @param {object} options.query - The query parameters for the request. * @param {object} options.body - The body if POST, PUT * @param {string} options.method - The method to be used. * @returns {Promise} The response in a promise. */ function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) } /** * Get a list of the datasets in JSON. * @param {object} options - The request set of options. * @param {number} options.query.limit - Limit the number of items returned. * @param {number} options.query.offset - Acts like pagination when limited results. */ module.exports.getDatasets = (options) => { return _sendRequest({ method: 'GET', endpoint: 'package_list', query: (options !== undefined ? options.query : '') }) } /** * Return a list of the site's tags. * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {string} options.query.vocabulary_id - The id or name of a vocabulary. * If given only tags that belong to this vocabulary will be returned. * @param {boolean} options.query.all_fields - Whether to include all fields. */ module.exports.getTags = (options) => { return _sendRequest({ method: 'GET', endpoint: 'tag_list', query: (options !== undefined ? options.query : '') }) } /** * Return a list of the site's tags. * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {string} options.body.id - The id of the data set. * For example: {"id": "dgt-translation-memory"} */ module.exports.getDataset = (options) => { return _sendRequest({ method: 'POST', endpoint: 'package_show', query: (options !== undefined ? options.query : ''), body: (options !== undefined ? options.body : {}) }) } /** * Searches for packages satisfying a given search criteria. * This action accepts solr search query parameters. * @see http://wiki.apache.org/solr/CommonQueryParameters * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {object} options.body - The body parameter. * This accepts the solr tags to filter results. */ module.exports.datasetSearch = (options) => { return _sendRequest({ method: 'POST', endpoint: 'package_search', query: (options !== undefined ? options.query : ''), body: (options !== undefined ? options.body : {}) }) }
kalinchernev/odp
lib/odp.js
JavaScript
mit
3,560
import logger from "./logger"; const middlewares = { logger, }; export default middlewares;
wiebersk/pennies
src/middleware/index.js
JavaScript
mit
96
import React, {PropTypes} from 'react'; import Anchor from './Anchor'; import getIdFromTitle from '../util/getIdFromTitle'; const Title = ({children}) => ( <h3> <Anchor id={getIdFromTitle(children)}> {children} </Anchor> </h3> ); Title.propTypes = { children: PropTypes.string.isRequired, }; export default Title;
Neophy7e/react-bootstrap-typeahead
example/components/Title.react.js
JavaScript
mit
339
import Component from '@ember/component'; export default Component.extend({ domains: null });
thecoolestguy/frontend
app/components/school-competencies-list.js
JavaScript
mit
97
import React from 'react'; import { Wrapper } from '../components'; const Container = () => <Wrapper>Journal Container</Wrapper>; export default Container;
redcom/pinstery
client/src/containers/CustomizeContainer.js
JavaScript
mit
158
/** * * Secure Hash Algorithm (SHA1) * http://www.webtoolkit.info/ * **/ export function SHA1(msg) { function rotate_left(n, s) { var t4 = (n << s) | (n >>> (32 - s)); return t4; }; function lsb_hex(val) { var str = ""; var i; var vh; var vl; for (i = 0; i <= 6; i += 2) { vh = (val >>> (i * 4 + 4)) & 0x0f; vl = (val >>> (i * 4)) & 0x0f; str += vh.toString(16) + vl.toString(16); } return str; }; function cvt_hex(val) { var str = ""; var i; var v; for (i = 7; i >= 0; i--) { v = (val >>> (i * 4)) & 0x0f; str += v.toString(16); } return str; }; function Utf8Encode(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; var blockstart; var i, j; var W = new Array(80); var H0 = 0x67452301; var H1 = 0xEFCDAB89; var H2 = 0x98BADCFE; var H3 = 0x10325476; var H4 = 0xC3D2E1F0; var A, B, C, D, E; var temp; msg = Utf8Encode(msg); var msg_len = msg.length; var word_array = new Array(); for (i = 0; i < msg_len - 3; i += 4) { j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3); word_array.push(j); } switch (msg_len % 4) { case 0: i = 0x080000000; break; case 1: i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000; break; case 2: i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000; break; case 3: i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80; break; } word_array.push(i); while ((word_array.length % 16) != 14) word_array.push(0); word_array.push(msg_len >>> 29); word_array.push((msg_len << 3) & 0x0ffffffff); for (blockstart = 0; blockstart < word_array.length; blockstart += 16) { for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i]; for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); A = H0; B = H1; C = H2; D = H3; E = H4; for (i = 0; i <= 19; i++) { temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 20; i <= 39; i++) { temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 40; i <= 59; i++) { temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 60; i <= 79; i++) { temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } H0 = (H0 + A) & 0x0ffffffff; H1 = (H1 + B) & 0x0ffffffff; H2 = (H2 + C) & 0x0ffffffff; H3 = (H3 + D) & 0x0ffffffff; H4 = (H4 + E) & 0x0ffffffff; } var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); return temp.toLowerCase(); };
cyanolive/vue-console
src/app/js/util/sha1.js
JavaScript
mit
4,395
/*global NULL*/ 'use strict'; var sha1 = require('sha1'); module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.bulkInsert('Mentors', [{ nameFirst: 'Betty', nameLast: 'Coder', email: 'betty@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/bettyc', skillSet1:'mean', skillLevel1: 2, skillSet2:'mern', skillLevel2: 1, bio:'Hi, I\'m Betty and I\'ve been coding since I was three.', userWebLink:'http://mybettyweb.com', mentorRating:3, photoLink: 'public/images/fakefemale1.png' }, { nameFirst: 'Archi', nameLast: 'Thompson', email: 'archi@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/archi', skillSet1: 'mern', skillLevel1: 3, skillSet2:'mean', skillLevel2: 2, bio:'I love helping new coders discover web development. Let me teach you the MERN stack.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/archithompson.png' }, { nameFirst: 'Cecile', nameLast: 'Diakonova', email: 'cjd@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/diakonova', skillSet1: 'mern', skillLevel1: 3, bio:'Fully versed in both LAMP and MERN stacks.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/fakefemale2.png' }, { nameFirst: 'Taylor', nameLast: 'Jackson', email: 'taylor@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/djackson', skillSet1: 'mean', skillLevel1: 3, bio:'I have been a developer for ten years. I am passionate about learning new technologies.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/taylor.jpeg' } ], {}) }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('Person', null, {}); */ return queryInterface.bulkDelete('Mentors', null, {}); } };
ftarlaci/AJD
seeders/MentorsTableSeederinitial.js
JavaScript
mit
2,446
'use strict' const getNamespace = require('continuation-local-storage').getNamespace const Promise = require('bluebird') const WorkerStopError = require('error-cat/errors/worker-stop-error') const Ponos = require('../') /** * A simple worker that will publish a message to a queue. * @param {object} job Object describing the job. * @param {string} job.queue Queue on which the message will be published. * @returns {promise} Resolved when the message is put on the queue. */ function basicWorker (job) { return Promise.try(() => { const tid = getNamespace('ponos').get('tid') if (!job.message) { throw new WorkerStopError('message is required', { tid: tid }) } console.log(`hello world: ${job.message}. tid: ${tid}`) }) } const server = new Ponos.Server({ tasks: { 'basic-queue-worker': basicWorker }, events: { 'basic-event-worker': basicWorker } }) server.start() .then(() => { console.log('server started') }) .catch((err) => { console.error('server error:', err.stack || err.message || err) }) process.on('SIGINT', () => { server.stop() .then(() => { console.log('server stopped') }) .catch((err) => { console.error('server error:', err.stack || err.message || err) }) })
Runnable/ponos
examples/basic-worker.js
JavaScript
mit
1,244
import { baseUniDriverFactory } from '../../test/utils/unidriver'; export const boxDriverFactory = base => { return { ...baseUniDriverFactory(base), }; };
wix/wix-style-react
packages/wix-style-react/src/Box/Box.uni.driver.js
JavaScript
mit
164
export default class MethodMissingClass { constructor() { const handler = { get: this._handleMethodMissing }; return new Proxy(this, handler); } _handleMethodMissing(target, name, receiver) { const origMethod = target[name]; // If it exist, return original member or function. if (Reflect.has(target, name) || name === "methodMissing") { return Reflect.get(target, name, receiver); } // If the method doesn't exist, call methodMissing. return function(...args) { return Reflect.get(target, "methodMissing").call(receiver, name, ...args); }; } methodMissing(name, ...args) { console.log( `Method "${name}" does not exist. Please override methodMissing method to add functionality.` ); } }
ramadis/unmiss
src/MethodMissingClass.js
JavaScript
mit
776
var dns = require('native-dns'), util = require('util'); var question = dns.Question({ name: 'www.google.com', type: 'A', // could also be the numerical representation }); var start = new Date().getTime(); var req = dns.Request({ question: question, server: '8.8.8.8', /* // Optionally you can define an object with these properties, // only address is required server: { address: '8.8.8.8', port: 53, type: 'udp' }, */ timeout: 1000, /* Optional -- default 4000 (4 seconds) */ }); req.on('timeout', function () { console.log('Timeout in making request'); }); req.on('message', function (err, res) { if(err) console.error(err, res); else console.log(res); /* answer, authority, additional are all arrays with ResourceRecords */ res.answer.forEach(function (a) { /* promote goes from a generic ResourceRecord to A, AAAA, CNAME etc */ console.log(a.address); }); }); req.on('end', function () { /* Always fired at the end */ var delta = (new Date().getTime()) - start; console.log('Finished processing request: ' + delta.toString() + 'ms'); }); req.send();
timothyliu/hosts-dns
query.js
JavaScript
mit
1,109
Meteor.startup(() => { AutoForm.setDefaultTemplate('ionic'); });
Astrocoders/marketcontrol
client/lib/autoform.js
JavaScript
mit
67
var Client = require('node-rest-client').Client; //REST server properties var host_url = "http://sapient5-evaluation-dw.demandware.net"; var api_path = "/s/SiteGenesis/dw/shop/v17_2/"; var server_url = host_url+api_path; var client_id = "5a40714c-52c3-44df-a00d-9d3bb2dc8ea8"; var max_suggestion = 2; var getURL = function(method){ return server_url+method; }; var client = new Client(); client.registerMethod("products",getURL('products')+"/${id}?all_images=true&expand=images,prices&client_id="+client_id, "GET"); client.registerMethod("productimage",getURL('products')+"/${id}/images?all_images=true&client_id="+client_id, "GET"); client.registerMethod("searchsuggestion",getURL('search_suggestion')+"?q=${arg1}&count=${arg2}&client_id="+client_id, "GET"); client.registerMethod("getCategories",getURL('categories')+"/${id}?level=${2}&client_id="+client_id, "GET"); client.registerMethod("searchproducts",getURL('product_search')+"?q=${arg1}&refine1=cgid=${arg2}&count=100&expand=images,prices&client_id="+client_id, "GET"); module.exports = { getProduct : function(product_id, callbackmethod) { var args = { path: { "id": product_id } // path substitution var }; client.methods.products(args,callbackmethod); }, getSuggestion : function(query,callbackmethod) { var args = { path: { "arg1" : query, "arg2" : max_suggestion } }; client.methods.searchsuggestion(args, callbackmethod); //http://hostname:port/dw/shop/v17_2/search_suggestion?q={String}&count={Integer}&currency={String}&locale={String} }, getProductImages : function(product_id,callbackmethod) { var args = { path: { "id": product_id } // path substitution var }; client.methods.productimage(args,callbackmethod); //http://hostname:port/dw/shop/v17_2/search_suggestion?q={String}&count={Integer}&currency={String}&locale={String} }, searchProducts : function(callbackmethod,query,refine) { var args = { path: { "arg1" : query, "arg2" : ((refine) ? refine : 'root')} }; console.log(JSON.stringify(args)); client.methods.searchproducts(args, callbackmethod); }, getCategories : function(callbackmethod,cgid) { var args = { path: { "id" : ((cgid) ? cgid : 'root'), "arg1" : 1} }; client.methods.getCategories(args, callbackmethod); } //http://sapient3-evaluation-dw.demandware.net/s/SiteGenesis/dw/shop/v17_2/product_search?q=shirt&client_id=5a40714c-52c3-44df-a00d-9d3bb2dc8ea8&expand=images,prices&refine_1=cgid=mens}, };
rkthakur/CoversationalCommerceBot
commerce/OCAPI.js
JavaScript
mit
2,455
(function() { 'use strict'; angular .module('app') .constant('FIREBASE_BASE_URL', 'https://word-game-d1e51.firebaseio.com'); })();
taritamas89/word-game
src/app/config/constants.js
JavaScript
mit
156
module.exports = function (grunt) { var idVideo = 0; var examples = require('./node_modules/grunt-json-mapreduce/examples'); var _ = require('underscore'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), cfg: { paths: { build: 'dist', bower: 'bower_components', npm: 'node_modules' }, files: { js: { vendor: [ '<%= cfg.paths.npm %>/underscore/underscore.js', '<%= cfg.paths.bower %>/angular/angular.js', '<%= cfg.paths.bower %>/angular-mocks/angular-mocks.js', '<%= cfg.paths.bower %>/angular-route/angular-route.js', '<%= cfg.paths.bower %>/angular-slugify/angular-slugify.js', '<%= cfg.paths.bower %>/angular-youtube-mb/src/angular-youtube-embed.js', // '<%= cfg.paths.bower %>/angular-youtube-embed/dist/angular-youtube-embed.js', // '<%= cfg.paths.bower %>/angular-youtube/angular-youtube-player-api.js', '<%= cfg.paths.bower %>/jquery/dist/jquery.js', '<%= cfg.paths.bower %>/bootstrap/dist/js/bootstrap.js' ], mixins: [ 'app/js/mixins/**/*.js' ], app: [ 'app/js/app.js', 'app/js/**/*.js', '!app/js/mock/*' ] }, css: { vendor: [ '<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap.css', '<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap-theme.css' ], app: [ 'app/assets/css/**/*.css' ] } } }, bump: { options: { files: ['package.json', 'bower.json'], pushTo: 'origin', commitFiles: ['-a'] } }, clean: { build: ['<%= cfg.paths.build %>'] }, copy: { static: { files: [{ '<%= cfg.paths.build %>/index.html': 'app/index.html', '<%= cfg.paths.build %>/favicon.png': 'app/assets/favicon.png' }, { expand: true, cwd: 'app/templates/', src: ["*.*", "**/*.*"], dest: '<%= cfg.paths.build %>/templates' }, { expand: true, cwd: 'app/assets/font/', src: ["*.*", "**/*.*"], dest: '<%= cfg.paths.build %>/font' } ] } }, cssmin: { vendor: { files: { '<%= cfg.paths.build %>/css/vendor.css': '<%= cfg.files.css.vendor %>' } }, app: { files: { '<%= cfg.paths.build %>/css/app.css': '<%= cfg.files.css.app %>' } } }, uglify: { options: { mangle: false }, vendor: { files: { '<%= cfg.paths.build %>/js/vendor.js': '<%= cfg.files.js.vendor %>' } }, mixins: { files: { '<%= cfg.paths.build %>/js/mixins.js': '<%= cfg.files.js.mixins %>' } }, app: { files: { '<%= cfg.paths.build %>/js/app.js': '<%= cfg.files.js.app %>' } } }, json_mapreduce: { events: { src: ['data/events/**/*.json'], dest: '<%= cfg.paths.build %>/data/events.json', options: { map: examples.map.pass, reduce: examples.reduce.concat } }, videos: { src: ['data/videos/**/*.json'], dest: '<%= cfg.paths.build %>/data/videos.json', options: { map: function (currentValue, index, array) { return currentValue.map(function (element) { element.id = ++idVideo; return element; }); }, reduce: examples.reduce.concat } }, speakers: { src: ['data/speakers/**/*.json'], dest: '<%= cfg.paths.build %>/data/speakers.json', options: { map: examples.map.pass, reduce: examples.reduce.concat } }, tags: { src: ['data/videos/**/*.json'], dest: '<%= cfg.paths.build %>/data/tags.json', options: { map: function (currentValue, index, array) { var tagLists = currentValue.map(function (element) { return element.tags; }); return _.union.apply(this, tagLists); }, reduce: function(previousValue, currentValue, index, array) { if (typeof previousValue === "undefined") { return currentValue; } else { return _.union(previousValue, currentValue); } } } } }, browserify: { app: { src: ['./app/js/mock/index.js'], dest: '<%= cfg.paths.build %>/js/mock.js' } }, 'http-server': { dist: { root: 'dist', host: '0.0.0.0', port: '9000' } }, jsonlint: { data: { src: ['data/**/*.json'] } }, jshint: { options: { jshintrc: true }, app: { src: ['app/js/**/*.js'] } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('test', [ 'jshint', 'jsonlint' ]); grunt.registerTask('build', [ 'clean', 'copy', 'cssmin', 'uglify' ]); grunt.registerTask('mock', [ 'json_mapreduce', 'browserify' ]); grunt.registerTask('run', [ 'http-server' ]); grunt.registerTask('default', [ 'test', 'build', 'mock', ]); };
ducin/watchjs.org
Gruntfile.js
JavaScript
mit
7,023
/** * Import Request event * @module tracker/events/import-request */ const NError = require('nerror'); const Base = require('./base'); /** * Import Request event class */ class ImportRequest extends Base { /** * Create service * @param {App} app The application * @param {object} config Configuration * @param {Logger} logger Logger service * @param {Registry} registry Registry service * @param {UserRepository} userRepo User repository * @param {DaemonRepository} daemonRepo Daemon repository * @param {PathRepository} pathRepo Path repository * @param {ConnectionRepository} connectionRepo Connection repository */ constructor(app, config, logger, registry, userRepo, daemonRepo, pathRepo, connectionRepo) { super(app); this._config = config; this._logger = logger; this._registry = registry; this._userRepo = userRepo; this._daemonRepo = daemonRepo; this._pathRepo = pathRepo; this._connectionRepo = connectionRepo; } /** * Service name is 'tracker.events.importRequest' * @type {string} */ static get provides() { return 'tracker.events.importRequest'; } /** * Dependencies as constructor arguments * @type {string[]} */ static get requires() { return [ 'app', 'config', 'logger', 'registry', 'repositories.user', 'repositories.daemon', 'repositories.path', 'repositories.connection' ]; } /** * Event name * @type {string} */ get name() { return 'import_request'; } /** * Event handler * @param {string} id ID of the client * @param {object} message The message */ async handle(id, message) { let client = this._registry.clients.get(id); if (!client) return; this._logger.debug('import-request', `Got IMPORT REQUEST from ${id}`); try { let daemons = []; if (client.daemonId) daemons = await this._daemonRepo.find(client.daemonId); let daemon = daemons.length && daemons[0]; if (!daemon) { let response = this.tracker.ImportResponse.create({ response: this.tracker.ImportResponse.Result.REJECTED, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending REJECTED IMPORT RESPONSE to ${id}`); return this.tracker.send(id, data); } let [paths, connections] = await Promise.all([ this._pathRepo.findByToken(message.importRequest.token), this._connectionRepo.findByToken(message.importRequest.token) ]); let path = paths.length && paths[0]; let connection = connections.length && connections[0]; let userId, actingAs; if (path) { actingAs = 'client'; userId = path.userId; } else if (connection) { actingAs = 'server'; userId = connection.userId; } else { let response = this.tracker.ImportResponse.create({ response: this.tracker.ImportResponse.Result.REJECTED, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending REJECTED IMPORT RESPONSE to ${id}`); return this.tracker.send(id, data); } let loadConnections = async path => { let result = []; let connections = await this._connectionRepo.findByPath(path); let connection = connections.length && connections[0]; if (connection) result.push(connection); let paths = await this._pathRepo.findByParent(path); let promises = []; for (let subPath of paths) promises.push(loadConnections(subPath)); let loaded = await Promise.all(promises); for (let subConnections of loaded) result = result.concat(subConnections); return result; }; if (actingAs === 'server') connections = [connection]; else connections = await loadConnections(path); let serverConnections = []; let clientConnections = []; let value; let users = await this._userRepo.find(userId); let user = users.length && users[0]; if (!user) { value = this.tracker.ImportResponse.Result.REJECTED; } else { value = this.tracker.ImportResponse.Result.ACCEPTED; if (actingAs === 'server') { let connection = connections.length && connections[0]; if (connection) { let paths = await this._pathRepo.find(connection.pathId); let path = paths.length && paths[0]; if (path) { let clients = []; for (let clientDaemon of await this._daemonRepo.findByConnection(connection)) { if (clientDaemon.actingAs !== 'client') continue; let clientUsers = await this._userRepo.find(clientDaemon.userId); let clientUser = clientUsers.length && clientUsers[0]; if (clientUser) clients.push(clientUser.email + '?' + clientDaemon.name); } let {address, port} = this._registry.addressOverride( connection.connectAddress, connection.connectPort, connection.addressOverride, connection.portOverride ); serverConnections.push(this.tracker.ServerConnection.create({ name: user.email + path.path, connectAddress: address, connectPort: port, encrypted: connection.encrypted, fixed: connection.fixed, clients: clients, })); } } } else { for (let connection of connections) { let paths = await this._pathRepo.find(connection.pathId); let path = paths.length && paths[0]; if (path) { let serverDaemons = await this._daemonRepo.findServerByConnection(connection); let serverDaemon = serverDaemons.length && serverDaemons[0]; let serverUsers = []; if (serverDaemon) serverUsers = await this._userRepo.find(serverDaemon.userId); let serverUser = serverUsers.length && serverUsers[0]; let {address, port} = this._registry.addressOverride( connection.listenAddress, connection.listenPort, connection.addressOverride, connection.portOverride ); clientConnections.push(this.tracker.ClientConnection.create({ name: user.email + path.path, listenAddress: address, listenPort: port, encrypted: connection.encrypted, fixed: connection.fixed, server: (serverDaemon && serverUser) ? serverUser.email + '?' + serverDaemon.name : '', })); } } } } let list = this.tracker.ConnectionsList.create({ serverConnections: serverConnections, clientConnections: clientConnections, }); let response = this.tracker.ImportResponse.create({ response: value, updates: list, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending RESULTING IMPORT RESPONSE to ${id}`); this.tracker.send(id, data); } catch (error) { this._logger.error(new NError(error, 'ImportRequest.handle()')); } } } module.exports = ImportRequest;
breedhub/bhit-node
modules/tracker/src/events/import-request.js
JavaScript
mit
10,123
/* SPDX-License-Identifier: MIT */ /** * Handles interaction with a GHData server. * @constructor */ function GHDataAPIClient (apiUrl, owner, repo, apiVersion) { this.owner = owner || ''; this.repo = repo || ''; this.url = apiUrl; this.apiversion = apiVersion || 'unstable'; } /* Request Handling * Create a friendly wrapper around XMLHttpRequest --------------------------------------------------------------*/ /** * Wraps XMLHttpRequest with many goodies. Credit to SomeKittens on StackOverflow. * @param {Object} opts - Stores the url (opts.url), method (opts.method), headers (opts.headers) and query parameters (opt.params). All optional. * @returns {Promise} Resolves with XMLHttpResponse.response */ GHDataAPIClient.prototype.request = function (opts) { // Use GHData by default opts.endpoint = opts.endpoint || ''; opts.url = opts.url || (this.url + this.apiversion + '/' + this.owner + '/' + this.repo + '/' + opts.endpoint); opts.method = opts.method || 'GET'; return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(opts.method, opts.url); xhr.onload = function () { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject({ status: this.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: this.status, statusText: xhr.statusText }); }; if (opts.headers) { Object.keys(opts.headers).forEach(function (key) { xhr.setRequestHeader(key, opts.headers[key]); }); } var params = opts.params; // We'll need to stringify if we've been given an object // If we have a string, this is skipped. if (params && typeof params === 'object') { params = Object.keys(params).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); } xhr.send(params); }); }; /** * Wraps the GET requests with the correct options for most GHData calls * @param {String} endpoint - Endpoint to send the request to * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with Object created from the JSON returned by GHData */ GHDataAPIClient.prototype.get = function (endpoint, params) { var self = this; return new Promise(function (resolve, request) { self.request({ method: 'GET', endpoint: endpoint, params: params }).then(function (response) { // Lets make this thing JSON var result = JSON.parse(response); resolve(result); }); }); }; /* Endpoints * Wrap all the API endpoints to make it as simple as possible --------------------------------------------------------------*/ /** * Commits timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.commitsByWeek = function (params) { return this.get('timeseries/commits', params); }; /** * Forks timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with forks timeeseries object */ GHDataAPIClient.prototype.forksByWeek = function (params) { return this.get('timeseries/forks', params); }; /** * Stargazers timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.stargazersByWeek = function (params) { return this.get('timeseries/stargazers', params); }; /** * Issues timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.issuesByWeek = function (params) { return this.get('timeseries/issues', params); }; /** * Pull Requests timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.pullRequestsByWeek = function (params) { return this.get('timeseries/pulls', params); }; /** * Pull Requests timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.contributionsByWeek = function (params) { return this.get('timeseries/contributions', params); }; /** * How quickly after issues are made they are commented on * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.issuesResponseTime = function (params) { return this.get('timeseries/issues/response_time', params); }; /** * Contributions timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.contributors = function (params) { return this.get('timeseries/contributors', params); }; /** * Locations of the committers * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.committerLocations = function (params) { return this.get('commits/locations', params); };
kalepeterson/ghdata
frontend/scripts/ghdata-api-client.js
JavaScript
mit
5,402
// LICENSE : MIT "use strict"; import React from "react" global.React = require('react'); var md2react = require("md2react"); var todoRegexp = /^-\s*\[[x ]\]\s*/; function isTODO(line) { return todoRegexp.test(line); } function flatten([first, ...rest]) { if (first === undefined) { return []; } else if (!Array.isArray(first)) { return [first, ...flatten(rest)]; } else { return [...flatten(first), ...flatten(rest)]; } } export default class RepositoryIssueList extends React.Component { static get propTypes() { return { issues: React.PropTypes.array } } //componentDidUpdate() { // this.markdownContainer = React.findDOMNode(this.refs.markdown); // if(!this.markdownContainer) { // return; // } // var list = this.markdownContainer.querySelectorAll("li.checked, li.unchecked"); // console.log(list); //} render() { if (this.props.issue == null) { return <div className="RepositoryIssueList"> <div className="markdown" ref="markdown"> </div> </div>; } var ownerSubTasks = this.props.issue.body.split("\n").filter(isTODO); var commentSubTasks = this.props.comments.map(function (comment) { return comment.body.split("\n").filter(isTODO); }); var subTasks = ownerSubTasks.concat(...commentSubTasks); var subTasksList = subTasks.join("\n"); return <div className="RepositoryIssueList"> <div className="markdown" ref="markdown"> {md2react(subTasksList, { tasklist: true })} </div> </div> } }
azu/github-issue-teev
lib/component/RepositoryIssueList.js
JavaScript
mit
1,759
var path = require('path'); module.exports = { // entry: ['babel-polyfill', './src/main.js'], entry: './src/main.js', target: 'node', output: { filename: 'main.js', path: path.resolve(__dirname, 'build') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ ['env', { targets: { node: '6.6.0' } }] ] } } } ] }, externals: { 'lodash' : 'commonjs lodash' } };
chall8908/screeps-scripts
webpack.config.js
JavaScript
mit
594
/* * oskari-compile */ module.exports = function(grunt) { grunt.registerMultiTask('compile', 'Compile appsetup js', function() { var starttime = (new Date()).getTime(); var options = this.data.options; // Run some sync stuff. grunt.log.writeln('Compiling...'); // Catch if required fields are not provided. if ( !options.appSetupFile ) { grunt.fail.warn('No path provided for Compile to scan.'); } if ( !options.dest ) { grunt.fail.warn('No destination path provided for Compile to use.'); } var fs = require('fs'), UglifyJS = require('uglify-js'), parser = require('../parser.js'), processedAppSetup = parser.getComponents(options.appSetupFile); grunt.log.writeln('Parsed appSetup:' + options.appSetupFile); // internal minify i18n files function this.minifyLocalization = function(langfiles, path) { for (var id in langfiles) { //console.log('Minifying loc:' + id + '/' + langfiles[id]); this.minifyJS(langfiles[id], path + 'oskari_lang_' + id + '.js', options.concat); } } // internal minify JS function this.minifyJS = function(files, outputFile, concat) { var okFiles = [], fileMap = {}, result = null; for (var i = 0; i < files.length; ++i) { if (!fs.existsSync(files[i])) { var msg = 'Couldnt locate ' + files[i]; throw msg; } // do not put duplicates on compiled code if(!fileMap[files[i]]) { fileMap[files[i]] = true; okFiles.push(files[i]); } else { grunt.log.writeln('File already added:' + files[i]); } } // minify or concatenate the files if (!concat) { result = UglifyJS.minify(okFiles, { //outSourceMap : "out.js.map", warnings : true, compress : true }); } else { // emulate the result uglify creates, but only concatenating result = {"code" : ""}; for (var j = 0, jlen = okFiles.length; j < jlen; j +=1) { result.code += fs.readFileSync(okFiles[j], 'utf8'); } } // write result to disk fs.writeFileSync(outputFile, result.code, 'utf8'); } // validate parsed appsetup var compiledDir = options.dest; if (!fs.existsSync(compiledDir)) { fs.mkdirSync(compiledDir); } var files = []; for (var j = 0; j < processedAppSetup.length; ++j) { var array = parser.getFilesForComponent(processedAppSetup[j], 'javascript'); files = files.concat(array); } this.minifyJS(files, compiledDir + 'oskari.min.js', options.concat); var langfiles = {}; for (var j = 0; j < processedAppSetup.length; ++j) { var deps = processedAppSetup[j].dependencies; for (var i = 0; i < deps.length; ++i) { for (var lang in deps[i].locales) { if (!langfiles[lang]) { langfiles[lang] = []; } langfiles[lang] = langfiles[lang].concat(deps[i].locales[lang]); } } } this.minifyLocalization(langfiles, compiledDir); var unknownfiles = []; for(var j = 0; j < processedAppSetup.length; ++j) { unknownfiles = unknownfiles.concat(parser.getFilesForComponent(processedAppSetup[j], 'unknown')); } if(unknownfiles.length != 0) { console.log('Appsetup referenced types of files that couldn\'t be handled: ' + unknownfiles); } var endtime = (new Date()).getTime(); grunt.log.writeln('Compile completed in ' + ((endtime - starttime) / 1000) + ' seconds'); }); };
uhef/Oskari-Routing-frontend
tools/tasks/compile.js
JavaScript
mit
4,181
/** * @param {string} s * @param {string} t * @return {boolean} */ var isIsomorphic = function(s, t) { var s = s.split(''); var t = t.split(''); if (new Set(s).size !== new Set(t).size) return false; var zip = new Set(); s.forEach(function (item, i) { zip.add(s[i] + ' ' + t[i]) }); return new Set(zip).size === new Set(s).size; }; var eq = require('assert').equal; eq(isIsomorphic('egg', 'add'), true); eq(isIsomorphic('egg', 'ddd'), false);
zhiyelee/leetcode
js/isomorphicStrings/isomorphic_strings.js
JavaScript
mit
470
'use strict'; angular .module('reflect.calendar') .filter('calendarTruncateEventTitle', function() { return function(string, length, boxHeight) { if (!string) { return ''; } //Only truncate if if actually needs truncating if (string.length >= length && string.length / 20 > boxHeight / 30) { return string.substr(0, length) + '...'; } else { return string; } }; });
el-besto/ts-angular-bootstrap-calendar
src/filters/calendarTruncateEventTitle.js
JavaScript
mit
444
'use strict'; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Any commits to this file should be reviewed with security in mind. * * Changes to this file can potentially create security vulnerabilities. * * An approval from 2 Core members with history of modifying * * this file is required. * * * * Does the change somehow allow for arbitrary javascript to be executed? * * Or allows for someone to change the prototype of built-in objects? * * Or gives undesired access to variables likes document or window? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var $sanitizeMinErr = angular.$$minErr('$sanitize'); var bind; var extend; var forEach; var isDefined; var lowercase; var noop; var htmlParser; var htmlSanitizeWriter; /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * Sanitizes an html string by stripping all potentially dangerous tokens. * * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string. * * The whitelist for URL sanitization of attribute values is configured using the functions * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider * `$compileProvider`}. * * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getAttribute('innerHTML')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ /** * @ngdoc provider * @name $sanitizeProvider * @this * * @description * Creates and configures {@link $sanitize} instance. */ function $SanitizeProvider() { var svgEnabled = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { if (svgEnabled) { extend(validElements, svgElements); } return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; /** * @ngdoc method * @name $sanitizeProvider#enableSvg * @kind function * * @description * Enables a subset of svg to be supported by the sanitizer. * * <div class="alert alert-warning"> * <p>By enabling this setting without taking other precautions, you might expose your * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned * outside of the containing element and be rendered over other elements on the page (e.g. a login * link). Such behavior can then result in phishing incidents.</p> * * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg * tags within the sanitized content:</p> * * <br> * * <pre><code> * .rootOfTheIncludedContent svg { * overflow: hidden !important; * } * </code></pre> * </div> * * @param {boolean=} flag Enable or disable SVG support in the sanitizer. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called * without an argument or self for chaining otherwise. */ this.enableSvg = function(enableSvg) { if (isDefined(enableSvg)) { svgEnabled = enableSvg; return this; } else { return svgEnabled; } }; ////////////////////////////////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////////////////////////////////// bind = angular.bind; extend = angular.extend; forEach = angular.forEach; isDefined = angular.isDefined; lowercase = angular.lowercase; noop = angular.noop; htmlParser = htmlParserImpl; htmlSanitizeWriter = htmlSanitizeWriterImpl; // Regular Expressions for parsing tags and attributes var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = toMap('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), optionalEndTagInlineElements = toMap('rp,rt'), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. // They can potentially allow for arbitrary javascript to be executed. See #11290 var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); // Blocked Elements (will be stripped) var blockedElements = toMap('script,style'); var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href'); var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); var validAttrs = extend({}, uriAttrs, svgAttrs, htmlAttrs); function toMap(str, lowercaseKeys) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) { obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; } return obj; } var inertBodyElement; (function(window) { var doc; if (window.document && window.document.implementation) { doc = window.document.implementation.createHTMLDocument('inert'); } else { throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); } var docElement = doc.documentElement || doc.getDocumentElement(); var bodyElements = docElement.getElementsByTagName('body'); // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one if (bodyElements.length === 1) { inertBodyElement = bodyElements[0]; } else { var html = doc.createElement('html'); inertBodyElement = doc.createElement('body'); html.appendChild(inertBodyElement); doc.appendChild(html); } })(window); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParserImpl(html, handler) { if (html === null || html === undefined) { html = ''; } else if (typeof html !== 'string') { html = '' + html; } inertBodyElement.innerHTML = html; //mXSS protection var mXSSAttempts = 5; do { if (mXSSAttempts === 0) { throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); } mXSSAttempts--; // strip custom-namespaced attributes on IE<=11 if (window.document.documentMode) { stripCustomNsAttrs(inertBodyElement); } html = inertBodyElement.innerHTML; //trigger mXSS inertBodyElement.innerHTML = html; } while (html !== inertBodyElement.innerHTML); var node = inertBodyElement.firstChild; while (node) { switch (node.nodeType) { case 1: // ELEMENT_NODE handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); break; case 3: // TEXT NODE handler.chars(node.textContent); break; } var nextNode; if (!(nextNode = node.firstChild)) { if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } nextNode = node.nextSibling; if (!nextNode) { while (nextNode == null) { node = node.parentNode; if (node === inertBodyElement) break; nextNode = node.nextSibling; if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } } } } node = nextNode; } while ((node = inertBodyElement.firstChild)) { inertBodyElement.removeChild(node); } } function attrToMap(attrs) { var map = {}; for (var i = 0, ii = attrs.length; i < ii; i++) { var attr = attrs[i]; map[attr.name] = attr.value; } return map; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.join('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriterImpl(buf, uriValidator) { var ignoreCurrentElement = false; var out = bind(buf, buf.push); return { start: function(tag, attrs) { tag = lowercase(tag); if (!ignoreCurrentElement && blockedElements[tag]) { ignoreCurrentElement = tag; } if (!ignoreCurrentElement && validElements[tag] === true) { out('<'); out(tag); forEach(attrs, function(value, key) { var lkey = lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out('>'); } }, end: function(tag) { tag = lowercase(tag); if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { out('</'); out(tag); out('>'); } // eslint-disable-next-line eqeqeq if (tag == ignoreCurrentElement) { ignoreCurrentElement = false; } }, chars: function(chars) { if (!ignoreCurrentElement) { out(encodeEntities(chars)); } } }; } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want * to allow any of these custom attributes. This method strips them all. * * @param node Root element to process */ function stripCustomNsAttrs(node) { if (node.nodeType === window.Node.ELEMENT_NODE) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attrNode = attrs[i]; var attrName = attrNode.name.toLowerCase(); if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { node.removeAttributeNode(attrNode); i--; l--; } } } var nextNode = node.firstChild; if (nextNode) { stripCustomNsAttrs(nextNode); } nextNode = node.nextSibling; if (nextNode) { stripCustomNsAttrs(nextNode); } } } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, noop); writer.chars(chars); return buf.join(''); } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); // angular sanitize end angular.module("events", ['ui.router', 'ngSanitize']) .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('events', { url : '/', controller: function($state) { $state.go('detail',{domain: "code it", event: 0}, {location: 'replace'}); } }) .state('detail', { url : '/{domain}/{event}', templateUrl : 'partials/event-list.html', controller : function($scope, EventService, $stateParams, params, $sce, $state){ $scope.$sce = $sce; $scope.images = [ "cse", "it", "ece", "eee", "mech", "chem", "bme", "civil", "nontech" ] $scope.domains = {}; EventService.getAllDomains().then(function(domains){ $scope.domains = domains; }) $scope.currDomain = $stateParams.domain; $scope.currEvent = $stateParams.event; // console.log($stateParams.domain) // console.log(params) $scope.hideUntilLoad = true; $scope.domain = []; EventService.getEventList($scope.currDomain).then(function(domain){ if(domain == void(0)) $state.go('detail',{domain: "code it", event: 0}, {location: 'replace'}); var domainInt = parseInt($scope.currEvent); console.log(domainInt) if((domain.length - 1 < domainInt || domainInt < 0) || isNaN(domainInt) ){ // console.log(domain) $state.go('detail',{domain: $scope.currDomain, event: 0}, {location: 'replace'}); } $scope.domain = domain; $scope.hideUntilLoad = false; }) // console.log($scope.domain) }, resolve:{ params: ['$stateParams', function($stateParams){ // console.log([$stateParams.domain, $stateParams.event]) return [$stateParams.domain, $stateParams.event]; }] } }) }) .directive('backImg', function(){ return function(scope, element, attrs){ var url = attrs.backImg; element.css({ 'background-image': 'url(' + url +')', 'background-size' : 'cover' }); }; }) // .controller("DomainController", ['$scope', 'EventService', '$stateParams', function($scope, EventService, $stateParams){ // $scope.domains = {}; // EventService.getAllDomains().then(function(domains){ // $scope.domains = domains; // }) // // console.log($stateParams) // $scope.domain = []; // EventService.getEventList("bme").then(function(domain){ // $scope.domain = domain; // }) // // console.log($scope.domain) // }]) .service('EventService', function($http) { var service = { getAllDomains: function() { return $http.get('data.json', { cache: true }).then(function(resp) { // console.log(resp.data) return resp.data; }); }, getEventList: function(id) { return service.getAllDomains().then(function (domains) { // console.log(domains) // console.log(domains[id]) return domains[id]; }); } } return service; })
ssn-invente/invente-website
events/index.js
JavaScript
mit
23,973
ArrangeSwapCommand = new Class({ Implements: ICommand, beginDepths: [], initialize: function(){}, // Move the target to the new depth. execute: function() { this.canvas.swapChildren(this.beginDepths[0], this.beginDepths[1]); }, // Place the target object back in its original depth. revert: function(target) { this.canvas.swapChildren(this.beginDepths[1], this.beginDepths[0]); }, setBeginDepths: function(a) { this.beginDepths = a; }, toString: function() { return '{name: ArrangeSwap, ptA: ' + this.beginDepths[0].toString() + ', ptB: ' + this.beginDepths[1].toString() + '}'; } });
somethingkindawierd/draw.txt
js/classes/commands/ArrangeSwapCommand.js
JavaScript
mit
645
define(['app', 'directives/search/search'], function() { 'use strict'; });
scbd/chm.cbd.int
app/views/database/index.js
JavaScript
mit
75
var visualization = function() { var vizData; var vizApp = this; var padding = 40; // padding between groups var max_group_width = 600; // TODO: this assumes fixed note width and height, potentially handle for importance of notes var max_note_width = 240; var max_note_height = 110; var container_width; var max_groups_in_row; var arrayOfNotes = []; var folderNameH6, vizContainer, colorButtons, layoutButtons, saveLayoutButton, notes; var init = function() { folderNameH6 = $('.js-group-name'); vizContainer = $('.js-vizContainer'); colorButtons = $('.coloring li'); layoutButtons = $('.positioning .layout'); saveLayoutButton = $('li[data-action="save_custom"]').hide() } var setData = function(data) { vizData = data; startViz(); } var startViz = function() { console.log(vizData); vizContainer.fadeIn(); container_width = vizContainer.width(); max_groups_in_row = parseInt(container_width / max_group_width) + 1; vizData.folderSpecificAnnotations.map(createNote); setGroupPositions(arrayOfNotes, 'category', true); saveCustomLayout(); notesEls = vizContainer.find('.ui-draggable'); notesEls.hover(function(){ var maxZ = 0; notesEls.each(function() { var index_current = parseInt($(this).css("zIndex"), 10); if(index_current > maxZ) { maxZ = index_current; } }); $(this).css('zIndex', maxZ+1); }) colorButtons.on('click', function() { colorButtons.removeClass('active'); $(this).addClass('active'); var cat = $(this).attr('data-color') console.log(cat); colorNotes(cat); }); layoutButtons.on('click', function() { layoutButtons.removeClass('active'); $(this).addClass('active'); var cat = $(this).attr('data-layout') console.log(cat); rearrangeNotes(cat); }); saveLayoutButton.on('click', saveCustomLayout); } var setGroupPositions = function(notes, type, start) { // create a map representing a group: // category:{'notes': [notes], 'height': height of a group based on num notes in group, 'posy': y position} var groups = {}; var category; notes.map(function(note) { if (type == 'category') { // group by topic category = note.getCategory(); } else { // group by paper category = note.getPaperId(); } if (category in groups) { groups[category]['notes'].push(note); } else { groups[category] = {'notes':[note], 'height': 0, 'posy': 0}; } }); // create grid-positioning for groups // determine the height of each by the number of notes in the group // height will be used to offset groups underneath other groups // width is limited by max_group_width, which currently only fits 2 notes (2 notes in a row within a group) for (var category in groups) { var group_notes = groups[category]['notes']; groups[category]['height'] = Math.ceil(group_notes.length/2) * (max_note_height + padding); } // set height for groups in rows in the viz beyond first row var group_keys = Object.keys(groups); for (var i = max_groups_in_row; i < group_keys.length; i++) { var key = group_keys[i]; // get key of the group directly above this group in the grid var group_above_key = group_keys[i-max_groups_in_row]; groups[key]['posy'] += groups[group_above_key]['height'] + groups[group_above_key]['posy']; } console.log(groups); // set note positions left_order = 0; // order of groups in a row for (var category in groups) { console.log(category); var group_notes = groups[category]['notes']; for (var i = 0; i < group_notes.length; i++) { var note = group_notes[i]; // get left position var left; if (i % 2 == 0) { left = left_order * max_group_width; } else { left = left_order * max_group_width + max_note_width; } // get top position var top; if (i % 2 == 0) { top = groups[category]['posy'] + ((i/2)*max_note_height) } else { top = groups[category]['posy'] + (parseInt(i/2)*max_note_height) } note.position([top,left], start); } left_order++; if (left_order >= max_groups_in_row) { left_order = 0; } } } var createNote = function(noteObj) { var newNote = new Note(noteObj, vizApp, arrayOfNotes.length-1); newNote.setBackground( colorArray[Math.floor(Math.random()*colorArray.length)]); arrayOfNotes.push(newNote); } var rearrangeNotes = function(arrangement) { if(arrangement == "custom") { arrayOfNotes.map(function(note) { var pos = note.customPosition(); note.position(pos); }); saveLayoutButton.fadeOut(); } else { setGroupPositions(arrayOfNotes, arrangement); } } var colorNotes = function(criteria) { if(criteria != "") { var arrayOfCriteria = generateArrayOfAttributes(criteria, arrayOfNotes); arrayOfNotes.map(function(note) { var attr = note.getNoteAttr(criteria); note.setBackground(colorArray[arrayOfCriteria.indexOf(attr)]) }); } else { arrayOfNotes.map(function(note) { note.setBackground('#eee') }); } } var saveCustomLayout = function() { arrayOfNotes.map(function(note) { var pos = note.position(); console.log("custom layout"); console.log(pos); note.customPosition(pos); }); saveLayoutButton.fadeOut(); } this.showSaveLayoutButton = function() { console.log('save button') saveLayoutButton.fadeIn(); } return { setData : setData, init : init } } function generateArrayOfAttributes(criteria, arrayOfNotes) { var rawArray = arrayOfNotes.map(function(note) { return note.getNoteAttr(criteria); }); return rawArray.getUnique(); } //http://stackoverflow.com/questions/1960473/unique-values-in-an-array Array.prototype.getUnique = function(){ var u = {}, a = []; for(var i = 0, l = this.length; i < l; ++i){ if(u.hasOwnProperty(this[i])) { continue; } a.push(this[i]); u[this[i]] = 1; } return a; } var colorArray = [ "#E1BEE7", "#D1C4E9", "#C5CAE9", "#BBDEFB", "#B2EBF2", "#DCEDC8", "#FFECB3", "#D7CCC8", "#CFD8DC", "#FFCDD2", "#F8BBD0" ]
SciutoAlex/ahasynth
webapp/js/visualization.js
JavaScript
mit
6,049