code
stringlengths
2
1.05M
version https://git-lfs.github.com/spec/v1 oid sha256:bfe73232377909f40756350fbb789ac5626485431111afcf8863defb2af912a8 size 15196
var path = require('path') var autoprefixer = require('autoprefixer') module.exports = { entry: './src/index.js', output: { path: __dirname + '/build', publicPath: '/build/', filename: 'bundle.js', }, module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, resolve: { extensions: [ '.js', '.jsx', ], }, loader: 'babel-loader', }, { test: /\.css$/, exclude: /node_modules/, use: [ 'style-loader', 'css-loader', ], }, { test: /\.scss$/, exclude: /node_modules/, use: [ 'style-loader', { loader: 'css-loader', options: { modules: true, sourceMap: true, camelCase: true, importLoaders: 1, localIdentName: '[name]__[local]__[hash:base64:5]', }, }, { loader: 'postcss-loader', options: { sourceMap: true, plugins: [ autoprefixer({ browsers: ['last 3 versions'], }), ], }, }, { loader: 'sass-loader', options: { sourceMap: true, }, }, ], }, { test: /\.woff(2)?$/, exclude: /node_modules/, loader: 'file-loader', }, { test: /\.jpg|\.png$/, exclude: /node_modules/, loader: 'url-loader', }, ], }, resolve: { alias: { assets: path.resolve('./src/assets'), fonts: path.resolve('./src/assets/fonts'), images: path.resolve('./src/assets/images'), components: path.resolve('./src/components'), constants: path.resolve('./src/constants'), containers: path.resolve('./src/containers'), reducers: path.resolve('./src/reducers'), styles: path.resolve('./src/styles'), colors: path.resolve('./src/styles/colors.scss'), utils: path.resolve('./src/utils'), }, }, devtool: 'source-map', mode: 'development', }
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import DigestEmail from './digest_email'; import fs from 'fs'; import juice from 'juice'; import Immutable from 'immutable'; import { jsdom } from 'jsdom'; import { exec } from 'child_process'; function render(callback) { const salesStats = Immutable.fromJS( JSON.parse( fs.readFileSync(__dirname + '/../data/sales_stats.json', { encoding: 'utf8' }) ).map(parseFloat) ); const css = fs.readFileSync(__dirname + '/styles.css', { encoding: 'utf8' }); const html = juice.inlineContent( ReactDOMServer.renderToStaticMarkup(<DigestEmail salesStats={salesStats}/>), css ); const document = jsdom(html); const svg = document.querySelector('svg'); let pngData; exec(`echo '${svg.outerHTML}' | rsvg-convert | base64`, (err, stdout, stderr) => { pngData = stdout; let img = document.createElement('img'); img.src = 'cid:salessparkline'; svg.parentNode.replaceChild(img, svg); callback(document.querySelector('html').outerHTML, [ { type: 'image/png', name: 'salessparkline', content: pngData, } ]); }); } export default render;
require(["h","../../nested/morenesting/i.js"],function(h,i){ window.__global.g = h + "ggg" + i; }); module.exports = "g done";
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import RaisedButton from 'material-ui/RaisedButton'; import authActions from '../../../Auth/AuthActions'; class HomePage extends Component { /** * Class constructor. */ constructor(props) { super(props); // set the initial component state this.state = { errors: {}, successMessage: '', user: { email: '', password: '', }, }; this.logout = this.logout.bind(this); } /** * Process the form. * * @param {object} event - the JavaScript event object */ logout(event) { const { dispatch } = this.props; event.preventDefault(); dispatch(authActions.logoutRequest()); } render() { const { isAuthenticated } = this.props; let links = null; if (isAuthenticated) { links = (<div> <Link to={'/posts'} > Posts </Link> <Link to={'/losts'} > Losts </Link> <Link to={'/founds'} > Founds </Link> <Link to={'#'} onClick={this.logout} > Logout </Link> <RaisedButton style={{ margin: 12 }} type="submit" label="Material UI Test Button" primary /> </div>); } else { links = (<div> <div><Link to="/login"><RaisedButton primary label="Login" /></Link></div> <div><Link to="/signup"><RaisedButton primary label="Signup" /></Link></div> </div>); } return ( <div> {links} </div> ); } } function mapStateToProps(state) { return { isAuthenticated: state.auth.isAuthenticated, }; } HomePage.contextTypes = { router: React.PropTypes.object, }; HomePage.propTypes = { isAuthenticated: React.PropTypes.bool, }; export default connect(mapStateToProps)(HomePage);
/*jslint browser: true */ /*global SOG */ /** * @namespace browser */ SOG.utils.namespace('SOG.browser.artboard'); /** * Makes the canvas word. Uses * {{#crossLink "browser.points"}}points{{/crossLink}}. * * @class artboard * @static */ SOG.browser.artboard = (function (points) { 'use strict'; var context, painting, startDrawing, stopDrawing, drawing, addPoint, draw, drawAll, offsetX, offsetY, changeCrayon, room, receivePoint; /** * Sets painting to true and add points. * * @method startDrawing * @private * @param e {object} Mouse-event. */ /** * Sets painting to false. * * @method stopDrawing * @private */ /** * Add point if painting is true. * * @method drawing * @private * @param e {object} Mouse-event. */ /** * Adds a point and draw it direct. * * @method receivePoint * @private * @param data {object} The data for the point. */ receivePoint = function (data) { if (Array.isArray(data)) { points.addArray(data); points.each(draw); } else { points.add(data); points.last(draw); } }; /** * Adds a point and draw it direct. And sends it to the server. * * @method addPoint * @private * @param x {int} The x cordination. * @param y {int} The y cordination. * @param dragging {boolean} True if not first point. */ /** * Draw line from previous to current point. * * @method draw * @private * @param prev {object} The previous point. * @param curr {object} The current point. */ /** * Draw line from previous to current point, with all points. * * @method drawAll * @private */ drawAll = function () { // Clear the canvas context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Pencil style context.lineJoin = 'round'; // Start drawing points.each(draw); }; /** * Change class of canvas to the crayon. * * @method changeCrayon * @private * @param color {string} The color. */ changeCrayon = function (color) { // Remove all colors from cursor ['white', 'black', 'red', 'orange', 'yellow', 'yellowgreen', 'green', 'lightskyblue', 'dodgerblue', 'violet', 'pink', 'burlywood', 'saddlebrown', 'brown'].forEach(function (c) { context.canvas.classList.remove(c + '_crayon'); }); // Add cursor with right color context.canvas.classList.add(color + '_crayon'); return color; }; return { /** * Constructor * * @method init * @param opt {object} Options. * @param opt.canvas {node} The canvas. * @param opt.room {object} The room. * @param opt.x {int} Offset on x-axis. * @param opt.y {int} Offset on y-axis. */ init: function (opt) { // Prevent Chrome from selecting the canvas // TODO Set on document? No need to select anything? opt.canvas.onselectstart = function () { return false; }; opt.canvas.onmousedown = function () { return false; }; // Set room room = opt.room; // Offset if needed offsetX = opt.x || 0; offsetY = opt.y || 0; // Set up artboard context = opt.canvas.getContext('2d'); this.clear(); // Change cursor this.setColor('red'); // Receive one point from server room.onReceivePoint(receivePoint); }, /** * Disable drawing. * * @method disable */ /** * Clears the artboard and remove all points. * * @method clear */ /** * Get image from the canvas. * * @method getImage * @return Returns a string with the base64 image. */ getImage: function () { if (points.nrOfPoints() > 10) { return context.canvas.toDataURL(); } return ''; } }; }(SOG.browser.points));
() => { const [startDate, setStartDate] = useState(new Date()); return ( <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} showYearPicker dateFormat="yyyy" yearItemNumber={9} /> ); };
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } root.Docusign.DisplayApplianceDocument = factory(root.Docusign.ApiClient); } }(this, function(ApiClient) { 'use strict'; /** * The DisplayApplianceDocument model module. * @module model/DisplayApplianceDocument * @version 3.0.0 */ /** * Constructs a new <code>DisplayApplianceDocument</code>. * @alias module:model/DisplayApplianceDocument * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>DisplayApplianceDocument</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/DisplayApplianceDocument} obj Optional instance to populate. * @return {module:model/DisplayApplianceDocument} The populated <code>DisplayApplianceDocument</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('attachmentDescription')) { obj['attachmentDescription'] = ApiClient.convertToType(data['attachmentDescription'], 'String'); } if (data.hasOwnProperty('documentId')) { obj['documentId'] = ApiClient.convertToType(data['documentId'], 'String'); } if (data.hasOwnProperty('documentType')) { obj['documentType'] = ApiClient.convertToType(data['documentType'], 'String'); } if (data.hasOwnProperty('envelopeId')) { obj['envelopeId'] = ApiClient.convertToType(data['envelopeId'], 'String'); } if (data.hasOwnProperty('externalDocumentId')) { obj['externalDocumentId'] = ApiClient.convertToType(data['externalDocumentId'], 'String'); } if (data.hasOwnProperty('latestPDFId')) { obj['latestPDFId'] = ApiClient.convertToType(data['latestPDFId'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('pages')) { obj['pages'] = ApiClient.convertToType(data['pages'], 'Number'); } } return obj; } /** * * @member {String} attachmentDescription */ exports.prototype['attachmentDescription'] = undefined; /** * Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute. * @member {String} documentId */ exports.prototype['documentId'] = undefined; /** * * @member {String} documentType */ exports.prototype['documentType'] = undefined; /** * The envelope ID of the envelope status that failed to post. * @member {String} envelopeId */ exports.prototype['envelopeId'] = undefined; /** * * @member {String} externalDocumentId */ exports.prototype['externalDocumentId'] = undefined; /** * * @member {String} latestPDFId */ exports.prototype['latestPDFId'] = undefined; /** * * @member {String} name */ exports.prototype['name'] = undefined; /** * * @member {Number} pages */ exports.prototype['pages'] = undefined; return exports; }));
/** * INSPINIA - Responsive Admin Theme * * Main directives.js file * Define directives for used plugin * * * Functions (directives) * - sideNavigation * - iboxTools * - minimalizaSidebar * - vectorMap * - sparkline * - icheck * - ionRangeSlider * - dropZone * - responsiveVideo * - chatSlimScroll * - customValid * - fullScroll * - closeOffCanvas * - clockPicker * - landingScrollspy * - fitHeight * - iboxToolsFullScreen * - slimScroll * */ /** * pageTitle - Directive for set Page title - mata title */ function pageTitle($rootScope, $timeout) { return { link: function(scope, element) { var listener = function(event, toState, toParams, fromState, fromParams) { // Default title - load on Dashboard 1 var title = 'Matozap | The sports playground'; // Create your own title pattern if (toState.data && toState.data.pageTitle) title = 'Matozap | ' + toState.data.pageTitle; $timeout(function() { element.text(title); }); }; $rootScope.$on('$stateChangeStart', listener); } } }; /** * sideNavigation - Directive for run metsiMenu on sidebar navigation */ function sideNavigation($timeout) { return { restrict: 'A', link: function(scope, element) { // Call the metsiMenu plugin and plug it to sidebar navigation $timeout(function(){ element.metisMenu(); }); } }; } /** * responsibleVideo - Directive for responsive video */ function responsiveVideo() { return { restrict: 'A', link: function(scope, element) { var figure = element; var video = element.children(); video .attr('data-aspectRatio', video.height() / video.width()) .removeAttr('height') .removeAttr('width') //We can use $watch on $window.innerWidth also. $(window).resize(function() { var newWidth = figure.width(); video .width(newWidth) .height(newWidth * video.attr('data-aspectRatio')); }).resize(); } } } /** * iboxTools - Directive for iBox tools elements in right corner of ibox */ function iboxTools($timeout) { return { restrict: 'A', scope: true, templateUrl: 'views/common/ibox_tools.html', controller: function ($scope, $element) { // Function for collapse ibox $scope.showhide = function () { var ibox = $element.closest('div.ibox'); var icon = $element.find('i:first'); var content = ibox.find('div.ibox-content'); content.slideToggle(200); // Toggle icon from up to down icon.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); ibox.toggleClass('').toggleClass('border-bottom'); $timeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); }; // Function for close ibox $scope.closebox = function () { var ibox = $element.closest('div.ibox'); ibox.remove(); } } }; } /** * iboxTools with full screen - Directive for iBox tools elements in right corner of ibox with full screen option */ function iboxToolsFullScreen($timeout) { return { restrict: 'A', scope: true, templateUrl: 'views/common/ibox_tools_full_screen.html', controller: function ($scope, $element) { // Function for collapse ibox $scope.showhide = function () { var ibox = $element.closest('div.ibox'); var icon = $element.find('i:first'); var content = ibox.find('div.ibox-content'); content.slideToggle(200); // Toggle icon from up to down icon.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); ibox.toggleClass('').toggleClass('border-bottom'); $timeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); }; // Function for close ibox $scope.closebox = function () { var ibox = $element.closest('div.ibox'); ibox.remove(); }; // Function for full screen $scope.fullscreen = function () { var ibox = $element.closest('div.ibox'); var button = $element.find('i.fa-expand'); $('body').toggleClass('fullscreen-ibox-mode'); button.toggleClass('fa-expand').toggleClass('fa-compress'); ibox.toggleClass('fullscreen'); setTimeout(function() { $(window).trigger('resize'); }, 100); } } }; } /** * minimalizaSidebar - Directive for minimalize sidebar */ function minimalizaSidebar($timeout) { return { restrict: 'A', template: '<a class="navbar-minimalize minimalize-styl-2 btn btn-primary " href="" ng-click="minimalize()"><i class="fa fa-bars"></i></a>', controller: function ($scope, $element) { $scope.minimalize = function () { $("body").toggleClass("mini-navbar"); if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) { // Hide menu in order to smoothly turn on when maximize menu $('#side-menu').hide(); // For smoothly turn on menu setTimeout( function () { $('#side-menu').fadeIn(500); }, 100); } else if ($('body').hasClass('fixed-sidebar')){ $('#side-menu').hide(); setTimeout( function () { $('#side-menu').fadeIn(500); }, 300); } else { // Remove all inline style from jquery fadeIn function to reset menu state $('#side-menu').removeAttr('style'); } } } }; }; function closeOffCanvas() { return { restrict: 'A', template: '<a class="close-canvas-menu" ng-click="closeOffCanvas()"><i class="fa fa-times"></i></a>', controller: function ($scope, $element) { $scope.closeOffCanvas = function () { $("body").toggleClass("mini-navbar"); } } }; } /** * vectorMap - Directive for Vector map plugin */ function vectorMap() { return { restrict: 'A', scope: { myMapData: '=', }, link: function (scope, element, attrs) { element.vectorMap({ map: 'world_mill_en', backgroundColor: "transparent", regionStyle: { initial: { fill: '#e4e4e4', "fill-opacity": 0.9, stroke: 'none', "stroke-width": 0, "stroke-opacity": 0 } }, series: { regions: [ { values: scope.myMapData, scale: ["#1ab394", "#22d6b1"], normalizeFunction: 'polynomial' } ] }, }); } } } /** * sparkline - Directive for Sparkline chart */ function sparkline() { return { restrict: 'A', scope: { sparkData: '=', sparkOptions: '=', }, link: function (scope, element, attrs) { scope.$watch(scope.sparkData, function () { render(); }); scope.$watch(scope.sparkOptions, function(){ render(); }); var render = function () { $(element).sparkline(scope.sparkData, scope.sparkOptions); }; } } }; /** * icheck - Directive for custom checkbox icheck */ function icheck($timeout) { return { restrict: 'A', require: 'ngModel', link: function($scope, element, $attrs, ngModel) { return $timeout(function() { var value; value = $attrs['value']; $scope.$watch($attrs['ngModel'], function (newValue) { $(element).iCheck('update'); }); return $(element).iCheck({ checkboxClass: 'icheckbox_square-green', radioClass: 'iradio_square-green' }).on('ifChanged', function(event) { if ($(element).attr('type') === 'checkbox' && $attrs['ngModel']) { $scope.$apply(function() { return ngModel.$setViewValue(event.target.checked); }); } if ($(element).attr('type') === 'radio' && $attrs['ngModel']) { return $scope.$apply(function() { return ngModel.$setViewValue(value); }); } }); }); } }; } /** * ionRangeSlider - Directive for Ion Range Slider */ function ionRangeSlider() { return { restrict: 'A', scope: { rangeOptions: '=' }, link: function (scope, elem, attrs) { elem.ionRangeSlider(scope.rangeOptions); } } } /** * dropZone - Directive for Drag and drop zone file upload plugin */ function dropZone() { return function(scope, element, attrs) { element.dropzone({ url: "/upload", maxFilesize: 100, paramName: "uploadfile", maxThumbnailFilesize: 5, init: function() { scope.files.push({file: 'added'}); this.on('success', function(file, json) { }); this.on('addedfile', function(file) { scope.$apply(function(){ alert(file); scope.files.push({file: 'added'}); }); }); this.on('drop', function(file) { alert('file'); }); } }); } } /** * chatSlimScroll - Directive for slim scroll for small chat */ function chatSlimScroll($timeout) { return { restrict: 'A', link: function(scope, element) { $timeout(function(){ element.slimscroll({ height: '234px', railOpacity: 0.4 }); }); } }; } /** * customValid - Directive for custom validation example */ function customValid(){ return { require: 'ngModel', link: function(scope, ele, attrs, c) { scope.$watch(attrs.ngModel, function() { // You can call a $http method here // Or create custom validation var validText = "Inspinia"; if(scope.extras == validText) { c.$setValidity('cvalid', true); } else { c.$setValidity('cvalid', false); } }); } } } /** * fullScroll - Directive for slimScroll with 100% */ function fullScroll($timeout){ return { restrict: 'A', link: function(scope, element) { $timeout(function(){ element.slimscroll({ height: '100%', railOpacity: 0.9 }); }); } }; } /** * slimScroll - Directive for slimScroll with custom height */ function slimScroll($timeout){ return { restrict: 'A', scope: { boxHeight: '@' }, link: function(scope, element) { $timeout(function(){ element.slimscroll({ height: scope.boxHeight, railOpacity: 0.9 }); }); } }; } /** * clockPicker - Directive for clock picker plugin */ function clockPicker() { return { restrict: 'A', link: function(scope, element) { element.clockpicker(); } }; }; /** * landingScrollspy - Directive for scrollspy in landing page */ function landingScrollspy(){ return { restrict: 'A', link: function (scope, element, attrs) { element.scrollspy({ target: '.navbar-fixed-top', offset: 80 }); } } } /** * fitHeight - Directive for set height fit to window height */ function fitHeight(){ return { restrict: 'A', link: function(scope, element) { element.css("height", $(window).height() + "px"); element.css("min-height", $(window).height() + "px"); } }; } /** * * Pass all functions into module */ angular .module('inspinia') .directive('pageTitle', pageTitle) .directive('sideNavigation', sideNavigation) .directive('iboxTools', iboxTools) .directive('minimalizaSidebar', minimalizaSidebar) .directive('vectorMap', vectorMap) .directive('sparkline', sparkline) .directive('icheck', icheck) .directive('ionRangeSlider', ionRangeSlider) .directive('dropZone', dropZone) .directive('responsiveVideo', responsiveVideo) .directive('chatSlimScroll', chatSlimScroll) .directive('customValid', customValid) .directive('fullScroll', fullScroll) .directive('closeOffCanvas', closeOffCanvas) .directive('clockPicker', clockPicker) .directive('landingScrollspy', landingScrollspy) .directive('fitHeight', fitHeight) .directive('iboxToolsFullScreen', iboxToolsFullScreen) .directive('slimScroll', slimScroll);
import { get } from 'ember-metal/property_get'; import { set } from 'ember-metal/property_set'; import EmberComponent from '../component'; import layout from '../templates/empty'; /** @module ember @submodule ember-views */ /** The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `checkbox`. See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details. ## Direct manipulation of `checked` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.Component @public */ export default EmberComponent.extend({ layout, instrumentDisplay: '{{input type="checkbox"}}', classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: [ 'type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form' ], type: 'checkbox', checked: false, disabled: false, indeterminate: false, didInsertElement() { this._super(...arguments); get(this, 'element').indeterminate = !!get(this, 'indeterminate'); }, change() { set(this, 'checked', this.$().prop('checked')); } });
/*! * Snail UI Resizable @VERSION * Depends: * snail.ui.core.js * snail.ui.mouse.js * snail.ui.widget.js */ (function( $, undefined ) { function num(v) { return parseInt(v, 10) || 0; } function isNumber(value) { return !isNaN(parseInt(value, 10)); } $.widget("sn.resizable", $.sn.mouse, { version: "@VERSION", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90 }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("sn-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || 'sn-resizable-helper' : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $('<div class="sn-wrapper" style="overflow: hidden;"></div>').css({ position: this.element.css('position'), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css('top'), left: this.element.css('left') }) ); //Overwrite the original this.element this.element = this.element.parent().data( "sn-resizable", this.element.data('sn-resizable') ); this.elementIsWrapper = true; //Move margins to the wrapper this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css('resize'); this.originalElement.css('resize', 'none'); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css('margin') }); // fix handlers offset this._proportionallyResize(); } this.handles = o.handles || (!$('.sn-resizable-handle', this.element).length ? "e,s,se" : { n: '.sn-resizable-n', e: '.sn-resizable-e', s: '.sn-resizable-s', w: '.sn-resizable-w', se: '.sn-resizable-se', sw: '.sn-resizable-sw', ne: '.sn-resizable-ne', nw: '.sn-resizable-nw' }); if(this.handles.constructor === String) { if ( this.handles === 'all') { this.handles = 'n,e,s,w,se,sw,ne,nw'; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = 'sn-resizable-'+handle; axis = $('<div class="sn-resizable-handle ' + hname + '"></div>'); // Apply zIndex to all handles - see #7960 axis.css({ zIndex: o.zIndex }); //TODO : What's going on here? if ('se' === handle) { axis.addClass('sn-icon sn-icon-gripsmall-diagonal-se'); } //Insert into internal handles object and append to element this.handles[handle] = '.sn-resizable-'+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = $(this.handles[i], this.element).show(); } //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... padPos = [ 'padding', /ne|nw|n/.test(i) ? 'Top' : /se|sw|s/.test(i) ? 'Bottom' : /^e$/.test(i) ? 'Right' : 'Left' ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $('.sn-resizable-handle', this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/sn-resizable-(se|sw|ne|nw|n|e|s|w)/i); } //Axis, default = se that.axis = axis && axis[1] ? axis[1] : 'se'; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("sn-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("sn-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("sn-resizable-autohide"); that._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("sn-resizable sn-resizable-disabled sn-resizable-resizing") .removeData("resizable").removeData("sn-resizable").unbind(".resizable").find('.sn-resizable-handle').remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css('position'), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css('top'), left: wrapper.css('left') }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css('resize', this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; // bugfix for http://dev.jquery.com/ticket/1749 if ( (/absolute/).test( el.css('position') ) ) { el.css({ position: 'absolute', top: el.css('top'), left: el.css('left') }); } else if (el.is('.sn-draggable')) { el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); } this._renderProxy(); curleft = num(this.helper.css('left')); curtop = num(this.helper.css('top')); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio === 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $('.sn-resizable-' + this.axis).css('cursor'); $('body').css('cursor', cursor === 'auto' ? this.axis + '-resize' : cursor); el.addClass("sn-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, prevTop = this.position.top, prevLeft = this.position.left, prevWidth = this.size.width, prevHeight = this.size.height, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; if (!trigger) { return false; } // Calculate the attrs that will be change data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); // plugins callbacks need to be called first this._propagate("resize", event); if (this.position.top !== prevTop) { props.top = this.position.top + "px"; } if (this.position.left !== prevLeft) { props.left = this.position.left + "px"; } if (this.size.width !== prevWidth) { props.width = this.size.width + "px"; } if (this.size.height !== prevHeight) { props.height = this.size.height + "px"; } el.css(props); if (!this._helper && this._proportionallyResizeElements.length) { this._proportionallyResize(); } // Call the user callback if the element was resized if ( ! $.isEmptyObject(props) ) { this._trigger('resize', event, this.ui()); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && $.sn.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $('body').css('cursor', 'auto'); this.element.removeClass("sn-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { // We want to create an enclosing box whose aspect ration is the requested one // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (isNumber(data.left)) { this.position.left = data.left; } if (isNumber(data.top)) { this.position.top = data.top; } if (isNumber(data.height)) { this.size.height = data.height; } if (isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === 'sw') { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === 'nw') { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')]; paddings = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: 'absolute', left: this.elementOffset.left +'px', top: this.elementOffset.top +'px', zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.sn.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } }); /* * Resizable Extensions */ $.sn.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).data("sn-resizable"), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.sn.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css('width'), 10), height: parseInt(that.element.css('height'), 10), top: parseInt(that.element.css('top'), 10), left: parseInt(that.element.css('left'), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.sn.plugin.add("resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $(this).data("sn-resizable"), o = that.options, el = that.element, oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) { return; } that.containerElement = $(ce); if (/document/.test(oc) || oc === document) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else { element = $(ce); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ($.sn.hasScroll(ce, "left") ? ce.scrollWidth : cw ); height = ($.sn.hasScroll(ce) ? ce.scrollHeight : ch); that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event ) { var woset, hoset, isParent, isOffsetRelative, that = $(this).data("sn-resizable"), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement; if (ce[0] !== document && (/static/).test(ce.css('position'))) { cop = co; } if (cp.left < (that._helper ? co.left : 0)) { that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left)); if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } that.position.left = o.helper ? co.left : 0; } if (cp.top < (that._helper ? co.top : 0)) { that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top); if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left+that.position.left; that.offset.top = that.parentData.top+that.position.top; woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ); hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); isParent = that.containerElement.get(0) === that.element.parent().get(0); isOffsetRelative = /relative|absolute/.test(that.containerElement.css('position')); if(isParent && isOffsetRelative) { woset -= that.parentData.left; } if (woset + that.size.width >= that.parentData.width) { that.size.width = that.parentData.width - woset; if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } } if (hoset + that.size.height >= that.parentData.height) { that.size.height = that.parentData.height - hoset; if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } } }, stop: function(){ var that = $(this).data("sn-resizable"), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $(that.helper), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if (that._helper && !o.animate && (/relative/).test(ce.css('position'))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if (that._helper && !o.animate && (/static/).test(ce.css('position'))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.sn.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).data("sn-resizable"), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("sn-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10) }); }); }; if (typeof(o.alsoResize) === 'object' && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).data("sn-resizable"), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("sn-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(sn.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left']; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === 'object' && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.sn.plugin.add("resizable", "ghost", { start: function() { var that = $(this).data("sn-resizable"), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass('sn-resizable-ghost') .addClass(typeof o.ghost === 'string' ? o.ghost : ''); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).data("sn-resizable"); if (that.ghost) { that.ghost.css({ position: 'relative', height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).data("sn-resizable"); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.sn.plugin.add("resizable", "grid", { resize: function() { var that = $(this).data("sn-resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); })(jQuery);
/* * Copyright (C) 2013 Vanderbilt University, All rights reserved. * * AUTO GENERATED CODE FOR PROJECT CyPhyLight */ "use strict"; define(['underscore', 'js/Utils/METAAspectHelper'], function (_underscore, METAAspectHelper) { var _metaID = 'CyPhyLight.META.js'; //META ASPECT TYPES var _metaTypes = { 'Component': '/-2/-19', 'ComponentAssemblies': '/-2/-15', 'ComponentAssembly': '/-2/-57', 'ComponentType': '/-2/-7', 'Components': '/-2/-14', 'Connection': '/-2/-40', 'Connector': '/-2/-27', 'ConnectorComposition': '/-2/-49', 'CyPhyLightModelicaLanguage': '/-2', 'CyPhyProject': '/-2/-56', 'DesignEntity': '/-2/-6', 'Environment': '/-2/-26', 'FCO': '/-2/-1', 'Folder': '/-2/-3', 'Metric': '/-2/-36', 'ModelicaConnector': '/-2/-28', 'ModelicaConnectorComposition': '/-2/-52', 'ModelicaModel': '/-2/-23', 'ModelicaModelType': '/-2/-22', 'ModelicaParameter': '/-2/-39', 'ModelicaParameterRedeclare': '/-2/-53', 'ModelicaTestBench': '/-2/-18', 'Parameter': '/-2/-33', 'PostProcessing': '/-2/-100', 'Property': '/-2/-30', 'PropertyType': '/-2/-2', 'SolverSettings': '/-2/-10', 'TestBenchType': '/-2/-17', 'TestComponent': '/-2/-20', 'TestComponents': '/-2/-50', 'Testing': '/-2/-16', 'TopLevelSystemUnderTest': '/-2/-21', 'ValueFlowComposition': '/-2/-41', 'ValueFlowTarget': '/-2/-29' }; //META ASPECT TYPE CHECKING var _isComponent = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Component); }; var _isComponentAssemblies = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ComponentAssemblies); }; var _isComponentAssembly = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ComponentAssembly); }; var _isComponentType = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ComponentType); }; var _isComponents = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Components); }; var _isConnection = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Connection); }; var _isConnector = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Connector); }; var _isConnectorComposition = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ConnectorComposition); }; var _isCyPhyLightModelicaLanguage = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.CyPhyLightModelicaLanguage); }; var _isCyPhyProject = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.CyPhyProject); }; var _isDesignEntity = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.DesignEntity); }; var _isEnvironment = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Environment); }; var _isFCO = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.FCO); }; var _isFolder = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Folder); }; var _isMetric = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Metric); }; var _isModelicaConnector = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaConnector); }; var _isModelicaConnectorComposition = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaConnectorComposition); }; var _isModelicaModel = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaModel); }; var _isModelicaModelType = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaModelType); }; var _isModelicaParameter = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaParameter); }; var _isModelicaParameterRedeclare = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaParameterRedeclare); }; var _isModelicaTestBench = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ModelicaTestBench); }; var _isParameter = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Parameter); }; var _isPostProcessing = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.PostProcessing); }; var _isProperty = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Property); }; var _isPropertyType = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.PropertyType); }; var _isSolverSettings = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.SolverSettings); }; var _isTestBenchType = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.TestBenchType); }; var _isTestComponent = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.TestComponent); }; var _isTestComponents = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.TestComponents); }; var _isTesting = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.Testing); }; var _isTopLevelSystemUnderTest = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.TopLevelSystemUnderTest); }; var _isValueFlowComposition = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ValueFlowComposition); }; var _isValueFlowTarget = function (objID) { return METAAspectHelper.isMETAType(objID, _metaTypes.ValueFlowTarget); }; var _queryMetaTypes = function () { var nMetaTypes = METAAspectHelper.getMETAAspectTypes(), m; if (!_.isEqual(_metaTypes,nMetaTypes)) { //TODO: when displaying an error message make sure it's the very same project /*var metaOutOfDateMsg = _metaID + " is not up to date with the latest META aspect. Please update your local copy!"; if (console.error) { console.error(metaOutOfDateMsg); } else { console.log(metaOutOfDateMsg); }*/ for (m in _metaTypes) { if (_metaTypes.hasOwnProperty(m)) { delete _metaTypes[m]; } } for (m in nMetaTypes) { if (nMetaTypes.hasOwnProperty(m)) { _metaTypes[m] = nMetaTypes[m]; } } } }; //hook up to META ASPECT CHANGES METAAspectHelper.addEventListener(METAAspectHelper.events.META_ASPECT_CHANGED, function () { _queryMetaTypes(); }); //generate the META types on the first run _queryMetaTypes(); //return utility functions return { META_TYPES: _metaTypes, TYPE_INFO: { isComponent: _isComponent, isComponentAssemblies: _isComponentAssemblies, isComponentAssembly: _isComponentAssembly, isComponentType: _isComponentType, isComponents: _isComponents, isConnection: _isConnection, isConnector: _isConnector, isConnectorComposition: _isConnectorComposition, isCyPhyLightModelicaLanguage: _isCyPhyLightModelicaLanguage, isCyPhyProject: _isCyPhyProject, isDesignEntity: _isDesignEntity, isEnvironment: _isEnvironment, isFCO: _isFCO, isFolder: _isFolder, isMetric: _isMetric, isModelicaConnector: _isModelicaConnector, isModelicaConnectorComposition: _isModelicaConnectorComposition, isModelicaModel: _isModelicaModel, isModelicaModelType: _isModelicaModelType, isModelicaParameter: _isModelicaParameter, isModelicaParameterRedeclare: _isModelicaParameterRedeclare, isModelicaTestBench: _isModelicaTestBench, isParameter: _isParameter, isPostProcessing: _isPostProcessing, isProperty: _isProperty, isPropertyType: _isPropertyType, isSolverSettings: _isSolverSettings, isTestBenchType: _isTestBenchType, isTestComponent: _isTestComponent, isTestComponents: _isTestComponents, isTesting: _isTesting, isTopLevelSystemUnderTest: _isTopLevelSystemUnderTest, isValueFlowComposition: _isValueFlowComposition, isValueFlowTarget: _isValueFlowTarget } }; });
var yAxisIndex; //add prepend ability Element.prototype.prependChild = function(child) { this.insertBefore(child, this.firstChild); }; Date.setLocale('en'); //A default configuration //Should change to more d3esque methods e.g. http://bost.ocks.org/mike/chart/ Gneiss.defaultGneissChartConfig = { container: "#chartContainer", //css id of target chart container svg_place: "#canvasSVG", editable: true, // reserved for enabling or dissabling on chart editing lineDotsThreshold: 15, //line charts will have dots on points until a series has this number of points dotRadius: 4, //the radius of dots used on line and scatter plots bargridLabelMargin: 4, //the horizontal space between a bargrid bar and it's label bargridBarThickness: 20, //thickness of the bars in a bargrid xAxisMargin: 8, //the vertical space between the plot area and the x axis footerMargin: 4, //the vertical space between the bottom of the bounding box and the meta information legendLabelSpacingX: 5, //the horizontal space between legend items legendLabelSpacingY: 4, //the vertical space between legend items columnGap: 1, //the horizontal space between two columns that have the same x-axis value axisBarGap: 5, //the horizontal space between a vertical axis and an adjacent bar maxColumnWidth: 7.5, // the maximum width of a column as a percent of the available chart width primaryAxisPosition: "right", // the first axis will be rendered on this side, "right" or "left" only primaryAxisPosition: "right", // the first axis will be rendered on this side, "right" or "left" only allowAxisOverlap: false, legend: true, // whether or not there should be a legend title: "", // the chart title titleBottomMargin: 5, // the vertical space between the title and the next element (sometimes a legend, sometimes an axis) bargridLabelBottomMargin: 5, //the space between the bargrid series label and the top most bar colors: ["#ff4cf4","#ffb3ff","#e69ce6","#cc87cc","#b373b3","#995f99","#804c80","#665266","#158eff","#99cdff","#9cc2e6","#87abcc","#7394b3","#5f7d99","#466780","#525c66"], padding :{ top: 5, bottom: 50, left: 10, right: 10 }, xAxis: { domain: [0,100], prefix: "", suffix: "", type: "linear", formatter: null, mixed: true, ticks: 5 }, yAxis: [ { domain: [null,null], tickValues: null, prefix: { value: "", use: "top" //can be "top" "all" "positive" or "negative" }, suffix: { value: "", use: "top" }, ticks: 4, formatter: null, color: null } ], series: [ { name: "apples", data: [5.5,10.2,6.1,3.8], source: "Some Org", type: "line", axis: 0, color: null }, { name: "oranges", data: [23,10,13,7], source: "Some Org", type: "line", axis: 0, color: null } ], xAxisRef: [ { name: "names", data: ["juicyness","color","flavor","travelability"] } ], sourceline: "", creditline: "Made with ..." }; Gneiss.dateParsers = { "mmddyyyy": function(d) { return [d.getMonth() + 1, d.getDate(), d.getFullYear()].join("/"); }, "ddmmyyyy": function(d) { return [d.getDate(), d.getMonth() + 1, d.getFullYear()].join("/"); }, "mmdd": function(d) { return [d.getMonth() + 1, d.getDate()].join("/"); }, "Mdd": function(d) { var month = d.getMonth() + 1; if(month == 5) { return d.format('{Mon}') + " " + d.getDate(); } else { return d.format('{Mon}.') + " " + d.getDate(); } }, "ddM": function(d) { var month = d.getMonth() + 1; if(month == 5) { return "" + d.getDate() + " " + d.format('{Mon}'); } else { return "" + d.getDate() + " " + d.format('{Mon}.'); } }, "mmyy": function(d) { return [d.getMonth() + 1, String(d.getFullYear()).split("").splice(2,2).join("")].join("/"); }, "yy": function(d) { return "’" + String(d.getFullYear()).split("").splice(2,2).join(""); }, "yyyy": function(d) { return "" + d.getFullYear(); }, "MM": function(d) { var month = d.getMonth() + 1; if(month == 1) { return "" + d.getFullYear(); } else { return d.format('{Month}'); } }, "M": function(d) { var month = d.getMonth() + 1; if(month == 1) { return "’" + String(d.getFullYear()).split("").splice(2,2).join(""); } else if(month == 5) { return d.format('{Mon}'); } else { return d.format('{Mon}.'); } }, "hmm": function(d) { if(d.getHours() === 0 && d.getMinutes() === 0) { return Gneiss.dateParsers.Mdd(d); } if(Date.getLocale().code == 'en') { return d.format('{12hr}:{mm}{tt}'); } else { return d.format('{24hr}:{mm}{tt}'); } }, "QJan": function(d) { var year = d.getFullYear(); var month = d.getMonth() + 1; var day = d.getDate(); if (day == 1) { if (month == 1) { return year; } if (month == 4 || month == 7 || month == 10) { return "Q" + (((month-1) / 3) + 1); } } return ""; }, "QJul": function(d) { var year = d.getFullYear(); var month = d.getMonth() + 1; var day = d.getDate(); if (day == 1) { if (month == 7) { return year; } if (month == 1) { return "Q3"; } if (month == 4) { return "Q4"; } if (month == 10) { return "Q2"; } } return ""; } }; Gneiss.helper = { multiextent: function(a, key) { // Find the min and max values of multiple arrays var data = []; var ext; for (var i = a.length - 1; i >= 0; i--) { ext = d3.extent(key ? key(a[i]) : a[i]); data.push(ext[0]); data.push(ext[1]); } return d3.extent(data); }, columnXandHeight: function(d, domain) { //a function to find the proper value to cut off a column if(d > 0 && domain[0] > 0) { return domain[0]; } else if (d < 0 && domain[1] < 0) { return domain[1]; } return 0; }, exactTicks: function(domain,numticks) { numticks -= 1; var ticks = []; var delta = domain[1] - domain[0]; for (var i=0; i < numticks; i++) { ticks.push(domain[0] + (delta/numticks)*i); } ticks.push(domain[1]); if(domain[1]*domain[0] < 0) { //if the domain crosses zero, make sure there is a zero line var hasZero = false; for (var i = ticks.length - 1; i >= 0; i--) { //check if there is already a zero line if(ticks[i] == 0) { hasZero = true; } } if(!hasZero) { ticks.push(0); } } return ticks; }, transformCoordOf: function(elem){ var separator = elem.attr("transform").indexOf(",") > -1 ? "," : " "; var trans = elem.attr("transform").split(separator); return { x: (trans[0] ? parseFloat(trans[0].split("(")[1]) : 0), y: (trans[1] ? parseFloat(trans[1].split(")")[0] ): 0) }; } }; function Gneiss(config) { var containerElement; var chartElement; var titleElement; var footerElement; var sourceElement; var creditElement; var defaultPadding; var containerId; var svgId; var seriesByType; var width; var height; var isBargrid; var hasColumns = false; var title; var sourceLine; var creditLine; var legend; var colors; var xAxis; var yAxis; var series; var xAxisRef; var lineDotsThreshold; var dotRadius; var bargridLabelMargin; var bargridBarThickness; var xAxisMargin; var footerMargin; var primaryAxisPosition; var legendLabelSpacingX; var legendLabelSpacingY; var columnGap; var maxColumnWidth; var titleBottomMargin; var bargridLabelBottomMargin; var axisBarGap; var allowAxisOverlap; var columnWidth; var columnGroupWidth; var columnGroupShift; this.containerId = function Gneiss$containerId(elem) { if (!arguments.length) { return containerId; } containerId = elem; }; this.svgId = function Gneiss$svgId(elem) { if (!arguments.length) { return svgId; } svgId = elem; }; this.containerElement = function Gneiss$containerElement(elem) { if (!arguments.length) { return containerElement; } containerElement = elem; }; this.footerElement = function Gneiss$footerElement(elem) { if (!arguments.length) { return footerElement; } footerElement = elem; }; this.sourceElement = function Gneiss$sourceElement(elem) { if (!arguments.length) { return sourceElement; } sourceElement = elem; }; this.creditElement = function Gneiss$creditElement(elem) { if (!arguments.length) { return creditElement; } creditElement = elem; }; this.defaultPadding = function Gneiss$defaultPadding(p) { if (!arguments.length) { return defaultPadding; } defaultPadding = p; }; this.padding = function Gneiss$padding(p) { if (!arguments.length) { return padding; } padding = p; }; this.width = function Gneiss$width(w) { if (!arguments.length) { return width; } width = w; }; this.height = function Gneiss$height(h) { if (!arguments.length) { return height; } height = h; }; this.seriesByType = function Gneiss$seriesByType(sbt) { if (!arguments.length) { return seriesByType; } seriesByType = sbt; }; this.isBargrid = function Gneiss$isBargrid(b) { if (!arguments.length) { return isBargrid; } isBargrid = b; }; this.title = function Gneiss$title(t) { if (!arguments.length) { return title; } title = t; }; this.titleElement = function Gneiss$titleElement(elem) { if (!arguments.length) { return titleElement; } titleElement = elem; }; this.source = function Gneiss$sourceLineText(s) { if (!arguments.length) { return source; } source = s; }; this.credit = function Gneiss$credit(c) { if (!arguments.length) { return credit; } credit = c; }; this.legend = function Gneiss$legend(l) { if (!arguments.length) { return legend; } legend = l; }; this.colors = function Gneiss$colors(c) { if (!arguments.length) { return colors; } colors = c; }; this.chartElement = function Gneiss$chartElement(c) { if (!arguments.length) { return chartElement; } chartElement = c; }; this.xAxis = function Gneiss$xAxis(x) { if (!arguments.length) { return xAxis; } xAxis = x; }; this.xAxisRef = function Gneiss$xAxisRef(x) { if (!arguments.length) { return xAxisRef; } xAxisRef = x; }; this.yAxis = function Gneiss$yAxis(y) { if (!arguments.length) { return yAxis; } yAxis = y; }; this.series = function Gneiss$series(s) { if (!arguments.length) { return series; } series = s; }; this.columnWidth = function Gneiss$columnWidth(w) { if (!arguments.length) { return columnWidth; } columnWidth = w; }; this.columnGroupWidth = function Gneiss$columnGroupWidth(w) { if (!arguments.length) { return columnGroupWidth; } columnGroupWidth = w; }; this.columnGroupShift = function Gneiss$columnGroupShift(w) { if (!arguments.length) { return columnGroupShift; } columnGroupShift = w; }; this.lineDotsThreshold = function Gneiss$lineDotsThreshold(n) { if (!arguments.length) { return lineDotsThreshold; } lineDotsThreshold = n; }; this.dotRadius = function Gneiss$dotRadius(n) { if (!arguments.length) { return dotRadius; } dotRadius = n; }; this.bargridLabelMargin = function Gneiss$bargridLabelMargin(n) { if (!arguments.length) { return bargridLabelMargin; } bargridLabelMargin = n; }; this.bargridBarThickness = function Gneiss$bargridBarThickness(n) { if (!arguments.length) { return bargridBarThickness; } bargridBarThickness = n; }; this.xAxisMargin = function Gneiss$xAxisMargin(n) { if (!arguments.length) { return xAxisMargin; } xAxisMargin = n; }; this.footerMargin = function Gneiss$footerMargin(n) { if (!arguments.length) { return footerMargin; } footerMargin = n; }; this.primaryAxisPosition = function Gneiss$primaryAxisPosition(n) { if (!arguments.length) { return primaryAxisPosition; } primaryAxisPosition = n; }; this.legendLabelSpacingX = function Gneiss$legendLabelSpacingX(n) { if (!arguments.length) { return legendLabelSpacingX; } legendLabelSpacingX = n; }; this.legendLabelSpacingY = function Gneiss$legendLabelSpacingY(n) { if (!arguments.length) { return legendLabelSpacingY; } legendLabelSpacingY = n; }; this.columnGap = function Gneiss$columnGap(n) { if (!arguments.length) { return columnGap; } columnGap = n; }; this.maxColumnWidth = function Gneiss$maxColumnWidth(n) { if (!arguments.length) { return maxColumnWidth; } maxColumnWidth = n; }; this.titleBottomMargin = function Gneiss$titleBottomMargin(n) { if (!arguments.length) { return titleBottomMargin; } titleBottomMargin = n; }; this.bargridLabelBottomMargin = function Gneiss$bargridLabelBottomMargin(n) { if (!arguments.length) { return bargridLabelBottomMargin; } bargridLabelBottomMargin = n; }; this.axisBarGap = function Gneiss$axisBarGap(n) { if(!arguments.length) { return axisBarGap; } axisBarGap = n; }; this.allowAxisOverlap = function Gneiss$allowAxisOverlap(b) { if(!arguments.length) { return allowAxisOverlap; } allowAxisOverlap = b; }; this.hasColumns = function Gneiss$hasColumns(b) { if(!arguments.length) { return hasColumns; } hasColumns = b; }; this.build = function Gneiss$build(config) { /* Initializes the chart from a config object */ if(!config) { throw new Error("build() must be called with a chart configuration"); } var g = this; // Set container as a jQuery object wrapping the DOM element specified in the config if(!config.container) { throw new Error("build() must be called with a chart configuration with a 'container' property"); } // Deep copy the config data to prevent side effects g.containerId(config.container.slice()); g.svgId(config.svg_place.slice()); g.containerElement( $(g.containerId() )); g.title(config.title.slice()); g.source(config.sourceline.slice()); g.credit(config.creditline.slice()); g.legend(config.legend === true ? true : false); g.colors($.extend(true, [], config.colors)); g.xAxis($.extend(true, {}, config.xAxis)); g.xAxisRef($.extend(true, [], config.xAxisRef)); g.yAxis($.extend(true, [], config.yAxis)); g.series($.extend(true, [], config.series)); g.defaultPadding($.extend(true, {}, config.padding)); g.padding($.extend(true, {}, config.padding)); g.lineDotsThreshold(config.lineDotsThreshold *1); g.dotRadius(config.dotRadius *1); g.bargridLabelMargin(config.bargridLabelMargin *1); g.bargridBarThickness(config.bargridBarThickness *1); g.xAxisMargin(config.xAxisMargin * 1); g.footerMargin(config.footerMargin * 1); g.primaryAxisPosition(config.primaryAxisPosition.slice()); g.legendLabelSpacingX(config.legendLabelSpacingX *1); g.legendLabelSpacingY(config.legendLabelSpacingY * 1); g.columnGap(config.columnGap * 1); g.maxColumnWidth(config.maxColumnWidth * 1); g.titleBottomMargin(config.titleBottomMargin * 1); g.bargridLabelBottomMargin(config.bargridLabelBottomMargin *1); g.axisBarGap(config.axisBarGap * 1); g.allowAxisOverlap(config.allowAxisOverlap); /*var zoom = d3.behavior.zoom() .scaleExtent([1, 10]) .on("zoom", zoomed); var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on("dragstart", dragstarted) .on("drag", dragged) .on("dragend", dragended);*/ //append svg to container using svg g.chartElement(d3.select(g.containerId()).select(g.svgId()).append("svg") .attr("id", "chart") .attr("width","100%") //set width to 100% .attr("height","100%")); //.call(zoom)); //set height to 100% $(function() { panZoomInstance = svgPanZoom("#chart", { zoomEnabled: true, //controlIconsEnabled: true, fit: true, center: true, minZoom: 0.5 }); // zoom out panZoomInstance.zoom(1) }) g.width(g.containerElement().width()-100); //save the width in pixels g.height(g.containerElement().height()-100); //save the height in pixels //add rect, use as a background to prevent transparency g.chartElement().append("rect") .attr("id","ground") .attr("width", g.width()) .attr("height", g.height()); //add a rect to allow for styling of the chart area g.chartElement().append("rect") .attr("id","plotArea") .attr("width", g.width()) .attr("height", g.height()); //group the series by their type g.seriesByType(this.splitSeriesByType(g.series())); this.updateGraphPropertiesBasedOnSeriesType(g, g.seriesByType()); g.titleElement(g.chartElement().append("text") .attr("y",18) .attr("x", g.padding().left) .attr("id","titleLine") .text(g.title())); this.calculateColumnWidths() .setYScales() .setXScales() .setYAxes(true) .setXAxis(true); this.drawSeriesAndLegend(true); g.footerElement(g.chartElement().append("g") .attr("id", "metaInfo") .attr("transform", "translate(0," + (g.height() - g.footerMargin()) + ")")); g.sourceElement(g.footerElement().append("text") .attr("text-anchor", "end") .attr("x", g.width() - g.padding().right) .attr("class", "metaText") .text(g.source())); g.creditElement(g.footerElement().append("text") .attr("x", g.padding().left) .attr("class", "metaText") .text(g.credit())); /*function zoomed() { svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); } function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", true); } function dragged(d) { d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y); } function dragended(d) { d3.select(this).classed("dragging", false); }*/ return this; }; this.numberFormat = d3.format(","); this.resize = function Gneiss$resize(){ /* Adjusts the size dependent stored variables */ var g = this; // Save the width and height in pixels g.width(g.containerElement().width()); g.height(g.containerElement().height()); // Insert a background rectangle to prevent transparency d3.select("rect#ground") .attr("width", g.width()) .attr("height", g.height()); //insert a background rectagle to style the plot area d3.select("rect#plotArea") .attr("transform","translate("+g.padding().left+","+g.padding().top+")") .attr("width",g.width()-g.padding().left-g.padding().right) .attr("height",g.height()-g.padding().top-g.padding().bottom); g.footerElement().attr("transform","translate(0," + (g.height() - g.footerMargin()) + ")"); return this; }; this.setYScales = function Gneiss$setYScales() { /* * Calculate and store the left and right y-axis scale information */ var g = this; var y = g.yAxis(); var p = g.padding(); var series = g.series() var calculatedDomain for (var i = series.length - 1; i >= 0; i--) { // Plot this series against the right y-axis if no axis has been defined yet if(series[i].axis === undefined) { series[i].axis = 0; } // This useLowestValueInAllSeries flag changes the independence // of the y-axii significantly. // // Setting it to true means that the extents for the right y-axis // use the smallest number in any series that will be graphed on either // axis, regardless of whether or not the series containing that value // is graphed against the right y-axis or not. // // Setting it to false results in completely independent axii such that // the extents are determined only by the values in the series charted // against the axis in question. The right y-axis extents will be // dependent only on series graphed against the right y-axis. var useLowestValueInAllSeries = false; if(y[i]) { calculatedDomain = Gneiss.helper.multiextent(g.series(), function(a) { if(a.axis === i || (useLowestValueInAllSeries && i == 0)) { // This series is charted against this axis // OR // This is the right y-axis and it should be rooted at // the lowest value in any series regardless of axis return a.data; } return []; }) for (var j = y[i].domain.length - 1; j >= 0; j--) { if(y[i].domain[j] === null) { // only use the calculated domain limit if one isn't specified y[i].domain[j] = calculatedDomain[j]; } } if(g.isBargrid()) { y[i].domain[0] = Math.min(y[i].domain[0], 0); } } } //set extremes in y axis objects and create scales for (var i = y.length - 1; i >= 0; i--){ if(!y[i].scale) { y[i].scale = d3.scale.linear(); } y[i].scale.domain(y[i].domain); } if(g.isBargrid()) { var width = (g.width() / g.seriesByType().bargrid.length) - p.right; for (var i = y.length - 1; i >= 0; i--) { y[i].scale.range([p.left, width]).nice(); } } else { for (var i = y.length - 1; i >= 0; i--) { y[i].scale.range([g.height() - p.bottom, p.top]).nice(); } } return this; }; this.setPadding = function Gneiss$setPadding() { /* calulates and stores the proper amount of extra padding beyond what the user specified (to account for axes, titles, legends, meta) */ var g = this, padding_top = g.defaultPadding().top, padding_bottom = g.defaultPadding().bottom, padding_left = g.defaultPadding().left, padding_right = g.defaultPadding().right; //Add the height of the title line to the padding, if the title line has a height //Add the height of the axis label if there is no title title_height = g.titleElement()[0][0].getBoundingClientRect().height; axis_label_height = d3.selectAll(".yAxis text")[0][0].getBoundingClientRect().height; padding_top += title_height > 0? title_height + g.titleBottomMargin() : axis_label_height + g.titleBottomMargin(); //if there is more than one axis or the default axis is on the left and it isn't a bar grid //add enough space for the top axis label padding_top += ( g.yAxis().length > 1 || g.primaryAxisPosition == "left" ) ? axis_label_height + g.titleBottomMargin() : 0 ; //if there is a legend and there is more than one series padding_top += (g.legend() && g.series().length > 1 ) ? g.legendLabelSpacingY() : 0 ; //if there is a legend and there is more than one series and a title and it's not a bargrid try { padding_top += ( g.legend() && g.series().length > 1 && g.title().length != 0 && !g.isBargrid() ) ? d3.selectAll("g.legendItem")[0][0].getBoundingClientRect().height : 0 ; }catch(e){/* this happens when switching from a bargrid back to a standard chart*/} //if this is a bargrid add padding to account for the series label if (g.isBargrid()) { try { padding_top += d3.selectAll(".bargridLabel")[0][0].getBoundingClientRect().height + g.bargridLabelBottomMargin() - g.bargridBarThickness()/2; } catch(e) {/* A race condition that doesn't matter was met, setPadding will be called again and everything will be okay*/} try { padding_top += g.titleElement().text().length != 0 ? title_height + g.titleBottomMargin() : 0 } catch(e) {/* A race condition that doesn't matter was met, setPadding will be called again and everything will be okay*/} } g.padding().top = padding_top; g.padding().bottom = padding_bottom; return this; }; this.setXScales = function Gneiss$setXScales() { /* * Calculate and store the x-axis scale information */ var g = this; var x = g.xAxis(); var data = g.xAxisRef()[0].data; var p = g.padding(); // Calculate extremes of x-axis if(x.type == "date") { var dateExtent = d3.extent(data); // Create a linear scale with date keys between the input start and end dates x.scale = d3.time.scale().domain(dateExtent); } else { // Create a ordinal scale with with row name keys x.scale = d3.scale.ordinal().domain(data); } // Set the range of the x-axis var rangeArray = []; var left; var right; if(g.isBargrid()) { rangeArray = [p.top, g.height() - p.bottom]; } else if(g.hasColumns()) { var halfColumnWidth = g.columnGroupWidth() / 2; left = p.left + halfColumnWidth + ((g.yAxis().length == 1) ? 0 : d3.selectAll("#leftAxis.yAxis g:not(.topAxisItem) text")[0].pop().getBoundingClientRect().width + g.axisBarGap()); right = g.width() - p.right - d3.selectAll("#rightAxis.yAxis g:not(.topAxisItem) text")[0].pop().getBoundingClientRect().width - halfColumnWidth - g.axisBarGap(); rangeArray = [left,right]; } else if(!g.allowAxisOverlap()) { try { left = p.left + ((g.yAxis().length == 1) ? 0 : d3.selectAll("#leftAxis.yAxis g:not(.topAxisItem) text")[0].pop().getBoundingClientRect().width); right = g.width() - p.right - d3.selectAll("#rightAxis.yAxis g:not(.topAxisItem) text")[0].pop().getBoundingClientRect().width - g.dotRadius(); rangeArray = [left,right]; } catch(e){ //the this happens when the axis hasn't been created yet rangeArray = [p.left, g.width() - p.right]; } } else { rangeArray = [p.left, g.width() - p.right]; } if(x.type == "date") { x.scale.range(rangeArray); } else { //defaults to ordinal x.scale.rangePoints(rangeArray); } return this; }; this.setLineMakers = function Gneiss$setLineMakers(first) { var g = this; for (var i = g.yAxis().length - 1; i >= 0; i--){ if(first || !g.yAxis()[i].line) { g.yAxis()[i].line = d3.svg.line(); } g.yAxis()[i].line.y(function(d,j){ return d || d === 0 ? g.yAxis()[yAxisIndex].scale(d) : null }); g.yAxis()[i].line.x(function(d,j){ return d || d === 0 ? g.xAxis().scale(g.xAxisRef()[0].data[j]) : null }); } return this; }; this.setYAxes = function Gneiss$setYAxes(first) { /* * * Y-Axis Drawing Section * */ var g = this; var curAxis; var axisGroup; //CHANGE if(g.yAxis().length == 1 ){ d3.select("#leftAxis").remove(); } for (var i = g.yAxis().length - 1; i >= 0; i--){ curAxis = g.yAxis()[i]; //create svg axis if(first || !g.yAxis()[i].axis) { curAxis.axis = d3.svg.axis() .scale(g.yAxis()[i].scale) .orient(i == 0 ? "right" : "left" ) .tickSize(g.width() - g.padding().left - g.padding().right) //.ticks(g.yAxis()[0].ticks) // I'm not using built in ticks because it is too opinionated .tickValues(g.yAxis()[i].tickValues?curAxis.tickValues:Gneiss.helper.exactTicks(curAxis.scale.domain(),g.yAxis()[0].ticks)) //append axis container axisGroup = g.chartElement().append("g") .attr("class","axis yAxis") .attr("id",i == 0 ? "rightAxis" : "leftAxis" ) .attr("transform",i == 0 ? "translate("+g.padding().left+",0)" : "translate("+( g.width()-g.padding().right)+",0)" ) .call(curAxis.axis); } else { curAxis.axis//.ticks(`)[0].ticks) // I'm not using built in ticks because it is too opinionated .tickValues(curAxis.tickValues?curAxis.tickValues:Gneiss.helper.exactTicks(curAxis.scale.domain(),g.yAxis()[0].ticks)); axisGroup = g.chartElement().selectAll(i == 0 ? "#rightAxis" : "#leftAxis") .call(curAxis.axis); } //adjust label position and add prefix and suffix var topAxisLabel, minY = Infinity; this.customYAxisFormat(axisGroup, i); axisGroup .selectAll("g") .each(function(d,j) { //create an object to store axisItem info var axisItem = { "item": d3.select(this).classed("topAxisItem",false) }; //store the position of the topAxisItem //(figure it out by parsing the transfrom attribute) axisItem.y = parseFloat(axisItem.item .attr("transform") .split(")")[0] .split(",")[1] ); //store the text element of the axisItem axisItem.text = d3.select(this).select("text"); //store the line element of the axisItem axisItem.line = d3.select(this).select("line") .attr("stroke","#E6E6E6"); //apply the prefix as appropriate switch(curAxis.prefix.use) { case "all": //if the prefix is supposed to be on every axisItem label, put it there axisItem.text.text(curAxis.prefix.value + axisItem.text.text()); break; case "positive": //if the prefix is supposed to be on positive values and it's positive, put it there if(parseFloat(axisItem.text.text()) > 0) { axisItem.text.text(curAxis.prefix.value + axisItem.text.text()); } break; case "negative": //if the prefix is supposed to be on negative values and it's negative, put it there if(parseFloat(axisItem.text.text()) < 0) { axisItem.text.text(curAxis.prefix.value + axisItem.text.text()); } break; case "top": //do nothing break; } //apply the suffix as appropriate switch(curAxis.suffix.use) { case "all": //if the suffix is supposed to be on every axisItem label, put it there axisItem.text.text(axisItem.text.text() + curAxis.suffix.value); break; case "positive": //if the suffix is supposed to be on positive values and it's positive, put it there if(parseFloat(axisItem.text.text()) > 0) { axisItem.text.text(axisItem.text.text() + curAxis.suffix.value); } break; case "negative": //if the suffix is supposed to be on negative values and it's negative, put it there if(parseFloat(axisItem.text.text()) < 0) { axisItem.text.text(axisItem.text.text() + curAxis.suffix.value); } break; case "top": //do nothing break; } //find the top most axisItem //store its text element if(axisItem.y < minY) { topAxisLabel = axisItem.text; g.topAxisItem = axisItem; minY = axisItem.y; } if(parseFloat( axisItem.text.text() ) == 0) { if(d == 0) { //if the axisItem represents the zero line //change it's class and make sure there's no decimal d3.select(this).classed("zero", true); axisItem.text.text("0"); } else { // A non-zero value was rounded into a zero // hide the whole group d3.select(this).style("display","none"); } } }); //class the top label as top g.topAxisItem.item.classed("topAxisItem",true); //add the prefix and suffix to the top most label as appropriate if(curAxis.suffix.use == "top" && curAxis.prefix.use == "top") { //both preifx and suffix should be added to the top most label if(topAxisLabel) { topAxisLabel.text(g.yAxis()[i].prefix.value + topAxisLabel.text() + g.yAxis()[i].suffix.value); } else { } } else if (curAxis.suffix.use == "top") { //only the suffix should be added (Because the prefix is already there) topAxisLabel.text(topAxisLabel.text() + g.yAxis()[i].suffix.value); } else if(curAxis.prefix.use == "top") { //only the prefix should be added (Because the suffix is already there) topAxisLabel.text(g.yAxis()[i].prefix.value + topAxisLabel.text()); } } try{ //the title will always be the same distance from the top, and will always be the top most element g.titleElement().attr("y",g.defaultPadding().top + g.titleElement()[0][0].getBoundingClientRect().height); }catch(e){/* There isn't a title element and I dont care to let you know */} if(g.isBargrid()){ //if it's a bargrid turn off the yAxis d3.selectAll(".yAxis").style("display","none"); } else { //isn't a bargrid so set the yAxis back to the default display prop d3.selectAll(".yAxis").style("display",null); } d3.selectAll(".yAxis").each(function(){this.parentNode.prependChild(this);}); d3.selectAll("#plotArea").each(function(){this.parentNode.prependChild(this);}); d3.selectAll("#ground").each(function(){this.parentNode.prependChild(this);}); return this; }; this.customYAxisFormat = function Gneiss$customYAxisFormat(axisGroup, i) { var g = this; axisGroup.selectAll("g") .each(function(d,j) { //create an object to store axisItem info var axisItem = {}; //store the position of the axisItem //(figure it out by parsing the transfrom attribute) axisItem.y = parseFloat(d3.select(this) .attr("transform") .split(")")[0] .split(",")[1] ); //store the text element of the axisItem //align the text right position it on top of the line axisItem.text = d3.select(this).select("text") .attr("text-anchor",i == 0 ? "end" : "start") .attr("fill",i==0 ? "#666666" : g.yAxis()[i].color) .attr("x",function(){var elemx = Number(d3.select(this).attr("x")); return i == 0 ? elemx-3 : elemx+3; }) //CHANGE - MAGIC NUMBER (maybe?) .attr("y",-9); }); }; this.setXAxis = function Gneiss$setXAxis(first) { var g = this; if(first) { /* * * X-Axis Drawing Section * */ g.xAxis().axis = d3.svg.axis() .scale(g.xAxis().scale) .orient(g.isBargrid() ? "left" : "bottom") .tickFormat(g.xAxis().formatter ? Gneiss.dateParsers[g.xAxis().formatter] : function(d) {return d;}) .ticks(g.xAxis().ticks); if(g.xAxis().type == "date") { if(g.xAxis().ticks === null || !isNaN(g.xAxis().ticks)) { //auto suggest the propper tick gap var timeSpan = g.xAxis().scale.domain()[1]-g.xAxis().scale.domain()[0], months = timeSpan/2592000000, years = timeSpan/31536000000, days = timeSpan/86400000; if(years > 30) { yearGap = 10; } if(years > 15) { yearGap = 5; } else { yearGap = 1; } if(days > 2) { hourGap = 6; } else if (days > 1) { hourGap = 4; } else { hourGap = 1; } switch(g.xAxis().formatter) { case "yy": g.xAxis().axis.ticks(d3.time.years,yearGap); break; case "yyyy": g.xAxis().axis.ticks(d3.time.years,yearGap); break; case "MM": g.xAxis().axis.ticks(d3.time.months,1); break; case "M": g.xAxis().axis.ticks(d3.time.months,1); break; case "YY": g.xAxis().axis.ticks(d3.time.years,1); break; case "QJan": g.xAxis().axis.ticks(d3.time.months,3); break; case "QJul": g.xAxis().axis.ticks(d3.time.months,3); break; case "hmm": g.xAxis().axis.ticks(d3.time.hour,hourGap) break } } else if(g.xAxis().ticks instanceof Array) { //use the specified tick gap var gap, gapString = g.xAxis().ticks[1], num = parseInt(g.xAxis().ticks[0]); if((/hour/i).text(gapString)) { gap = d3.time.hour } if((/day/i).test(gapString)) { gap = d3.time.hour; } else if((/week/i).test(gapString)) { gap = d3.time.day; } else if((/month/i).test(gapString)) { gap = d3.time.months; } else if((/year/i).test(gapString)) { gap = d3.time.years; } g.xAxis().axis.ticks(gap,num); } else { throw new Error("xAxis.ticks set to invalid date format"); } } g.chartElement().append("g") .attr("class",'axis') .attr("id","xAxis") .attr("transform",g.isBargrid() ? "translate(" + g.padding().left + ",0)" : "translate(0," + (g.height() - g.padding().bottom + g.xAxisMargin()) + ")") .call(g.xAxis().axis); } else { //not first g.xAxis().axis.scale(g.xAxis().scale) .tickFormat(g.xAxis().formatter ? Gneiss.dateParsers[g.xAxis().formatter] : function(d) { return d; }) .ticks(g.isBargrid() ? g.series()[0].data.length : g.xAxis().ticks) .orient(g.isBargrid() ? "left" : "bottom"); if(g.xAxis().type == "date") { if(g.xAxis().ticks === null || !isNaN(g.xAxis().ticks)) { //auto suggest the propper tick gap var timeSpan = g.xAxis().scale.domain()[1]-g.xAxis().scale.domain()[0], months = timeSpan/2592000000, years = timeSpan/31536000000, days = timeSpan/86400000, hours = timeSpan/3600000, minutes = timeSpan/60000; if(years > 30) { yearGap = 10; } if(years > 15) { yearGap = 5; } else { yearGap = 1; } if(days > 2) { hourGap = 6; } else if (days >= 1) { hourGap = 4; } else if (hours > 7) { hourGap = 4; } else if (hours > 1){ hourGap = 1; } console.log(hours, hourGap); switch(g.xAxis().formatter) { case "yy": g.xAxis().axis.ticks(d3.time.years,yearGap); break; case "yyyy": g.xAxis().axis.ticks(d3.time.years,yearGap); break; case "MM": g.xAxis().axis.ticks(d3.time.months,1); break; case "M": g.xAxis().axis.ticks(d3.time.months,1); break; case "YY": g.xAxis().axis.ticks(d3.time.years,1); break; case "QJan": g.xAxis().axis.ticks(d3.time.months,3); break; case "QJul": g.xAxis().axis.ticks(d3.time.months,3); break; case "hmm": g.xAxis().axis.ticks(d3.time.hours,hourGap); break } } else if(g.xAxis().ticks instanceof Array) { var gap; var gapString = g.xAxis().ticks[1]; var num = parseInt(g.xAxis().ticks[0],10); if( (/hour/i).test(gapString) ) { gap = d3.time.hours; } else if((/day/i).test(gapString)) { gap = d3.time.days; } else if((/week/i).test(gapString)) { gap = d3.time.weeks; } else if((/month/i).test(gapString)) { gap = d3.time.months; } else if((/year/i).test(gapString)) { gap = d3.time.years; } g.xAxis().axis.ticks(gap,num); } else { throw new Error("xAxis.ticks set to invalid date format"); } } g.chartElement().selectAll("#xAxis") .attr("transform",g.isBargrid() ? "translate(" + g.padding().left + ",0)" : "translate(0," + (g.height() - g.padding().bottom + g.xAxisMargin()) + ")") .call(g.xAxis().axis); } g.chartElement().selectAll("#xAxis text") .attr("text-anchor", g.xAxis().type == "date" ? (g.seriesByType().column.length>0 && g.seriesByType().line.length == 0 && g.seriesByType().scatter.length == 0 ? "middle" : "start"): (g.isBargrid() ? "end" : "middle")) //.attr("text-anchor", g.isBargrid ? "end":"middle") .each(function() { var pwidth = this.parentNode.getBoundingClientRect().width var attr = this.parentNode.getAttribute("transform") var attrx = Number(attr.split("(")[1].split(",")[0]) var attry = Number(attr.split(")")[0].split(",")[1]) if(!g.isBargrid()) { // fix labels to not fall off edge when not bargrid if (pwidth + attrx > g.width()) { this.setAttribute("x",Number(this.getAttribute("x"))-(pwidth + attrx - g.width() + g.padding().right)) this.setAttribute("text-anchor","start") } else if (attrx - pwidth < 0) { this.setAttribute("text-anchor","start") } g.padding().left = g.defaultPadding().left } else { //adjust padding for bargrid if(g.padding().left - pwidth < g.defaultPadding().left) { g.padding().left = pwidth + g.defaultPadding().left; g.redraw() //CHANGE (maybe) } } }); return this; }; this.calculateColumnWidths = function Gneiss$calculateColumnWidths() { /* * Calculate the proper width for columns in column charts */ var g = this; var x = g.xAxis(); var data = g.xAxisRef()[0].data; var numColumnSeries = g.seriesByType().column.length; if(numColumnSeries === 0) { return this; } var numDataPoints = 0; // Calculate the number of data points based on x-axis extents if(x.type == "date") { var dateExtent = d3.extent(data); // Calculate smallest gap between two dates (in ms) var shortestPeriod = Infinity; for (var i = data.length - 2; i >= 0; i--) { shortestPeriod = Math.min(shortestPeriod, Math.abs(data[i] - data[i+1])); } numDataPoints = Math.abs(Math.floor((dateExtent[0] - dateExtent[1]) / shortestPeriod)); } else { var series = g.series(); for (var i = series.length - 1; i >= 0; i--) { numDataPoints = Math.max(numDataPoints, series[i].data.length); }; } // Determine the proper column width var effectiveChartWidth = g.width() - g.padding().right - g.padding().left - g.axisBarGap(); var columnWidth = Math.floor((effectiveChartWidth / numDataPoints) / numColumnSeries); columnWidth = columnWidth - g.columnGap() // Make sure the columns are at least a pixel wide columnWidth = Math.max(columnWidth, 1); // Make sure columns are not wider than the specified portion of the available width columnWidth = Math.min(columnWidth, effectiveChartWidth * g.maxColumnWidth()/100); g.columnWidth(columnWidth); g.columnGroupWidth((columnWidth + g.columnGap()) * numColumnSeries); g.columnGroupShift(columnWidth + g.columnGap()); return this; }; this.drawSeriesAndLegend = function Gneiss$drawSeriesAndLegend(first){ this.drawSeries(first); this.drawLegend(); return this; }; this.drawSeries = function Gneiss$drawSeries(first) { /* * * Series Drawing Section * */ var g = this; //construct line maker Gneiss.helper functions for each yAxis this.setLineMakers(first); //store split by type for convenience var sbt = g.seriesByType(); var colors = g.colors(); var columnWidth = g.columnWidth(); var columnGroupShift = g.columnGroupShift(); var lineSeries; if(first) { //create a group to contain series g.seriesContainer = g.chartElement().append("g") .attr("id","seriesContainer"); lineSeries = g.seriesContainer.selectAll("path"); columnSeries = g.seriesContainer.selectAll("g.seriesColumn"); var columnGroups; var columnRects; var lineSeriesDots = g.seriesContainer.selectAll("g.lineSeriesDots"); var scatterSeries = g.seriesContainer.selectAll("g.seriesScatter"); //create a group to contain the legend items g.legendItemContainer = g.chartElement().append("g") .attr("id","legendItemContainer"); //add columns to chart columnGroups = columnSeries.data(sbt.column) .enter() .append("g") .attr("class","seriesColumn seriesGroup") .attr("fill",function(d,i){return d.color? d.color : colors[i+sbt.line.length]}) .attr("transform",function(d,i){return "translate("+(i*columnGroupShift - (columnGroupShift * (sbt.column.length-1)/2))+",0)"}) columnGroups.selectAll("rect") .data(function(d,i){return d.data}) .enter() .append("rect") .attr("width",columnWidth) .attr("height", function(d,i) {yAxisIndex = d3.select(this.parentNode).data()[0].axis; return Math.abs(g.yAxis()[yAxisIndex].scale(d)-g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain())))}) .attr("x", function(d,i) { return g.xAxis().scale(g.xAxisRef()[0].data[i]) - columnWidth/2 }) .attr("y",function(d,i) {yAxisIndex = d3.select(this.parentNode).data()[0].axis; return (g.yAxis()[yAxisIndex].scale(d)-g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain()))) >= 0 ? g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain())) : g.yAxis()[yAxisIndex].scale(d)}) //add lines to chart lineSeries.data(sbt.line) .enter() .append("path") .attr("d",function(d,j) { yAxisIndex = d.axis; pathString = g.yAxis()[d.axis].line(d.data).split("L0,0").join("M").split("L0,0").join(""); return pathString.indexOf("NaN")==-1?pathString:"M0,0"}) .attr("class","seriesLine seriesGroup") .attr("stroke",function(d,i){return d.color? d.color : colors[i]}) lineSeriesDotGroups = lineSeriesDots.data(sbt.line) .enter() .append("g") .attr("class","lineSeriesDots seriesGroup") .attr("fill", function(d,i){return d.color? d.color : colors[i]}) lineSeriesDotGroups .filter(function(d){return d.data.length < g.lineDotsThreshold()}) .selectAll("circle") .data(function(d){ return d.data}) .enter() .append("circle") .attr("r",g.dotRadius()) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; return "translate("+(g.xAxis().type=="date" ? g.xAxis().scale(g.xAxisRef()[0].data[i]): g.xAxis().scale(i)) + "," + g.yAxis()[yAxisIndex].scale(d) + ")" }) //add scatter to chart scatterGroups = scatterSeries.data(sbt.scatter) .enter() .append("g") .attr("class","seriesScatter seriesGroup") .attr("fill", function(d,i){return d.color? d.color : colors[i]}) scatterDots = scatterGroups .selectAll("circle") .data(function(d){ return d.data}) scatterDots.enter() .append("circle") .attr("r",g.dotRadius()) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; return "translate("+(g.xAxis().type=="date" ? g.xAxis().scale(g.xAxisRef()[0].data[i]): g.xAxis().scale(i)) + "," + g.yAxis()[yAxisIndex].scale(d) + ")" }) } else { //update don't create lineSeries = g.seriesContainer.selectAll("path"); columnSeries = g.seriesContainer.selectAll("g.seriesColumn") scatterSeries = g.seriesContainer.selectAll("g.seriesScatter") lineSeriesDotGroups = g.seriesContainer.selectAll("g.lineSeriesDots") var columnGroups var columnRects if(g.isBargrid()) { //add bars to chart columnGroups = g.seriesContainer.selectAll("g.seriesColumn") .data(sbt.bargrid) .attr("fill",function(d,i){return d.color? d.color : colors[i+sbt.line.length]}) var seriesColumns = columnGroups.enter() .append("g") .attr("class","seriesColumn") .attr("fill",function(d,i){return d.color? d.color : colors[i+g.series().length]}) .attr("transform",function(d,i){return "translate(0," + g.padding().top + ")"}); var bargridLabel = columnGroups.selectAll("text.bargridLabel") .data(function(d,i){return [d]}) .text(function(d,i){return d.name}) bargridLabel.enter() .append("text") .text(function(d,i){return d.name}) .attr("class","bargridLabel") bargridLabel.transition() .attr("x",g.yAxis()[0].scale(0)) .attr("y",function(d){ var y = g.defaultPadding().top + d3.select(this)[0][0].getBoundingClientRect().height //if there is a title bumb the series labels down y += g.titleElement().text().length > 0 ? g.titleElement()[0][0].getBoundingClientRect().height + g.titleBottomMargin(): 0; return y }) .text(function(d,i){return d.name}) //update the text in case it changed without new data bargridLabel.exit().remove() columnSeries.transition() .duration(500) .attr("transform",function(d,i){return "translate("+(i * ( g.width()-g.padding().left)/g.series().length)+",0)"}) columnGroups.exit().remove() columnRects = columnGroups.selectAll("rect") .data(function(d,i){return d.data}) columnRects.enter() .append("rect") .attr("height", g.bargridBarThickness()) .attr("width", function(d,i) { yAxisIndex = d3.select(this.parentNode).data()[0].axis; return Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(0)) }) .attr("x", function(d,i) { yAxisIndex = d3.select(this.parentNode).data()[0].axis; return g.yAxis()[yAxisIndex].scale(0) - (d<0?Math.abs(g.yAxis()[yAxisIndex].scale(d)):0) }) .attr("y",function(d,i) { return g.xAxis().scale(g.xAxisRef()[0].data[i]) - g.bargridBarThickness()/2 }) columnRects.transition() .duration(500) .attr("height", g.bargridBarThickness()) .attr("width", function(d,i) { yAxisIndex = d3.select(this.parentNode).data()[0].axis; return Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(0)) }) .attr("x", function(d,i) { yAxisIndex = d3.select(this.parentNode).data()[0].axis; return g.yAxis()[yAxisIndex].scale(0) - (d<0?Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(0)):0) }) .attr("y",function(d,i) { return g.xAxis().scale(g.xAxisRef()[0].data[i]) - g.bargridBarThickness()/2 }) //add label to each bar var barLabels = columnGroups.selectAll("text.barLabel") .data(function(d,i){return d.data}); barLabels.enter() .append("text") .attr("class","barLabel") //update the text in each label //if it's the top label add the prefix and suffix barLabels.text(function(d,i){ var yAxisIndex = d3.select(this.parentNode).data()[0].axis; var output = g.numberFormat(d); if((i==0 && g.yAxis()[yAxisIndex].prefix.use == "top") || g.yAxis()[yAxisIndex].prefix.use == "all") { output = g.yAxis()[yAxisIndex].prefix.value + output; } else if (g.yAxis()[yAxisIndex].prefix.use == "positive" && d > 0){ output = g.yAxis()[yAxisIndex].prefix.value + output; } else if (g.yAxis()[yAxisIndex].prefix.use == "top" && i == 0) { output = g.yAxis()[yAxisIndex].prefix.value + output; } if((i==0 && g.yAxis()[yAxisIndex].suffix.use == "top") || g.yAxis()[yAxisIndex].suffix.use == "all") { output += g.yAxis()[yAxisIndex].suffix.value; } else if (g.yAxis()[yAxisIndex].suffix.use == "positive" && d > 0){ output += g.yAxis()[yAxisIndex].suffix.value; } else if (g.yAxis()[yAxisIndex].suffix.use == "top" && i == 0) { output += g.yAxis()[yAxisIndex].suffix.value; } return output; }) //reset the padding to the default before mucking with it in the label postitioning g.padding.right = g.defaultPadding().right barLabels.transition() .attr("x", function(d,i) { var yAxisIndex = d3.select(this.parentNode).data()[0].axis, x = g.bargridLabelMargin() + g.yAxis()[yAxisIndex].scale(0) - (d<0?Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(0)):0) + Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(0)), bbox = this.getBBox() parentCoords = Gneiss.helper.transformCoordOf(d3.select(this.parentNode)) if (x + bbox.width + parentCoords.x > g.width()) { //the label will fall off the edge and thus the chart needs more padding if(bbox.width + g.defaultPadding().right < (g.width()-g.padding().left)/g.series.length) { //add more padding if there is room for it g.padding().right = bbox.width + g.defaultPadding().right g.redraw() } } else if (x + bbox.width + parentCoords.x < g.width() - 20){ //if there is too much left over space (typically caused by deleting a prefix or suffix) reset the padding g.padding().right = g.defaultPadding().right; g.redraw } return x }) .attr("y",function(d,i) {return g.xAxis().scale(g.xAxisRef()[0].data[i]) + d3.select(this)[0][0].getBoundingClientRect().height/4}) //remove non bargrid stuff scatterSeries.remove() columnRects.exit().remove() lineSeriesDotGroups.remove() lineSeries.remove() } else { //Not a bargrid //add columns to chart columnGroups = g.seriesContainer.selectAll("g.seriesColumn") .data(sbt.column) .attr("fill",function(d,i){return d.color? d.color : colors[i+sbt.line.length]}) //remove bar labels columnGroups.selectAll("text.barLabel").remove() //remove bargrid labels columnGroups.selectAll("text.bargridLabel").remove() columnGroups.enter() .append("g") .attr("class","seriesColumn") .attr("fill",function(d,i){return d.color? d.color : colors[i+sbt.line.length]}) .attr("transform",function(d,i){return "translate("+(i*columnGroupShift - (columnGroupShift * (sbt.column.length-1)/2))+",0)"}) columnSeries.transition() .duration(500) .attr("transform",function(d,i){return "translate("+(i*columnGroupShift - (columnGroupShift * (sbt.column.length-1)/2))+",0)"}) columnGroups.exit().remove() columnRects = columnGroups.selectAll("rect") .data(function(d,i){return d.data}) columnRects.enter() .append("rect") columnRects.transition() .duration(500) .attr("width",columnWidth) .attr("height", function(d,i) {yAxisIndex = d3.select(this.parentNode).data()[0].axis; return Math.abs(g.yAxis()[yAxisIndex].scale(d) - g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain())))}) .attr("x",g.xAxis().type =="date" ? function(d,i) {return g.xAxis().scale(g.xAxisRef()[0].data[i]) - columnWidth/2}: function(d,i) {return g.xAxis().scale(i) - columnWidth/2} ) .attr("y",function(d,i) {yAxisIndex = d3.select(this.parentNode).data()[0].axis; return (g.yAxis()[yAxisIndex].scale(d)-g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain()))) >= 0 ? g.yAxis()[yAxisIndex].scale(Gneiss.helper.columnXandHeight(d,g.yAxis()[yAxisIndex].scale.domain())) : g.yAxis()[yAxisIndex].scale(d)}) columnRects.exit().remove() //add lines lineSeries = g.seriesContainer.selectAll("path") .data(sbt.line) .attr("stroke",function(d,i){return d.color? d.color : colors[i]}); lineSeries.enter() .append("path") .attr("d",function(d,j) { yAxisIndex = d.axis; pathString = g.yAxis()[d.axis].line(d.data).split("L0,0L").join("M0,0M").split("L0,0").join(""); return pathString;}) .attr("class","seriesLine") .attr("stroke",function(d,i){return d.color? d.color : colors[i]}) lineSeries.transition() .duration(500) .attr("d",function(d,j) { yAxisIndex = d.axis; pathString = g.yAxis()[d.axis].line(d.data).split("L0,0L").join("M0,0M").split("L0,0").join(""); return pathString;}) lineSeries.exit().remove() //Add dots to the appropriate line series lineSeriesDotGroups = g.seriesContainer.selectAll("g.lineSeriesDots") .data(sbt.line) .attr("fill",function(d,i){return d.color? d.color : colors[i]}) lineSeriesDotGroups .enter() .append("g") .attr("class","lineSeriesDots") .attr("fill", function(d,i){return d.color? d.color : colors[i]}) lineSeriesDotGroups.exit().remove() lineSeriesDots = lineSeriesDotGroups.filter(function(d){return d.data.length < g.lineDotsThreshold()}) .selectAll("circle") .data(function(d,i){return d.data}) lineSeriesDotGroups.filter(function(d){return d.data.length >= g.lineDotsThreshold()}) .remove() lineSeriesDots.enter() .append("circle") .attr("r",g.dotRadius()) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; var y = d || d ===0 ? g.yAxis()[yAxisIndex].scale(d) : -100; return "translate("+ g.xAxis().scale(g.xAxisRef()[0].data[i]) + "," + y + ")"; }) lineSeriesDots.transition() .duration(500) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; var y = d || d ===0 ? g.yAxis()[yAxisIndex].scale(d) : -100; return "translate("+ g.xAxis().scale(g.xAxisRef()[0].data[i]) + "," + y + ")"; }) lineSeriesDots.exit().remove() //add scatter scatterGroups = g.seriesContainer.selectAll("g.seriesScatter") .data(sbt.scatter) .attr("fill", function(d,i){return d.color? d.color : colors[i]}) scatterGroups.enter() .append("g") .attr("class","seriesScatter") .attr("fill",function(d,i){return d.color? d.color : colors[i+sbt.line.length+sbt.column.length]}) scatterGroups.exit().remove() scatterDots = scatterGroups .selectAll("circle") .data(function(d){return d.data}) scatterDots.enter() .append("circle") .attr("r",g.dotRadius()) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; return "translate("+g.xAxis().scale(g.xAxisRef()[0].data[i]) + "," + g.yAxis()[yAxisIndex].scale(d) + ")" }) scatterDots.transition() .duration(500) .attr("transform",function(d,i){ yAxisIndex = d3.select(this.parentNode).data()[0].axis; return "translate("+g.xAxis().scale(g.xAxisRef()[0].data[i]) + "," + g.yAxis()[yAxisIndex].scale(d) + ")" }) } } //arrange elements in proper order //bring bars to front if(sbt.column.length > 0) { columnGroups.each(function(){if(this.parentNode){this.parentNode.appendChild(this);}}) columnSeries.each(function(){if(this.parentNode){this.parentNode.appendChild(this);}}) } //bring lines to front if(sbt.line.length > 0){ lineSeries.each(function(){if(this.parentNode){this.parentNode.appendChild(this);}}) //bring dots to front lineSeriesDotGroups.each(function(){if(this.parentNode){this.parentNode.appendChild(this);}}) } //bring scatter to front if(sbt.scatter.length > 0) { scatterGroups.each(function(){this.parentNode.appendChild(this);}) scatterDots.each(function(){this.parentNode.appendChild(this);}) } return this; }; this.drawLegend = function Gneiss$drawLegend() { var g = this; var legendItemY; var colors = g.colors(); //remove current legends g.legendItemContainer.selectAll("g.legendItem").remove() if(!g.isBargrid()) { //add legend to chart var legendGroups = g.legendItemContainer.selectAll("g") .data(g.series()); var legItems = legendGroups.enter() .append("g") .attr("class","legendItem") .attr("transform","translate("+g.padding().left+","+(g.defaultPadding().top + g.titleElement()[0][0].getBoundingClientRect().height) +")"); legendGroups.exit().remove() var legLabels = legItems.append("text") .filter(function(){return g.series().length > 1}) .attr("class","legendLabel") .attr("x",12) .attr("y",18) .attr("fill",function(d,i){return d.color? d.color : colors[i]}) .text(function(d,i){return d.name}); //if there is more than one line if(g.series().length > 1) { legItems.append("rect") .attr("width",10) .attr("height",10) .attr("x",0) .attr("y",8) .attr("fill", function(d,i){return d.color? d.color : colors[i]}) legendGroups.filter(function(d){return d != g.series()[0]}) .attr("transform",function(d,i) { //label isn't for the first series var prev = d3.select(legendGroups[0][i]); var prevWidth = parseFloat(prev.node().getBoundingClientRect().width); var prevCoords = Gneiss.helper.transformCoordOf(prev); var cur = d3.select(this); var curBoundingRect = cur.node().getBoundingClientRect(); var curWidth = parseFloat(curBoundingRect.width); var curCoords = Gneiss.helper.transformCoordOf(cur); var curHeight = parseFloat(curBoundingRect.height) legendItemY = prevCoords.y; var x = prevCoords.x + prevWidth + g.legendLabelSpacingX(); if(x + curWidth > g.width()) { x = g.padding().left; legendItemY += curHeight + g.legendLabelSpacingY(); } return "translate("+x+","+legendItemY+")"; }) } else { //not bargrid } } return this; }; this.updateMetaAndTitle = function Gneiss$updateMetaAndTitle() { var g = this; g.footerElement().attr("transform","translate(0," + (g.height() - g.footerMargin()) + ")"); return this; }; this.splitSeriesByType = function Gneiss$splitSeriesByType(series) { /* Partition the data by the way it is supposed to be displayed */ var seriesByType = { "line": [], "column": [], "bargrid": [], "scatter": [] }; for (var i = 0; i < series.length; i++) { seriesByType[series[i].type].push(series[i]); } return seriesByType; }; this.updateGraphPropertiesBasedOnSeriesType = function Gneiss$updateGraphPropertiesBasedOnSeriesType(graph, seriesByType) { /* Update graph properties based on the type of data series displayed */ graph.hasColumns(seriesByType.column.length > 0); graph.isBargrid(seriesByType.bargrid.length > 0); }; this.redraw = function Gneiss$redraw() { /* Redraw the chart */ //group the series by their type this.seriesByType(this.splitSeriesByType(this.series())); this.updateGraphPropertiesBasedOnSeriesType(this, this.seriesByType()); this.calculateColumnWidths() this.setPadding() .setYScales() .setXScales() .setYAxes() .setXAxis() .drawSeriesAndLegend() .updateMetaAndTitle(); return this; }; // Call build() when someone attempts to construct a new Gneiss object return this.build(config); }
/** * auth.js * * Functions for making api calls for authentication */ 'use strict'; /* jslint browser: true */ var lib = require('../lib'), // I have no idea why this shouldn't be '../lib' request = require('superagent'); var url = 'http://localhost:3000/'; module.exports = { register: function register(data, cb) { request .post(url + 'auth/register') .send(data) .end(lib.respond(cb)); }, login: function register(data, cb) { request .post(url + 'auth/login') .send(data) .end(lib.respond(cb)); }, };
/* //Event Listeners //this is the imperative version of the program //Create DIV element var div = document.createElement('DIV'); //Set height of element div.style.height = "100vh"; //Append Element to DOM document.body.appendChild(div); //Add Event listener to Element. Moving the mouse sends an event to the callback function. // Example of asynchronous programming because events are not at regular intervals. div.addEventListener('mousemove', function(event) { console.log(event); var x = event.clientX; var y = event.clientY; div.textContent = x + ', ' + y; div.style.backgroundColor = 'rgb(' +x+ ','+y+ ', 50)'; }); */ //This is the functional version of the program //Event Listeners //A funtion to create element to be passed to the event listener function fullScreen(element) { var newElement = document.createElement(element); //Set height of element newElement.style.height = "100vh"; //append element to the DOM document.body.appendChild(newElement); return newElement; } function input(inputType,DOMElement,callback) { DOMElement.addEventListener(inputType, function(event) { var x = event.clientX; var y = event.clientY; callback(DOMElement, x, y); }); } function output(element, x, y) { element.textContent = x + ', ' + y; element.style.backgroundColor = 'rgb(' +x+ ','+y+ ', 150)'; } //Connect parts together and instantiate(call)the input function. input('mousemove', fullScreen('DIV'), output)
// Common Webpack configuration used by webpack.config.development and webpack.config.production const path = require('path'); const webpack = require('webpack'); const webpackConfig = require('../utils/webpack-config')(); const helpers = require('../utils/helpers'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const isDevServer = helpers.isWebpackDevServer(); const environment = helpers.getEnvironment(); module.exports = function () { return { entry: webpackConfig.entryPoints, resolve: { extensions: ['.jsx', '.js', '.json'], modules: [ helpers.getAbsolutePath('node_modules') ] }, output: { publicPath: '/' }, module: { loaders: [{ test: /\.(js|jsx)$/, exclude: /(node_modules|bower_components|webfont.config.js)/, use: { loader: 'babel-loader' } }, { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url-loader', query: { limit: 8192, name: 'images/[name].[ext]?[hash]' } }] }, plugins: [ new CleanWebpackPlugin([ 'dist' ], { root: helpers.getAbsolutePath('/') }), new webpack.DefinePlugin({ isDevServer, "process.env": { NODE_ENV: JSON.stringify(environment) } }) ] }; };
/* * Globalize Culture tg-Cyrl-TJ * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "tg-Cyrl-TJ", "default", { name: "tg-Cyrl-TJ", englishName: "Tajik (Cyrillic, Tajikistan)", nativeName: "Тоҷикӣ (Тоҷикистон)", language: "tg-Cyrl", numberFormat: { ",": " ", ".": ",", groupSizes: [3,0], negativeInfinity: "-бесконечность", positiveInfinity: "бесконечность", percent: { pattern: ["-n%","n%"], groupSizes: [3,0], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], groupSizes: [3,0], ",": " ", ".": ";", symbol: "т.р." } }, calendars: { standard: { "/": ".", days: { names: ["Яш","Душанбе","Сешанбе","Чоршанбе","Панҷшанбе","Ҷумъа","Шанбе"], namesAbbr: ["Яш","Дш","Сш","Чш","Пш","Ҷм","Шн"], namesShort: ["Яш","Дш","Сш","Чш","Пш","Ҷм","Шн"] }, months: { names: ["Январ","Феврал","Март","Апрел","Май","Июн","Июл","Август","Сентябр","Октябр","Ноябр","Декабр",""], namesAbbr: ["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек",""] }, monthsGenitive: { names: ["январи","феврали","марти","апрели","маи","июни","июли","августи","сентябри","октябри","ноябри","декабри",""], namesAbbr: ["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yy", D: "d MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d MMMM yyyy H:mm", F: "d MMMM yyyy H:mm:ss", Y: "MMMM yyyy" } } } }); }( this ));
function addvalueToAutoComplete(elementID,autocompleteName,parmName,checked){ var src=$("#"+autocompleteName).autocomplete('option','source'); src=addvalueToSrc(elementID,parmName,src); $("#"+autocompleteName).autocomplete('option','source',src); } function addvalueToSrc(elementID,parmName,src,checked){ if(!parmName)parmName=elementID; if(!checked)checked=false; src+="&"; var re = new RegExp("\&"+parmName+"\=.*?\&","g"); src=src.replace(re,"&"); if (!checked) src += parmName + "=" + escapestr($("#" + elementID).val()); else src+=parmName+"="+$("#"+elementID).prop("checked"); return src; } function htmlEncode(value) { return $('<div/>').text(value).html(); } function htmlDecode(value) { return $('<div/>').html(value).text(); } function escapestr(str) { //return htmlEncode(str); str = encodeURIComponent(str); //str=str.replace(new RegExp('\\+','g'),'%2B'); //str=str.replace(new RegExp('\\/','g'),'%2F'); //str = str.replace(new RegExp('%20', 'g'), '+'); str = encodeURIComponent(str); return str; }
require.config({ urlArgs: 'cb=' + Math.random(), packages: [{ name: 'streamhub-backbone', location: 'lib/streamhub-backbone' },{ name: 'streamhub-slidesjs', location: '.' }], paths: { jquery: 'lib/jquery/jquery', underscore: 'lib/underscore/underscore', backbone: 'lib/backbone/backbone', mustache: 'lib/mustache/mustache', isotope: 'lib/isotope/jquery.isotope', text: 'lib/requirejs-text/text', jasmine: 'lib/jasmine/lib/jasmine-core/jasmine', 'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html', 'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery', slidesjs: 'lib/slidesjs-bower/source/slides.jquery', fyre: 'http://zor.t402.livefyre.com/wjs/v3.0/javascripts/livefyre' }, shim: { jasmine: { exports: 'jasmine' }, slidesjs: { deps: ['jquery'], }, 'jasmine-html': { deps: ['jasmine'], exports: 'jasmine' }, 'jasmine-jquery': { deps: ['jquery', 'jasmine'] }, fyre: { exports: 'fyre' }, backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, underscore: { exports: '_' } } });
describe('date parser', function() { var dateParser; beforeEach(module('ui.bootstrap.dateparser')); beforeEach(inject(function (uibDateParser) { dateParser = uibDateParser; })); function expectParse(input, format, date) { expect(dateParser.parse(input, format)).toEqual(date); } describe('with custom formats', function() { it('should work correctly for `dd`, `MM`, `yyyy`', function() { expectParse('17.11.2013', 'dd.MM.yyyy', new Date(2013, 10, 17, 0)); expectParse('31.12.2013', 'dd.MM.yyyy', new Date(2013, 11, 31, 0)); expectParse('08-03-1991', 'dd-MM-yyyy', new Date(1991, 2, 8, 0)); expectParse('03/05/1980', 'MM/dd/yyyy', new Date(1980, 2, 5, 0)); expectParse('10.01/1983', 'dd.MM/yyyy', new Date(1983, 0, 10, 0)); expectParse('11-09-1980', 'MM-dd-yyyy', new Date(1980, 10, 9, 0)); expectParse('2011/02/05', 'yyyy/MM/dd', new Date(2011, 1, 5, 0)); }); it('should work correctly for `yy`', function() { expectParse('17.11.13', 'dd.MM.yy', new Date(2013, 10, 17, 0)); expectParse('02-05-11', 'dd-MM-yy', new Date(2011, 4, 2, 0)); expectParse('02/05/80', 'MM/dd/yy', new Date(2080, 1, 5, 0)); expectParse('55/02/05', 'yy/MM/dd', new Date(2055, 1, 5, 0)); expectParse('11-08-13', 'dd-MM-yy', new Date(2013, 7, 11, 0)); }); it('should work correctly for `M`', function() { expectParse('8/11/2013', 'M/dd/yyyy', new Date(2013, 7, 11, 0)); expectParse('07.11.05', 'dd.M.yy', new Date(2005, 10, 7, 0)); expectParse('02-5-11', 'dd-M-yy', new Date(2011, 4, 2, 0)); expectParse('2/05/1980', 'M/dd/yyyy', new Date(1980, 1, 5, 0)); expectParse('1955/2/05', 'yyyy/M/dd', new Date(1955, 1, 5, 0)); expectParse('02-5-11', 'dd-M-yy', new Date(2011, 4, 2, 0)); }); it('should work correctly for `MMM`', function() { expectParse('30.Sep.10', 'dd.MMM.yy', new Date(2010, 8, 30, 0)); expectParse('02-May-11', 'dd-MMM-yy', new Date(2011, 4, 2, 0)); expectParse('Feb/05/1980', 'MMM/dd/yyyy', new Date(1980, 1, 5, 0)); expectParse('1955/Feb/05', 'yyyy/MMM/dd', new Date(1955, 1, 5, 0)); }); it('should work correctly for `MMMM`', function() { expectParse('17.November.13', 'dd.MMMM.yy', new Date(2013, 10, 17, 0)); expectParse('05-March-1980', 'dd-MMMM-yyyy', new Date(1980, 2, 5, 0)); expectParse('February/05/1980', 'MMMM/dd/yyyy', new Date(1980, 1, 5, 0)); expectParse('1949/December/20', 'yyyy/MMMM/dd', new Date(1949, 11, 20, 0)); }); it('should work correctly for `d`', function() { expectParse('17.November.13', 'd.MMMM.yy', new Date(2013, 10, 17, 0)); expectParse('8-March-1991', 'd-MMMM-yyyy', new Date(1991, 2, 8, 0)); expectParse('February/5/1980', 'MMMM/d/yyyy', new Date(1980, 1, 5, 0)); expectParse('1955/February/5', 'yyyy/MMMM/d', new Date(1955, 1, 5, 0)); expectParse('11-08-13', 'd-MM-yy', new Date(2013, 7, 11, 0)); }); it('should work correctly for `HH`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.HH', new Date(2015, 2, 22, 22)); expectParse('8-March-1991-11', 'd-MMMM-yyyy-HH', new Date(1991, 2, 8, 11)); expectParse('February/5/1980/00', 'MMMM/d/yyyy/HH', new Date(1980, 1, 5, 0)); expectParse('1955/February/5 03', 'yyyy/MMMM/d HH', new Date(1955, 1, 5, 3)); expectParse('11-08-13 23', 'd-MM-yy HH', new Date(2013, 7, 11, 23)); }); it('should work correctly for `hh`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.hh', undefined); expectParse('22.March.15.12', 'd.MMMM.yy.hh', new Date(2015, 2, 22, 12)); expectParse('8-March-1991-11', 'd-MMMM-yyyy-hh', new Date(1991, 2, 8, 11)); expectParse('February/5/1980/00', 'MMMM/d/yyyy/hh', new Date(1980, 1, 5, 0)); expectParse('1955/February/5 03', 'yyyy/MMMM/d hh', new Date(1955, 1, 5, 3)); expectParse('11-08-13 23', 'd-MM-yy hh', undefined); expectParse('11-08-13 09', 'd-MM-yy hh', new Date(2013, 7, 11, 9)); }); it('should work correctly for `H`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.H', new Date(2015, 2, 22, 22)); expectParse('8-March-1991-11', 'd-MMMM-yyyy-H', new Date(1991, 2, 8, 11)); expectParse('February/5/1980/0', 'MMMM/d/yyyy/H', new Date(1980, 1, 5, 0)); expectParse('1955/February/5 3', 'yyyy/MMMM/d H', new Date(1955, 1, 5, 3)); expectParse('11-08-13 23', 'd-MM-yy H', new Date(2013, 7, 11, 23)); }); it('should work correctly for `h`', function() { expectParse('22.March.15.12', 'd.MMMM.yy.h', new Date(2015, 2, 22, 12)); expectParse('8-March-1991-11', 'd-MMMM-yyyy-h', new Date(1991, 2, 8, 11)); expectParse('February/5/1980/0', 'MMMM/d/yyyy/h', new Date(1980, 1, 5, 0)); expectParse('1955/February/5 3', 'yyyy/MMMM/d h', new Date(1955, 1, 5, 3)); expectParse('11-08-13 3', 'd-MM-yy h', new Date(2013, 7, 11, 3)); }); it('should work correctly for `mm`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.mm', new Date(2015, 2, 22, 0, 22)); expectParse('8-March-1991-59', 'd-MMMM-yyyy-mm', new Date(1991, 2, 8, 0, 59)); expectParse('February/5/1980/00', 'MMMM/d/yyyy/mm', new Date(1980, 1, 5, 0, 0)); expectParse('1955/February/5 03', 'yyyy/MMMM/d mm', new Date(1955, 1, 5, 0, 3)); expectParse('11-08-13 46', 'd-MM-yy mm', new Date(2013, 7, 11, 0, 46)); expectParse('22.March.15.22:33', 'd.MMMM.yy.HH:mm', new Date(2015, 2, 22, 22, 33)); expectParse('22.March.15.2:01', 'd.MMMM.yy.H:mm', new Date(2015, 2, 22, 2, 1)); }); it('should work correctly for `m`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.m', new Date(2015, 2, 22, 0, 22)); expectParse('8-March-1991-59', 'd-MMMM-yyyy-m', new Date(1991, 2, 8, 0, 59)); expectParse('February/5/1980/0', 'MMMM/d/yyyy/m', new Date(1980, 1, 5, 0, 0)); expectParse('1955/February/5 3', 'yyyy/MMMM/d m', new Date(1955, 1, 5, 0, 3)); expectParse('11-08-13 46', 'd-MM-yy m', new Date(2013, 7, 11, 0, 46)); expectParse('22.March.15.22:3', 'd.MMMM.yy.HH:m', new Date(2015, 2, 22, 22, 3)); expectParse('22.March.15.2:1', 'd.MMMM.yy.H:m', new Date(2015, 2, 22, 2, 1)); }); it('should work correctly for `sss`', function() { expectParse('22.March.15.123', 'd.MMMM.yy.sss', new Date(2015, 2, 22, 0, 0, 0, 123)); expectParse('8-March-1991-059', 'd-MMMM-yyyy-sss', new Date(1991, 2, 8, 0, 0, 0, 59)); expectParse('February/5/1980/000', 'MMMM/d/yyyy/sss', new Date(1980, 1, 5, 0, 0, 0)); expectParse('1955/February/5 003', 'yyyy/MMMM/d sss', new Date(1955, 1, 5, 0, 0, 0, 3)); expectParse('11-08-13 046', 'd-MM-yy sss', new Date(2013, 7, 11, 0, 0, 0, 46)); expectParse('22.March.15.22:33:044', 'd.MMMM.yy.HH:mm:sss', new Date(2015, 2, 22, 22, 33, 0, 44)); expectParse('22.March.15.0:0:001', 'd.MMMM.yy.H:m:sss', new Date(2015, 2, 22, 0, 0, 0, 1)); }); it('should work correctly for `ss`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.ss', new Date(2015, 2, 22, 0, 0, 22)); expectParse('8-March-1991-59', 'd-MMMM-yyyy-ss', new Date(1991, 2, 8, 0, 0, 59)); expectParse('February/5/1980/00', 'MMMM/d/yyyy/ss', new Date(1980, 1, 5, 0, 0, 0)); expectParse('1955/February/5 03', 'yyyy/MMMM/d ss', new Date(1955, 1, 5, 0, 0, 3)); expectParse('11-08-13 46', 'd-MM-yy ss', new Date(2013, 7, 11, 0, 0, 46)); expectParse('22.March.15.22:33:44', 'd.MMMM.yy.HH:mm:ss', new Date(2015, 2, 22, 22, 33, 44)); expectParse('22.March.15.0:0:01', 'd.MMMM.yy.H:m:ss', new Date(2015, 2, 22, 0, 0, 1)); }); it('should work correctly for `s`', function() { expectParse('22.March.15.22', 'd.MMMM.yy.s', new Date(2015, 2, 22, 0, 0, 22)); expectParse('8-March-1991-59', 'd-MMMM-yyyy-s', new Date(1991, 2, 8, 0, 0, 59)); expectParse('February/5/1980/0', 'MMMM/d/yyyy/s', new Date(1980, 1, 5, 0, 0, 0)); expectParse('1955/February/5 3', 'yyyy/MMMM/d s', new Date(1955, 1, 5, 0, 0, 3)); expectParse('11-08-13 46', 'd-MM-yy s', new Date(2013, 7, 11, 0, 0, 46)); expectParse('22.March.15.22:33:4', 'd.MMMM.yy.HH:mm:s', new Date(2015, 2, 22, 22, 33, 4)); expectParse('22.March.15.22:3:4', 'd.MMMM.yy.HH:m:s', new Date(2015, 2, 22, 22, 3, 4)); }); it('should work correctly for `a`', function() { expectParse('22.March.15.10AM', 'd.MMMM.yy.hha', new Date(2015, 2, 22, 10)); expectParse('22.March.15.10PM', 'd.MMMM.yy.hha', new Date(2015, 2, 22, 22)); expectParse('8-March-1991-11AM', 'd-MMMM-yyyy-hha', new Date(1991, 2, 8, 11)); expectParse('8-March-1991-11PM', 'd-MMMM-yyyy-hha', new Date(1991, 2, 8, 23)); expectParse('February/5/1980/12AM', 'MMMM/d/yyyy/hha', new Date(1980, 1, 5, 0)); expectParse('February/5/1980/12PM', 'MMMM/d/yyyy/hha', new Date(1980, 1, 5, 12)); expectParse('1955/February/5 03AM', 'yyyy/MMMM/d hha', new Date(1955, 1, 5, 3)); expectParse('1955/February/5 03PM', 'yyyy/MMMM/d hha', new Date(1955, 1, 5, 15)); expectParse('11-08-13 09AM', 'd-MM-yy hha', new Date(2013, 7, 11, 9)); expectParse('11-08-13 09PM', 'd-MM-yy hha', new Date(2013, 7, 11, 21)); }); }); describe('with predefined formats', function() { it('should work correctly for `shortDate`', function() { expectParse('9/3/10', 'shortDate', new Date(2010, 8, 3, 0)); }); it('should work correctly for `mediumDate`', function() { expectParse('Sep 3, 2010', 'mediumDate', new Date(2010, 8, 3, 0)); }); it('should work correctly for `longDate`', function() { expectParse('September 3, 2010', 'longDate', new Date(2010, 8, 3, 0)); }); it('should work correctly for `fullDate`', function() { expectParse('Friday, September 3, 2010', 'fullDate', new Date(2010, 8, 3, 0)); }); }); describe('with edge case', function() { it('should not work for invalid number of days in February', function() { expect(dateParser.parse('29.02.2013', 'dd.MM.yyyy')).toBeUndefined(); }); it('should not work for 0 number of days', function() { expect(dateParser.parse('00.02.2013', 'dd.MM.yyyy')).toBeUndefined(); }); it('should work for 29 days in February for leap years', function() { expectParse('29.02.2000', 'dd.MM.yyyy', new Date(2000, 1, 29, 0)); }); it('should not work for 31 days for some months', function() { expect(dateParser.parse('31-04-2013', 'dd-MM-yyyy')).toBeUndefined(); expect(dateParser.parse('November 31, 2013', 'MMMM d, yyyy')).toBeUndefined(); }); it('should work when base date is a string', function() { expect(dateParser.parse('01-02-2034', 'dd-MM-yyyy', '05-06-2078')).toEqual(new Date(2034, 1, 1)); }); it('should work when base date is an invalid date', function() { expect(dateParser.parse('30-12-2015', 'dd-MM-yyyy', new Date('foo'))).toEqual(new Date(2015, 11, 30)); }); }); it('should not parse non-string inputs', function() { expect(dateParser.parse(123456, 'dd.MM.yyyy')).toBe(123456); var date = new Date(); expect(dateParser.parse(date, 'dd.MM.yyyy')).toBe(date); }); it('should not parse if no format is specified', function() { expect(dateParser.parse('21.08.1951', '')).toBe('21.08.1951'); }); it('should reinitialize when locale changes', inject(function($locale) { spyOn(dateParser, 'init').and.callThrough(); expect($locale.id).toBe('en-us'); $locale.id = 'en-uk'; dateParser.parse('22.March.15.22', 'd.MMMM.yy.s'); expect(dateParser.init).toHaveBeenCalled(); })); });
window.Setting = Backbone.Model.extend({ idAttribute: 'name', defaults: { name: "", value: "" } }); window.SettingCollection = Backbone.Collection.extend({ url: "../api/setting", model: Setting });
// @flow import { Map } from '../MapView'; const $fragmentRefs: any = null; const $refType: any = null; const data = coordinates => ({ id: '1', coordinates, $refType, $fragmentRefs, }); const oldTown = data({ lat: 50.08566, lng: 14.4195, }); const vysehrad = data({ lat: 50.06, lng: 14.42, }); const ruzyne = data({ lat: 50.08, lng: 14.30083, }); const andel = data({ lat: 50.06841, lng: 14.40445, }); describe('MapView', () => { it('returns basic region zoomed on single result', () => { const component = new Map({ onSelectMarker: jest.fn(), selectedIndex: 0, data: [oldTown], }); expect(component.state.region).toEqual({ latitude: 50.08566, longitude: 14.4195, longitudeDelta: 0.005, latitudeDelta: 0.005, }); }); it('returns region with size of the area between for two coords', () => { const component = new Map({ onSelectMarker: jest.fn(), selectedIndex: 0, data: [oldTown, vysehrad], }); expect(component.state.region).toEqual({ latitude: 50.08566, longitude: 14.4195, latitudeDelta: 0.02565999999999491, // distance between oldTown and vysehrad longitudeDelta: 0.0005000000000006111, }); }); it('excludes extremes from region to avoid ugly heap of markers', () => { // ruzyne is excluded from region calculation as extreme const component = new Map({ onSelectMarker: jest.fn(), selectedIndex: 0, data: [oldTown, vysehrad, ruzyne, andel], }); expect(component.state.region).toEqual({ latitude: 50.08566, longitude: 14.4195, latitudeDelta: 0.02565999999999491, // distance between oldTown and vysehrad longitudeDelta: 0.015549999999999287, // distance between vysehrad and andel }); }); });
'use strict'; const _ = require('lodash'), express = require('express'), tools = require('../tools'); module.exports = (config, manager) => { const router = express.Router(); router.get('/', getScaling); router.patch('/', updateScaling); return router; //////////// function getScaling(req, res) { return res.send(config.instance.scaling); } function updateScaling(req, res) { const payload = req.body; tools.checkScalingIntegrity(payload); const scaling = config.instance.scaling, oldScaling = _.cloneDeep(scaling); _.merge(scaling, payload); if (_.isEqual(scaling, oldScaling)) { return res.sendStatus(204); } else { manager.emit('scaling:updated', scaling); return res.send(scaling); } } };
'use strict'; module.exports = function(mObjectName){ return '<tns:paramsDescribeMObject>' + '<objectName>' + mObjectName + '</objectName>' + '</tns:paramsDescribeMObject>'; };
var express = require('express') var app = express() app.get('/', function(request, response) {   response.send('Welcome to the homepage!'); }); app.get('/about', function(request, response) {   response.send('Welcome to the about page!'); }); app.get("*", function(request, response) {   response.send("404 error!"); }); app.listen(3000)
import { createDevTools} from 'redux-devtools'; import { render } from 'react-dom'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; import React from 'react' import { Provider } from 'react-redux'; const DevTools = createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' changeMonitorKey='ctrl-m'> <LogMonitor theme='tomorrow' /> <SliderMonitor keyboardEnabled /> </DockMonitor> ); export function runDevTools($ngRedux, $rootScope) { render( <Provider store={$ngRedux}> <div> <DevTools /> </div> </Provider>, document.getElementById('devTools') ); //Hack to reflect state changes when disabling/enabling actions via the monitor $ngRedux.subscribe(_ => { setTimeout($rootScope.$apply.bind($rootScope), 100); }); } export default DevTools;
( function () { var React = require( 'react' ), Main = require( './main/Main.js' ); var remote = window.require( 'remote' ); window.React = React; React.render( <Main />, document.getElementById('app') ); } )();
module.exports = [ // Singular: // 1. ich { "word": "ich", "translation": "me" }, // 2. du { "word": "du", "translation": "you" }, // 3.1 er { "word": "Jangles der Mondaffe", "translation": "Jangles the moon monkey" }, // 3.2 sie { "word": "ihre Katze Whiskers", "translation": "her cat Whiskers" }, // 3.3 es { "word": "mein Haustier Krokodil", "translation": "my pet crocodile" }, // Plural: // 1. wir { "word": "ich und mein Papagei", "translation": "me and my parrot" }, { "word": "ich und deine Mutter", "translation": "me and your mother" }, { "word": "ich und die Piraten", "translation": "me and pirates" }, // 2. ihr { "word": "ihr und mein Gefangener", "translation": "you (Pl.) and my prisoner" }, { "word": "euer Huhn und ihr", "translation": "your chicken and you (Pl.)" }, { "word": "der Bär und du", "translation": "the bear and you" }, { "word": "du und deine Eule", "translation": "you and your owl" }, // 3.1 sie/Sie { "word": "Herr Husemann und unser Roboter", "translation": "Mr. Husemann and our robot" }, { "word": "eure Affen", "translation": "your monkeys" }, { "word": "der Schäfer und seine Schafe", "translation": "sheepherder and his sheep" }, ];
/* * Angular JS Multi Select * Creates a dropdown-like button with checkboxes. * * Project started on: Tue, 14 Jan 2014 - 5:18:02 PM * Current version: 4.0.0 * * Released under the MIT License * -------------------------------------------------------------------------------- * The MIT License (MIT) * * Copyright (c) 2014 Ignatius Steven (https://github.com/isteven) * * 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. * -------------------------------------------------------------------------------- */ 'use strict' angular.module( 'isteven-multi-select', ['ng'] ).directive( 'istevenMultiSelect' , [ '$sce', '$timeout', '$templateCache', function ( $sce, $timeout, $templateCache ) { return { restrict: 'AE', scope: { // models inputModel : '=', outputModel : '=', thisLength : '=', selectLabel : '=', refreshSelect : '=', // settings based on attribute isDisabled : '=', // callbacks onClear : '&', onClose : '&', onSearchChange : '&', onItemClick : '&', onOpen : '&', onReset : '&', onSelectAll : '&', onSelectNone : '&', // i18n translation : '=' }, /* * The rest are attributes. They don't need to be parsed / binded, so we can safely access them by value. * - buttonLabel, directiveId, helperElements, itemLabel, maxLabels, orientation, selectionMode, minSearchLength, * tickProperty, disableProperty, groupProperty, searchProperty, maxHeight, outputProperties */ templateUrl: 'isteven-multi-select.htm', link: function ( $scope, element, attrs ) { $scope.backUp = []; $scope.varButtonLabel = ''; $scope.spacingProperty = ''; $scope.indexProperty = ''; $scope.orientationH = false; $scope.orientationV = true; $scope.filteredModel = []; $scope.inputLabel = { labelFilter: '' }; $scope.tabIndex = 0; $scope.lang = {}; $scope.helperStatus = { all : true, none : true, reset : true, filter : true }; var prevTabIndex = 0, helperItems = [], helperItemsLength = 0, checkBoxLayer = '', scrolled = false, selectedItems = [], formElements = [], vMinSearchLength = 0, clickedItem = null // v3.0.0 // clear button clicked $scope.clearClicked = function( e ) { $scope.inputLabel.labelFilter = ''; $scope.updateFilter(); $scope.select( 'clear', e ); } // A little hack so that AngularJS ng-repeat can loop using start and end index like a normal loop // http://stackoverflow.com/questions/16824853/way-to-ng-repeat-defined-number-of-times-instead-of-repeating-over-array $scope.numberToArray = function( num ) { return new Array( num ); } // Call this function when user type on the filter field $scope.searchChanged = function() { if ( $scope.inputLabel.labelFilter.length < vMinSearchLength && $scope.inputLabel.labelFilter.length > 0 ) { return false; } $scope.updateFilter(); } $scope.updateFilter = function() { // we check by looping from end of input-model $scope.filteredModel = []; var i = 0; if ( typeof $scope.inputModel === 'undefined' ) { return false; } for( i = $scope.inputModel.length - 1; i >= 0; i-- ) { // if it's group end, we push it to filteredModel[]; if ( typeof $scope.inputModel[ i ][ attrs.groupProperty ] !== 'undefined' && $scope.inputModel[ i ][ attrs.groupProperty ] === false ) { $scope.filteredModel.push( $scope.inputModel[ i ] ); } // if it's data var gotData = false; if ( typeof $scope.inputModel[ i ][ attrs.groupProperty ] === 'undefined' ) { // If we set the search-key attribute, we use this loop. if ( typeof attrs.searchProperty !== 'undefined' && attrs.searchProperty !== '' ) { for (var key in $scope.inputModel[ i ] ) { if ( typeof $scope.inputModel[ i ][ key ] !== 'boolean' && String( $scope.inputModel[ i ][ key ] ).toUpperCase().indexOf( $scope.inputLabel.labelFilter.toUpperCase() ) >= 0 && attrs.searchProperty.indexOf( key ) > -1 ) { gotData = true; break; } } } // if there's no search-key attribute, we use this one. Much better on performance. else { for ( var key in $scope.inputModel[ i ] ) { if ( typeof $scope.inputModel[ i ][ key ] !== 'boolean' && String( $scope.inputModel[ i ][ key ] ).toUpperCase().indexOf( $scope.inputLabel.labelFilter.toUpperCase() ) >= 0 ) { gotData = true; break; } } } if ( gotData === true ) { // push $scope.filteredModel.push( $scope.inputModel[ i ] ); } } // if it's group start if ( typeof $scope.inputModel[ i ][ attrs.groupProperty ] !== 'undefined' && $scope.inputModel[ i ][ attrs.groupProperty ] === true ) { if ( typeof $scope.filteredModel[ $scope.filteredModel.length - 1 ][ attrs.groupProperty ] !== 'undefined' && $scope.filteredModel[ $scope.filteredModel.length - 1 ][ attrs.groupProperty ] === false ) { $scope.filteredModel.pop(); } else { $scope.filteredModel.push( $scope.inputModel[ i ] ); } } } if($scope.refreshSelect && $scope.outputModel.length != 0){ $scope.filteredModel = $scope.backUp; } $scope.filteredModel.reverse(); $timeout( function() { $scope.getFormElements(); // Callback: on filter change if ( $scope.inputLabel.labelFilter.length > vMinSearchLength ) { var filterObj = []; angular.forEach( $scope.filteredModel, function( value, key ) { if ( typeof value !== 'undefined' ) { if ( typeof value[ attrs.groupProperty ] === 'undefined' ) { var tempObj = angular.copy( value ); var index = filterObj.push( tempObj ); delete filterObj[ index - 1 ][ $scope.indexProperty ]; delete filterObj[ index - 1 ][ $scope.spacingProperty ]; } } }); $scope.onSearchChange({ data: { keyword: $scope.inputLabel.labelFilter, result: filterObj } }); } },0); }; // List all the input elements. We need this for our keyboard navigation. // This function will be called everytime the filter is updated. // Depending on the size of filtered mode, might not good for performance, but oh well.. $scope.getFormElements = function() { formElements = []; var selectButtons = [], inputField = [], checkboxes = [], clearButton = []; // If available, then get select all, select none, and reset buttons if ( $scope.helperStatus.all || $scope.helperStatus.none || $scope.helperStatus.reset ) { selectButtons = element.children().children().next().children().children()[ 0 ].getElementsByTagName( 'button' ); // If available, then get the search box and the clear button if ( $scope.helperStatus.filter ) { // Get helper - search and clear button. inputField = element.children().children().next().children().children().next()[ 0 ].getElementsByTagName( 'input' ); clearButton = element.children().children().next().children().children().next()[ 0 ].getElementsByTagName( 'button' ); } } else { if ( $scope.helperStatus.filter ) { // Get helper - search and clear button. inputField = element.children().children().next().children().children()[ 0 ].getElementsByTagName( 'input' ); clearButton = element.children().children().next().children().children()[ 0 ].getElementsByTagName( 'button' ); } } // Get checkboxes if ( !$scope.helperStatus.all && !$scope.helperStatus.none && !$scope.helperStatus.reset && !$scope.helperStatus.filter ) { checkboxes = element.children().children().next()[ 0 ].getElementsByTagName( 'input' ); } else { checkboxes = element.children().children().next().children().next()[ 0 ].getElementsByTagName( 'input' ); } // Push them into global array formElements[] for ( var i = 0; i < selectButtons.length ; i++ ) { formElements.push( selectButtons[ i ] ); } for ( var i = 0; i < inputField.length ; i++ ) { formElements.push( inputField[ i ] ); } for ( var i = 0; i < clearButton.length ; i++ ) { formElements.push( clearButton[ i ] ); } for ( var i = 0; i < checkboxes.length ; i++ ) { formElements.push( checkboxes[ i ] ); } } // check if an item has attrs.groupProperty (be it true or false) $scope.isGroupMarker = function( item , type ) { if ( typeof item[ attrs.groupProperty ] !== 'undefined' && item[ attrs.groupProperty ] === type ) return true; return false; } $scope.removeGroupEndMarker = function( item ) { if ( typeof item[ attrs.groupProperty ] !== 'undefined' && item[ attrs.groupProperty ] === false ) return false; return true; } // call this function when an item is clicked $scope.syncItems = function( item, e, ng_repeat_index ) { e.preventDefault(); e.stopPropagation(); // if the directive is globaly disabled, do nothing if ( typeof attrs.disableProperty !== 'undefined' && item[ attrs.disableProperty ] === true ) { return false; } // if item is disabled, do nothing if ( typeof attrs.isDisabled !== 'undefined' && $scope.isDisabled === true ) { return false; } // if end group marker is clicked, do nothing if ( typeof item[ attrs.groupProperty ] !== 'undefined' && item[ attrs.groupProperty ] === false ) { return false; } var index = $scope.filteredModel.indexOf( item ); // if the start of group marker is clicked ( only for multiple selection! ) // how it works: // - if, in a group, there are items which are not selected, then they all will be selected // - if, in a group, all items are selected, then they all will be de-selected if ( typeof item[ attrs.groupProperty ] !== 'undefined' && item[ attrs.groupProperty ] === true ) { // this is only for multiple selection, so if selection mode is single, do nothing if ( typeof attrs.selectionMode !== 'undefined' && attrs.selectionMode.toUpperCase() === 'SINGLE' ) { return false; } var i,j,k; var startIndex = 0; var endIndex = $scope.filteredModel.length - 1; var tempArr = []; // nest level is to mark the depth of the group. // when you get into a group (start group marker), nestLevel++ // when you exit a group (end group marker), nextLevel-- var nestLevel = 0; // we loop throughout the filtered model (not whole model) for( i = index ; i < $scope.filteredModel.length ; i++) { // this break will be executed when we're done processing each group if ( nestLevel === 0 && i > index ) { break; } if ( typeof $scope.filteredModel[ i ][ attrs.groupProperty ] !== 'undefined' && $scope.filteredModel[ i ][ attrs.groupProperty ] === true ) { // To cater multi level grouping if ( tempArr.length === 0 ) { startIndex = i + 1; } nestLevel = nestLevel + 1; } // if group end else if ( typeof $scope.filteredModel[ i ][ attrs.groupProperty ] !== 'undefined' && $scope.filteredModel[ i ][ attrs.groupProperty ] === false ) { nestLevel = nestLevel - 1; // cek if all are ticked or not if ( tempArr.length > 0 && nestLevel === 0 ) { var allTicked = true; endIndex = i; for ( j = 0; j < tempArr.length ; j++ ) { if ( typeof tempArr[ j ][ $scope.tickProperty ] !== 'undefined' && tempArr[ j ][ $scope.tickProperty ] === false ) { allTicked = false; break; } } if ( allTicked === true ) { for ( j = startIndex; j <= endIndex ; j++ ) { if ( typeof $scope.filteredModel[ j ][ attrs.groupProperty ] === 'undefined' ) { if ( typeof attrs.disableProperty === 'undefined' ) { $scope.filteredModel[ j ][ $scope.tickProperty ] = false; // we refresh input model as well inputModelIndex = $scope.filteredModel[ j ][ $scope.indexProperty ]; $scope.inputModel[ inputModelIndex ][ $scope.tickProperty ] = false; } else if ( $scope.filteredModel[ j ][ attrs.disableProperty ] !== true ) { $scope.filteredModel[ j ][ $scope.tickProperty ] = false; // we refresh input model as well inputModelIndex = $scope.filteredModel[ j ][ $scope.indexProperty ]; $scope.inputModel[ inputModelIndex ][ $scope.tickProperty ] = false; } } } } else { for ( j = startIndex; j <= endIndex ; j++ ) { if ( typeof $scope.filteredModel[ j ][ attrs.groupProperty ] === 'undefined' ) { if ( typeof attrs.disableProperty === 'undefined' ) { $scope.filteredModel[ j ][ $scope.tickProperty ] = true; // we refresh input model as well inputModelIndex = $scope.filteredModel[ j ][ $scope.indexProperty ]; $scope.inputModel[ inputModelIndex ][ $scope.tickProperty ] = true; } else if ( $scope.filteredModel[ j ][ attrs.disableProperty ] !== true ) { $scope.filteredModel[ j ][ $scope.tickProperty ] = true; // we refresh input model as well inputModelIndex = $scope.filteredModel[ j ][ $scope.indexProperty ]; $scope.inputModel[ inputModelIndex ][ $scope.tickProperty ] = true; } } } } } } // if data else { tempArr.push( $scope.filteredModel[ i ] ); } } } // if an item (not group marker) is clicked else { // If it's single selection mode if ( typeof attrs.selectionMode !== 'undefined' && attrs.selectionMode.toUpperCase() === 'SINGLE' ) { // first, set everything to false for( i=0 ; i < $scope.filteredModel.length ; i++) { $scope.filteredModel[ i ][ $scope.tickProperty ] = false; } for( i=0 ; i < $scope.inputModel.length ; i++) { $scope.inputModel[ i ][ $scope.tickProperty ] = false; } // then set the clicked item to true $scope.filteredModel[ index ][ $scope.tickProperty ] = true; } // Multiple else { $scope.filteredModel[ index ][ $scope.tickProperty ] = !$scope.filteredModel[ index ][ $scope.tickProperty ]; } // we refresh input model as well var inputModelIndex = $scope.filteredModel[ index ][ $scope.indexProperty ]; $scope.inputModel[ inputModelIndex ][ $scope.tickProperty ] = $scope.filteredModel[ index ][ $scope.tickProperty ]; } // we execute the callback function here clickedItem = angular.copy( item ); if ( clickedItem !== null ) { $timeout( function() { delete clickedItem[ $scope.indexProperty ]; delete clickedItem[ $scope.spacingProperty ]; $scope.onItemClick( { data: clickedItem } ); clickedItem = null; }, 0 ); } $scope.refreshOutputModel(); $scope.refreshButton(); // We update the index here prevTabIndex = $scope.tabIndex; $scope.tabIndex = ng_repeat_index + helperItemsLength; // Set focus on the hidden checkbox e.target.focus(); // set & remove CSS style $scope.removeFocusStyle( prevTabIndex ); $scope.setFocusStyle( $scope.tabIndex ); if ( typeof attrs.selectionMode !== 'undefined' && attrs.selectionMode.toUpperCase() === 'SINGLE' ) { // on single selection mode, we then hide the checkbox layer $scope.toggleCheckboxes( e ); } } // update $scope.outputModel $scope.refreshOutputModel = function() { $scope.outputModel = []; var outputProps = [], tempObj = {}; // v4.0.0 if ( typeof attrs.outputProperties !== 'undefined' ) { outputProps = attrs.outputProperties.split(' '); angular.forEach( $scope.inputModel, function( value, key ) { if ( typeof value !== 'undefined' && typeof value[ attrs.groupProperty ] === 'undefined' && value[ $scope.tickProperty ] === true ) { tempObj = {}; angular.forEach( value, function( value1, key1 ) { if ( outputProps.indexOf( key1 ) > -1 ) { tempObj[ key1 ] = value1; } }); var index = $scope.outputModel.push( tempObj ); delete $scope.outputModel[ index - 1 ][ $scope.indexProperty ]; delete $scope.outputModel[ index - 1 ][ $scope.spacingProperty ]; } }); } else { angular.forEach( $scope.inputModel, function( value, key ) { if ( typeof value !== 'undefined' && typeof value[ attrs.groupProperty ] === 'undefined' && value[ $scope.tickProperty ] === true ) { var temp = angular.copy( value ); var index = $scope.outputModel.push( temp ); delete $scope.outputModel[ index - 1 ][ $scope.indexProperty ]; delete $scope.outputModel[ index - 1 ][ $scope.spacingProperty ]; } }); } } // refresh button label $scope.refreshButton = function() { $scope.varButtonLabel = ''; var ctr = 0; // refresh button label... if ( $scope.outputModel.length === 0 ) { // https://github.com/isteven/angular-multi-select/pull/19 $scope.varButtonLabel = $scope.lang.nothingSelected; } else { var tempMaxLabels = parseInt($scope.thisLength); if ( typeof attrs.maxLabels !== 'undefined' && attrs.maxLabels !== '' ) { tempMaxLabels = attrs.maxLabels; } // if max amount of labels displayed.. if ( $scope.outputModel.length > tempMaxLabels ) { $scope.more = true; } else { $scope.more = false; } angular.forEach( $scope.inputModel, function( value, key ) { if ( typeof value !== 'undefined' && value[ attrs.tickProperty ] === true ) { if ( ctr < tempMaxLabels ) { $scope.varButtonLabel += ( $scope.varButtonLabel.length > 0 ? '</div>, <div class="buttonLabel">' : '<div class="buttonLabel">') + $scope.writeLabel( value, 'buttonLabel' ); } ctr++; } }); if ( $scope.more === true ) { // https://github.com/isteven/angular-multi-select/pull/16 if (tempMaxLabels > 0) { $scope.varButtonLabel += ', ... '; } $scope.varButtonLabel += '(' + $scope.outputModel.length + ')'; } } $scope.varButtonLabel = $sce.trustAsHtml( $scope.varButtonLabel + '<span class="caret"></span>' ); } // Check if a checkbox is disabled or enabled. It will check the granular control (disableProperty) and global control (isDisabled) // Take note that the granular control has higher priority. $scope.itemIsDisabled = function( item ) { if ( typeof attrs.disableProperty !== 'undefined' && item[ attrs.disableProperty ] === true ) { return true; } else { if ( $scope.isDisabled === true ) { return true; } else { return false; } } } // A simple function to parse the item label settings. Used on the buttons and checkbox labels. $scope.writeLabel = function( item, type ) { // type is either 'itemLabel' or 'buttonLabel' var temp = attrs[ type ].split( ' ' ); var label = ''; angular.forEach( temp, function( value, key ) { item[ value ] && ( label += '&nbsp;' + value.split( '.' ).reduce( function( prev, current ) { return prev[ current ]; }, item )); }); if ( type.toUpperCase() === 'BUTTONLABEL' ) { return label; } return $sce.trustAsHtml( label ); } // UI operations to show/hide checkboxes based on click event.. $scope.toggleCheckboxes = function( e ) { // We grab the button var clickedEl = element.children()[0]; // Just to make sure.. had a bug where key events were recorded twice angular.element( document ).off( 'click', $scope.externalClickListener ); angular.element( document ).off( 'keydown', $scope.keyboardListener ); // The idea below was taken from another multi-select directive - https://github.com/amitava82/angular-multiselect // His version is awesome if you need a more simple multi-select approach. // close if ( angular.element( checkBoxLayer ).hasClass( 'show' )) { angular.element( checkBoxLayer ).removeClass( 'show' ); angular.element( clickedEl ).removeClass( 'buttonClicked' ); angular.element( document ).off( 'click', $scope.externalClickListener ); angular.element( document ).off( 'keydown', $scope.keyboardListener ); // clear the focused element; $scope.removeFocusStyle( $scope.tabIndex ); if ( typeof formElements[ $scope.tabIndex ] !== 'undefined' ) { formElements[ $scope.tabIndex ].blur(); } // close callback $timeout( function() { $scope.onClose(); }, 0 ); // set focus on button again element.children().children()[ 0 ].focus(); } // open else { // clear filter $scope.inputLabel.labelFilter = ''; $scope.updateFilter(); helperItems = []; helperItemsLength = 0; angular.element( checkBoxLayer ).addClass( 'show' ); angular.element( clickedEl ).addClass( 'buttonClicked' ); // Attach change event listener on the input filter. // We need this because ng-change is apparently not an event listener. angular.element( document ).on( 'click', $scope.externalClickListener ); angular.element( document ).on( 'keydown', $scope.keyboardListener ); // to get the initial tab index, depending on how many helper elements we have. // priority is to always focus it on the input filter $scope.getFormElements(); $scope.tabIndex = 0; var helperContainer = angular.element( element[ 0 ].querySelector( '.helperContainer' ) )[0]; if ( typeof helperContainer !== 'undefined' ) { for ( var i = 0; i < helperContainer.getElementsByTagName( 'BUTTON' ).length ; i++ ) { helperItems[ i ] = helperContainer.getElementsByTagName( 'BUTTON' )[ i ]; } helperItemsLength = helperItems.length + helperContainer.getElementsByTagName( 'INPUT' ).length; } // focus on the filter element on open. if ( element[ 0 ].querySelector( '.inputFilter' ) ) { element[ 0 ].querySelector( '.inputFilter' ).focus(); $scope.tabIndex = $scope.tabIndex + helperItemsLength - 2; // blur button in vain angular.element( element ).children()[ 0 ].blur(); } // if there's no filter then just focus on the first checkbox item else { if ( !$scope.isDisabled ) { $scope.tabIndex = $scope.tabIndex + helperItemsLength; if ( $scope.inputModel.length > 0 ) { formElements[ $scope.tabIndex ].focus(); $scope.setFocusStyle( $scope.tabIndex ); // blur button in vain angular.element( element ).children()[ 0 ].blur(); } } } // open callback $scope.onOpen(); } } // handle clicks outside the button / multi select layer $scope.externalClickListener = function( e ) { var targetsArr = element.find( e.target.tagName ); for (var i = 0; i < targetsArr.length; i++) { if ( e.target == targetsArr[i] ) { return; } } angular.element( checkBoxLayer.previousSibling ).removeClass( 'buttonClicked' ); angular.element( checkBoxLayer ).removeClass( 'show' ); angular.element( document ).off( 'click', $scope.externalClickListener ); angular.element( document ).off( 'keydown', $scope.keyboardListener ); // close callback $timeout( function() { $scope.onClose(); }, 0 ); // set focus on button again element.children().children()[ 0 ].focus(); } // select All / select None / reset buttons $scope.select = function( type, e ) { var helperIndex = helperItems.indexOf( e.target ); $scope.tabIndex = helperIndex; switch( type.toUpperCase() ) { case 'ALL': angular.forEach( $scope.filteredModel, function( value, key ) { if ( typeof value !== 'undefined' && value[ attrs.disableProperty ] !== true ) { if ( typeof value[ attrs.groupProperty ] === 'undefined' ) { value[ $scope.tickProperty ] = true; } } }); $scope.refreshOutputModel(); $scope.refreshButton(); $scope.onSelectAll(); break; case 'NONE': angular.forEach( $scope.filteredModel, function( value, key ) { if ( typeof value !== 'undefined' && value[ attrs.disableProperty ] !== true ) { if ( typeof value[ attrs.groupProperty ] === 'undefined' ) { value[ $scope.tickProperty ] = false; } } }); $scope.refreshOutputModel(); $scope.refreshButton(); $scope.onSelectNone(); break; case 'RESET': angular.forEach( $scope.filteredModel, function( value, key ) { if ( typeof value[ attrs.groupProperty ] === 'undefined' && typeof value !== 'undefined' && value[ attrs.disableProperty ] !== true ) { var temp = value[ $scope.indexProperty ]; value[ $scope.tickProperty ] = $scope.backUp[ temp ][ $scope.tickProperty ]; } }); $scope.refreshOutputModel(); $scope.refreshButton(); $scope.onReset(); break; case 'CLEAR': $scope.tabIndex = $scope.tabIndex + 1; $scope.onClear(); break; case 'FILTER': $scope.tabIndex = helperItems.length - 1; break; default: } } // just to create a random variable name function genRandomString( length ) { var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; var temp = ''; for( var i=0; i < length; i++ ) { temp += possible.charAt( Math.floor( Math.random() * possible.length )); } return temp; } // count leading spaces $scope.prepareGrouping = function() { var spacing = 0; angular.forEach( $scope.filteredModel, function( value, key ) { value[ $scope.spacingProperty ] = spacing; if ( value[ attrs.groupProperty ] === true ) { spacing+=2; } else if ( value[ attrs.groupProperty ] === false ) { spacing-=2; } }); } // prepare original index $scope.prepareIndex = function() { var ctr = 0; angular.forEach( $scope.filteredModel, function( value, key ) { value[ $scope.indexProperty ] = ctr; ctr++; }); } // navigate using up and down arrow $scope.keyboardListener = function( e ) { var key = e.keyCode ? e.keyCode : e.which; var isNavigationKey = false; // ESC key (close) if ( key === 27 ) { e.preventDefault(); e.stopPropagation(); $scope.toggleCheckboxes( e ); } // next element ( tab, down & right key ) else if ( key === 40 || key === 39 || ( !e.shiftKey && key == 9 ) ) { isNavigationKey = true; prevTabIndex = $scope.tabIndex; $scope.tabIndex++; if ( $scope.tabIndex > formElements.length - 1 ) { $scope.tabIndex = 0; prevTabIndex = formElements.length - 1; } while ( formElements[ $scope.tabIndex ].disabled === true ) { $scope.tabIndex++; if ( $scope.tabIndex > formElements.length - 1 ) { $scope.tabIndex = 0; } if ( $scope.tabIndex === prevTabIndex ) { break; } } } // prev element ( shift+tab, up & left key ) else if ( key === 38 || key === 37 || ( e.shiftKey && key == 9 ) ) { isNavigationKey = true; prevTabIndex = $scope.tabIndex; $scope.tabIndex--; if ( $scope.tabIndex < 0 ) { $scope.tabIndex = formElements.length - 1; prevTabIndex = 0; } while ( formElements[ $scope.tabIndex ].disabled === true ) { $scope.tabIndex--; if ( $scope.tabIndex === prevTabIndex ) { break; } if ( $scope.tabIndex < 0 ) { $scope.tabIndex = formElements.length - 1; } } } if ( isNavigationKey === true ) { e.preventDefault(); // set focus on the checkbox formElements[ $scope.tabIndex ].focus(); var actEl = document.activeElement; if ( actEl.type.toUpperCase() === 'CHECKBOX' ) { $scope.setFocusStyle( $scope.tabIndex ); $scope.removeFocusStyle( prevTabIndex ); } else { $scope.removeFocusStyle( prevTabIndex ); $scope.removeFocusStyle( helperItemsLength ); $scope.removeFocusStyle( formElements.length - 1 ); } } isNavigationKey = false; } // set (add) CSS style on selected row $scope.setFocusStyle = function( tabIndex ) { angular.element( formElements[ tabIndex ] ).parent().parent().parent().addClass( 'multiSelectFocus' ); } // remove CSS style on selected row $scope.removeFocusStyle = function( tabIndex ) { angular.element( formElements[ tabIndex ] ).parent().parent().parent().removeClass( 'multiSelectFocus' ); } /********************* ********************* * * 1) Initializations * ********************* *********************/ // attrs to $scope - attrs-$scope - attrs - $scope // Copy some properties that will be used on the template. They need to be in the $scope. $scope.groupProperty = attrs.groupProperty; $scope.tickProperty = attrs.tickProperty; $scope.directiveId = attrs.directiveId; // Unfortunately I need to add these grouping properties into the input model var tempStr = genRandomString( 5 ); $scope.indexProperty = 'idx_' + tempStr; $scope.spacingProperty = 'spc_' + tempStr; // set orientation css if ( typeof attrs.orientation !== 'undefined' ) { if ( attrs.orientation.toUpperCase() === 'HORIZONTAL' ) { $scope.orientationH = true; $scope.orientationV = false; } else { $scope.orientationH = false; $scope.orientationV = true; } } // get elements required for DOM operation checkBoxLayer = element.children().children().next()[0]; // set max-height property if provided if ( typeof attrs.maxHeight !== 'undefined' ) { var layer = element.children().children().children()[0]; angular.element( layer ).attr( "style", "height:" + attrs.maxHeight + "; overflow-y:scroll;" ); } // some flags for easier checking for ( var property in $scope.helperStatus ) { if ( $scope.helperStatus.hasOwnProperty( property )) { if ( typeof attrs.helperElements !== 'undefined' && attrs.helperElements.toUpperCase().indexOf( property.toUpperCase() ) === -1 ) { $scope.helperStatus[ property ] = false; } } } if ( typeof attrs.selectionMode !== 'undefined' && attrs.selectionMode.toUpperCase() === 'SINGLE' ) { $scope.helperStatus[ 'all' ] = false; $scope.helperStatus[ 'none' ] = false; } // helper button icons.. I guess you can use html tag here if you want to. $scope.icon = {}; $scope.icon.selectAll = '&#10003;'; // a tick icon $scope.icon.selectNone = '&times;'; // x icon $scope.icon.reset = '&#8630;'; // undo icon // this one is for the selected items $scope.icon.tickMark = '&#10003;'; // a tick icon // configurable button labels if ( typeof attrs.translation !== 'undefined' ) { $scope.lang.selectAll = $sce.trustAsHtml( $scope.icon.selectAll + '&nbsp;&nbsp;' + $scope.translation.selectAll ); $scope.lang.selectNone = $sce.trustAsHtml( $scope.icon.selectNone + '&nbsp;&nbsp;' + $scope.translation.selectNone ); $scope.lang.reset = $sce.trustAsHtml( $scope.icon.reset + '&nbsp;&nbsp;' + $scope.translation.reset ); $scope.lang.search = $scope.translation.search; $scope.lang.nothingSelected = $sce.trustAsHtml( $scope.translation.nothingSelected ); } else { $scope.lang.selectAll = $sce.trustAsHtml( $scope.icon.selectAll + '&nbsp;&nbsp;Select All' ); $scope.lang.selectNone = $sce.trustAsHtml( $scope.icon.selectNone + '&nbsp;&nbsp;Select None' ); $scope.lang.reset = $sce.trustAsHtml( $scope.icon.reset + '&nbsp;&nbsp;Reset' ); $scope.lang.search = 'Search...'; if(typeof attrs.selectLabelTitle === 'undefined'){ $scope.lang.nothingSelected = 'Select'; }else{ $scope.lang.nothingSelected = attrs.selectLabelTitle; } } $scope.icon.tickMark = $sce.trustAsHtml( $scope.icon.tickMark ); // min length of keyword to trigger the filter function if ( typeof attrs.MinSearchLength !== 'undefined' && parseInt( attrs.MinSearchLength ) > 0 ) { vMinSearchLength = Math.floor( parseInt( attrs.MinSearchLength ) ); } /******************************************************* ******************************************************* * * 2) Logic starts here, initiated by watch 1 & watch 2 * ******************************************************* *******************************************************/ // watch1, for changes in input model property // updates multi-select when user select/deselect a single checkbox programatically // https://github.com/isteven/angular-multi-select/issues/8 $scope.$watch( 'inputModel' , function( newVal ) { if ( newVal ) { $scope.refreshOutputModel(); $scope.refreshButton(); } }, true ); // watch2 for changes in input model as a whole // this on updates the multi-select when a user load a whole new input-model. We also update the $scope.backUp variable $scope.$watch( 'inputModel' , function( newVal ) { if ( newVal ) { $scope.backUp = angular.copy( $scope.inputModel ); $scope.updateFilter(); $scope.prepareGrouping(); $scope.prepareIndex(); $scope.refreshOutputModel(); $scope.refreshButton(); } }); // watch for changes in directive state (disabled or enabled) $scope.$watch( 'isDisabled' , function( newVal ) { $scope.isDisabled = newVal; }); // this is for touch enabled devices. We don't want to hide checkboxes on scroll. var onTouchStart = function( e ) { $scope.$apply( function() { $scope.scrolled = false; }); }; angular.element( document ).bind( 'touchstart', onTouchStart); var onTouchMove = function( e ) { $scope.$apply( function() { $scope.scrolled = true; }); }; angular.element( document ).bind( 'touchmove', onTouchMove); // unbind document events to prevent memory leaks $scope.$on( '$destroy', function () { angular.element( document ).unbind( 'touchstart', onTouchStart); angular.element( document ).unbind( 'touchmove', onTouchMove); }); } } }]).run( [ '$templateCache' , function( $templateCache ) { var template = '<span class="multiSelect inlineBlock" ng-class="{none: outputModel.length == 0}">' + // main button '<button id="{{directiveId}}" class="label-holder" type="button"' + 'ng-click="toggleCheckboxes( $event ); refreshSelectedItems(); refreshButton(); prepareGrouping; prepareIndex();"' + 'ng-bind-html="varButtonLabel"' + 'ng-disabled="disable-button"' + '>' + '</button>' + // overlay layer '<div class="checkboxLayer">' + // container of the helper elements '<div class="helperContainer" ng-if="helperStatus.filter || helperStatus.all || helperStatus.none || helperStatus.reset ">' + // container of the first 3 buttons, select all, none and reset '<div class="line" ng-if="helperStatus.all || helperStatus.none || helperStatus.reset ">' + // select all '<button type="button" class="helperButton"' + 'ng-disabled="isDisabled"' + 'ng-if="helperStatus.all"' + 'ng-click="select( \'all\', $event );"' + 'ng-bind-html="lang.selectAll">' + '</button>'+ // select none '<button type="button" class="helperButton"' + 'ng-disabled="isDisabled"' + 'ng-if="helperStatus.none"' + 'ng-click="select( \'none\', $event );"' + 'ng-bind-html="lang.selectNone">' + '</button>'+ // reset '<button type="button" class="helperButton reset"' + 'ng-disabled="isDisabled"' + 'ng-if="helperStatus.reset"' + 'ng-click="select( \'reset\', $event );"' + 'ng-bind-html="lang.reset">'+ '</button>' + '</div>' + // the search box '<div class="line" style="position:relative" ng-if="helperStatus.filter">'+ // textfield '<input placeholder="{{lang.search}}" type="text"' + 'ng-click="select( \'filter\', $event )" '+ 'ng-model="inputLabel.labelFilter" '+ 'ng-change="searchChanged()" class="inputFilter"'+ '/>'+ // clear button '<button type="button" class="clearButton" ng-click="clearClicked( $event )" >×</button> '+ '</div> '+ '</div> '+ // selection items '<div class="checkBoxContainer">'+ '<div '+ 'ng-repeat="item in filteredModel | filter:removeGroupEndMarker" class="multiSelectItem"'+ 'ng-class="{selected: item[ tickProperty ], horizontal: orientationH, vertical: orientationV, multiSelectGroup:item[ groupProperty ], disabled:itemIsDisabled( item )}"'+ 'ng-click="syncItems( item, $event, $index );" '+ 'ng-mouseleave="removeFocusStyle( tabIndex );"> '+ // this is the spacing for grouped items '<div class="acol" ng-if="item[ spacingProperty ] > 0" ng-repeat="i in numberToArray( item[ spacingProperty ] ) track by $index">'+ '</div> '+ '<div class="acol">'+ '<label>'+ // input, so that it can accept focus on keyboard click '<input class="checkbox focusable" type="checkbox" '+ 'ng-disabled="itemIsDisabled( item )" '+ 'ng-checked="item[ tickProperty ]" '+ 'ng-click="syncItems( item, $event, $index )" />'+ // item label using ng-bind-hteml '<span '+ 'ng-class="{disabled:itemIsDisabled( item )}" '+ 'ng-bind-html="writeLabel( item, \'itemLabel\' )">'+ '</span>'+ '</label>'+ '</div>'+ // the tick/check mark '<span class="tickMark" ng-if="item[ groupProperty ] !== true && item[ tickProperty ] === true" ng-bind-html="icon.tickMark"></span>'+ '</div>'+ '</div>'+ '</div>'+ '</span>'; $templateCache.put( 'isteven-multi-select.htm' , template ); }]);
/* JavaScript autoComplete v1.0.4 Copyright (c) 2014 Simon Steinberger / Pixabay GitHub: https://github.com/Pixabay/JavaScript-autoComplete License: http://www.opensource.org/licenses/mit-license.php Heavily edited by Adam Chyb 2016 */ var autoComplete = (function() { // "use strict"; function autoComplete(options) { if (!document.querySelector) return; // helpers function addEvent(el, type, handler) { if (el.attachEvent) el.attachEvent('on' + type, handler); else el.addEventListener(type, handler); } function removeEvent(el, type, handler) { // if (el.removeEventListener) not working in IE11 if (el.detachEvent) el.detachEvent('on' + type, handler); else el.removeEventListener(type, handler); } var o = { selector: 0, source: 0, minChars: 3, delay: 150, offsetLeft: 0, offsetTop: 1, cache: 1, menuClass: '', renderItem: function(item, search) { // escape special characters search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>'; }, clearItems: function() {}, onSelect: function(e, term, item) {}, onControlKey: function(keyCode) {} }; for (var k in options) { if (options.hasOwnProperty(k)) o[k] = options[k]; } // init var elems = typeof o.selector == 'object' ? [o.selector] : document.querySelectorAll(o.selector); for (var i = 0; i < elems.length; i++) { var that = elems[i]; that.cache = {}; that.last_val = ''; var suggest = function(val, data) { that.cache[val] = data; o.clearItems(); if (data.length && val.length >= o.minChars) { for (var i = 0; i < data.length; i++) { var item = o.renderItem(data[i], val); addEvent(item, 'click', o.onSelect); } } } that.keydownHandler = function(e) { var key = window.event ? e.keyCode : e.which; // down, up, enter if (key == 40 || key == 38 || key == 13 || key == 9) { o.onControlKey(that, key); } }; addEvent(that, 'keydown', that.keydownHandler); that.keyupHandler = function(e) { var key = window.event ? e.keyCode : e.which; if (!key || (key < 35 || key > 40) && key != 13 && key != 27) { var val = that.value; if (val.length >= o.minChars) { if (val != that.last_val) { that.last_val = val; clearTimeout(that.timer); if (o.cache) { if (val in that.cache) { suggest(val, that.cache[val]); return; } // no requests if previous suggestions were empty for (var i = 1; i < val.length - o.minChars; i++) { var part = val.slice(0, val.length - i); if (part in that.cache && !that.cache[part].length) { suggest(val, []); return; } } } that.timer = setTimeout(function() { o.source(val, suggest) }, o.delay); } } else { that.last_val = val; o.clearItems(); } } }; addEvent(that, 'keyup', that.keyupHandler); that.focusHandler = function(e) { that.last_val = '\n'; that.keyupHandler(e) }; if (!o.minChars) addEvent(that, 'focus', that.focusHandler); } // public destroy method this.destroy = function() { for (var i = 0; i < elems.length; i++) { var that = elems[i]; removeEvent(window, 'resize', that.updateSC); removeEvent(that, 'blur', that.blurHandler); removeEvent(that, 'focus', that.focusHandler); removeEvent(that, 'keydown', that.keydownHandler); removeEvent(that, 'keyup', that.keyupHandler); if (that.autocompleteAttr) that.setAttribute('autocomplete', that.autocompleteAttr); else that.removeAttribute('autocomplete'); document.body.removeChild(that.sc); that = null; } }; } return autoComplete; })(); (function() { if (typeof define === 'function' && define.amd) define('autoComplete', function() { return autoComplete; }); else if (typeof module !== 'undefined' && module.exports) module.exports = autoComplete; else window.autoComplete = autoComplete; })();
/*globals Handlebars, Metamorph:true */ /*jshint newcap:false*/ /** @module ember @submodule ember-handlebars */ import EmberHandlebars from "ember-handlebars-compiler"; // EmberHandlebars.SafeString; var SafeString = EmberHandlebars.SafeString; import Ember from "ember-metal/core"; // Ember.K var K = Ember.K; var Metamorph = requireModule('metamorph'); import EmberError from "ember-metal/error"; import { get } from "ember-metal/property_get"; import { set } from "ember-metal/property_set"; import merge from "ember-metal/merge"; import run from "ember-metal/run_loop"; import { computed } from "ember-metal/computed"; import View from "ember-views/views/view"; import { cloneStates, states } from "ember-views/views/states"; var viewStates = states; import _MetamorphView from "ember-handlebars/views/metamorph_view"; import { handlebarsGet } from "ember-handlebars/ext"; function SimpleHandlebarsView(path, pathRoot, isEscaped, templateData) { this.path = path; this.pathRoot = pathRoot; this.isEscaped = isEscaped; this.templateData = templateData; this.morph = Metamorph(); this.state = 'preRender'; this.updateId = null; this._parentView = null; this.buffer = null; } SimpleHandlebarsView.prototype = { isVirtual: true, isView: true, destroy: function () { if (this.updateId) { run.cancel(this.updateId); this.updateId = null; } if (this._parentView) { this._parentView.removeChild(this); } this.morph = null; this.state = 'destroyed'; }, propertyWillChange: K, propertyDidChange: K, normalizedValue: function() { var path = this.path, pathRoot = this.pathRoot, result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = this.templateData; result = handlebarsGet(pathRoot, path, { data: templateData }); } return result; }, renderToBuffer: function(buffer) { var string = ''; string += this.morph.startTag(); string += this.render(); string += this.morph.endTag(); buffer.push(string); }, render: function() { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = this.isEscaped; var result = this.normalizedValue(); if (result === null || result === undefined) { result = ""; } else if (!(result instanceof SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } return result; }, rerender: function() { switch(this.state) { case 'preRender': case 'destroyed': break; case 'inBuffer': throw new EmberError("Something you did tried to replace an {{expression}} before it was inserted into the DOM."); case 'hasElement': case 'inDOM': this.updateId = run.scheduleOnce('render', this, 'update'); break; } return this; }, update: function () { this.updateId = null; this.morph.html(this.render()); }, _transitionTo: function(state) { this.state = state; } }; states = cloneStates(viewStates); merge(states._default, { rerenderIfNeeded: K }); merge(states.inDOM, { rerenderIfNeeded: function(view) { if (view.normalizedValue() !== view._lastNormalizedValue) { view.rerender(); } } }); /** `Ember._HandlebarsBoundView` is a private view created by the Handlebars `{{bind}}` helpers that is used to keep track of bound properties. Every time a property is bound using a `{{mustache}}`, an anonymous subclass of `Ember._HandlebarsBoundView` is created with the appropriate sub-template and context set up. When the associated property changes, just the template for this view will re-render. @class _HandlebarsBoundView @namespace Ember @extends Ember._MetamorphView @private */ var _HandlebarsBoundView = _MetamorphView.extend({ instrumentName: 'boundHandlebars', _states: states, /** The function used to determine if the `displayTemplate` or `inverseTemplate` should be rendered. This should be a function that takes a value and returns a Boolean. @property shouldDisplayFunc @type Function @default null */ shouldDisplayFunc: null, /** Whether the template rendered by this view gets passed the context object of its parent template, or gets passed the value of retrieving `path` from the `pathRoot`. For example, this is true when using the `{{#if}}` helper, because the template inside the helper should look up properties relative to the same object as outside the block. This would be `false` when used with `{{#with foo}}` because the template should receive the object found by evaluating `foo`. @property preserveContext @type Boolean @default false */ preserveContext: false, /** If `preserveContext` is true, this is the object that will be used to render the template. @property previousContext @type Object */ previousContext: null, /** The template to render when `shouldDisplayFunc` evaluates to `true`. @property displayTemplate @type Function @default null */ displayTemplate: null, /** The template to render when `shouldDisplayFunc` evaluates to `false`. @property inverseTemplate @type Function @default null */ inverseTemplate: null, /** The path to look up on `pathRoot` that is passed to `shouldDisplayFunc` to determine which template to render. In addition, if `preserveContext` is `false,` the object at this path will be passed to the template when rendering. @property path @type String @default null */ path: null, /** The object from which the `path` will be looked up. Sometimes this is the same as the `previousContext`, but in cases where this view has been generated for paths that start with a keyword such as `view` or `controller`, the path root will be that resolved object. @property pathRoot @type Object */ pathRoot: null, normalizedValue: function() { var path = get(this, 'path'), pathRoot = get(this, 'pathRoot'), valueNormalizer = get(this, 'valueNormalizerFunc'), result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = get(this, 'templateData'); result = handlebarsGet(pathRoot, path, { data: templateData }); } return valueNormalizer ? valueNormalizer(result) : result; }, rerenderIfNeeded: function() { this.currentState.rerenderIfNeeded(this); }, /** Determines which template to invoke, sets up the correct state based on that logic, then invokes the default `Ember.View` `render` implementation. This method will first look up the `path` key on `pathRoot`, then pass that value to the `shouldDisplayFunc` function. If that returns `true,` the `displayTemplate` function will be rendered to DOM. Otherwise, `inverseTemplate`, if specified, will be rendered. For example, if this `Ember._HandlebarsBoundView` represented the `{{#with foo}}` helper, it would look up the `foo` property of its context, and `shouldDisplayFunc` would always return true. The object found by looking up `foo` would be passed to `displayTemplate`. @method render @param {Ember.RenderBuffer} buffer */ render: function(buffer) { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = get(this, 'isEscaped'); var shouldDisplay = get(this, 'shouldDisplayFunc'), preserveContext = get(this, 'preserveContext'), context = get(this, 'previousContext'); var inverseTemplate = get(this, 'inverseTemplate'), displayTemplate = get(this, 'displayTemplate'); var result = this.normalizedValue(); this._lastNormalizedValue = result; // First, test the conditional to see if we should // render the template or not. if (shouldDisplay(result)) { set(this, 'template', displayTemplate); // If we are preserving the context (for example, if this // is an #if block, call the template with the same object. if (preserveContext) { set(this, '_context', context); } else { // Otherwise, determine if this is a block bind or not. // If so, pass the specified object to the template if (displayTemplate) { set(this, '_context', result); } else { // This is not a bind block, just push the result of the // expression to the render context and return. if (result === null || result === undefined) { result = ""; } else if (!(result instanceof SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } buffer.push(result); return; } } } else if (inverseTemplate) { set(this, 'template', inverseTemplate); if (preserveContext) { set(this, '_context', context); } else { set(this, '_context', result); } } else { set(this, 'template', function() { return ''; }); } return this._super(buffer); } }); export { _HandlebarsBoundView, SimpleHandlebarsView };
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M17 4h3v16h-3zM5 14h3v6H5zm6-5h3v11h-3z" }), 'SignalCellularAlt');
/* global describe, beforeAll, afterAll, it, expect */ /* eslint prefer-arrow-callback: 0 */ 'use strict'; const Promise = require('bluebird'); const oddcast = require('oddcast'); const AWSTransport = require('../lib/oddcast-aws-transport'); const SQS_OPTIONS = { accessKeyId: '', secretAccessKey: '', region: '', QueueUrl: '', WaitTimeSeconds: null, MaxNumberOfMessages: null, pollingInterval: 1 }; const SQS_TRANSPORT = AWSTransport.sqsTransport(SQS_OPTIONS); describe('with oddcast bus', function () { const componentA = { bus: oddcast.bus(), sqs: SQS_TRANSPORT, sns: AWSTransport.snsTransport({ server: { hostname: 'localhost', port: 8001 }, sns: { accessKeyId: '', secretAccessKey: '', region: '', topicArn: '', endpoints: [ 'http://locahost:8001', 'http://locahost:8002', 'http://locahost:8003' ] } }), initialize() { // Initialize the SNS transport first. return this.sns.initialize().then(() => { // There is no need to wait for the SQS transport to initialize. this.sqs.initialize(); this.bus.commands.use({role: 'catalog'}, this.sqs); this.bus.events.use({role: 'catalog'}, this.sns); return this; }); }, close() { const sqsClosed = new Promise(resolve => { this.sqs.close(resolve); }); const snsClosed = new Promise(resolve => { this.sns.close(resolve); }); return Promise.all([sqsClosed, snsClosed]); } }; const componentB = { bus: oddcast.bus(), sqs: SQS_TRANSPORT, sns: AWSTransport.snsTransport({ server: { hostname: 'localhost', port: 8002 }, sns: { accessKeyId: '', secretAccessKey: '', region: '', topicArn: '', endpoints: [ 'http://locahost:8001', 'http://locahost:8002', 'http://locahost:8003' ] } }), payloads: [], errorEvents: [], database: {}, error: null, initialize() { this.bus.commands.on('error', err => { this.errorEvents.push(err); }); this.bus.events.on('error', err => { this.errorEvents.push(err); }); // Initialize the SNS transport first. return this.sns.initialize().then(() => { // There is no need to wait for the SQS transport to initialize. this.sqs.initialize(); this.bus.commands.use({role: 'catalog'}, this.sqs); this.bus.events.use({role: 'catalog'}, this.sns); this.bus.commandHandler( {role: 'catalog', cmd: 'setVideo'}, this.commandHandler.bind(this) ); return this; }); }, commandHandler(payload) { this.payloads.push(payload); if (!this.error && payload.errorMessage) { throw new Error(payload.errorMessage); } this.database[payload.id] = payload; }, close() { const sqsClosed = new Promise(resolve => { this.sqs.close(resolve); }); const snsClosed = new Promise(resolve => { this.sns.close(resolve); }); return Promise.all([sqsClosed, snsClosed]); } }; const componentC = { bus: oddcast.bus(), sqs: SQS_TRANSPORT, sns: AWSTransport.snsTransport({ server: { hostname: 'localhost', port: 8003 }, sns: { accessKeyId: '', secretAccessKey: '', region: '', topicArn: '', endpoints: [ 'http://locahost:8001', 'http://locahost:8002', 'http://locahost:8003' ] } }), payloads: [], errorEvents: [], database: {}, error: null, initialize() { this.bus.commands.on('error', err => { this.errorEvents.push(err); }); this.bus.events.on('error', err => { this.errorEvents.push(err); }); // Initialize the SNS transport first. return this.sns.initialize().then(() => { // There is no need to wait for the SQS transport to initialize. this.sqs.initialize(); this.bus.commands.use({role: 'catalog'}, this.sqs); this.bus.events.use({role: 'catalog'}, this.sns); this.bus.commandHandler( {role: 'catalog', cmd: 'setImage'}, this.commandHandler.bind(this) ); return this; }); }, commandHandler(payload) { this.payloads.push(payload); if (!this.error && payload.errorMessage) { throw new Error(payload.errorMessage); } this.database[payload.id] = payload; }, close() { const sqsClosed = new Promise(resolve => { this.sqs.close(resolve); }); const snsClosed = new Promise(resolve => { this.sns.close(resolve); }); return Promise.all([sqsClosed, snsClosed]); } }; const videos = [1, 2, 3, 4].map(i => { const item = { id: i.toString(), type: 'video', url: `http://example.com/videos/${i}` }; if (i === 2) { item.errorMessage = 'Video forced error'; } return item; }); const images = [1, 2, 3, 4].map(i => { const item = { id: i.toString(), type: 'image', url: `http://example.com/images/${i}` }; if (i === 2) { item.errorMessage = 'Image forced error'; } return item; }); const components = [componentA, componentB, componentC]; beforeAll(function (done) { return Promise.resolve(null) // Initialize all the components. .then(() => { console.log('initialize all components'); return Promise.all(components.map(comp => { return comp.initialize(); })); }) // Send all the setVideo commands .then(() => { console.log('send all the setVideo commands'); return Promise.all(videos.map(item => { return componentA.bus.sendCommand({role: 'catalog', cmd: 'setVideo'}, item).then(res => { console.log(`result ${item.id}:`, res); return null; }).catch(err => { console.log(`ERROR ${item.id}:`, err.message); return null; }); })); }) // Send all the setImage commands .then(() => { return Promise.all(images.map(item => { return componentA.bus.sendCommand({role: 'catalog', cmd: 'setImage'}, item); })); }) // Fini .catch(done.fail) .then(done); }); afterAll(function (done) { return Promise.resolve(null) // Close all the components. .then(() => { return Promise.all(components.map(comp => { return comp.close(); })); }) // Fini .catch(done.fail) .then(done); }); describe('component A', function () { let subject; beforeAll(() => { subject = componentA; }); it('has payloads', function () { expect(subject.payloads.length).toBe(3); }); }); });
'use strict'; (function() { // Billings Controller Spec describe('Billings Controller Tests', function() { // Initialize global variables var BillingsController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Billings controller. BillingsController = $controller('BillingsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Billing object fetched from XHR', inject(function(Billings) { // Create sample Billing using the Billings service var sampleBilling = new Billings({ name: 'New Billing' }); // Create a sample Billings array that includes the new Billing var sampleBillings = [sampleBilling]; // Set GET response $httpBackend.expectGET('billings').respond(sampleBillings); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.billings).toEqualData(sampleBillings); })); it('$scope.findOne() should create an array with one Billing object fetched from XHR using a billingId URL parameter', inject(function(Billings) { // Define a sample Billing object var sampleBilling = new Billings({ name: 'New Billing' }); // Set the URL parameter $stateParams.billingId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/billings\/([0-9a-fA-F]{24})$/).respond(sampleBilling); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.billing).toEqualData(sampleBilling); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Billings) { // Create a sample Billing object var sampleBillingPostData = new Billings({ name: 'New Billing' }); // Create a sample Billing response var sampleBillingResponse = new Billings({ _id: '525cf20451979dea2c000001', name: 'New Billing' }); // Fixture mock form input values scope.name = 'New Billing'; // Set POST response $httpBackend.expectPOST('billings', sampleBillingPostData).respond(sampleBillingResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Billing was created expect($location.path()).toBe('/billings/' + sampleBillingResponse._id); })); it('$scope.update() should update a valid Billing', inject(function(Billings) { // Define a sample Billing put data var sampleBillingPutData = new Billings({ _id: '525cf20451979dea2c000001', name: 'New Billing' }); // Mock Billing in scope scope.billing = sampleBillingPutData; // Set PUT response $httpBackend.expectPUT(/billings\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/billings/' + sampleBillingPutData._id); })); it('$scope.remove() should send a DELETE request with a valid billingId and remove the Billing from the scope', inject(function(Billings) { // Create new Billing object var sampleBilling = new Billings({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Billings array and include the Billing scope.billings = [sampleBilling]; // Set expected DELETE response $httpBackend.expectDELETE(/billings\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleBilling); $httpBackend.flush(); // Test array after successful delete expect(scope.billings.length).toBe(0); })); }); }());
'use strict'; import { forOwn } from 'lodash'; class SubscriptionWrapper { constructor(subscription) { forOwn(subscription.toObject(), (n, key) => { this[key] = n; }); this._subscription = subscription; } get(key) { /* istanbul ignore if */ if (!this._subscription.meta) { return null; } return this._subscription.meta[key]; } delayTill(dateTime) { this._subscription.nextPoll = dateTime; } set(key, value) { this._subscription.meta = this._subscription.meta || /* istanbul ignore next */ {}; this._subscription.meta[key] = value; this._subscription.markModified('meta'); } save() { return this._subscription.saveAsync(); } } export default SubscriptionWrapper;
'use strict' module.exports = { flags: 'command', desc: 'Attempts to (re)apply its own dir', setup: sywac => sywac.commandDirectory('../cyclic'), run: argv => {} }
import socketIO from 'socket.io'; import notificationLogic from'../../models/notification'; import cloudWatchLogs from '../logger/logger_messages'; let IOPort = process.env.IO_PORT || 8082; exports.initNotificationService = (app) => { let server = app.listen(IOPort); let socket = socketIO.listen(server); global.Clients = []; global.IO = socket; socket.on('connection', (client) => { client.on('newUser', (data) => { Clients.push({id : client.id, userId : data.userId}); cloudWatchLogs.LogNewClient(data.userId); }); client.on('disconnect', () => { for (var c in Clients) { if (Clients[c].id === client.id) Clients.splice(c, 1); } }); }); } exports.sendNotification = (data, cb) => { let socket = global.IO; notificationLogic.postNotification(data, (err, res) => { if (err) { cloudWatchLogs.LogMongoError(err); return cb(err); } else { global.Clients.map((entry) => { if (entry.userId === data.pictureOwner) { socket.sockets.connected[entry.id].emit('notification', {_id : res._id, userId : data.userId, type : data.type, pictureOwner : data.pictureOwner , pictureUrl : data.pictureUrl, message : data.message }); cloudWatchLogs.LogNotificationSent(data.pictureOwner); return cb(null, res); } }); return cb(null, res); } }); }
/** * @author chenx * @date 2015.1.4 * copyright 2015 Qcplay All Rights Reserved. * * action 属性基类 */ var Prop = qc.Prop = function(action, path, propertyId) { var self = this; // action instance self.action = action; self.path = path; self.propertyId = propertyId; // 属性列表 self.propMap = {}; // 属性默认值 self.propDefaultValue = {}; // 关键帧序号映射 self.keyIndexMap = {}; }; Prop.prototype.constructor = Prop; // 析构 Prop.prototype.destroy = function() { this.action = null; this.propMap = {}; } // 返回该曲线属性的信息 Prop.prototype.getPropMap = function() { return this.propMap; } // 转换成序列化格式 Prop.prototype.saveValue = function(type, value, context) { var ret; // 按类型赋值 switch (type) { case Serializer.INT: case Serializer.NUMBER: case Serializer.STRING: case Serializer.BOOLEAN: case Serializer.MAPPING: // 普通的类型 ret = value; break; case Serializer.COLOR: if (!(value instanceof Color)) ret = null; else ret = value.toNumber(true); break; case Serializer.GEOM: case Serializer.POINT: case Serializer.RECTANGLE: case Serializer.CIRCLE: case Serializer.ELLIPSE: ret = [value.class, value.toJson()]; break; case Serializer.TEXTURE: if (!value) ret = null; else if (!(value[0] instanceof qc.Atlas)) ret = null; else { var atlas = value[0], frame = value[1]; // 记录资源依赖 context.dependences.push({ key : atlas.key, uuid : atlas.uuid }); ret = [atlas.uuid, frame]; } break; case Serializer.AUDIO: if (!(value instanceof qc.SoundAsset)) ret = null; else { // 记录资源依赖 context.dependences.push({ key : value.key, uuid : value.uuid }); ret = value.uuid; } break; default: throw new Error('unsupported asset type:' + type); } return ret; } // 还原值 Prop.prototype.restoreValue = function(type, value) { var ret; // 按类型赋值 switch (type) { case Serializer.INT: case Serializer.NUMBER: case Serializer.STRING: case Serializer.BOOLEAN: case Serializer.MAPPING: // 普通的类型 ret = value; break; case Serializer.COLOR: ret = new Color(value); break; case Serializer.GEOM: case Serializer.POINT: case Serializer.RECTANGLE: case Serializer.CIRCLE: case Serializer.ELLIPSE: if (!value) ret = null; else { var func = qc.Util.findClass(value[0]); var geom = new func(); geom.fromJson(value[1]); ret = geom; } break; case Serializer.TEXTURE: if (!value) ret = []; else { var texture = value[0], frame = value[1]; var atlas = this.action.game.assets.findByUUID(texture); if (!atlas) { console.error('贴图资源尚未载入,无法反序列化。', value); ret = [null, frame]; } else if (!(atlas instanceof qc.Atlas)) ret = [null, frame]; else ret = [atlas, frame]; } break; case Serializer.AUDIO: if (!value) ret = null; else { var atlas = this.action.game.assets.findByUUID(value); if (!atlas) { console.error('音频资源尚未载入,无法反序列化。', value); ret = null; } else if (!(atlas instanceof qc.SoundAsset)) ret = null; else ret = atlas; } break; default: throw new Error('unsupported asset type:' + type); } return ret; } // 设置数据 // 子类根据需要自行重载 Prop.prototype.setData = function(attrib, data) { return; } // 反序列化属性数据 // 子类需要重载 Prop.prototype.fromJson = function(propertyInfo, json) { return 0; } // 序列化 // 子类需要重载 Prop.prototype.toJson = function(context) { return []; } // 增加关键帧 // 子类需要重载 Prop.prototype.addKey = function(attrib, time, value) { return 0; } // 删除关键帧 // 子类需要重载 Prop.prototype.deleteKey = function(attrib, index) { return 0; } // 时长 // 子类需要重载 Prop.prototype.getDuration = function() { return {}; } // 取得指定时间对应的值 // 子类需要重载 Prop.prototype.getValue = function(attrib, time) { return; } // 取得指定帧序号对应的值 // 子类需要重载 Prop.prototype.getValueByIndex = function(attrib, keyIndex) { return; } // 设置指定时间对应的值 // 返回 true 表示新增关键帧 // 子类需要重载 Prop.prototype.setValue = function(attrib, time, value) { return; } // 判断指定时间点是否为关键帧 // 子类需要重载 Prop.prototype.isKey = function(attrib, time) { return false; } // 帧调度 // 子类需要重载 Prop.prototype.update = function(target, elapsedTime, isBegin, inEditor, forceUpdate) { } // 属性重置 Prop.prototype.reset = function() { this.keyIndexMap = {}; }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; import type { NormalizationOperation, NormalizationSplitOperation, } from './NormalizationNode'; import type {ReaderFragment, ReaderInlineDataFragment} from './ReaderNode'; /** * Represents a common GraphQL request that can be executed, an `operation` * containing information to normalize the results, and a `fragment` derived * from that operation to read the response data (masking data from child * fragments). */ export type ConcreteRequest = {| +kind: 'Request', +fragment: ReaderFragment, +operation: NormalizationOperation, +params: RequestParameters, |}; export type ConcreteUpdatableQuery = {| +kind: 'UpdatableQuery', +fragment: ReaderFragment, |}; export type NormalizationRootNode = | ConcreteRequest | NormalizationSplitOperation; export type ProvidedVariablesType = {+[key: string]: {|get(): mixed|}}; /** * Contains the parameters required for executing a GraphQL request. * The operation can either be provided as a persisted `id` or `text`. If given * in `text` format, a `cacheID` as a hash of the text should be set to be used * for local caching. */ export type RequestParameters = | {| +id: string, +text: null, // common fields +name: string, +operationKind: 'mutation' | 'query' | 'subscription', +providedVariables?: ProvidedVariablesType, +metadata: {[key: string]: mixed, ...}, |} | {| +cacheID: string, +id: null, +text: string, // common fields +name: string, +operationKind: 'mutation' | 'query' | 'subscription', +providedVariables?: ProvidedVariablesType, +metadata: {[key: string]: mixed, ...}, |}; export type GeneratedNode = | ConcreteRequest | ReaderFragment | ReaderInlineDataFragment | NormalizationSplitOperation | ConcreteUpdatableQuery; const RelayConcreteNode = { ACTOR_CHANGE: 'ActorChange', CONDITION: 'Condition', CLIENT_COMPONENT: 'ClientComponent', CLIENT_EDGE: 'ClientEdge', CLIENT_EXTENSION: 'ClientExtension', DEFER: 'Defer', CONNECTION: 'Connection', FLIGHT_FIELD: 'FlightField', FRAGMENT: 'Fragment', FRAGMENT_SPREAD: 'FragmentSpread', INLINE_DATA_FRAGMENT_SPREAD: 'InlineDataFragmentSpread', INLINE_DATA_FRAGMENT: 'InlineDataFragment', INLINE_FRAGMENT: 'InlineFragment', LINKED_FIELD: 'LinkedField', LINKED_HANDLE: 'LinkedHandle', LITERAL: 'Literal', LIST_VALUE: 'ListValue', LOCAL_ARGUMENT: 'LocalArgument', MODULE_IMPORT: 'ModuleImport', RELAY_RESOLVER: 'RelayResolver', RELAY_LIVE_RESOLVER: 'RelayLiveResolver', REQUIRED_FIELD: 'RequiredField', OBJECT_VALUE: 'ObjectValue', OPERATION: 'Operation', REQUEST: 'Request', ROOT_ARGUMENT: 'RootArgument', SCALAR_FIELD: 'ScalarField', SCALAR_HANDLE: 'ScalarHandle', SPLIT_OPERATION: 'SplitOperation', STREAM: 'Stream', TYPE_DISCRIMINATOR: 'TypeDiscriminator', UPDATABLE_QUERY: 'UpdatableQuery', VARIABLE: 'Variable', }; module.exports = RelayConcreteNode;
function zeros(dimensions) { var array = []; for (var i = 0; i < dimensions[0]; ++i) { array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1))); } array[dimensions[0]/2][dimensions[1]/2] = 1; return array; } setInterval(function (){ slider= document.getElementById("myRange").value; document.getElementById("sliderValue").value = slider; },200) function getSliderValue(){ slider= document.getElementById("myRange").value; return slider; } var canvas1 = document.getElementById('main'); var mctx = canvas1.getContext('2d'); var dict = {}; function drawMap(dist) { var map = zeros([30, 30]); mctx.clearRect(0, 0, 301, 301); //splitting up array of sensor data and creating dictionary of sensor:sensorData var n = dist.split("|"); //console.log(n); scale = getSliderValue(); for (var i = 0; i < n.length; i++) { var split = n[i].split(','); //console.log(n[i]); if (parseFloat(split[1]) <= 20.0 && parseFloat(split[1]) > 4) { dict[split[0]] = parseFloat(split[1]) / (2*scale/100); } } //console.log(dict); //storing values in sensor and distance for (var key in dict) { var sensor = key; var distance = dict[key]; angle = parseFloat(getAngle(sensor)) * Math.PI / 180; findEdge(distance, angle, sensor); } for (var i = 0; i < map.length; i++) { for (var j = 0; j < map[i].length; j++) { if (map[i][j] === 1) { mctx.fillStyle = 'Red'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 2) { mctx.fillStyle = 'Yellow'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 3) { mctx.fillStyle = 'Cyan'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 4) { mctx.fillStyle = 'Green'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 5) { mctx.fillStyle = 'DarkBlue'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 6) { mctx.fillStyle = 'Pink'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 7) { mctx.fillStyle = 'Aquamarine'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 8) { mctx.fillStyle = 'Beige'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 9) { mctx.fillStyle = 'Coral'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 10) { mctx.fillStyle = 'Crimson'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 11) { mctx.fillStyle = 'MediumOrchid'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 12) { mctx.fillStyle = 'PaleVioletRed'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 13) { mctx.fillStyle = 'Tomato'; mctx.fillRect(j * 10, i * 10, 10, 10); } if (map[i][j] == 14) { mctx.fillStyle = 'SkyBlue'; mctx.fillRect(j * 10, i * 10, 10, 10); } } } function findEdge(distance, angle, sensor) { //R2 position = map[15][15] var centerAngle = angle; for (var i = 0; i < 4; i++) { //going counterclockwise var xComponent = Math.floor(distance * Math.cos(centerAngle)); var yComponent = Math.floor(distance * Math.sin(centerAngle)); map[15 - yComponent][15 + xComponent] = getColor(sensor); centerAngle += 5 * Math.PI / 180; } for (var i = 0; i < 4; i++) { //going clockwise var xComponent = Math.floor(distance * Math.cos(angle)); var yComponent = Math.floor(distance * Math.sin(angle)); map[15 - yComponent][15 + xComponent] = getColor(sensor); angle -= 5 * Math.PI / 180; } //column, row } function getColor(sensor) { var color = 0; switch (sensor) { case "U1SENSOR": color = 2; break; case "U2SENSOR": color = 3; break; case "U3SENSOR": color = 4; break; case "U4SENSOR": color = 5; break; case "U5SENSOR": color = 6; break; case "U6SENSOR": color = 7; break; case "U7SENSOR": color = 8; break; case "U8SENSOR": color = 9; break; case "U9SENSOR": color = 10; break; case "U10SENSOR": color = 11; break; case "U11SENSOR": color = 12; break; case "U12SENSOR": color = 13; break; case "U13SENSOR": color = 14; break; case "U14SENSOR": color = 15; break; } return color; } function getAngle(sensor) { var angle = 0; switch (sensor) { case "U1SENSOR": angle = 25; break; case "U2SENSOR": angle = 50; break; case "U3SENSOR": angle = 75; break; case "U4SENSOR": angle = 100; break; case "U5SENSOR": angle = 125; break; case "U6SENSOR": angle = 150; break; case "U7SENSOR": angle = 175; break; case "U8SENSOR": angle = 200; break; case "U9SENSOR": angle = 225; break; case "U10SENSOR": angle = 250; break; case "U11SENSOR": angle = 275; break; case "U12SENSOR": angle = 300; break; case "U13SENSOR": angle = 325; break; case "U14SENSOR": angle = 350; break; } return angle; } } function drawBoard() { for (var x = 0; x <= 301; x += 10) { mctx.moveTo(0.5 + x + 0, 0); mctx.lineTo(0.5 + x + 0, 300 + 0); } for (var x = 0; x <= 301; x += 10) { mctx.moveTo(0, 0.5 + x + 0); mctx.lineTo(300 + 0, 0.5 + x + 0); } mctx.strokeStyle = "black"; mctx.stroke(); }
import axios from 'axios'; export const API_URL = 'https://api.ledgerwallet.com/blockchain/v2/btc'; export function getBitcoin(address: string) { const url = API_URL + '/addresses/' + address + '/transactions?noToken=true'; return axios.get(url); }
let {expect} = require('chai'); let dom = require('../lib/dom'); let html = `<input type = "text" disabled /><input type = "password" disabled/>`; let win; let $; describe('enable()', function() { this.timeout(5000); before(done => { dom(html).then(vars => { [win, $] = vars; done(); }).catch(done); }); after(() => win.close()); it('enables all specified elements', () => { let disabled = $('input').attr('disabled'); expect(disabled).to.eql(['disabled', 'disabled']); $('input').enable(); let f = () => $('input').attrArr('disabled'); expect(f).to.throw(/one of the elements does not have/); }); });
/* Checks IAM Users, Groups and Roles for managed policy attachments. Wildcard * is supported. Options: (Object) * `allow`: (Array[String]) List of allowed ARNs (whitelist, wildcard * can be used) * `deny`: (Array[String]) List of denied ARNs (blacklist, wildcard * can be used) */ "use strict"; var _ = require("lodash"); var wildstring = require("wildstring"); function filterPartResource(object) { return object.Part === "Resource"; } function filterTypeIamEntity(object) { return object.Type === "AWS::IAM::Group" || object.Type === "AWS::IAM::Role" || object.Type === "AWS::IAM::User"; } function extractManagedPolicyARNs(object) { return object.Properties.ManagedPolicyArns; } exports.check = function(objects, options, cb) { var findings = []; function checker(object) { var managedPolicyARNs = extractManagedPolicyARNs(object); _.each(managedPolicyARNs, function(managedPolicyARN) { if (options.allow !== undefined && _.some(options.allow, function(allow) { return wildstring.match(allow, managedPolicyARN); }) === false) { findings.push({ logicalID: object.LogicalId, message: "ManagedPolicyARN " + managedPolicyARN + " not allowed" }); } if (options.deny !== undefined && _.some(options.deny, function(deny) { return wildstring.match(deny, managedPolicyARN); }) === true) { findings.push({ logicalID: object.LogicalId, message: "ManagedPolicyARN " + managedPolicyARN + " denied" }); } }); } _.chain(objects) .filter(filterPartResource) .filter(filterTypeIamEntity) .each(checker) .value(); cb(null, findings); };
var isFunction = require("core.is_function"); var ObjectProto_toString = Object.prototype.toString, FunctionProto_toString = Function.prototype.toString, reNative = RegExp("^" + String(ObjectProto_toString) // escape regexp characters .replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&') // replace `toString` with `.*?` for a generic template // replace `for ...` for environments which add extra info (Rhino) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); module.exports = isNative; function isNative(value) { return isFunction(value) && reNative.test(FunctionProto_toString.call(value)); }
/** * @module app.draw.featurePopupDirective */ /** * @fileoverview Provides a feature popup directive. */ import appModule from '../module.js'; /** * @param {string} appFeaturePopupTemplateUrl URL to the directive template. * @return {angular.Directive} The Directive Definition Object. * @ngInject */ const exports = function(appFeaturePopupTemplateUrl) { return { restrict: 'A', scope: { 'feature': '=appFeaturePopupFeature', 'map': '=appFeaturePopupMap' }, controller: 'AppFeaturePopupController', controllerAs: 'ctrl', bindToController: true, templateUrl: appFeaturePopupTemplateUrl }; }; appModule.directive('appFeaturePopup', exports); export default exports;
'use strict'; const expect = require('chai').expect, MySQLAdapter = require('../../lib/adapters/mysql'); describe('MySQL adapter', function() { it('is defined', function() { expect(MySQLAdapter).to.be.defined; }); it('can be instantiated', function() { expect(function() { new MySQLAdapter(); }).not.to.throw; const adapter = new MySQLAdapter(); expect(adapter).to.not.be.null; }); describe('getColumns', function() { it('returns a list of columns', function(done) { const adapter = new MySQLAdapter(); adapter.connect() .then(function() { return adapter.getColumns('models'); }) .then(function(columns) { expect(columns).to.eql(['id', 'name']); done(); }); }); }); describe('escape', function() { it('escapes the argument', function() { const adapter = new MySQLAdapter(); expect(adapter.escape('foo')).to.equal('foo'); expect(adapter.escape('foo\'bar')).to.equal('foo\\\'bar'); expect(adapter.escape('foo.bar')).to.equal('foo.bar'); }); }); describe('escapeId', function() { it('escapes the argument', function() { const adapter = new MySQLAdapter(); expect(adapter.escapeId('foo')).to.equal('foo'); expect(adapter.escapeId('foo\'bar')).to.equal('foo\'bar'); expect(adapter.escapeId('foo.bar')).to.equal('foo`.`bar'); }); }); });
/** * A bunch of global variables for our calculator application */ var display = "0"; var pendingOperation = ""; var leftVariable = ""; /** * Functions triggered by button presses */ function buttonPressed(number) { addToDisplay(number); } function buttonSubstractPressed() { pendingOperation = "substract"; storeAndClear(); } function buttonAddPressed() { pendingOperation = "add"; storeAndClear(); } function buttonDividePressed() { pendingOperation = "divide"; storeAndClear(); } function buttonMultiplyPressed() { pendingOperation = "multiply"; storeAndClear(); } function buttonEqualsPressed() { performPendingOperation() updateDisplay(); store(); } function buttonDecimalPressed() { addDecimal(); updateDisplay(); } /** * Get the value of what is currently in display, add to it or update it based on global variable display */ function getDisplayValue() { var displayElement = document.getElementById('calculator-display'); return displayElement.textContent; } var maxDisplayLength = 10; function addToDisplay(number) { if (display.length > maxDisplayLength) return; if (display == "0" || display == "Infinity" || display == "NaN") { display = ""; } display = display.toString(); display += number.toString(); updateDisplay(); } function updateDisplay() { var displayElement = document.getElementById('calculator-display'); displayElement.textContent = display.substring(0, maxDisplayLength); } /** * Add a decimal to display */ function addDecimal() { displayString = "" + display; if (displayString.indexOf(".") > -1) { return; } else { display += "."; } } /** * Perform operations */ function performPendingOperation() { var tempLeft = +leftVariable; switch (pendingOperation) { case "add": display = tempLeft + +getDisplayValue(); break; case "substract": display = tempLeft - +getDisplayValue(); break; case "divide": display = tempLeft / +getDisplayValue(); break; case "multiply": display = tempLeft * +getDisplayValue(); break; } //Make sure we keep display a string so there aren't problems later display = display.toString(); pendingOperation = ""; } /** * For storing the current number on the display into the leftVariable variable and clearing the screen */ function storeAndClear() { store(); clear(); } function store() { var displayElement = document.getElementById('calculator-display'); leftVariable = displayElement.textContent; } function clear() { var displayElement = document.getElementById('calculator-display'); displayElement.textContent = "0"; display = "0"; } /** * Stuff for handling keydown events */ //We bind key press events to our keyHandler(e) function document.onkeydown = keyHandler; //Keycode for enter var enterKeyCode = 13; //Some keycodes for numpad keys on the keyboard var numpad0KeyCode = 96; var numpad9KeyCode = 105; var numpadMultiplyKeyCode = 106; var numpadAddKeyCode = 107; var numpadSubstractKeyCode = 109; var numpadDecimalKeyCode = 110; var numpadDivideKeyCode = 111; function keyHandler(e) { var event = window.event; var pressedKey = event.keyCode; //If enter was pressed call the appropriate function if (pressedKey == enterKeyCode) buttonEqualsPressed(); //Else if it was a number or operand button on the keypad do some stuff with magic ints else if (isNumpadKey(pressedKey)) { //If its a number if (pressedKey <= numpad9KeyCode) handleNumberNumpadKeyPressed(pressedKey); //Else if its not a number and it's something like divide or enter.. else handleNonNumericNumpadKeyPressed(pressedKey); } } function isNumpadKey(keyCode) { return (numpad0KeyCode <= keyCode && keyCode <= numpadDivideKeyCode); } function handleNumberNumpadKeyPressed(pressedKey) { buttonPressed(getNumberFromNumpadKey(pressedKey)); } function handleNonNumericNumpadKeyPressed(pressedKey) { switch (pressedKey) { case numpadMultiplyKeyCode: buttonMultiplyPressed(); break; case numpadDivideKeyCode: buttonDividePressed(); break; case numpadAddKeyCode: buttonAddPressed(); break; case numpadSubstractKeyCode: buttonSubstractPressed(); break; case numpadDecimalKeyCode: buttonPressed("."); break; } } function getNumberFromNumpadKey(pressedKey) { var adjustementToGetNumberFromKeyCode = 96; var number = pressedKey - adjustementToGetNumberFromKeyCode; return number; }
/* global module, require */ module.exports = function (grunt) { 'use strict'; /* jshint maxstatements: false */ /* jshint camelcase: false */ // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ bower: { install: { options: { copy: false, } } }, /* Needed since sass/compass doesn't have any decent way to include plain CSS files yet */ rename: { sirTrevor: { files: [ {src: 'bower_components/sir-trevor-js/sir-trevor.css', dest: 'bower_components/sir-trevor-js/_sir-trevor.scss'}, {src: 'bower_components/sir-trevor-js/sir-trevor-icons.css', dest: 'bower_components/sir-trevor-js/_sir-trevor-icons.scss'} ] } }, clean: { dist: [ '.tmp', 'dist', 'blag/**/*.pyc', 'blag/server-assets', 'thusoy-blag-0.1.0', '*.egg-info', 'cover', '.coverage', ] }, compass: { dist: { options: { sassDir: 'blag/static/sass/', cssDir: '.tmp/static/css/', outputStyle: 'compressed', importPath: ["bower_components"], } } }, concurrent: { server: { tasks: ['watch', 'shell:server'], options: { logConcurrentOutput: true, } } }, copy: { 'fetch-server-assets': { files: [{ src: '.tmp/static/css/core.css', dest: 'blag/server-assets/core.css', }, { src: '.tmp/static/js/inline.min.js', dest: 'blag/server-assets/inline.js', }] }, 'misc-static': { files: [{ expand: true, cwd: 'blag/static', src: ['img/favicon.ico'], dest: '.tmp/static/', }] }, }, filerev: { options: { algorithm: 'md5', length: 8, }, images: { src: '.tmp/static/img/*.jpg', }, styles: { src: '.tmp/static/css/*.css', }, js: { src: '.tmp/static/js/*.js', }, misc: { src: [ '.tmp/static/img/favicon.ico', ] }, }, filerev_assets: { dist: { options: { cwd: '.tmp/static/', dest: 'blag/server-assets/filerevs.json', prettyPrint: true, } } }, imagemin: { static: { files: [{ expand: true, cwd: 'blag/static/', src: 'img/*.{png,jpg}', dest: '.tmp/static/', }] } }, shell: { options: { stdout: true, stderr: true, }, server: { command: './manage.py devserver', }, }, uglify: { options: { sourceMap: true, sourceMapIncludeSources: true, }, static: { files: { '.tmp/static/js/main.min.js': [ 'blag/static/js/main.js', ], '.tmp/static/js/lcp.min.js': [ 'blag/static/js/lcp.js', ], '.tmp/static/js/writePost.min.js': [ 'bower_components/jquery/dist/jquery.js', 'bower_components/underscore/underscore.js', 'bower_components/Eventable/eventable.js', 'bower_components/sir-trevor-js/sir-trevor.js', 'blag/static/js/blocks/code.js', 'blag/static/js/blocks/markdown.js', 'blag/static/js/blocks/sourced-quote.js', 'blag/static/js/writeEntry.js', ], }, }, inline: { options: { sourceMap: false, }, files: { '.tmp/static/js/inline.min.js': [ 'blag/static/js/inline.js', ], } } }, watch: { options: { livereload: true, }, python: { files: ['blag/**/*.py'], tasks: [] }, sass: { files: ['blag/static/sass/*.scss'], tasks: ['buildStyles'], }, js: { files: ['blag/static/js/**/*.js'], tasks: ['uglify'] }, templates: { files: ['blag/templates/*.html'], tasks: [], }, }, }); grunt.registerTask('default', [ 'prep', 'concurrent:server', ]); grunt.registerTask('build', [ 'prep', 'rev-static', ]); grunt.registerTask('prep', [ 'clean', 'compass', 'uglify', 'copy:fetch-server-assets', 'imagemin', 'copy:misc-static', ]); grunt.registerTask('rev-static', [ 'filerev', 'filerev_assets', ]); grunt.registerTask('init-deps', [ 'bower', 'rename:sirTrevor', ]); };
import React, { Component } from "react"; import PropTypes from "prop-types"; import CardList from "../../common/cardList/CardList"; import theme from "../../../theme/theme"; import { getIconName } from "../../../routes/main/clubFeed/helper"; export default class ClubMembersCard extends Component { static propTypes = { clubMembers: PropTypes.arrayOf( PropTypes.shape({ firstname: PropTypes.string, lastname: PropTypes.string, profile: PropTypes.string, country: PropTypes.string }) ).isRequired }; render() { const { clubMembers } = this.props; return ( <CardList title="MEMBERS" list={clubMembers.map(member => ({ key: member.id, image: { name: getIconName("runner"), color: theme.PrimaryColor }, text: member.firstname }))} /> ); } }
/** * Assemble <http://assemble.io> * * Copyright (c) 2014, Jon Schlinkert, Brian Woodward, contributors. * Licensed under the MIT License (MIT). */ var collection = require('../lib/collection'); var expect = require('chai').expect; var grunt = require('grunt'); var path = require('path'); var _ = require('lodash'); var getCollection = function(file) { return grunt.file.readJSON(path.join('./test/fixtures/data/collections', file)); }; var fakeCollection = getCollection('fakeCollection.json'); describe('Collections', function() { describe('Sorts', function() { it('by item name asc', function(done) { var expected = getCollection('expected-sortby-item-asc.json'); var col = _.cloneDeep(fakeCollection); var actual = collection.sort(col); grunt.verbose.writeln(require('util').inspect(actual, null, 10)); expect(actual).to.deep.equal(expected); done(); }); it('by item name desc', function(done) { var expected = getCollection('expected-sortby-item-desc.json'); var col = _.cloneDeep(fakeCollection); col.sortorder = 'DESC'; var actual = collection.sort(col); grunt.verbose.writeln(require('util').inspect(actual, null, 10)); expect(actual).to.deep.equal(expected); done(); }); it('by page property asc', function(done) { var expected = getCollection('expected-sortby-page-property-asc.json'); var col = _.cloneDeep(fakeCollection); col.sortby = 'title'; var actual = collection.sort(col); grunt.verbose.writeln(require('util').inspect(actual, null, 10)); expect(actual).to.deep.equal(expected); done(); }); it('by page property desc', function(done) { var expected = getCollection('expected-sortby-page-property-desc.json'); var col = _.cloneDeep(fakeCollection); col.sortorder = 'DESC'; col.sortby = 'title'; var actual = collection.sort(col); grunt.verbose.writeln(require('util').inspect(actual, null, 10)); expect(actual).to.deep.equal(expected); done(); }); }); });
/* * jquery-nude-templates * https://github.com/jesseluoto/jquerytempla * * Copyright (c) 2014 Jesse Luoto * Licensed under the MIT license. */ (function($) { // Collection method. $.fn.nude = function(variables) { return this.each(function() { // Do something awesome to each selected element. $(this).html($.nude($(this).html(), variables)); }); }; // Static method. $.nude = function(template, variables) { return template.replace(/\[\[(.*?\]?)\]\]/g, function(r,item) { // Don't allow functions to be executed if(/\((.*)\)/g.test(item)) { return ""; } // Use sandbox so one can't read e.g. window.* variables unintentinally var sandbox = variables; // Evaluate the variable var val = null; try { val = eval("sandbox." + item); } catch(e) { return ""; } // Handle empty values properly if (typeof val === "undefined" || val === null) { return ""; } // All good, return compiled variable return val; }); }; }(jQuery));
import Lexer from './Lexer' import functions from '../models/functions' export default class LatexLexer extends Lexer { constructor(mathString) { super(mathString) } next_token() { this.prev_col = this.col this.prev_line = this.line if (this.pos >= this.text.length) { return { type: 'EOF' } } if (this.current_char() == '\n') { this.col = 0 this.line++ } const blank_chars = [' ', '\n'] for (let blank of blank_chars) { if (this.text.startsWith(blank, this.pos)) { this.increment(blank.length) return this.next_token() } } if (this.current_char().match(/[0-9]/)) { return this.number() } if (this.current_char().match(/[a-zA-Z]/)) { return this.alphabetic() } if (this.current_char() == '(') { this.increment() return { type: 'bracket', open: true, value: '(' } } if (this.current_char() == ')') { this.increment() return { type: 'bracket', open: false, value: ')' } } if (this.current_char() == '+') { this.increment() return { type: 'operator', value: 'plus' } } if (this.current_char() == '-') { this.increment() return { type: 'operator', value: 'minus' } } if (this.current_char() == '*') { this.increment() return { type: 'operator', value: 'multiply' } } if (this.current_char() == '/') { this.increment() return { type: 'operator', value: 'divide' } } if (this.current_char() == '^') { this.increment() return { type: 'operator', value: 'exponent' } } if (this.current_char() == '=') { this.increment() return { type: 'equal' } } if (this.current_char() == '_') { this.increment() return { type: 'underscore' } } this.error('Unknown symbol: ' + this.current_char()) } // Token contains string of alphabetic characters alphabetic() { let token = '' while ( this.current_char().match(/[a-zA-Z]/) && this.pos <= this.text.length ) { token += this.current_char() this.increment() } if (functions.includes(token)) { return { type: 'keyword', value: token, } } return { type: 'variable', value: token, } } }
(function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, args, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { args = this.arguments && this.arguments.map(function (a) { return a.eval(env) }); for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(args, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments).rules); match = true; } catch (e) { throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; } } } if (match) { return rules; } else { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index }; } } } throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index }; } }; tree.mixin.Definition = function (name, params, rules, condition) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.condition = condition; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, evalParams: function (env, args) { var frame = new(tree.Ruleset)(null, []); for (var i = 0, val; i < this.params.length; i++) { if (this.params[i].name) { if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return frame; }, eval: function (env, args) { var frame = this.evalParams(env, args), context, _arguments = []; for (var i = 0; i < Math.max(this.params.length, args && args.length); i++) { _arguments.push(args[i] || this.params[i].value); } frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len, frame; if (argsLength < this.required) { return false } if ((this.required > 0) && (argsLength > this.params.length)) { return false } if (this.condition && !this.condition.eval({ frames: [this.evalParams(env, args)].concat(env.frames) })) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree'));
import { dirname, relative, sep } from 'path'; import { ensureDotSlash, filterMatchingPaths, formatPath, removeExtension, } from './fileHelpers'; const renameLiteral = (j, newName) => path => { j(path).replaceWith(() => j.literal(newName)); }; export default function importDeclarationTransform(file, api, options) { const { path: filePath, source } = file; const { jscodeshift: j } = api; let { paths, printOptions = {} } = options; if (!Array.isArray(paths)) paths = [{ ...options }]; const root = j(source); const basedir = dirname(filePath); const requireDeclarations = root .find(j.CallExpression, { callee: { type: 'Identifier', name: 'require' }, }) .find(j.Literal); const importDeclarations = root.find(j.ImportDeclaration).find(j.Literal); const exportDeclarations = root .find(j.ExportNamedDeclaration) .filter(path => path.value.source !== null) .find(j.Literal); const exportAllDeclarations = root .find(j.ExportAllDeclaration) .find(j.Literal); const allPaths = [].concat( requireDeclarations.paths(), importDeclarations.paths(), exportDeclarations.paths(), exportAllDeclarations.paths() ); const indexRegex = new RegExp('\\' + sep + 'index$'); const indexJsRegex = new RegExp('\\' + sep + 'index.js$'); paths.forEach(({ prevFilePath, nextFilePath }) => { const matchesPath = filterMatchingPaths(basedir, prevFilePath); const nodesToUpdate = j(allPaths).filter(matchesPath); const noop = nodesToUpdate.length <= 0; if (noop) return; let relativeNextFilePath = formatPath(ensureDotSlash( removeExtension(relative(basedir, nextFilePath)) )); const relativeNextFilePathNoIndex = relativeNextFilePath.replace(indexRegex, '') if (relativeNextFilePathNoIndex !== '.') { if (prevFilePath.replace(indexJsRegex, '') !== prevFilePath) { relativeNextFilePath = relativeNextFilePathNoIndex } } nodesToUpdate.forEach(renameLiteral(j, relativeNextFilePath)); }); return root.toSource(printOptions); }
'use strict'; /** * @ngdoc service * @name nashaLeptaApp.FirebaseLink * @description * # FirebaseLink * Constant in the nashaLeptaApp. */ angular.module('nashaLeptaApp') .constant('FirebaseLink', 'https://popping-heat-1147.firebaseio.com');
require("consoloid-framework/Consoloid/Widget/JQoteTemplate"); require('consoloid-framework/Consoloid/Widget/Widget'); require('consoloid-console/Consoloid/Ui/Dialog'); require('consoloid-framework/Consoloid/Test/UnitTest'); require('../AbstractDialog'); require('../../Error/UserMessage'); describeUnitTest('Tada.Git.Dialog.AbstractDialog', function() { var tada, Dialog, repo, remoteService, repositoryTemplate; beforeEach(function() { repositoryTemplate = { get: sinon.stub() }; tada = { getConfig: sinon.stub().returns({'tada':{}, 'foo':{}}) } env.addServiceMock('tada', tada); repo = { mention: sinon.stub() } env.addServiceMock('git.project', { getRepository: sinon.stub().returns(repo) }); Dialog = env.create('Tada.Git.Dialog.AbstractDialog', { repositoryTemplate: repositoryTemplate, remoteMethod: 'foo' }); Dialog.arguments = {}; Dialog._renderExpressionAndResponse = function(){}; Dialog._animateDialogShowup = function(){}; Dialog._bindEventListeners = function(){}; }); describe('#__construct(options)', function() { it('should require a repositoryTemplateId property if repositoryTemplate does not exist', function(){ (function(){ env.create('Tada.Git.Dialog.AbstractDialog', { remoteMethod: 'foo' } ); }).should.throw(); }); it('should create the repositoryTemplate if the repositoryTemplateId is present', function(){ Dialog = env.create('Tada.Git.Dialog.AbstractDialog', { remoteMethod: 'foo', repositoryTemplateId: 'alma'} ); Dialog.repositoryTemplate.should.be.ok; }); }); describe('#setup()', function(){ it('should set the requestedRepositories if the repo argument is filled', function(){ Dialog.arguments.repo = { value: 'tada' }; Dialog.setup(); Dialog.requestedRepositories.should.be.eql(['tada']); }); it('should fill the requestedRepositories with the all repository if the repo argument is missing', function(){ Dialog.setup(); Dialog.requestedRepositories.should.be.eql(['tada', 'foo']) }); it("should attempt to mention repo if the argument was set", function() { Dialog.arguments.repo = { value: 'tada' }; Dialog.setup(); repo.mention.calledOnce.should.be.ok; }); }); describe("#__processRequestedRepositories()", function() { it("Should render an error if error was thrown inside _processRepository", function() { Dialog.arguments.repo = { value: 'tada' }; Dialog.setup(); Dialog._renderRepository = sinon.stub(); Dialog._processRepository = sinon.stub().throws(new Tada.Git.Error.UserMessage({ message: "Rampamparam" })); Dialog.__processRequestedRepositories(); Dialog._renderRepository.args[0][1].message.type.should.equal(Tada.Git.Dialog.AbstractDialog.MESSAGE_ERROR); }); }) });
module.exports = function (email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); }
// All code points in the Miscellaneous Mathematical Symbols-B block as per Unicode v8.0.0: [ 0x2980, 0x2981, 0x2982, 0x2983, 0x2984, 0x2985, 0x2986, 0x2987, 0x2988, 0x2989, 0x298A, 0x298B, 0x298C, 0x298D, 0x298E, 0x298F, 0x2990, 0x2991, 0x2992, 0x2993, 0x2994, 0x2995, 0x2996, 0x2997, 0x2998, 0x2999, 0x299A, 0x299B, 0x299C, 0x299D, 0x299E, 0x299F, 0x29A0, 0x29A1, 0x29A2, 0x29A3, 0x29A4, 0x29A5, 0x29A6, 0x29A7, 0x29A8, 0x29A9, 0x29AA, 0x29AB, 0x29AC, 0x29AD, 0x29AE, 0x29AF, 0x29B0, 0x29B1, 0x29B2, 0x29B3, 0x29B4, 0x29B5, 0x29B6, 0x29B7, 0x29B8, 0x29B9, 0x29BA, 0x29BB, 0x29BC, 0x29BD, 0x29BE, 0x29BF, 0x29C0, 0x29C1, 0x29C2, 0x29C3, 0x29C4, 0x29C5, 0x29C6, 0x29C7, 0x29C8, 0x29C9, 0x29CA, 0x29CB, 0x29CC, 0x29CD, 0x29CE, 0x29CF, 0x29D0, 0x29D1, 0x29D2, 0x29D3, 0x29D4, 0x29D5, 0x29D6, 0x29D7, 0x29D8, 0x29D9, 0x29DA, 0x29DB, 0x29DC, 0x29DD, 0x29DE, 0x29DF, 0x29E0, 0x29E1, 0x29E2, 0x29E3, 0x29E4, 0x29E5, 0x29E6, 0x29E7, 0x29E8, 0x29E9, 0x29EA, 0x29EB, 0x29EC, 0x29ED, 0x29EE, 0x29EF, 0x29F0, 0x29F1, 0x29F2, 0x29F3, 0x29F4, 0x29F5, 0x29F6, 0x29F7, 0x29F8, 0x29F9, 0x29FA, 0x29FB, 0x29FC, 0x29FD, 0x29FE, 0x29FF ];
import { assert } from '../../_setup' describe('LinkedCollection#remove', function () { it('should remove an item from the collection', function () { this.UserCollection.createIndex('age') const user = this.UserCollection.add({ id: 1, age: 30 }) const user2 = this.UserCollection.add({ id: 2, age: 31 }) const user3 = this.UserCollection.add({ id: 3, age: 32 }) const users = [user, user2, user3] assert.strictEqual(this.UserCollection.get(1), user, 'user 1 is in the store') assert.strictEqual(this.UserCollection.get(2), user2, 'user 2 is in the store') assert.strictEqual(this.UserCollection.get(3), user3, 'user 3 is in the store') assert.deepEqual(this.UserCollection.between([30], [32], { rightInclusive: true, index: 'age' }), users, 'users can be selected by age index') this.UserCollection.remove(1) assert(!this.UserCollection.get(1), 'user 1 is no longer in the store') users.shift() assert.deepEqual(this.UserCollection.between([30], [32], { rightInclusive: true, index: 'age' }), users, 'user 1 cannot be retrieved by index') }) })
lucid.html.base.tags.inputEmail = function(factory){ this.factory = factory; lucid.html.base.tags.input.apply(this, arguments); this.tag = 'input'; this.allowedAttributes.push('autocomplete'); this.allowedAttributes.push('size'); this.parameters = ['name', 'value', 'required', 'placeholder']; this.attributes['type'] = 'email'; }; lucid.html.base.tags.inputEmail.prototype = Object.create(lucid.html.base.tags.input.prototype); lucid.html.factory.tags.inputEmail = lucid.html.base.tags.inputEmail;
$(document).ready(function(){ $('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if(!a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } }); });
steal('can','./init.ejs', function(can, initView){ /** * @class candd/details * @alias Details */ return can.Control( /** @Static */ { defaults : {} }, /** @Prototype */ { init : function(){ this.element.html(initView({ message: "Hello World from Details" })); } }); });
/** * This file is part of the RedKite CMS Application and it is distributed * under the GPL LICENSE Version 2.0. To use this application you must leave * intact this copyright notice. * * Copyright (c) RedKite Labs <info@redkite-labs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * For extra documentation and help please visit http://www.redkite-labs.com * * @license GPL LICENSE Version 2.0 * */ var slotEditorModel; var blockEditorModel; var timeout = 100; $(document).ready(function() { slotEditorModel = new SlotEditorModel(); ko.applyBindings(slotEditorModel, document.getElementById('rkcms-slots-editor-panel')); blockEditorModel = new BlockEditorModel(); ko.applyBindings(blockEditorModel, document.getElementById('rkcms-blocks-editor-panel')); $('.rkcms-slot').each(function(){ var element = $(this); var blocks = ko.utils.parseJson(decodeURIComponent(element.attr("data-slot"))); var slotName = element.attr("data-slotname"); var slot = new SlotModel(blocks, slotName, element.attr("data-next")); ko.applyBindings(slot, this); }); $('.rkcms-warning-btn').popover(); $('#rkcms-control-panel-btn') .popover() .on('shown.bs.popover', function () { var status = $('body').data('rkcms.editor-button-status'); var moveMode = $('body').data('rkcms.editor-move-mode'); var model = new ControlPanelModel(status, moveMode); ko.applyBindings(model, document.getElementById('rkcms-control-panel-body')); }) .on('hide.bs.popover', function () { $('.rkcms-edit').each(function(){ ko.cleanNode(this); }); }) ; var seoModel = new SeoModel($('#rkcms-seo').attr("data-seo")); ko.applyBindings(seoModel, document.getElementById('rkcms-seo')); Highlight(); }); function Highlight() { window.setTimeout(function(){ $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }, timeout); } function mediaLibrary(url, callback) { $('<div/>').dialogelfinder({ url : url, lang : $('#al_available_languages option:selected').val(), width : 840, destroyOnClose : true, commandsOptions : { getfile: { oncomplete: 'destroy' } }, getFileCallback : function(file, fm) { callback(file, fm); } }).dialogelfinder('instance'); }
'use strict'; const BundleTracker = require('webpack-bundle-tracker'); const autoprefixer = require('autoprefixer'); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); const eslintFormatter = require('react-dev-utils/eslintFormatter'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const paths = require('./paths'); const getClientEnvironment = require('./env'); // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. // const publicPath = paths.servedPath; const publicPath = "/static/bundles/"; // Some apps do not use client-side routing with pushState. // For these, "homepage" can be set to "." to enable relative asset paths. const shouldUseRelativeAssetPaths = publicPath === './'; // Source maps are resource heavy and can cause out of memory issue for large source files. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. const publicUrl = publicPath.slice(0, -1); // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // Assert this just to be safe. // Development builds of React are slow and not intended for production. if (env.stringified['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.'); } // Note: defined here because it will be used more than once. const cssFilename = 'css/[name].[contenthash:8].css'; // ExtractTextPlugin expects the build output to be flat. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27) // However, our output is structured with css, js and media folders. // To have this structure working with relative paths, we have to use custom options. const extractTextPluginOptions = shouldUseRelativeAssetPaths ? // Making sure that the publicPath goes back to to build folder. { publicPath: Array(cssFilename.split('/').length).join('../') } : {}; // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. // The development configuration is different and lives in a separate file. module.exports = { // Don't attempt to continue if there are any errors. bail: true, // We generate sourcemaps in production. This is slow but gives good results. // You can exclude the *.map files from the build during deployment. devtool: shouldUseSourceMap ? 'source-map' : false, // In production, we only want to load the polyfills and the app code. entry: [require.resolve('./polyfills'), paths.appIndexJs], output: { // The build folder. path: paths.appBuild, // Generated JS file names (with nested folders). // There will be one main bundle, and one file per asynchronous chunk. // We don't currently advertise code splitting but Webpack supports it. // filename: 'static/js/[name].[chunkhash:8].js', // chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', filename: 'js/[name].[chunkhash:8].js', chunkFilename: 'js/[name].[chunkhash:8].chunk.js', // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: publicPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path .relative(paths.appSrc, info.absoluteResourcePath) .replace(/\\/g, '/'), }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 modules: ['node_modules', paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 // `web` extension prefixes have been added for better support // for React Native Web. extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), ], }, module: { strictExportPresence: true, rules: [ // TODO: Disable require.ensure as it's not a standard language feature. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. // { parser: { requireEnsure: false } }, // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx|mjs)$/, enforce: 'pre', use: [ { options: { formatter: eslintFormatter, eslintPath: require.resolve('eslint'), }, loader: require.resolve('eslint-loader'), }, ], include: paths.appSrc, }, { // "oneOf" will traverse all following loaders until one will // match the requirements. When no loader matches it will fall // back to the "file" loader at the end of the loader list. oneOf: [ // "url" loader works just like "file" loader but it also embeds // assets smaller than specified size as data URLs to avoid requests. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'media/[name].[hash:8].[ext]', // name: 'static/media/[name].[hash:8].[ext]', }, }, // Process JS with Babel. { test: /\.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { compact: true, }, }, // The notation here is somewhat confusing. // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader normally turns CSS into JS modules injecting <style>, // but unlike in development configuration, we do something different. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders // (second argument), then grabs the result CSS and puts it into a // separate file in our build process. This way we actually ship // a single CSS file in production instead of JS code injecting <style> // tags. If you use code splitting, however, any async bundles will still // use the "style" loader inside the async code so CSS from them won't be // in the main CSS file. { test: /\.css$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: { loader: require.resolve('style-loader'), options: { hmr: false, }, }, use: [ { loader: require.resolve('css-loader'), options: { importLoaders: 1, minimize: true, sourceMap: shouldUseSourceMap, }, }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, ], }, extractTextPluginOptions ) ), // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. }, // "file" loader makes sure assets end up in the `build` folder. // When you `import` an asset, you get its filename. // This loader doesn't use a "test" so it will catch all modules // that fall through the other loaders. { loader: require.resolve('file-loader'), // Exclude `js` files to keep "css" loader working as it injects // it's runtime that would otherwise processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/], options: { // name: 'static/media/[name].[hash:8].[ext]', name: 'media/[name].[hash:8].[ext]', }, }, // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ], }, ], }, plugins: [ // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In production, it will be an empty string unless you specify "homepage" // in `package.json`, in which case it will be the pathname of that URL. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV was set to production here. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env.stringified), // Minify the code. new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, // Disabled because of an issue with Uglify breaking seemingly valid code: // https://github.com/facebookincubator/create-react-app/issues/2376 // Pending further investigation: // https://github.com/mishoo/UglifyJS2/issues/2011 comparisons: false, }, mangle: { safari10: true, }, output: { comments: false, // Turned on because emoji and regex is not minified properly using default // https://github.com/facebookincubator/create-react-app/issues/2488 ascii_only: true, }, sourceMap: shouldUseSourceMap, }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. new ExtractTextPlugin({ filename: cssFilename, }), // Generate a manifest file which contains a mapping of all asset filenames // to their corresponding output file so that tools can pick it up without // having to parse `index.html`. new ManifestPlugin({ fileName: 'asset-manifest.json', }), // Generate a service worker script that will precache, and keep up to date, // the HTML & assets that are part of the Webpack build. new SWPrecacheWebpackPlugin({ // By default, a cache-busting query parameter is appended to requests // used to populate the caches, to ensure the responses are fresh. // If a URL is already hashed by Webpack, then there is no concern // about it being stale, and the cache-busting can be skipped. dontCacheBustUrlsMatching: /\.\w{8}\./, filename: 'service-worker.js', logger(message) { if (message.indexOf('Total precache size is') === 0) { // This message occurs for every build and is a bit too noisy. return; } if (message.indexOf('Skipping static resource') === 0) { // This message obscures real errors so we ignore it. // https://github.com/facebookincubator/create-react-app/issues/2612 return; } console.log(message); }, minify: true, // For unknown URLs, fallback to the index page navigateFallback: publicUrl + '/index.html', // Ignores URLs starting from /__ (useful for Firebase): // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219 navigateFallbackWhitelist: [/^(?!\/__).*/], // Don't precache sourcemaps (they're large) and build asset manifest: staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/], }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new BundleTracker({path: paths.statsRoot, filename: 'webpack-stats.prod.json'}), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', }, };
/** * Created by Nguyen on 27/2/2015. */ 'use strict'; angular.module('myApp.question', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/question', { templateUrl: 'question/question.html', controller: 'QuestionCtrl' }); }]) .controller('QuestionCtrl', [function() { }]);
var host = window.geocloud_host || ""; window.__ = function (string) { if (typeof gc2i18n !== 'undefined') { if (gc2i18n.dict[string]) { return gc2i18n.dict[string]; } } return string; }; if (typeof $ === "undefined") { document.write("<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js' type='text/javascript'><\/script>"); } if (window.geocloud_maplib === "ol2") { document.write("<script src='http://cdn.eu1.mapcentia.com/js/openlayers/OpenLayers.js' type='text/javascript'><\/script>"); } else if (window.geocloud_maplib === "leaflet") { document.write("<script src='" + host + "/js/leaflet/leaflet-all.js' type='text/javascript'><\/script>"); } document.write("<script src='http://cdn.eu1.mapcentia.com/js/openlayers/proj4js-combined.js' type='text/javascript'><\/script>"); document.write("<script src='" + host + "/api/v1/baselayerjs' type='text/javascript'><\/script>"); document.write("<script src='" + host + "/api/v3/js/geocloud.js'><\/script>"); document.write("<script src='" + host + "/js/i18n/" + "en_US" + ".js'><\/script>"); // Load some css if (window.geocloud_maplib === "leaflet") { document.write("<link rel='stylesheet' type='text/css' href='" + host + "/js/leaflet/plugins/awesome-markers/leaflet.awesome-markers.css'>"); document.write("<link rel='stylesheet' type='text/css' href='" + host + "/js/leaflet/plugins/Leaflet.draw/leaflet.draw.css'>"); document.write("<link rel='stylesheet' type='text/css' href='" + host + "/js/leaflet/plugins/Leaflet.label/leaflet.label.css'>"); document.write("<link rel='stylesheet' type='text/css' href='" + host + "/js/leaflet/plugins/markercluster/MarkerCluster.Default.css'>"); document.write("<link rel='stylesheet' type='text/css' href='https://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>"); }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0 */ goog.provide('ng.material.components.tooltip'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.tooltip */ angular .module('material.components.tooltip', [ 'material.core' ]) .directive('mdTooltip', MdTooltipDirective); /** * @ngdoc directive * @name mdTooltip * @module material.components.tooltip * @description * Tooltips are used to describe elements that are interactive and primarily graphical (not textual). * * Place a `<md-tooltip>` as a child of the element it describes. * * A tooltip will activate when the user focuses, hovers over, or touches the parent. * * @usage * <hljs lang="html"> * <md-button class="md-fab md-accent" aria-label="Play"> * <md-tooltip> * Play Music * </md-tooltip> * <md-icon icon="img/icons/ic_play_arrow_24px.svg"></md-icon> * </md-button> * </hljs> * * @param {expression=} md-visible Boolean bound to whether the tooltip is currently visible. * @param {number=} md-delay How many milliseconds to wait to show the tooltip after the user focuses, hovers, or touches the parent. Defaults to 300ms. * @param {boolean=} md-autohide If present or provided with a boolean value, the tooltip will hide on mouse leave, regardless of focus * @param {string=} md-direction Which direction would you like the tooltip to go? Supports left, right, top, and bottom. Defaults to bottom. */ function MdTooltipDirective($timeout, $window, $$rAF, $document, $mdUtil, $mdTheming, $rootElement, $animate, $q) { var TOOLTIP_SHOW_DELAY = 0; var TOOLTIP_WINDOW_EDGE_SPACE = 8; return { restrict: 'E', transclude: true, priority:210, // Before ngAria template: '<div class="md-content" ng-transclude></div>', scope: { delay: '=?mdDelay', visible: '=?mdVisible', autohide: '=?mdAutohide', direction: '@?mdDirection' // only expect raw or interpolated string value; not expression }, link: postLink }; function postLink(scope, element, attr) { $mdTheming(element); var parent = $mdUtil.getParentWithPointerEvents(element), content = angular.element(element[0].getElementsByClassName('md-content')[0]), tooltipParent = angular.element(document.body), debouncedOnResize = $$rAF.throttle(function () { updatePosition(); }); if ($animate.pin) $animate.pin(element, parent); // Initialize element setDefaults(); manipulateElement(); bindEvents(); // Default origin transform point is 'center top' // positionTooltip() is always relative to center top updateContentOrigin(); configureWatchers(); addAriaLabel(); function setDefaults () { if (!angular.isDefined(attr.mdDelay)) scope.delay = TOOLTIP_SHOW_DELAY; } function updateContentOrigin() { var origin = 'center top'; switch (scope.direction) { case 'left' : origin = 'right center'; break; case 'right' : origin = 'left center'; break; case 'top' : origin = 'center bottom'; break; case 'bottom': origin = 'center top'; break; } content.css('transform-origin', origin); } function configureWatchers () { scope.$on('$destroy', function() { scope.visible = false; element.remove(); angular.element($window).off('resize', debouncedOnResize); }); scope.$watch('visible', function (isVisible) { if (isVisible) showTooltip(); else hideTooltip(); }); scope.$watch('direction', updatePosition ); } function addAriaLabel () { if (!parent.attr('aria-label') && !parent.text().trim()) { parent.attr('aria-label', element.text().trim()); } } function manipulateElement () { element.detach(); element.attr('role', 'tooltip'); } function bindEvents () { var mouseActive = false; var ngWindow = angular.element($window); // add an mutationObserver when there is support for it // and the need for it in the form of viable host(parent[0]) if (parent[0] && 'MutationObserver' in $window) { // use an mutationObserver to tackle #2602 var attributeObserver = new MutationObserver(function(mutations) { mutations .forEach(function (mutation) { if (mutation.attributeName === 'disabled' && parent[0].disabled) { setVisible(false); scope.$digest(); // make sure the elements gets updated } }); }); attributeObserver.observe(parent[0], { attributes: true}); } // Store whether the element was focused when the window loses focus. var windowBlurHandler = function() { elementFocusedOnWindowBlur = document.activeElement === parent[0]; }; var elementFocusedOnWindowBlur = false; function windowScrollHandler() { setVisible(false); } ngWindow.on('blur', windowBlurHandler); ngWindow.on('resize', debouncedOnResize); document.addEventListener('scroll', windowScrollHandler, true); scope.$on('$destroy', function() { ngWindow.off('blur', windowBlurHandler); ngWindow.off('resize', debouncedOnResize); document.removeEventListener('scroll', windowScrollHandler, true); attributeObserver && attributeObserver.disconnect(); }); var enterHandler = function(e) { // Prevent the tooltip from showing when the window is receiving focus. if (e.type === 'focus' && elementFocusedOnWindowBlur) { elementFocusedOnWindowBlur = false; return; } parent.on('blur mouseleave touchend touchcancel', leaveHandler ); setVisible(true); }; var leaveHandler = function () { var autohide = scope.hasOwnProperty('autohide') ? scope.autohide : attr.hasOwnProperty('mdAutohide'); if (autohide || mouseActive || ($document[0].activeElement !== parent[0]) ) { parent.off('blur mouseleave touchend touchcancel', leaveHandler ); parent.triggerHandler("blur"); setVisible(false); } mouseActive = false; }; // to avoid `synthetic clicks` we listen to mousedown instead of `click` parent.on('mousedown', function() { mouseActive = true; }); parent.on('focus mouseenter touchstart', enterHandler ); } function setVisible (value) { setVisible.value = !!value; if (!setVisible.queued) { if (value) { setVisible.queued = true; $timeout(function() { scope.visible = setVisible.value; setVisible.queued = false; }, scope.delay); } else { $mdUtil.nextTick(function() { scope.visible = false; }); } } } function showTooltip() { // Insert the element before positioning it, so we can get the position // and check if we should display it tooltipParent.append(element); // Check if we should display it or not. // This handles hide-* and show-* along with any user defined css if ( $mdUtil.hasComputedStyle(element, 'display', 'none')) { scope.visible = false; element.detach(); return; } updatePosition(); angular.forEach([element, content], function (element) { $animate.addClass(element, 'md-show'); }); } function hideTooltip() { var promises = []; angular.forEach([element, content], function (it) { if (it.parent() && it.hasClass('md-show')) { promises.push($animate.removeClass(it, 'md-show')); } }); $q.all(promises) .then(function () { if (!scope.visible) element.detach(); }); } function updatePosition() { if ( !scope.visible ) return; updateContentOrigin(); positionTooltip(); } function positionTooltip() { var tipRect = $mdUtil.offsetRect(element, tooltipParent); var parentRect = $mdUtil.offsetRect(parent, tooltipParent); var newPosition = getPosition(scope.direction); var offsetParent = element.prop('offsetParent'); // If the user provided a direction, just nudge the tooltip onto the screen // Otherwise, recalculate based on 'top' since default is 'bottom' if (scope.direction) { newPosition = fitInParent(newPosition); } else if (offsetParent && newPosition.top > offsetParent.scrollHeight - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE) { newPosition = fitInParent(getPosition('top')); } element.css({ left: newPosition.left + 'px', top: newPosition.top + 'px' }); function fitInParent (pos) { var newPosition = { left: pos.left, top: pos.top }; newPosition.left = Math.min( newPosition.left, tooltipParent.prop('scrollWidth') - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.left = Math.max( newPosition.left, TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.top = Math.min( newPosition.top, tooltipParent.prop('scrollHeight') - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE ); newPosition.top = Math.max( newPosition.top, TOOLTIP_WINDOW_EDGE_SPACE ); return newPosition; } function getPosition (dir) { return dir === 'left' ? { left: parentRect.left - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE, top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 } : dir === 'right' ? { left: parentRect.left + parentRect.width + TOOLTIP_WINDOW_EDGE_SPACE, top: parentRect.top + parentRect.height / 2 - tipRect.height / 2 } : dir === 'top' ? { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2, top: parentRect.top - tipRect.height - TOOLTIP_WINDOW_EDGE_SPACE } : { left: parentRect.left + parentRect.width / 2 - tipRect.width / 2, top: parentRect.top + parentRect.height + TOOLTIP_WINDOW_EDGE_SPACE }; } } } } MdTooltipDirective.$inject = ["$timeout", "$window", "$$rAF", "$document", "$mdUtil", "$mdTheming", "$rootElement", "$animate", "$q"]; ng.material.components.tooltip = angular.module("material.components.tooltip");
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getBlocks = getBlocks; exports.generateCode = generateCode; exports.compile = compile; var _template = require('./template'); var _template2 = _interopRequireDefault(_template); var _style = require('./style'); var _style2 = _interopRequireDefault(_style); var _script = require('./script'); var _script2 = _interopRequireDefault(_script); var _fs = require('fs'); var _path = require('path'); var _vueTemplateCompiler = require('vue-template-compiler'); var _glob = require('glob'); var _glob2 = _interopRequireDefault(_glob); var _jsBeautify = require('js-beautify'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * parse .vue content to an object with all blocks' code * @param {string} filepath the path of .vue file * * @return {Object} an object with all blocks' code */ /** * @file compile .vue to .js * @author JoeRay61(joeray199261@gmail.com) */ function getBlocks(filepath) { if (!filepath) { return; } var content = (0, _fs.readFileSync)(filepath, 'utf8'); var result = (0, _vueTemplateCompiler.parseComponent)(content); var ret = { template: { code: result.template.content }, script: { code: result.script.content }, styles: [] }; result.styles.forEach(function (e, i) { ret.styles[i] = { code: e.content }; }); result.customBlocks.forEach(function (e, i) { var type = e.type; ret[type] = ret[type] || []; ret[type].push({ code: e.content }); }); return ret; } /** * compile vue file to js code * * @param {string} filepath the path of .vue file * @param {string} mode the output mode, it should be * one of amd/commonjs/global/umd * @return {string} js code with appointed mode */ function generateCode(filepath) { var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd'; // support 4 types of output as follows: // amd/commonjs/global/umd var choice = { amd: { prefix: 'define([\'module\', \'exports\'], function (module, exports) {', suffix: '});' }, commonjs: { prefix: '', suffix: '' }, global: { prefix: '(function (module, exports) {', suffix: '})(this, this.exports = this.exports || {});' }, umd: { prefix: '\n (function (global, factory) {\n typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n (factory(global, global.exports = global.exports || {}));\n }(this, (function (module, exports) {\n ', suffix: '})));' } }; var _ref = choice[mode] || choice.amd, prefix = _ref.prefix, suffix = _ref.suffix; //const content = readFileSync(filepath, 'utf8'); //const result = parseComponent(content); var result = getBlocks(filepath); var templateCode = result.template.code; var styleCode = result.styles.map(function (style) { return (0, _style2.default)(style.code); }).join('\n'); var scriptCode = result.script.code; var code = '\n ' + prefix + '\n /* append style */\n ' + styleCode + '\n\n /* get render function */\n var _module1 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _template2.default)(templateCode) + '\n })(_module1, _module1.exports);\n\n /* get script output data */\n var _module2 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _script2.default)(scriptCode) + '\n })(_module2, _module2.exports);\n\n var obj = _module2.exports.default || _module2.exports;\n obj.render = _module1.exports.render;\n obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n module.exports = obj;\n ' + suffix + '\n '; return (0, _jsBeautify.js_beautify)(code); } /** * compile .vue to .js with appointed destination directory * * @param {Object} options compile config info * @param {string} options.resource glob pattern file path * @param {string} options.dest output destination directory * @param {string} options.mode one of amd/commonjs/umd/global */ function compile(_ref2) { var resource = _ref2.resource, dest = _ref2.dest, mode = _ref2.mode; dest = dest || 'dest'; resource = resource || '*.vue'; mode = ['amd', 'commonjs', 'umd', 'global'].indexOf(mode) > -1 ? mode : 'amd'; if ((0, _fs.existsSync)(dest)) { if (!(0, _fs.statSync)(dest).isDirectory()) { throw new Error('the destination path is already exist and it is not a directory'); } } else { (0, _fs.mkdirSync)(dest); } var files = _glob2.default.sync(resource); files.forEach(function (file) { var name = (0, _path.parse)(file).name; try { var code = generateCode(file, mode); var outputPath = (0, _path.format)({ dir: dest, name: name, ext: '.js' }); (0, _fs.writeFileSync)(outputPath, code); } catch (e) { throw e; } }); }
function KeyboardInputManager() { this.events = {}; this.listen(); } KeyboardInputManager.prototype.on = function (event, callback) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(callback); }; KeyboardInputManager.prototype.emit = function (event, data) { var callbacks = this.events[event]; if (callbacks) { callbacks.forEach(function (callback) { callback(data); }); } }; KeyboardInputManager.prototype.listen = function () { var self = this; var map = { 38: 0, // Up 39: 1, // Right 40: 2, // Down 37: 3, // Left 75: 0, // vim keybindings 76: 1, 74: 2, 72: 3 }; var runButton = document.getElementById('run-button'); runButton.addEventListener('click', function(e) { e.preventDefault(); timerStart = new Date() self.emit('run') }) }; KeyboardInputManager.prototype.restart = function (event) { event.preventDefault(); this.emit("restart"); };
var mod = require('module').prototype; var originalCompile = mod._compile; var esprima = require('esprima'); var enabled = false; var getContainingAyncblock = function(node, asyncblockVarName){ if(asyncblockVarName == null){ return null; } var parent = node; while(parent !== null){ if(parent.callee && parent.callee.name === asyncblockVarName) { return parent; } parent = parent._parent; } return null; }; var getFlowVarName = function(node){ return (node.arguments[0].params[0] || {}).name || '__asyncblock_flow'; }; var getArgsContent = function(args, content){ if(args.length === 0){ return ''; } var firstArg = args[0]; var lastArg = args[args.length - 1]; return content.substring(firstArg && firstArg.range && firstArg.range[0], lastArg && lastArg.range && lastArg.range[1]); }; var getGrandparent = function(node){ return node._parent && node._parent._parent; }; var getGreatGrandparent = function(node){ var grandparent = getGrandparent(node); return grandparent && grandparent._parent; }; var recursiveWalk = function(node, parent, handlers){ var func = handlers[node.type]; node._parent = parent; if(func){ func(node); } for(var key in node){ if(key === '_parent'){ return; } var prop = node[key]; if(Array.isArray(prop)){ prop.forEach(function(prop){ if(prop && prop.type){ recursiveWalk(prop, node, handlers); } }); } else { if(prop && prop.type){ recursiveWalk(prop, node, handlers); } } } }; var _replaceVariableAccess = function(block, variableName, transformations){ recursiveWalk(block, null, { Identifier: function(node){ if(node.name === variableName){ var parent = node._parent; if( (parent.type !== 'VariableDeclarator' || parent.id !== node) && //var x = ..., or var y = x (parent.type !== 'AssignmentExpression' || parent.right === node) && //x = ..., or ... = x parent.type !== 'FunctionExpression' && //function(x) { ... } (parent.type !== 'MemberExpression' || parent.object === node) && //y.x, or x.y parent.key !== node) // { x: ... } { //Make sure variable transformations occur before transformations for the same position transformations.push({ position: node.range[0], insert: '(', priority: -1 }); transformations.push({ position: node.range[1], insert: ' && ' + variableName + '.__lookupGetter__("result") ? ' + variableName + '.result : ' + variableName + ')', priority: -1 }); } } } }); }; var _handleSync = function(node, content, asyncblockVarName, transformations){ var grandparent = getGrandparent(node); var parent = node._parent; var block = getContainingAyncblock(node, asyncblockVarName); if(grandparent && grandparent.type === 'CallExpression' && block){ var prevCallEnd = node._parent.object.range[1]; var chainedFuncArgs = parent.object.arguments; var syncArgs = grandparent.arguments; var syncArgsStr = getArgsContent(syncArgs, content); var flowVarName = getFlowVarName(block); var prefix = chainedFuncArgs.length > 0 ? ', ' : ''; var flowInsertion = prefix + flowVarName + '.addAndReuseFiber(' + syncArgsStr + ')'; //Add flow.sync( before transformations.push({ position: grandparent.range[0], insert: flowVarName + '.sync( '}); //Add in flow.addAndReuseFiber() transformations.push({ position: prevCallEnd - 1, insert: flowInsertion }); //Take off the .sync() transformations.push({ position: parent.range[1] - node.name.length - 1, remove: grandparent.range[1] - parent.range[1] + node.name.length + 1 }); //Add flow.sync closing paren transformations.push({ position: grandparent.range[1], insert: ' )' }); } }; var _handleDeferFuture = function(node, content, asyncblockVarName, transformations){ var grandparent = getGrandparent(node); var parent = node._parent; var block = getContainingAyncblock(node, asyncblockVarName); if(grandparent && grandparent.type === 'CallExpression' && block){ var prevCallEnd = node._parent.object.range[1]; var chainedFuncArgs = parent.object.arguments; var syncArgs = grandparent.arguments; var syncArgsStr = getArgsContent(syncArgs, content); var flowVarName = getFlowVarName(block); var prefix = chainedFuncArgs.length > 0 ? ', ' : ''; var flowInsertion = prefix + flowVarName + '.callback(' + syncArgsStr + ')'; //Add flow.sync( before transformations.push({ position: grandparent.range[0], insert: flowVarName + '.future( '}); //Add in flow.callback() transformations.push({ position: prevCallEnd - 1, insert: flowInsertion }); //Take off the .defer() transformations.push({ position: parent.range[1] - node.name.length - 1, remove: grandparent.range[1] - parent.range[1] + node.name.length + 1 }); //Add flow.defer closing paren transformations.push({ position: grandparent.range[1], insert: ' )' }); } }; exports.compileContents = function(content){ //If the content doesn't contain "asyncblock" or any calls to defer, sync, or future, don't process it if(!(/asyncblock/.test(content) && /\)\s*\.\s*defer\s*\(|\)\s*\.\s*sync\s*\(|\)\s*\.\s*future\s*\(/.test(content))){ return content; } var ast = esprima.parse(content, { range: true, tolerant: true }); if(ast.errors && ast.errors.length > 0){ var hasNonReturnError = ast.errors.some(function(error){ return error.message.indexOf('Illegal return statement') < 0; }); //If there's a parsing error, don't attempt to process the file //Note that we allow for top level return statements as this is often used in conjunction with asyncblock.enableTransform if(hasNonReturnError){ return content; } } var _asyncblockVarName; var transformations = []; //Track locations of asyncblocks recursiveWalk(ast, null, { CallExpression: function(node){ if(_asyncblockVarName && node.callee && node.callee.name === _asyncblockVarName){ //Make sure the flow variable is defined var func = node.arguments[0]; if(func && func.params && func.params.length === 0){ var functionDef = content.substring(func.range[0], func.range[1]); var parenPos = functionDef.indexOf('('); transformations.push({ position: func.range[0] + parenPos + 1, insert: '__asyncblock_flow' }); } } if(!_asyncblockVarName && node.callee && node.callee.name === 'require' && node.arguments && node.arguments[0] && (node.arguments[0].value === 'asyncblock' || node.arguments[0].value === 'asyncblock-generators')){ var parent = node._parent; if(parent.type === 'AssignmentExpression'){ _asyncblockVarName = parent.left.name; } else if(parent.type === 'VariableDeclarator'){ _asyncblockVarName = parent.id.name; } } }, Identifier: function(node){ //Make sure it's x.sync() instead of x.sync, etc. if(node._parent && node._parent.object && node._parent.object.type === 'CallExpression'){ if(node.name === 'sync'){ _handleSync(node, content, _asyncblockVarName, transformations); } else if (node.name === 'defer'){ var greatGrandparent = getGreatGrandparent(node); if(greatGrandparent){ var variableName; if(greatGrandparent.type === 'VariableDeclarator'){ variableName = greatGrandparent.id.name; } else if(greatGrandparent.type === 'AssignmentExpression' && greatGrandparent.left.type === 'Identifier'){ variableName = greatGrandparent.left.name; } else { //defer doesn't work here, use sync instead to retain behavior _handleSync(node, content, _asyncblockVarName, transformations); return; } var block = getContainingAyncblock(node, _asyncblockVarName); if(block){ _handleDeferFuture(node, content, _asyncblockVarName, transformations); _replaceVariableAccess(block, variableName, transformations); } } } else if(node.name === 'future'){ _handleDeferFuture(node, content, _asyncblockVarName, transformations); } } } }); //Sort in descending order so we can make updates to the content without throwing off indexes transformations.sort(function(left, right){ if(left.position < right.position){ return -1; } else if(left.position > right.position){ return 1; } else { if((left.priority || 0) < (right.priority || 0)){ return -1; } else if((left.priority || 0) > (right.priority || 0)){ return 1; } else { return 0; } } }); //console.log(transformations); for(var i = transformations.length - 1; i >= 0; i--){ var transformation = transformations[i]; if(transformation.insert){ content = content.substring(0, transformation.position) + transformation.insert + content.substring(transformation.position); } else if(transformation.remove){ content = content.substring(0, transformation.position) + content.substring(transformation.position + transformation.remove); } } return content; }; exports.enableTransform = function(){ if(enabled){ return false; } else { enabled = true; } mod._compile = function(content, filename) { arguments[0] = exports.compileContents(content, filename); //console.log(arguments[0]) return originalCompile.apply(this, arguments); }; return true; };
var User = require('../models/userModel.js'); var _ = require('lodash'); var signToken = require('../../auth/auth').signToken; exports.params = function(req, res, next, id) { User.findById(id) .select('-password') .exec() .then(function(user) { if (!user) { next(new Error('No user with that id')); } else { req.user = user; next(); } }, function(err) { next(err); }); }; exports.get = function(req, res, next) { User.find({}) .select('-password') .exec() .then(function(user) { res.json(user); }, function(err) { next(err); }) }; exports.getOne = function(req, res, next) { var user = req.user; res.json(user); }; exports.put = function(req, res, next) { var user = req.user; var update = req.body; _.merge(user, update); user.save(function(err, saved) { if (err) { next(err); } else { res.json(saved.toJson()); } }) }; exports.post = function(req, res, next) { var newUser = new User(req.body); newUser.save(function(err, user) { if(err) { return next(err);} var token = signToken(user._id); res.json({token: token}); }); }; exports.delete = function(req, res, next) { req.user.remove(function(err, removed) { if (err) { next(err); } else { res.json(removed.toJson()); } }) }; exports.me = function(req, res) { res.json(req.user.toJson()); };
//! pattern /(\s|query)\(.*?\)\.prev\(/ define('query.prev', ['query'], function (query) { query.fn.prev = function () { var list = []; if (this.length) { var node = this[0].previousElementSibling; if (node) { list.push(node); } return query(list, this.context); } return query([], this.context); }; });
require('newrelic'); var Server = require('./server/server'); var configName = `${__dirname}/config/default.json`; if (process.env.config) configName = require('path').resolve(process.cwd(), process.env.config); var server = new Server(configName); server.start();
import Server from '../services/Server'; import User from '../models/User'; import React, { Component, View, ProgressBarAndroid, StyleSheet, ToastAndroid, Text, AsyncStorage, PropTypes } from 'react-native'; import { MKButton, MKTextField } from 'react-native-material-kit'; export default class LoginView extends Component { constructor(props) { super(props); this.state = { isLoading: false, user: { email: null, name: null, }, }; } successFullyLoggedIn(user) { let registerdUser = new User(user); this.setState({ user: registerdUser }); this.saveData().then(() => { this.props.navigator.replace({ name: 'Add Entry' }); }); } sendData() { let data = { user: this.state.user }; this.setState({ isLoading: true }); Server.post('/users/register.json', data) .then((res) => { this.successFullyLoggedIn(res.user); }) .catch(() => { this.setState({ isLoading: false }); ToastAndroid.show('Sorry, we couldn\'t connect to the server', ToastAndroid.SHORT, 2000); }); } saveData() { return AsyncStorage.setItem('UserDetails', JSON.stringify(this.state.user)); } isFormEmpty() { return !(this.state.user.name && this.state.user.email); } onRegister() { let userData = { email: this.state.email, name: this.state.name }; this.setState({ user: new User(userData) }); if(!this.isFormEmpty()) { this.sendData(); } else { ToastAndroid.show('Name and email id is required', ToastAndroid.SHORT, 2000); } } render() { if(this.state.isLoading) { return ( <View style={styles.progressBar}> <ProgressBarAndroid styleAttr="Inverse"/> </View> ); } else { return ( <View> <MKTextField floatingLabelEnabled floatingLabelFont={{ fontSize: 15, fontWeight: '100' }} highlightColor="#fdc300" keyboardType="default" onChangeText={(name) => this.setState({ name })} placeholder="Name" style={styles.textfieldWithFloatingLabel} /> <MKTextField floatingLabelEnabled floatingLabelFont={{ fontSize: 15, fontWeight: '100' }} highlightColor="#fdc300" keyboardType="email-address" onChangeText={(email) => this.setState({ email })} placeholder="Email" style={styles.textfieldWithFloatingLabel} /> <MKButton backgroundColor={'#43ca01'} onPress={() => this.onRegister()} style={styles.register} > <Text pointerEvents="none" style={{ color: 'white', fontWeight: 'bold', textAlign: 'center' }} > REGISTER </Text> </MKButton> </View> ); } } } LoginView.propTypes = { navigator: PropTypes.object, }; const styles = StyleSheet.create({ textfieldWithFloatingLabel: { height: 50, margin: 10, marginTop: 15, }, progressBar: { flex: 1, justifyContent: 'space-around', alignItems: 'center', }, googleSignIn: { height: 38, padding: 10, margin: 10, marginTop: 20, }, register: { height: 38, padding: 10, margin: 10, }, });
version https://git-lfs.github.com/spec/v1 oid sha256:ac1b43337dbd26721835219d4891bf0fc39b61ae00639be2f6303830e4d660e0 size 1505
import angular from 'angular'; import {CostsReportsDetailComponent} from './costs-reports-detail.component'; import {CostsReportsFormComponent} from './costs-reports-form.component'; import {CostsReportsListComponent} from './costs-reports-list.component'; // Main section component names export const CostsReportsDetail = 'costsReportsDetail'; export const CostsReportsForm = 'costsReportsForm'; export const CostsReportsList = 'costsReportsList'; export const CostsReportsModule = angular .module('app.costs-reports', []) .component(CostsReportsDetail, CostsReportsDetailComponent) .component(CostsReportsForm, CostsReportsFormComponent) .component(CostsReportsList, CostsReportsListComponent) .name;
/*! * multilang-apidocs <https://github.com/nknapp/multilang-apidocs> * * Copyright (c) 2015 Nils Knappmeier. * Released under the MIT license. */ var multilangApidocs = require('../../') var _ = require('lodash') var path = require('path') var fs = require('fs') var outputDir = path.resolve(__dirname, '..', '..', 'test-output') if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir) } /** * * @param fixture {string} * @param opts {object} * @returns {string[]} */ module.exports = function runApidocs (fixture, opts) { var contents = fs.readFileSync(path.resolve(__dirname, '..', 'fixtures', fixture), 'utf-8') var result = multilangApidocs( contents, _.merge({ filename: fixture }, opts )) fs.writeFileSync(path.join(outputDir, fixture + '.md'), result.join('\n')) return result }
function foo() { a(); function bar() {} b(); }
var app = app || {}; (function(){ app.TestButton = React.createClass({displayName: "TestButton", handleClick: function() { this.props.submitTestTask(this.props.btnType); }, render: function() { return ( React.createElement("button", {onClick: this.handleClick, className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) ); } }); app.CodeEditor = React.createClass({displayName: "CodeEditor", handleType:function(){ this.props.updateCode(this.editor.session.getValue()); }, componentDidMount:function(){ this.editor = ace.edit("codeeditor"); this.editor.setTheme("ace/theme/clouds"); this.editor.setOptions({ fontSize: "1.2em" }); this.editor.session.setMode("ace/mode/"+this.props.language); }, render:function(){ return ( React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType}) ); } }); app.TokenEditor = React.createClass({displayName: "TokenEditor", handleChange:function(){ var new_token = this.refs.tokenInput.value; this.props.updateToken(new_token); }, render: function(){ return ( React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"}) ); } }); app.UrlEditor = React.createClass({displayName: "UrlEditor", getInitialState: function(){ return { url_vaild:true } }, handleChange:function(){ //if url valid, update state, if not, warn var url_str = this.refs.urlInput.value; if (app.isUrl(url_str)){ this.setState({url_vaild:true}); //this.probs.updateUrl(url_str) }else{ this.setState({url_vaild:false}); } this.props.updateUrl(url_str); }, classNames:function(){ return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error'); }, render: function(){ return ( React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"}) ); } }); var ServerList = app.ServerList = React.createClass({displayName: "ServerList", getInitialState:function(){ return {chosedServer:-1, currentDisplay:"Servers",servers:[]}; }, componentDidMount:function(){ //get server list this.serverRequest = $.get('http://localhost:8000/home/servers', function (result) { if( result.isSuccessful ){ this.setState({servers:result.servers}); } }.bind(this)); }, componentWillUnmount: function() { this.serverRequest.abort(); }, onServerClick:function(event){ this.setState({currentDisplay:event.currentTarget.dataset.servername}); }, render:function(){ return ( React.createElement("div", null, React.createElement("div", {className: "dropdown"}, React.createElement("button", {ref: "menu_display", className: "btn btn-default dropdown-toggle", type: "button", id: "dropdownMenu1", "data-toggle": "dropdown"}, this.state.currentDisplay, React.createElement("span", {className: "caret"}) ), React.createElement("ul", {className: "dropdown-menu", role: "menu", "aria-labelledby": "dropdownMenu1"}, this.state.servers.map(function(server){ return React.createElement("li", {role: "presentation"}, React.createElement("a", {"data-serverName": server.name, "data-serverid": server.id, onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, server.name)) }.bind(this)) ), React.createElement("button", {className: "btn btn-primary"}, "Add new server") ) ) ); } }) var ResultDisplay = app.ResultDisplay = React.createClass({displayName: "ResultDisplay", getInitialState:function(){ return {'level':-1, test_type:0, 'steps':[]} }, displayResult:function(res_dict){ console.log(res_dict); var test_type = res_dict.test_type this.setState({'test_type':test_type}) if (test_type == 0){ this.setState({'level':res_dict.level}); } this.setState({'steps':res_dict['steps']}); }, render: function(){ return ( React.createElement("div", {className: "result-container"}, React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)), React.createElement("div", {className: "detail-result"}, React.createElement("div", {className: "result-sum"}, this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null ), this.state.steps.map(function(step){ return React.createElement(StepDisplay, {stepInfo: step}) }) ) ) ) } }); var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay", getInitialState: function(){ return { is_img_hide:true, is_modal_show:false, is_has_image:false } }, componentDidMount:function(){ if(this.props.stepInfo.addi){ this.setState({is_has_image:true}); } }, handleTextClick:function(){ if (this.state.is_has_image){ this.setState({is_img_hide:!this.state.is_img_hide}); } }, handleShowFullImage:function(event){ event.stopPropagation(); this.setState({is_modal_show:true}); }, handleHideModal(){ this.setState({is_modal_show:false}); }, handleShowModal(){ this.setState({is_modal_show: true}); }, render:function(){ return ( React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick}, React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, this.props.stepInfo.desc)), React.createElement("div", {hidden: this.state.is_img_hide && !this.state.is_has_image, className: "step-img-block"}, React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"), React.createElement("img", {className: "img-responsive img-rounded step-img", src: this.props.stepInfo.addi}) ), this.state.is_modal_show && this.state.is_has_image ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: this.props.stepInfo.addi})}) : null ) ); } }); app.UserBtnArea = React.createClass({displayName: "UserBtnArea", handleLogout:function(){ app.showMsg("Logout"); }, render:function(){ return ( React.createElement("div", {className: "user-op"}, React.createElement("button", {className: "btn btn-user", onClick: this.props.history_action}, "History"), React.createElement("button", {className: "btn btn-user"}, "Search Task"), React.createElement("button", {className: "btn btn-user"}, "Change Password"), React.createElement("button", {className: "btn btn-user", onClick: this.handleLogout}, React.createElement("span", {className: "glyphicon glyphicon-off"})) ) ); } }); var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea", render:function(){ return( React.createElement("img", {src: this.props.img_src, className: "img-responsive"}) ); } }); var TaskItem = app.TaskItem = React.createClass({displayName: "TaskItem", handleClick:function(){ this.props.itemClicked(this.props.task_id); }, render:function(){ return ( React.createElement("div", {className: "list-item", onClick: this.handleClick}, React.createElement("span", null, "Task ID:"), this.props.task_id ) ); } }); var TaskList = app.TaskList = React.createClass({displayName: "TaskList", render:function(){ return ( React.createElement("div", {className: "task-list"}, React.createElement("h2", null, "History Tasks"), React.createElement("div", {className: "list-content"}, this.props.tasks.map(function(task_id){ return React.createElement(TaskItem, {itemClicked: this.props.fetchTaskDetail, task_id: task_id}) },this) ) ) ); } }); var HistoryViewer = app.HistoryViewer = React.createClass({displayName: "HistoryViewer", getInitialState:function(){ return {tasks:[]}; }, updateTestResult:function(res){ this.refs.res_area.displayResult(res); }, componentDidMount:function(){ window.hist = this; var postData = { token:$.cookie('fhir_token') }; var self = this; console.log(postData); $.ajax({ url:'http://localhost:8000/home/history', type:'POST', data:JSON.stringify(postData), dataType:'json', cache:false, success:function(data){ if( data.isSuccessful ){ self.setState({tasks:data.tasks}); } } }); }, getTaskDetail:function(task_id){ console.log(task_id); app.setup_websocket(task_id,2) }, render:function(){ return ( React.createElement("div", {className: "history-area"}, React.createElement(TaskList, {fetchTaskDetail: this.getTaskDetail, tasks: this.state.tasks}), React.createElement(ResultDisplay, {ref: "res_area"}) ) ); } }); var Modal = app.Modal = React.createClass({displayName: "Modal", componentDidMount(){ $(ReactDOM.findDOMNode(this)).modal('show'); $(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal); }, render:function(){ return ( React.createElement("div", {className: "modal modal-wide fade"}, React.createElement("div", {className: "modal-dialog"}, React.createElement("div", {className: "modal-content"}, React.createElement("div", {className: "modal-header"}, React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")), React.createElement("h4", {className: "modal-title"}, this.props.title) ), React.createElement("div", {className: "modal-body"}, this.props.content ), React.createElement("div", {className: "modal-footer text-center"}, React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close") ) ) ) ) ); } }); })();
const {ipcRenderer} = require('electron') const {runInThisContext} = require('vm') // Check whether pattern matches. // https://developer.chrome.com/extensions/match_patterns const matchesPattern = function (pattern) { if (pattern === '<all_urls>') return true const regexp = new RegExp(`^${pattern.replace(/\*/g, '.*')}$`) const url = `${location.protocol}//${location.host}${location.pathname}` return url.match(regexp) } // Run the code with chrome API integrated. const runContentScript = function (extensionId, url, code) { const context = {} require('./chrome-api').injectTo(extensionId, false, context) const wrapper = `((chrome) => {\n ${code}\n })` const compiledWrapper = runInThisContext(wrapper, { filename: url, lineOffset: 1, displayErrors: true }) return compiledWrapper.call(this, context.chrome) } const runAllContentScript = function (scripts, extensionId) { for (const {url, code} of scripts) { runContentScript.call(window, extensionId, url, code) } } const runStylesheet = function (url, code) { const wrapper = `((code) => { function init() { const styleElement = document.createElement('style'); styleElement.textContent = code; document.head.append(styleElement); } document.addEventListener('DOMContentLoaded', init); })` const compiledWrapper = runInThisContext(wrapper, { filename: url, lineOffset: 1, displayErrors: true }) return compiledWrapper.call(this, code) } const runAllStylesheet = function (css) { for (const {url, code} of css) { runStylesheet.call(window, url, code) } } // Run injected scripts. // https://developer.chrome.com/extensions/content_scripts const injectContentScript = function (extensionId, script) { if (!script.matches.some(matchesPattern)) return if (script.js) { const fire = runAllContentScript.bind(window, script.js, extensionId) if (script.runAt === 'document_start') { process.once('document-start', fire) } else if (script.runAt === 'document_end') { process.once('document-end', fire) } else { document.addEventListener('DOMContentLoaded', fire) } } if (script.css) { const fire = runAllStylesheet.bind(window, script.css) if (script.runAt === 'document_start') { process.once('document-start', fire) } else if (script.runAt === 'document_end') { process.once('document-end', fire) } else { document.addEventListener('DOMContentLoaded', fire) } } } // Handle the request of chrome.tabs.executeJavaScript. ipcRenderer.on('CHROME_TABS_EXECUTESCRIPT', function (event, senderWebContentsId, requestId, extensionId, url, code) { const result = runContentScript.call(window, extensionId, url, code) ipcRenderer.sendToAll(senderWebContentsId, `CHROME_TABS_EXECUTESCRIPT_RESULT_${requestId}`, result) }) // Read the renderer process preferences. const preferences = process.getRenderProcessPreferences() if (preferences) { for (const pref of preferences) { if (pref.contentScripts) { for (const script of pref.contentScripts) { injectContentScript(pref.extensionId, script) } } } }
import App from '../containers/App'; if (typeof System === 'undefined') { var System = { import: (m) => { return new Promise((resolve,reject)=> { resolve(require(m)); }) } } } function errorLoading(err) { console.error('Dynamic page loading failed', err); } function loadRoute(cb) { return (module) => { cb(null, module.default); } } export default { component: App, childRoutes: [ { path: '/', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/Main").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/counter', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/Counter").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/stock-tickers', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/StockTickers").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/about-signalr', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/About").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/slides', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/Slides").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/scalability', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/Scalability").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/sqldependency', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/SQLDependency").then(loadRoute(cb)).catch(errorLoading); } }, { path: '/dashboard', getComponent(location, cb) { //cb(null, Counter) System.import( "../components/Dashboard").then(loadRoute(cb)).catch(errorLoading); } } ] };
/* * dashboard script for futurgo vehicle * extends Vizi.Script */ FuturgoDashboardScript = function(param) { param = param || {}; Vizi.Script.call(this, param); this.enabled = (param.enabled !== undefined) ? param.enabled : true; this.backgroundColor = param.backgroundColor || '#ff0000'; this.textColor = param.textColor || '#aa0000'; this._speed = 0; this._rpm = 0; this._carController = null; this.needsUpdate = false; Object.defineProperties(this, { speed: { get : function() { return this._speed; }, set: function(v) { this.setSpeed(v); } }, rpm: { get : function() { return this._rpm; }, set: function(v) { this._rpm = v; this.needsUpdate = true; } }, carController: { get : function() { return this._carController; }, set: function(controller) { this.setCarController(controller); } }, }); } goog.inherits(FuturgoDashboardScript, Vizi.Script); FuturgoDashboardScript.prototype.realize = function() { // Set up the gauges var gauge = this._object.findNode("head_light_L1"); var visual = gauge.visuals[0]; // Create a new canvas element for drawing var canvas = document.createElement("canvas"); canvas.width = 512; canvas.height = 512; // Create a new Three.js texture with the canvas var texture = new THREE.Texture(canvas); texture.wrapS = texture.wrapT = THREE.RepeatWrapping; visual.material.map = texture; this.texture = texture; this.canvas = canvas; this.context = canvas.getContext("2d"); // Load the textures for the dashboard and dial this.dashboardImage = null; this.dialImage = null; var that = this; var image1 = new Image(); image1.onload = function () { that.dashboardImage = image1; that.needsUpdate = true; } image1.src = FuturgoDashboardScript.dashboardURL; var image2 = new Image(); image2.onload = function () { that.dialImage = image2; that.needsUpdate = true; } image2.src = FuturgoDashboardScript.dialURL; // Force an initial update this.needsUpdate = true; } FuturgoDashboardScript.prototype.update = function() { if (this.needsUpdate) { this.draw(); // this.texture.offset.x += 0.01; this.texture.needsUpdate = true; this.needsUpdate = false; } } FuturgoDashboardScript.prototype.draw = function() { var context = this.context; var canvas = this.canvas; context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle = this.backgroundColor; context.fillRect(0, 0, canvas.width, canvas.height); context.fillStyle = this.textColor; if (this.dashboardImage) { context.drawImage(this.dashboardImage, 0, 0); } var speeddeg = this._speed * 10 - 120; var speedtheta = THREE.Math.degToRad(speeddeg); var rpmdeg = this._rpm * 20 - 90; var rpmtheta = THREE.Math.degToRad(rpmdeg); if (this.dialImage) { context.save(); context.translate(FuturgoDashboardScript.speedDialLeftOffset, FuturgoDashboardScript.speedDialTopOffset); context.rotate(speedtheta); context.translate(-FuturgoDashboardScript.dialCenterLeftOffset, -FuturgoDashboardScript.dialCenterTopOffset); context.drawImage(this.dialImage, 0, 0); // 198, 25, 115); context.restore(); context.save(); context.translate(FuturgoDashboardScript.rpmDialLeftOffset, FuturgoDashboardScript.rpmDialTopOffset); context.rotate(rpmtheta); context.translate(-FuturgoDashboardScript.dialCenterLeftOffset, -FuturgoDashboardScript.dialCenterTopOffset); context.drawImage(this.dialImage, 0, 0); // 198, 25, 115); context.restore(); } } FuturgoDashboardScript.prototype.setSpeed = function(speed) { this._speed = speed; this.needsUpdate = true; } FuturgoDashboardScript.prototype.setRPM = function(rpm) { this._rpm = rpm; this.needsUpdate = true; } FuturgoDashboardScript.prototype.setCarController = function(controller) { this._carController = controller; var that = this; controller.addEventListener("speed", function(speed) { that.setSpeed(speed); }); controller.addEventListener("rpm", function(rpm) { that.setRPM(rpm); }); } // Constants FuturgoDashboardScript.imagePath = '../models/futurgo_mobile/images/'; FuturgoDashboardScript.dashboardURL = FuturgoDashboardScript.imagePath + 'gauges.png'; FuturgoDashboardScript.dialURL = FuturgoDashboardScript.imagePath + 'dial2.png'; FuturgoDashboardScript.speedDialLeftOffset = 256; FuturgoDashboardScript.speedDialTopOffset = 175; FuturgoDashboardScript.rpmDialLeftOffset = 403; FuturgoDashboardScript.rpmDialTopOffset = 360; FuturgoDashboardScript.dialCenterLeftOffset = 12; FuturgoDashboardScript.dialCenterTopOffset = 90;
import test from 'ava'; import getUnit from './'; test('Should be a function', t => { t.is(typeof getUnit, 'function'); t.end(); }); test('Should return normal units', t => { t.is(getUnit('5m'), 'm'); t.is(getUnit('300cm'), 'cm'); t.is(getUnit('2CM'), 'CM'); t.end(); }); test('Should return the right unit when having a dot in the amount', t => { t.is(getUnit('5.5m'), 'm'); t.is(getUnit('.4mm'), 'mm'); t.is(getUnit('3.3000009999009h'), 'h'); t.end(); }); test('Should return the right unit when having a comma in the amount', t => { t.is(getUnit('5,5m'), 'm'); t.is(getUnit(',4mm'), 'mm'); t.is(getUnit('3,3000009999009h'), 'h'); t.end(); }); test('Should throw when passing something that isn\'t a string', t => { [4, undefined, true, null, function () {}].forEach(val => { t.throws(() => { getUnit(val); }, TypeError); }); t.end(); }); test('Should trim whitespace', t => { [' 5mm', '5mm ', ' 5mm '].forEach(val => { t.is(getUnit(val), 'mm'); }); t.end(); }); test('Should return null when there is no unit', t => { t.is(getUnit('5'), null); t.is(getUnit('555'), null); t.is(getUnit('1.003'), null); t.is(getUnit('1,003'), null); t.end(); }); test('Should return a trimmed unit with a space between value and unit', t => { t.is(getUnit('5,5 m'), 'm'); t.is(getUnit(',4 mm'), 'mm'); t.is(getUnit('3,3000009999009 h'), 'h'); t.end(); });
var f = function(a, b) { var g = b.bind(f, 2); g(); console.log(g); } f(1, function(x) { console.log(x); })
/** * @author Anthony Pizzimenti * @desc Checks whether a parameter exists and is of the desired type. * @param {*} param Paramter to check. * @param {string} type Desired type. * @returns {boolean} * @private */ function _paramExist (param, type) { return typeof param === type && param !== undefined && param !== null; } /** * @author Anthony Pizzimenti * @desc Creates an absolute URL from the provided path and root. * @param {string} root Root URL. * @param {string} path Root-relative path. * @returns {*} */ function absurl (root, path) { if (_paramExist(root, "string") && _paramExist(path, "string")) { if (root[root.length - 1] === "/") { return root + path; } else { return root + "/" + path; } } return null; }
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Contributor(s): * * * * ***** END LICENSE BLOCK ***** */ define('ace/mode/dart', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/dart_highlight_rules', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var DartHighlightRules = require("./dart_highlight_rules").DartHighlightRules; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { var highlighter = new DartHighlightRules(); this.foldingRules = new CStyleFoldMode(); this.$tokenizer = new Tokenizer(highlighter.getRules()); }; oop.inherits(Mode, TextMode); (function() { }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/dart_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DartHighlightRules = function() { var constantLanguage = "true|false|null"; var variableLanguage = "this|super"; var keywordControl = "try|catch|finally|throw|break|case|continue|default|do|else|for|if|in|return|switch|while|new"; var keywordDeclaration = "abstract|class|extends|external|factory|implements|interface|get|native|operator|set|typedef"; var storageModifier = "static|final|const"; var storageType = "void|bool|num|int|double|Dynamic|var|String"; var keywordMapper = this.createKeywordMapper({ "constant.language.dart": constantLanguage, "variable.language.dart": variableLanguage, "keyword.control.dart": keywordControl, "keyword.declaration.dart": keywordDeclaration, "storage.modifier.dart": storageModifier, "storage.type.primitive.dart": storageType }, "identifier"); var stringfill = { token : "string", regex : ".+" }; this.$rules = { "start": [ { "token" : "comment", "regex" : /\/\/.*$/ }, { "token" : "comment", // multi line comment "regex" : /\/\*/, "next" : "comment" }, { "token": ["meta.preprocessor.script.dart"], "regex": "^(#!.*)$" }, { "token": [ "keyword.other.import.dart", "meta.declaration.dart"], "regex": "#(?:\\b)(?:library|import|source|resource)(?:\\b)" }, { "token" : ["keyword.other.import.dart", "text"], "regex" : "(?:\\b)(prefix)(\\s*:)" }, { "regex": "\\bas\\b", "token": "keyword.cast.dart" }, { "regex": "\\?|:", "token": "keyword.control.ternary.dart" }, { "regex": "(?:\\b)(is\\!?)(?:\\b)", "token": ["keyword.operator.dart"] }, { "regex": "(<<|>>>?|~|\\^|\\||&)", "token": ["keyword.operator.bitwise.dart"] }, { "regex": "((?:&|\\^|\\||<<|>>>?)=)", "token": ["keyword.operator.assignment.bitwise.dart"] }, { "regex": "(===?|!==?|<=?|>=?)", "token": ["keyword.operator.comparison.dart"] }, { "regex": "((?:[+*/%-]|\\~)=)", "token": ["keyword.operator.assignment.arithmetic.dart"] }, { "regex": "=", "token": "keyword.operator.assignment.dart" }, { "token" : "string", "regex" : "'''", "next" : "qdoc" }, { "token" : "string", "regex" : '"""', "next" : "qqdoc" }, { "token" : "string", "regex" : "'", "next" : "qstring" }, { "token" : "string", "regex" : '"', "next" : "qqstring" }, { "regex": "(\\-\\-|\\+\\+)", "token": ["keyword.operator.increment-decrement.dart"] }, { "regex": "(\\-|\\+|\\*|\\/|\\~\\/|%)", "token": ["keyword.operator.arithmetic.dart"] }, { "regex": "(!|&&|\\|\\|)", "token": ["keyword.operator.logical.dart"] }, { "token" : "constant.numeric", // hex "regex" : "0[xX][0-9a-fA-F]+\\b" }, { "token" : "constant.numeric", // float "regex" : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { "token" : keywordMapper, "regex" : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ], "qdoc" : [ { "token" : "string", "regex" : ".*?'''", "next" : "start" }, stringfill], "qqdoc" : [ { "token" : "string", "regex" : '.*?"""', "next" : "start" }, stringfill], "qstring" : [ { "token" : "string", "regex" : "[^\\\\']*(?:\\\\.[^\\\\']*)*'", "next" : "start" }, stringfill], "qqstring" : [ { "token" : "string", "regex" : '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', "next" : "start" }, stringfill] } }; oop.inherits(DartHighlightRules, TextHighlightRules); exports.DartHighlightRules = DartHighlightRules; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i + match[0].length, 1); } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; }).call(FoldMode.prototype); });
/** * @module Application */ define([ 'prompts/Prompt', 'require.text!templates/prompts/prompt-rdng.html' ], function(Prompt, DesktopTemplate) { /** * @class PromptRdng * @extends {Prompt} */ var PromptRdng = Prompt.extend({ /** * @method initialize * @param {Object} [options] * @param {PromptController} controller * @param {DataReview} review * @constructor */ initialize: function(options, controller, review) { Prompt.prototype.initialize.call(this, options, controller, review); }, /** * @method render * @returns {PromptRdng} */ render: function() { app.timer.setLimits(30, 15); this.$el.html(this.compile(DesktopTemplate)); Prompt.prototype.render.call(this); this.canvas.hideGrid().hide(); return this; }, /** * @method renderAnswer * @returns {PromptRdng} */ renderAnswer: function() { Prompt.prototype.renderAnswer.call(this); if (app.user.settings.isAudioEnabled()) { this.vocab.playAudio(); } this.elements.buttonWrong.hide(); this.elements.fieldHelpText.hide(); this.elements.fieldQuestion.hide(); this.elements.fieldReading.html(this.vocab.getReading(null, { style: app.user.settings.get('readingStyle') })); if (this.vocab.isJapanese() && app.fn.isKana(this.vocab.get('writing'))) { if (this.vocab.get('writing').length === 1) { this.elements.fieldWriting.html(this.vocab.getWriting()); this.elements.fieldReading.html(this.vocab.getDefinition()); } this.elements.fieldDefinition.empty(); } else { this.elements.fieldWriting.html(this.vocab.getWriting()); this.elements.fieldDefinition.html(this.vocab.getDefinition()); } this.elements.fieldHighlight.show(); return this; }, /** * @method renderQuestion * @returns {PromptRdng} */ renderQuestion: function() { Prompt.prototype.renderQuestion.call(this); this.elements.fieldHighlight.hide(); if (this.vocab.isJapanese() && app.fn.isKana(this.vocab.get('writing'))) { if (this.vocab.get('writing').length === 1 ) { this.elements.fieldWriting.html(this.vocab.getWriting()); } else { this.elements.fieldJapaneseDefinition.html(this.vocab.getDefinition()); } } else { this.elements.fieldWriting.html(this.vocab.getWriting()); } this.elements.fieldQuestion.html(app.strings.prompt['reading-question']); return this; }, /** * @method handlePromptClicked * @param {Event} event */ handlePromptClicked: function(event) { if (Prompt.prototype.handlePromptClicked.call(this, event)) { if (this.review.getAt('answered')) { this.next(); } else { this.renderAnswer(); } } }, /** * @method handleWrongButtonClicked * @param {Event} event */ handleWrongButtonClicked: function(event) { if (Prompt.prototype.handleWrongButtonClicked.call(this, event)) { this.review.setAt('score', 1); this.renderAnswer(); } }, /** * @method resize * @returns {PromptRdng} */ resize: function() { Prompt.prototype.resize.call(this); var canvasSize = this.canvas.getWidth(); var contentHeight = app.router.currentPage.getContentHeight(); var contentWidth = app.router.currentPage.getContentWidth(); if (app.isPortrait()) { this.$el.css({ height: contentHeight, width: contentWidth }); this.elements.fieldDefinition.css({ 'max-height': contentHeight / 2.2, 'padding': '0 10px' }); } else { this.$el.css({ height: canvasSize, width: contentWidth }); this.elements.fieldDefinition.css({ 'max-height': contentHeight / 4, 'padding': '0 60px' }); } return this; } }); return PromptRdng; });
/** * Creates/updates tabs and waits for process finished (returns Promise) * Saves initial and final urls. */ const thenChrome = require('then-chrome'); // map of tabs that are currently loading (waiting "complete" status) const tabs = new Map(); /** * Creates new tab * @param {Object} info * @returns {Promise} */ exports.create = function (info) { ensureListeners(); return Promise.resolve() .then(() => thenChrome.tabs.create(info)) .then(createLoadingTab); }; /** * Updates tab * @param {Number} tabId * @param {Object} info * @returns {Promise} */ exports.update = function (tabId, info) { ensureListeners(); return Promise.resolve() .then(() => thenChrome.tabs.update(tabId, info)) .then(createLoadingTab); }; /** * Waits for existing tab to get loaded (receive 'complete' status) * * @param {Number} tabId * @param {Boolean} force - wait for complete event even if tab in complete status now * @returns {Promise} */ exports.wait = function (tabId, force = false) { ensureListeners(); return thenChrome.tabs.get(tabId) .then(tab => { if (tab.status === 'loading' || force) { return createLoadingTab(tab); } }); }; function ensureListeners() { if (!chrome.tabs.onUpdated.hasListener(onTabUpdated)) { chrome.tabs.onUpdated.addListener(onTabUpdated); } } function onTabUpdated(tabId, changeInfo, tab) { if (tabs.has(tabId) && changeInfo.status === 'complete') { const info = tabs.get(tabId); tab.initialUrl = info.initialUrl; info.resolve(tab); tabs.delete(tabId); } } function createLoadingTab(tab) { if (tabs.has(tab.id)) { const tabInfo = tabs.get(tab.id); // reject previous promise tabInfo.reject(); tabs.delete(tab.id); } return new Promise((resolve, reject) => { const tabInfo = {resolve, reject, initialUrl: tab.url}; tabs.set(tab.id, tabInfo); }); }
$(document).ready(function(){ $.ajax({ url : "simulatedAnnealing.js", dataType: "text", success : function (data) { $("#simulatedAnnealingCode").html(data); } }); var annealingCanvas; var text,line,background; var w,h; var two; var sa; var x = 0; // Current Index var f; // The objective function var DELAY = 1 * 60; var POINTS = 30; // Number of points of the objective function var INITIAL_TEMP = 50; var K = 1; // Boltzmann constant function init(){ annealingCanvas = document.getElementById("annealingCanvas"); annealingCanvas.addEventListener("click", handleClick, false); w = annealingCanvas.offsetWidth; h = 300; two = new Two({ width: w, height: h }).appendTo(annealingCanvas); sa = new SimulatedAnnealing(x,K,INITIAL_TEMP); text = two.makeText("Temperature: "+INITIAL_TEMP,w/2 ,10,'normal'); line = two.makeLine(x,0,x,h); line.stroke = 'orangered'; line.linewidth = 5; setupScene(); } init(); two.bind('update', function(frameCount){ if(frameCount % DELAY == 0){ x = sa.anneal(f); // Translate the point according to the new chosen point line.translation.set(x*w/POINTS,h/2); y = Math.round(f[x]*100)/100; text.value = "Temperature: "+sa.T + " ("+x+" , "+y+")"; } }).play(); function handleClick(){ // When ever the canvas is clicked // recalculate and redraw the background // and reinitialize the sa object setupScene(); x = 0; sa = new SimulatedAnnealing(x,K,INITIAL_TEMP); } function setupScene(){ // If background already exists, // then clear it if(background != null) two.remove(background); f = new Array(POINTS); background = new Array(POINTS-1); f[0] = 0; for(var i = 1; i < f.length; i++){ // f[i] ranges between 0 and 3*h/4 f[i] = Math.random() * 3*h/4; sx = (i-1) * w/POINTS; sy = h - f[i-1]; fx = i * w/POINTS; fy = h - f[i]; // Draw lines connecting all f[i] background[i-1] = two.makeLine(sx,sy,fx,fy); background[i-1].linewidth = 2; background[i-1].stroke = '#090A3B'; } two.update(); } });
(function () { 'use strict'; angular.module('myApp.directives') .directive('d3TimeSeries', [function () { return { restrict: 'EA', scope: { data: "=", label: "@", onClick: "&" }, link: function (scope, iElement, iAttrs) { // initialise svg and binds it to DOM var svg = d3.select(iElement[0]).append("svg") .attr("width", "100%") .attr("height", "100%") // watch for data changes and re-render scope.$watch('data', function (newVals, oldVals) { return scope.render(newVals); }, true); // Watch for changes in parent element size scope.$watch(function () { return d3.select(iElement[0])[0][0].offsetHeight; }, function () { return scope.render(scope.data); }); scope.$watch(function () { return d3.select(iElement[0])[0][0].offsetWidth; }, function () { return scope.render(scope.data); }); // define render function scope.render = function (data) { // refresh canvas by removing all previous items at the start of each rendering svg.selectAll("*").remove(); // Get width and height of element var elementWidth = d3.select(iElement[0])[0][0].offsetWidth; var elementHeight = d3.select(iElement[0])[0][0].offsetHeight; // stop rendering and return immediately if DOM is not fully initialised if (elementHeight == 0) { return; } var margin = { top: 20, right: 50, bottom: 30, left: 50 } var legendWidth = 80; var chartWidth = elementWidth - margin.left - margin.right - legendWidth; var chartHeight = elementHeight - margin.top - margin.bottom; var chart = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var parseDate = d3.time.format("%B").parse; var x = d3.time.scale() .range([0, chartWidth]); var y = d3.scale.linear() .range([chartHeight, 0]); var color = d3.scale.ordinal(); color.range(['#5CAFAF', '#FF6262', 'black']); color.domain(d3.keys(data[0]).filter(function (key) { return key !== "month"; })); var xAxis = d3.svg.axis() .scale(x) .ticks(d3.time.month) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .tickSize(chartWidth) .orient("right"); var line = d3.svg.line() .interpolate("linear") //basis, linear .x(function (d) { return x(d.month); }) .y(function (d) { return y(d.total); }); // transform data // to check if month is a text, for monthIsText() function var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var parseMonth = function () { if (monthIsText(data[0].month)) { data.forEach(function (d) { d.month = parseDate(d.month); }); } ; } var monthIsText = function (month) { var isText = false; months.forEach(function (d) { if (month === d) { isText = true; } }); return isText; } parseMonth(); // create new data set // 'color' is not involved except for providing its set of domain var sources = color.domain().map(function (name) { return { name: name, values: data.map(function (d) { return { month: +d.month, total: +d[name] // '+' here works like Number( ), to typeset the data into number }; }) }; }); x.domain(d3.extent(data, function (d) { return d.month; })); y.domain([ 0, d3.max(sources, function (s) { return d3.max(s.values, function (x) { return x.total; }); }) ]); chart.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + chartHeight + ")") .call(xAxis); var yA = chart.append("g") .attr("class", "y axis") .call(yAxis); yA.selectAll("g").filter(function (d) { return d; }) .classed("minor", true); yA.selectAll("text") .attr("x", -20) .attr("dy", 2.5); var source = chart.selectAll(".source") .data(sources) .enter().append("g") .attr("class", "source"); source.append("path") .attr("class", "line") .attr("d", function (d) { return line(d.values); // line is a function defined above to handle these values }) .style("stroke", function (d) { return color(d.name); }); // TODO: Refactor code for bisector source.selectAll(".miniCircle1") .data(data) .enter() .append("circle") .attr("cx", function (d) { return x(d.month); }) .attr("cy", function (d) { return y(d["agencies"]); }) .attr("fill", function (d) { return color("agencies"); }) .attr("r", 3) source.selectAll(".miniCircle2") .data(data) .enter() .append("circle") .attr("cx", function (d) { return x(d.month); }) .attr("cy", function (d) { return y(d["jobBoard"]); }) .attr("fill", function (d) { return color("jobBoard"); }) .attr("r", 3) source.selectAll(".miniCircle3") .data(data) .enter() .append("circle") .attr("cx", function (d) { return x(d.month); }) .attr("cy", function (d) { return y(d["referrals"]); }) .attr("fill", function (d) { return color("referrals"); }) .attr("r", 3) var offsetForLegendRect = (elementHeight - (sources.length * 35)) / 2; var legend = svg.selectAll(".legend") .data(sources) .enter().append("g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(0," + ((i * 35) + offsetForLegendRect) + ")"; }); legend.append("rect") .attr("x", margin.left + chartWidth + 20) .attr("width", 35) .attr("height", 30) .style("fill", function (d) { return color(d.name) }); // display name for each source in legend var sourcesMap = { agencies: "Agencies", jobBoard: "Job Board", referrals: "Referrals" }; legend.append("text") .attr("x", margin.left + chartWidth + 60) .attr("y", 9) .attr("dy", ".8em") .style("text-anchor", "start") .text(function (d) { return sourcesMap[d.name]; }); var sourceTotal = function (s) { var total = 0; for (var i = 0; i < s.values.length; i++) { total += s.values[i].total; } ; return total; }; var sourcesSum = (function () { var sum = 0; for (var i = 0; i < sources.length; i++) { sum += sourceTotal(sources[i]); } return sum; })(); // to display percentage for each source legend.append("text") .attr("x", margin.left + chartWidth + 23) .attr("y", 9) .attr("dy", ".8em") .attr("fill", "white") .style("text-anchor", "start") .text(function (d, i) { return (((sourceTotal(sources[i])) / sourcesSum) * 100).toFixed(1) + "%"; }); // to display header 'Total' for legend svg.append("text") .attr("x", margin.left + chartWidth + 22) .attr("y", offsetForLegendRect - 15) .attr("font-size", 11) .text("Total"); var bisectMonth = d3.bisector(function (d) { return d.month; }).left; var focusLine = svg.append("line") .style("display", "none"); var focus1 = svg.append("g") .attr("class", "focus") .style("display", "none"); focus1.append("circle") .attr("r", 3); focus1.append("rect") .attr("rx", 2) .attr("ry", 2) .attr("x", 7) .attr("y", -6) .attr("height", 12) .attr("width", 21) .attr("fill", "white") .style("opacity", "0.8") .style("stroke", "black") .style("stroke-width", "1") ; focus1.append("text") .attr("x", 12) .attr("dy", ".35em"); var focus2 = svg.append("g") .attr("class", "focus") .style("display", "none"); focus2.append("circle") .attr("r", 3); focus2.append("rect") .attr("rx", 2) .attr("ry", 2) .attr("x", 7) .attr("y", -6) .attr("height", 12) .attr("width", 21) .attr("fill", "white") .style("opacity", "0.8") .style("stroke", "black") .style("stroke-width", "1") ; focus2.append("text") .attr("x", 12) .attr("dy", ".35em"); var focus3 = svg.append("g") .attr("class", "focus") .style("display", "none"); focus3.append("circle") .attr("r", 3); focus3.append("rect") .attr("rx", 2) .attr("ry", 2) .attr("x", 7) .attr("y", -6) .attr("height", 12) .attr("width", 21) .attr("fill", "white") .style("opacity", "0.8") .style("stroke", "black") .style("stroke-width", "1") ; focus3.append("text") .attr("x", 12) .attr("dy", ".35em"); chart.append("rect") .attr("class", "overlay") .attr("width", chartWidth) .attr("height", chartHeight) .on("mouseover", function () { focus1.style("display", null); focus2.style("display", null); focus3.style("display", null); focusLine.style("display", null); }) .on("mouseout", function () { focus1.style("display", "none"); focus2.style("display", "none"); focus3.style("display", "none"); focusLine.style("display", "none"); }) .on("mousemove", mousemove); function mousemove() { var x0 = x.invert(d3.mouse(this)[0]), // invert range to get the domain for x, which will return the date i = bisectMonth(data, x0, 1), d0 = data[i - 1], d1 = data[i], d = x0 - d0.month > d1.month - x0 ? d1 : d0; // highlight the node that is closer to the mouse focus1.attr("transform", "translate(" + (margin.left + x(d.month)) + "," + (margin.top + y(d.agencies)) + ")"); focus1.select("text").text(d.agencies); focus2.attr("transform", "translate(" + (margin.left + x(d.month)) + "," + (margin.top + y(d.jobBoard)) + ")"); focus2.select("text").text(d.jobBoard); focus3.attr("transform", "translate(" + (margin.left + x(d.month)) + "," + (margin.top + y(d.referrals)) + ")"); focus3.select("text").text(d.referrals); focusLine.attr("x1", margin.left + x(d.month)) .attr("y1", margin.top) .attr("x2", margin.left + x(d.month)) .attr("y2", margin.top + chartHeight) .attr("stroke-width", 1) .style("stroke", "#4C4C4C"); } }; } }; }]); }());
import Ember from 'ember'; import HistoryTable from '../../mixins/compostPileHistoryTable' const { computed } = Ember; export default Ember.Component.extend(HistoryTable, { columns: computed(function() { return [{ label: 'Date', valuePath: 'date', width: '250px', }, { label: 'Temperature', valuePath: 'temperature', width: '200px' }, { label: 'Moisture', valuePath: 'moisture', width: '200px' }, { label: 'Is Turned', valuePath: 'turned' }, { label: 'Scraps Added', valuePath: 'scrapsadded' }]; }), });
// app.controller("YoutubeCtrl", ["$scope", "$http", function($scope, $http) { // // $scope.tracks = [1, 2, 3]; // $scope.submit = function() { // $http.post("/youtube/search").success(function(data){ // console.log(data) // }) // } // }]);
class GameOfLife { constructor (props) { this.grid = {} this.offsets = [-1, 0, 1] if (props) { this.minX = props.minX this.minY = props.minY this.maxX = props.maxX this.maxY = props.maxY } } setAlive (coords) { if (this.isValidCoords(coords)) { this.grid[coords] = true } } setDead (coords) { delete this.grid[coords] } clear () { this.grid = {} } *getAliveCells () { for (let coordsStr of Object.keys(this.grid)) { yield this.getCoordsFromStr(coordsStr) } } isValidCoords (coords) { if ( this.isWithinBoundary(coords[0], this.minX, 'min') && this.isWithinBoundary(coords[1], this.minY, 'min') && this.isWithinBoundary(coords[0], this.maxX, 'max') && this.isWithinBoundary(coords[1], this.maxY, 'max') ) { return true } else { return false } } isWithinBoundary (value, boundary, boundaryType) { if (typeof boundary === 'undefined') { return true } switch (boundaryType) { case 'min': return value >= boundary case 'max': return value <= boundary } } isAlive (coords) { return Boolean(this.grid[coords]) } nextFrame () { const newGrid = {} for (let coords of this.getUniqueCoordsToRerender()) { if (this.isAliveInNextState(coords)) { newGrid[coords] = true } } this.grid = newGrid } *getUniqueCoordsToRerender () { const yielded = [] for (let coords of this.getCoordsToRerender()) { if (yielded.indexOf(coords.toString()) == -1) { yield coords yielded.push(coords.toString()) } } } *getCoordsToRerender () { for (let aliveCoords of this.getAliveCoords()) { yield aliveCoords for (let deadNeighbourCoords of this.getDeadNeighbourCoords(aliveCoords)) { yield deadNeighbourCoords } } } *getAliveCoords () { for (let coordsStr of Object.keys(this.grid)) { const coords = this.getCoordsFromStr(coordsStr) if (this.isAlive(coords)) { yield coords } } } getCoordsFromStr (str) { return str.split(',').map(coord => parseInt(coord)) } isAliveInNextState (coords) { if (this.isAlive(coords)) { return this.canLiveOn(coords) } else { return this.comesToLife(coords) } } canLiveOn (coords) { const aliveNeighbours = this.getAmountAliveNeighbours(coords) if (aliveNeighbours > 1 && aliveNeighbours < 4) { return true } else { return false } } comesToLife (coords) { return this.getAmountAliveNeighbours(coords) == 3 } getAmountAliveNeighbours (coords) { let amount = 0 for (let neighbourCoords of this.getNeighbourCoords(coords)) { amount += +this.isAlive(neighbourCoords) } return amount } *getDeadNeighbourCoords (coords) { for (let neighbourCoords of this.getValidNeighbourCoords(coords)) { if (!this.isAlive(neighbourCoords)) yield neighbourCoords } } *getValidNeighbourCoords (coords) { for (let neighbourCoords of this.getNeighbourCoords(coords)) { if (this.isValidCoords(neighbourCoords)) { yield neighbourCoords } } } *getNeighbourCoords (coords) { for (let [xOffset, yOffset] of this.getNeighbourOffsets()) { yield [ coords[0] + xOffset, coords[1] + yOffset ] } } *getNeighbourOffsets () { for (let xOffset of this.offsets) { for (let yOffset of this.offsets) { if (xOffset == 0 && yOffset == 0) continue yield [xOffset, yOffset] } } } }
import { defineMessages } from 'react-intl' /* eslint-disable max-len */ export default defineMessages({ chain: 'Chain', network: 'Network', host: 'Host', section_basic_title: 'Basic', section_autopilot_title: 'Autopilot', section_autopilot_tooltip: 'Autopilot automates the process of finding, funding and establishing payment channels with other nodes.', section_naming_title: 'Naming', section_naming_connections: 'Connections', section_delete_title: 'Delete', section_connection_details: 'Connection details', create_wallet_button_text: 'Create new wallet', launch_wallet_button_text: 'Launch now', delete_wallet_dialog_acknowledgement: 'I understand this is an irreversible action', delete_wallet_dialog_warning: 'Deleting the wallet data may cause loss of funds. All data from the following wallet directory will be removed:', delete_wallet_dialog_header: 'Are you sure you want to delete this wallet?', delete_wallet_dialog_delete_text: 'Delete', delete_wallet_dialog_cancel_text: 'Cancel', settings_title: 'Settings', delete_wallet_button_text: 'Delete wallet', wallet_settings_name_label: 'Wallet name', wallet_settings_name_description: 'The wallet name is only visible to you inside Zap.', wallet_settings_name_placeholder: 'Enter name', wallet_settings_alias_label: 'Alias', wallet_settings_alias_description: 'The alias is visible to others on the network.', wallet_settings_alias_placeholder: 'Enter alias', wallet_settings_autopilotAllocation_label: 'Percentage of Balance', wallet_settings_autopilotMaxchannels_label: 'Number of Channels max', wallet_settings_autopilotMinchansize_label: 'Minimum channel size', wallet_settings_autopilotMaxchansize_label: 'Maximum channel size', wallet_settings_reset_autopilot_button_text: 'Set Autopilot settings to default', wallets_menu_local_title: 'Your wallets', wallets_menu_other_title: 'More', wallet_unlocker_password_label: 'Enter Password', wallet_unlocker_password_placeholder: 'Enter your password', wallet_unlocker_button_label: 'Enter', no_active_wallet_message: 'Please select a wallet from the wallets menu.', or: 'or', no_wallets_message: 'Unfortunately you don’t have any wallets 😢', create_wallet_prompt: 'Start creating one from here:', saved_notification: 'Settings have been updated', saved_error: 'Something went wrong', button_save: 'Save', button_cancel: 'Cancel', hostname_title: 'Host', cert_title: 'TLS Certificate', macaroon_title: 'Macaroon', cert_description: 'Path to the lnd tls cert.', hostname_description: 'Hostname and port of the Lnd gRPC interface.', macaroon_description: 'Path to the lnd macaroon file.', hide_connection_string: 'Hide connection string', connection_string: 'Connection string', neutrinoUrl_label: 'Neutrino nodes', neutrinoUrl_description: 'Neutrino compliant node addresses', neutrinoUrl_tooltip: 'Connect only to the specified peers at startup. Each URL must start from new line.', wallet_settings_reset_neutrino_button_text: 'Set neutrino settings to default', wallet_settings_whitelist_peers: 'Connect only to specified nodes', })
var request = require('request'); var crypto = require('crypto'); var key = '*********'; var secret = '***********'; var timestamp = Date.now().toString(); console.log(timestamp) var method = 'GET'; var path = '/v1/me/getpositions?product_code=FX_BTC_JPY'; var text = timestamp + method + path; console.log(text) var sign = crypto.createHmac('sha256', secret).update(text).digest('hex'); console.log(sign) var options = { url: 'https://api.bitflyer.jp' + path, method: method, headers: { 'ACCESS-KEY': key, 'ACCESS-TIMESTAMP': timestamp, 'ACCESS-SIGN': sign } }; request(options, function (err, response, payload) { console.log(payload); });
'use strict'; angular.module('auth.bearer-token').provider('authBearerTokenStorage', ['authBearerTokenHttpInterceptorProvider', function authBearerTokenStorageProvider(authBearerTokenHttpInterceptorProvider) { this.$get = ['$localStorage', '$log', '$rootScope', 'authBearerTokenEvents', 'authBearerTokenCookieName', function($localStorage, $log, $rootScope, authBearerTokenEvents, authBearerTokenCookieName) { var log = authBearerTokenHttpInterceptorProvider.options.log ? $log[authBearerTokenHttpInterceptorProvider.options.log] : function () {}; /** * Get or set the auth token to be included in * @param {string|false|null} newToken - New token or false/null to clear the token * @param {object} authResponse - The HTTP Response; used by the interceptor * @return {object} - The current token */ return function(newToken, authResponse) { var existingCookie; if (false === newToken || null === newToken) { log('authBearerTokenStorage - removing token from cookie'); delete $localStorage[authBearerTokenCookieName]; $rootScope.$broadcast(authBearerTokenEvents.SESSION_END); return null; } if (newToken) { existingCookie = $localStorage[authBearerTokenCookieName]; if (!existingCookie) { // if no token exists yet, we're starting the session log('authBearerTokenStorage - saving token into cookie'); $localStorage[authBearerTokenCookieName] = newToken; $rootScope.$broadcast(authBearerTokenEvents.SESSION_START, authResponse); } else if (newToken !== existingCookie) { // if token exists but it has changed, we're updating the session log('authBearerTokenStorage - saving updated token into cookie'); $localStorage[authBearerTokenCookieName] = newToken; $rootScope.$broadcast(authBearerTokenEvents.SESSION_UPDATE, authResponse); } else { // if token is the same, no session event has occurred log('authBearerTokenStorage - token matches existing; no event triggered'); $localStorage[authBearerTokenCookieName] = newToken; } } return $localStorage[authBearerTokenCookieName]; }; } ]; } ]);
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/testproject', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _iceCap = require('ice-cap'); var _iceCap2 = _interopRequireDefault(_iceCap); var _DocBuilderJs = require('./DocBuilder.js'); var _DocBuilderJs2 = _interopRequireDefault(_DocBuilderJs); /** * Identifier output builder class. */ var IdentifiersDocBuilder = (function (_DocBuilder) { function IdentifiersDocBuilder() { _classCallCheck(this, IdentifiersDocBuilder); _get(Object.getPrototypeOf(IdentifiersDocBuilder.prototype), 'constructor', this).apply(this, arguments); } _inherits(IdentifiersDocBuilder, _DocBuilder); _createClass(IdentifiersDocBuilder, [{ key: 'exec', /** * execute building output. * @param {function(html: string, filePath: string)} callback - is called with output. */ value: function exec(callback) { var ice = this._buildLayoutDoc(); var title = this._getTitle('Index'); ice.load('content', this._buildIdentifierDoc()); ice.text('title', title, _iceCap2['default'].MODE_WRITE); callback(ice.html, 'identifiers.html'); } }, { key: '_buildIdentifierDoc', /** * build identifier output. * @return {IceCap} built output. * @private */ value: function _buildIdentifierDoc() { var indexInfo = this._getInfo(); var ice = new _iceCap2['default'](this._readTemplate('identifiers.html')); ice.text('title', indexInfo.title); ice.text('version', indexInfo.version, 'append'); ice.text('url', indexInfo.url); ice.attr('url', 'href', indexInfo.url); ice.text('description', indexInfo.desc); ice.load('classSummary', this._buildSummaryHTML(null, 'class', 'Class Summary'), 'append'); ice.load('interfaceSummary', this._buildSummaryHTML(null, 'interface', 'Interface Summary'), 'append'); ice.load('functionSummary', this._buildSummaryHTML(null, 'function', 'Function Summary'), 'append'); ice.load('variableSummary', this._buildSummaryHTML(null, 'variable', 'Variable Summary'), 'append'); ice.load('typedefSummary', this._buildSummaryHTML(null, 'typedef', 'Typedef Summary'), 'append'); return ice; } }]); return IdentifiersDocBuilder; })(_DocBuilderJs2['default']); exports['default'] = IdentifiersDocBuilder; module.exports = exports['default'];
'use strict'; var chalk, fs, inArray, sortPrompts, yeoman, yosay; yeoman = require('yeoman-generator'); chalk = require('chalk'); yosay = require('yosay'); fs = require('fs'); inArray = function(value, array) { var val, _i, _len; for (_i = 0, _len = array.length; _i < _len; _i++) { val = array[_i]; if (val === value) { return true; } } return false; }; sortPrompts = function(a, b) { if (a.name > b.name) { return 1; } if (b.name > a.name) { return -1; } return 0; }; module.exports = yeoman.generators.Base.extend({ initializing: function() { this.pkg = require('../package.json'); }, prompting: { welcome: function() { this.log(yosay('Welcome to the fantastic ' + chalk.red('WebappKit') + ' generator!')); }, name: function() { var done, prompts, _appname; _appname = this.appname; done = this.async(); prompts = [ { type: 'input', name: 'appName', message: 'What is your app name', "default": _appname } ]; this.prompt(prompts, (function(props) { props.appName = props.appName.replace(/\s/g, '-'); this.config.set(props); done(); }).bind(this)); }, authors: function() { var done, prompt; done = this.async(); prompt = [ { type: 'input', name: 'authors', message: 'Author: ', store: true } ]; this.prompt(prompt, (function(props) { this.config.set(props); done(); }).bind(this)); }, description: function() { var done, prompt; done = this.async(); prompt = [ { type: 'input', name: 'description', message: 'Description: ' } ]; this.prompt(prompt, (function(props) { this.config.set(props); done(); }).bind(this)); }, license: function() { var done, prompt; done = this.async(); prompt = [ { type: 'input', name: 'license', message: 'License: ', "default": 'MIT' } ]; this.prompt(prompt, (function(props) { this.config.set(props); done(); }).bind(this)); }, plugins: function() { var done, prompt; done = this.async(); prompt = [ { type: 'checkbox', name: 'plugins', message: 'Select plugins: ', choices: [ { name: 'Bootstrap', value: { name: 'bootstrap', installer: 'npm' } }, { name: 'Pure.css', value: { name: 'purecss', installer: 'npm' } }, { name: 'Normalize.css', value: { name: 'normalize.css', installer: 'npm' } }, { name: 'jQuery', value: { name: 'jquery', installer: 'npm' } }, { name: 'AngularJS', value: { name: 'angular', installer: 'npm' } }, { name: 'Vue.js', value: { name: 'vue', installer: 'npm' } } ].sort(sortPrompts) } ]; this.prompt(prompt, (function(props) { this.config.set(props); done(); }).bind(this)); } }, configuring: { packageJSON: function() { this.fs.copyTpl(this.templatePath('_package.json'), this.destinationPath('package.json'), { appName: this.config.get('appName'), authors: this.config.get('authors'), description: this.config.get('description'), license: this.config.get('license') }); }, bowerFiles: function() { this.fs.copyTpl(this.templatePath('_bower.json'), this.destinationPath('bower.json'), { appName: this.config.get('appName') }); }, editorconfigFile: function() { this.fs.copy(this.templatePath('editorconfig'), this.destinationPath('.editorconfig')); }, jshintrcFile: function() { this.fs.copy(this.templatePath('jshintrc'), this.destinationPath('.jshintrc')); }, jscsrcFile: function() { this.fs.copy(this.templatePath('jscsrc'), this.destinationPath('.jscsrc')); }, gitFile: function() { this.fs.copy(this.templatePath('gitignore'), this.destinationPath('.gitignore')); this.fs.copy(this.templatePath('gitattributes'), this.destinationPath('.gitattributes')); }, coffeelint: function() { this.fs.copy(this.templatePath('_coffeelint.json'), this.destinationPath('coffeelint.json')); } }, writing: { readme: function() { this.fs.copyTpl(this.templatePath('_Readme.md'), this.destinationPath('Readme.md'), { appName: this.config.get('appName'), description: this.config.get('description') }); }, gruntfile: function() { this.fs.copy(this.templatePath('_Gruntfile.coffee'), this.destinationPath('Gruntfile.coffee')); }, webpack: function() { this.fs.copy(this.templatePath('_webpack.config.js'), this.destinationPath('webpack.config.js')); this.fs.copy(this.templatePath('_webpack.production.config.js'), this.destinationPath('webpack.production.config.js')); }, folders: function() { this.fs.write(this.destinationPath('HTML/Readme.md'), '#HTML开发目录'); this.fs.write(this.destinationPath('scripts/Readme.md'), '#脚本开发目录'); this.fs.write(this.destinationPath('fake-response/Readme.md'), '#模拟响应目录'); this.fs.write(this.destinationPath('images/Readme.md'), '#图片目录'); this.fs.write(this.destinationPath('plugins/Readme.md'), '#插件目录'); this.fs.write(this.destinationPath('psd/Readme.md'), '#设计PSD目录'); this.fs.write(this.destinationPath('stylesheets/Readme.md'), '#CSS开发目录'); }, commonHTML: function() { this.fs.copy(this.templatePath('__page-head.html'), this.destinationPath('HTML/common/_page-head.html')); this.fs.copy(this.templatePath('__page-foot.html'), this.destinationPath('HTML/common/_page-foot.html')); }, commonStyle: function() { this.fs.copy(this.templatePath('_util.css'), this.destinationPath('stylesheets/common/util.css')); return this.fs.write(this.destinationPath('stylesheets/common/common.css'), '/* common style */'); }, indexTemplate: function() { this.fs.copy(this.templatePath('_index.html'), this.destinationPath('HTML/index.html')); this.fs.write(this.destinationPath('stylesheets/pages/website-index.css'), '/* Stuff your style */'); this.fs.write(this.destinationPath('scripts/pages/website-index.js'), '(function(){ \'use strict\';require(\'stylesheets/pages/website-index.css\'); })();'); return this.fs.write(this.destinationPath('app-entry.js'), 'module.exports = { "website-index": "./website-index" }'); } }, install: { grunt: function() { var list, _me; _me = this; list = ['matchdep', 'grunt', 'grunt-contrib-watch', 'grunt-contrib-imagemin', 'grunt-include-replace', 'grunt-usemin', 'grunt-filerev', 'grunt-filerev-assets', 'grunt-cwebp', 'grunt-contrib-jshint', 'grunt-coffeelint']; this.npmInstall(list, { saveDev: true }); }, webpack: function() { var list; list = ['webpack', 'dev-server-fe', 'coffee-loader', 'script-loader', 'babel-loader', 'extract-text-webpack-plugin', 'style-loader', 'css-loader', 'file-loader', 'url-loader', 'less-loader', 'sass-loader', 'assets-webpack-plugin', 'postcss-loader', 'autoprefixer', 'postcss-color-rgba-fallback', 'postcss-opacity', 'postcss-pseudoelements', 'postcss-sprites', 'webpcss', 'jshint-loader', 'jscs-loader', 'coffeelint-loader', 'vue-loader']; this.npmInstall(list, { saveDev: true }); }, plugins: function() { var bowerList, npmList, plugin, pluginsList, _i, _len; pluginsList = this.config.get('plugins'); bowerList = []; npmList = []; if ((pluginsList != null) && pluginsList.length > 0) { for (_i = 0, _len = pluginsList.length; _i < _len; _i++) { plugin = pluginsList[_i]; switch (plugin.installer) { case 'npm': npmList.push(plugin.name); break; case 'bower': bowerList.push(plugin.name); } } this.npmInstall(npmList, { save: true }); this.bowerInstall(bowerList, { save: true }); } } } });
/// <reference path="../../../Scripts/endgate.d.ts" /> /// <reference path="SmokePoof.ts" /> // Wrap in module to keep code out of global scope var AudioHandling; (function (AudioHandling) { var SmokePoofManager = (function () { function SmokePoofManager(_mouse, _scene, _onClickSound) { var _this = this; this._mouse = _mouse; this._scene = _scene; this._onClickSound = _onClickSound; this._smokePoofIds = 0; var that = this; this._smokePoofs = {}; // Trigger when any mouse button is clicked over the game area this._mouse.OnClick.Bind(function (event) { var smokePoofId = that._smokePoofIds++, smokePoof = new AudioHandling.SmokePoof(event.Position.X, event.Position.Y, function () { // This is the on animation completed callback // We want to remove the explosions from our list of active explosions (so we don't update it anymore) delete that._smokePoofs[smokePoofId]; // And we want to remove it from the scene so we don't draw it anymore that._scene.Remove(smokePoof.Graphic); }); // Play the smoke poof sound. Since the sound clip has a bit of dead silence at the start we want to seek to 100ms where the actual poof sound starts _this._onClickSound.Play().Seek(.1); // Save the created explosion so we can now update/draw it that._smokePoofs[smokePoofId] = smokePoof; that._scene.Add(smokePoof.Graphic); }); } SmokePoofManager.prototype.Update = function (gameTime) { for (var id in this._smokePoofs) { this._smokePoofs[id].Update(gameTime); } }; return SmokePoofManager; })(); AudioHandling.SmokePoofManager = SmokePoofManager; })(AudioHandling || (AudioHandling = {})); //@ sourceMappingURL=SmokePoofManager.js.map