code
stringlengths
2
1.05M
import React from 'react' import { Input } from 'shengnian-ui-react' const InputExampleFluid = () => ( <Input fluid icon='search' placeholder='Search...' /> ) export default InputExampleFluid
var GroupLib4Cult = function( _positionX, _positionY ){ // Parse main scope var self = this; var alpha = 1; // Vector for elements inside group var elementsInGroup = []; // Position of group var position = { x: _positionX || 0, y: _positionY || 0, last: { x: 0, y: 0 } } var pivot = { x: 0, y: 0 }; var layer = 0; var rotation = 0; self.setOpacity = function( _alpha ){ alpha = _alpha; for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].setOpacity( alpha ); } } self.setRotation = function( _degrees ){ rotation = _degrees; for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].setRotation( rotation ); } } self.setPivot = function( _pivot ){ pivot = _pivot; for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].setPivot( pivot ); } } self.setLayer = function( _index ){ layer = _index; } self.getOpacity = function(){ return alpha; } self.getRotation = function(){ return rotation; } self.getLayer = function(){ return layer; } // Mehotd for add components in group self.add = function( _element ){ if( typeof _element.push === 'function' ){ for( var i = 0; i < _element.length; i++ ){ elementsInGroup.push( _element[i] ); } }else{ elementsInGroup.push( _element ); } } // Method for drift out all components self.empty = function(){ elementsInGroup = []; } // Setter for modify coord in X self.setX = function( _x ){ position.x = _x; if( elementsInGroup.length > 0 ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].setPivot(position.x, position.y); } } // Setter for modify coord in Y self.setY = function( _y ){ position.y = _y; if( elementsInGroup.length > 0 ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].setPivot(position.x, position.y); } } self.getX = function(){ return position.x; } // getter for info about coord X self.getY = function(){ return position.y; } // getter for info about coord Y // Method for logic from update self.update = function(){ // Verify if exists components in this group if( elementsInGroup.length > 0 ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].update(); } // Verify if coord X was modified if( position.x != position.last.x ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].incX(position.x); } position.last.x = position.x; // Verify if coord X was modified if( position.y != position.last.y ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].incY(position.y); } position.last.y = position.y; } // Method render elements in canvas self.render = function( _context ){ // Verify if exists elements in this group if( elementsInGroup.length > 0 ) for( var i = 0; i < elementsInGroup.length; i++ ){ elementsInGroup[i].render( _context ); } } }
CKEDITOR.dialog.add( 'fnlabelDialog', function( editor ) { return { title: 'Formula Properties', minWidth: 400, minHeight: 200, contents: [ { id: 'tab-basic', label: 'Enter Settings', elements: [{ type: "hbox", widths: ["50%", "50%"], children: [{ type: 'text', id: 'name', label: 'Name', validate: CKEDITOR.dialog.validate.notEmpty( "Name field cannot be empty." ) }, { type: 'text', id: 'equation', label: 'Equation', validate: CKEDITOR.dialog.validate.notEmpty( "Equation field cannot be empty." ) }] }] }, { id: 'tab-adv', label: 'Advanced Settings', elements: [ { type: 'text', id: 'id', label: 'Id' } ] } ], onOk: function() { var dialog = this; var tmp = editor.document.createElement( 'label' ); tmp.setAttribute( 'id', 'fn_label_'+dialog.getValueOf( 'tab-basic', 'name' ) ); tmp.setAttribute('class','interactive_fn'); tmp.setAttribute('data', dialog.getValueOf( 'tab-basic', 'equation' )); tmp.setText( 'fn('+dialog.getValueOf( 'tab-basic', 'equation' )+')'); var id = dialog.getValueOf( 'tab-adv', 'id' ); if ( id ) tmp.setAttribute( 'id', id ); editor.insertElement( tmp ); } }; });
require( ["service-edit"], function ( serviceEdit ) { console.log( "\n\n ************** _main: loaded *** \n\n" ); // Shared variables need to be visible prior to scope $( document ).ready( function () { initialize(); } ); function initialize() { CsapCommon.configureCsapAlertify(); $( '#showServiceDialog' ).click( function () { // alertify.notify("Getting clusters") ; var params = { serviceName: serviceName, hostName: hostName } $.get( serviceEditUrl, params, serviceEdit.showServiceDialog, 'html' ); return false; } ); // for testing page without launching dialog serviceEdit.configureForTest() ; } } );
var searchData= [ ['root',['root',['../namespacetranswarp.html#a4636e35a2f178eda191ecf3d67325df4',1,'transwarp']]] ];
'use strict'; module.exports = { db: 'mongodb://localhost/means7-dev', app: { title: 'MeanS7 - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/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' } } } };
;(function() { var autiobtn = document.getElementsByClassName('audio')[0]; var addClass = function(ele, strClass) { var reg = new RegExp("(^| )" + strClass + "( |$)"); if (reg.test(ele.className)) { } else { ele.className = ele.className.trim() + " " + strClass; } }; var removeClass = function(ele, strClass) { if (!(ele && ele.nodeType == 1)) { throw new Error('็ฌฌไธ€ๅ‚ๆ•ฐele้œ€่ฆๆ˜ฏไธ€ไธชDOMๅ…ƒ็ด ๅฏน่ฑก'); } if (typeof strClass != 'string') { throw new Error('็ฌฌไบŒๅ‚ๆ•ฐๅฟ…้กปไธบstring็ฑปๅž‹'); } var reg = new RegExp("(?:^| )" + strClass + "(?: |$)", "g"); ele.className = ele.className.replace(reg, '').trim(); }; autiobtn.onclick = function() { var audio = document.getElementById('media'); if(audio!==null){ if(audio.paused){ audio.play(); addClass(autiobtn, 'rotate'); }else{ audio.pause(); removeClass(autiobtn, 'rotate'); } } } })();
import { Route } from 'react-router'; import React from 'react'; import CoreLayout from 'layouts/CoreLayout'; import MenuView from 'views/MenuView'; import InventoryView from 'views/InventoryView'; import OrderListView from 'views/OrderListView'; import ManageView from 'views/ManageView'; export default ( <Route component={CoreLayout}> <Route name='menu' path='/' component={MenuView} /> <Route name='inventory' path='/inventar' component={InventoryView} /> <Route name='orders' path='/bectellungen' component={OrderListView} /> <Route name='manage' path='/verwaltunc' component={ManageView} /> </Route> );
define(['text!./base-template.html', 'knockout'], function(template, ko) { 'use strict'; var ViewModel = function (params, componentInfo) { var self = this; self.components = params.page.components; }; return { viewModel: { createViewModel: function(params, componentInfo) { return new ViewModel(params, componentInfo); } }, template: template }; });
'use strict'; module.exports = { conditions: [''], name: 'SingleLineCommentChars', rules: ['SingleLineCommentChar SingleLineCommentChars', 'SingleLineCommentChar'], handlers: ['$$ = $1 + $2;', '$$ = $1;'], subRules: [] };
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import Marty from 'marty'; import cx from 'classnames'; import Portal from 'react-portal'; import styles from './Modal.css'; const baseZIndex = 900; export class Modal extends Component { handleModalClick = (e) => { if (e.target === findDOMNode(this.refs.modal)) { this.handleCloseModal(); } } handleCloseModal = () => { if (this.props.onStateChange) { this.props.onStateChange({ open: false }); } this.app.modalActions.close(this.props.id); } handleOpenModal = () => { if (this.props.onStateChange) { this.props.onStateChange({ open: true }); } this.app.modalActions.open(this.props.id); } render() { const { isOpen, width, marginTop, kind, zIndex } = this.props; if (!isOpen) { return null; } const dialogStyle = { width, marginTop, }; const bodyClasses = cx(styles.body, { [styles.rounded]: kind === 'rounded', }); const localStyle = { zIndex: baseZIndex + zIndex, }; return ( <Portal isOpened={isOpen}> <div className={styles.modal} style={localStyle} ref="modal" onMouseDown={this.handleModalClick}> <div className={styles.dialog} style={dialogStyle}> <div className={bodyClasses}> {this.props.children} </div> </div> </div> </Portal> ); } } Modal.propTypes = { id: PropTypes.string.isRequired, marginTop: PropTypes.number.isRequired, isOpen: PropTypes.bool, width: PropTypes.number.isRequired, onStateChange: PropTypes.func, kind: PropTypes.bool, children: PropTypes.node, }; Modal.defaultProps = { width: 600, marginTop: 0, }; export const ModalContainer = Marty.createContainer(Modal, { listenTo: 'modalStore', done() { return ( <Modal ref="innerComponent" isOpen={this.app.modalStore.isOpen(this.props.id)} zIndex={this.app.modalStore.getZOffset(this.props.id)} {...this.props} /> ); }, }); ModalContainer.prototype.open = function() { this.refs.innerComponent.handleOpenModal(); }; ModalContainer.prototype.close = function() { this.refs.innerComponent.handleCloseModal(); }; let uniqueId = 0; export default function createModalComponent(ModalBody, ModalHeader, ModalFooter) { const thisId = ++uniqueId; return class ThisModal extends Component { render() { return ( <ModalContainer ref="modal" id={thisId} {...this.props}> {ModalHeader && <ModalHeader />} <ModalBody {...this.props} close={this.close.bind(this)} open={this.open.bind(this)} /> {ModalFooter && <ModalFooter />} </ModalContainer> ); } open() { return this.refs.modal.open(); } close() { return this.refs.modal.close(); } }; }
import React from 'react'; function LogoGithub() { return ( <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fillRule="evenodd" clipRule="evenodd" strokeLinejoin="round" strokeMiterlimit="1.414"> <path d="M8 0C3.58 0 0 3.582 0 8c0 3.535 2.292 6.533 5.47 7.59.4.075.547-.172.547-.385 0-.19-.007-.693-.01-1.36-2.226.483-2.695-1.073-2.695-1.073-.364-.924-.89-1.17-.89-1.17-.725-.496.056-.486.056-.486.803.056 1.225.824 1.225.824.714 1.223 1.873.87 2.33.665.072-.517.278-.87.507-1.07-1.777-.2-3.644-.888-3.644-3.953 0-.873.31-1.587.823-2.147-.083-.202-.358-1.015.077-2.117 0 0 .672-.215 2.2.82.638-.178 1.323-.266 2.003-.27.68.004 1.364.092 2.003.27 1.527-1.035 2.198-.82 2.198-.82.437 1.102.163 1.915.08 2.117.513.56.823 1.274.823 2.147 0 3.073-1.87 3.75-3.653 3.947.287.246.543.735.543 1.48 0 1.07-.01 1.933-.01 2.195 0 .215.144.463.55.385C13.71 14.53 16 11.534 16 8c0-4.418-3.582-8-8-8" /> </svg> ); } export default LogoGithub;
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import registerServiceWorker from './registerServiceWorker'; import thunk from 'redux-thunk'; import reducer from '../src/reducers/index'; import Application from './components'; const logger = store => next => action => { //console.group(action.type); //console.info('dispatching', action); let result = next(action); //console.log('next state', store.getState()); //console.groupEnd(action.type); return result; }; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const reduxDevTools = composeEnhancers(applyMiddleware(logger, thunk)); const store = createStore(reducer, reduxDevTools) const template = ( <BrowserRouter> <Provider store={store}> <Application/> </Provider> </BrowserRouter> ); ReactDOM.render(template, document.getElementById('root')); registerServiceWorker();
var webpack = require("webpack"); module.exports = { entry: './app.js', output: { path: '../static', filename: 'bundle.js', }, plugins: [ new webpack.optimize.UglifyJsPlugin(), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /(node-modules|bower_components)/, loader: 'babel', query: { presets: ['react', 'es2015'] }, }, ], }, resolve: { extensions: ['', '.js', '.jsx'], } };
exports.config = { // See http://brunch.io/#documentation for docs. files: { javascripts: { joinTo: "js/app.js" // To use a separate vendor.js bundle, specify two files path // https://github.com/brunch/brunch/blob/master/docs/config.md#files // joinTo: { // "js/app.js": /^(js)/, // "js/vendor.js": /^(vendor)|(deps)/ // } // // To change the order of concatenation of files, explicitly mention here // https://github.com/brunch/brunch/tree/master/docs#concatenation // order: { // before: [ // "vendor/js/jquery-2.1.1.js", // "vendor/js/bootstrap.min.js" // ] // } }, stylesheets: { joinTo: "css/app.css" } }, conventions: { // This option sets where we should place non-css and non-js assets in. // By default, we set this to "/assets/static". Files in this directory // will be copied to `paths.public`, which is set below to "../public". assets: /^(static)/, // Don't scan for js files inside elm-stuff folders ignored: [/elm-stuff/] }, // paths configuration paths: { // Dependencies and current project directories to watch watched: ["static", "scss", "js", "vendor", "elm"], // Where to compile files to public: "../public" }, // Configure your plugins plugins: { babel: { // Do not use ES6 compiler in vendor code ignore: [/vendor/, /node_modules/] }, elmBrunch: { elmFolder: "elm", mainModules: ["Main.elm"], makeParameters: ["--warn", "--debug"], outputFolder: "../js" }, sass: { options: { includePaths: ["node_modules/bootstrap/scss"], precision: 8 } } }, modules: { autoRequire: { "js/app.js": ["js/app"] } } }; exports.npm = { globals: { $: 'jquery', jQuery: 'jquery', Popper: 'popper.js', } }
/* globals $ */ /* Create a function that takes an id or DOM element and: */ function solve(){ return function (selector) { var classBtn = document.querySelectorAll('.button'), classContent = document.querySelectorAll('.content'); if(selector == undefined){ throw new Error(); } if(selector !== HTMLElement){ selector = document.getElementById(selector); } if(selector == null){ throw new Error(); } var i, len = classBtn.length; function ShowHideFn(){ var next = this.nextElementSibling; while(next.className !== 'button'){ if (next.className === 'content') { break; } next = next.nextElementSibling; } if (next.className === 'content' && next.style.display == '') { this.innerHTML = 'show'; next.style.display = "none"; } else { this.innerHTML = "hide"; next.style.display = ''; } } for(i = 0; i < len; i+=1) { classBtn[i].innerHTML = "hide"; classBtn[i].addEventListener('click', ShowHideFn, false); } }; } module.exports = solve;
// encoding: utf8 var assert, hanp; if (typeof window === 'object') { // web browser assert = { strictEqual: function(arg1, arg2) { if (arg1 !== arg2) throw new Error('Test fail!'); } }; hanp = window.hanp; } else if (typeof require === 'function') { // node.js assert = require('assert'); hanp = require("../hangul-postposition"); } //hanp.options({halfTranslate: true}); assert.strictEqual(hanp.translatePostpositions(''), ''); // empty string assert.strictEqual(hanp.translatePostpositions('Hello World!'), 'Hello World!'); // non-hangul string assert.strictEqual(hanp.translatePostpositions('์‚ฌ์ž์€(๋Š”) ํ† ๋ผ์„(๋ฅผ) ๋จน๊ณ  ๋ง์€(๋Š”) ํ’€์„(๋ฅผ) ๋จน๋Š”๋‹ค.'), '์‚ฌ์ž๋Š” ํ† ๋ผ๋ฅผ ๋จน๊ณ  ๋ง์€ ํ’€์„ ๋จน๋Š”๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์‚ฌ๋žŒ๊ณผ(์™€) ๊ณ ์–‘์ด๊ณผ(์™€) ๊ฐœ'), '์‚ฌ๋žŒ๊ณผ ๊ณ ์–‘์ด์™€ ๊ฐœ'); assert.strictEqual(hanp.translatePostpositions('๋ฐฐ์ด(๊ฐ€) ๊ณ ํŒŒ์š”. ๋ฐฅ์ด(๊ฐ€) ๋จน๊ณ  ์‹ถ์–ด์š”.'), '๋ฐฐ๊ฐ€ ๊ณ ํŒŒ์š”. ๋ฐฅ์ด ๋จน๊ณ  ์‹ถ์–ด์š”.'); assert.strictEqual(hanp.translatePostpositions('๋‘˜๋ฆฌ์•„(์•ผ)! ํฌ๋™์•„(์•ผ)!'), '๋‘˜๋ฆฌ์•ผ! ํฌ๋™์•„!'); assert.strictEqual(hanp.translatePostpositions('์ข…์ด์ด์–ด(์—ฌ)์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์ด์–ด(์—ฌ)์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'), '์ข…์ด์—ฌ์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์ด์–ด์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์ด์—(์˜ˆ)์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์ด์—(์˜ˆ)์š”.'), '์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์ด์—์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์˜ˆ์š”.'); assert.strictEqual(hanp.translatePostpositions('๊ทธ๋Š” ๊ณฐ์ด์—ˆ(์˜€)์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์ด์—ˆ(์˜€)๋‹ค.'), '๊ทธ๋Š” ๊ณฐ์ด์—ˆ์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์˜€๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('๋ถˆ(์ด)์•ผ! ์†Œ๋ฐฉ์ฐจ(์ด)์•ผ!'), '๋ถˆ์ด์•ผ! ์†Œ๋ฐฉ์ฐจ์•ผ!'); assert.strictEqual(hanp.translatePostpositions('๋น„(์ด)๋‹ค. ์•„๋‹ˆ๋‹ค. ๋ˆˆ(์ด)๋‹ค.'), '๋น„๋‹ค. ์•„๋‹ˆ๋‹ค. ๋ˆˆ์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์„œ์šธ(์œผ)๋กœ ์•ˆ ๊ฐ€๋‹ˆ?'), '์„œ์šธ๋กœ ์•ˆ ๊ฐ€๋‹ˆ?'); assert.strictEqual(hanp.translatePostpositions('๊ธฐ์ฐจ(์œผ)๋กœ ๋ถ€์‚ฐ(์œผ)๋กœ ๊ฐˆ ๊ฒƒ์ด๋‹ค.'), '๊ธฐ์ฐจ๋กœ ๋ถ€์‚ฐ์œผ๋กœ ๊ฐˆ ๊ฒƒ์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('4๊ณผ(์™€) 7์„(๋ฅผ) ๋”ํ•˜๋ฉด 11(์ด)๋‹ค.'), '4์™€ 7์„ ๋”ํ•˜๋ฉด 11์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('1(์œผ)๋กœ 1์„(๋ฅผ) 7(์œผ)๋กœ 7์„(๋ฅผ) 8(์œผ)๋กœ 8์„(๋ฅผ)'), '1๋กœ 1์„ 7๋กœ 7์„ 8๋กœ 8์„'); assert.strictEqual(hanp.translatePostpositions('3(์œผ)๋กœ 3์„(๋ฅผ) 6(์œผ)๋กœ 6์„(๋ฅผ) 0(์œผ)๋กœ 0์„(๋ฅผ)'), '3์œผ๋กœ 3์„ 6์œผ๋กœ 6์„ 0์œผ๋กœ 0์„'); assert.strictEqual(hanp.translatePostpositions('2(์œผ)๋กœ 2์„(๋ฅผ) 4(์œผ)๋กœ 4์„(๋ฅผ) 5(์œผ)๋กœ 5์„(๋ฅผ) 9(์œผ)๋กœ 9์„(๋ฅผ)'), '2๋กœ 2๋ฅผ 4๋กœ 4๋ฅผ 5๋กœ 5๋ฅผ 9๋กœ 9๋ฅผ'); hanp.options({halfTranslate: false}); assert.strictEqual(hanp.translatePostpositions(''), ''); // empty string assert.strictEqual(hanp.translatePostpositions('Hello World!'), 'Hello World!'); // non-hangul string assert.strictEqual(hanp.translatePostpositions('์‚ฌ์ž์€(๋Š”) ํ† ๋ผ์„(๋ฅผ) ๋จน๊ณ  ๋ง์€(๋Š”) ํ’€์„(๋ฅผ) ๋จน๋Š”๋‹ค.'), '์‚ฌ์ž๋Š” ํ† ๋ผ๋ฅผ ๋จน๊ณ  ๋ง์€ ํ’€์„ ๋จน๋Š”๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์‚ฌ์ž๋Š”(์€) ํ† ๋ผ๋ฅผ(์„) ๋จน๊ณ  ๋ง๋Š”(์€) ํ’€๋ฅผ(์„) ๋จน๋Š”๋‹ค.'), '์‚ฌ์ž๋Š” ํ† ๋ผ๋ฅผ ๋จน๊ณ  ๋ง์€ ํ’€์„ ๋จน๋Š”๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์‚ฌ๋žŒ๊ณผ(์™€) ๊ณ ์–‘์ด๊ณผ(์™€) ๊ฐœ'), '์‚ฌ๋žŒ๊ณผ ๊ณ ์–‘์ด์™€ ๊ฐœ'); assert.strictEqual(hanp.translatePostpositions('์‚ฌ๋žŒ์™€(๊ณผ) ๊ณ ์–‘์ด์™€(๊ณผ) ๊ฐœ'), '์‚ฌ๋žŒ๊ณผ ๊ณ ์–‘์ด์™€ ๊ฐœ'); assert.strictEqual(hanp.translatePostpositions('๋ฐฐ์ด(๊ฐ€) ๊ณ ํŒŒ์š”. ๋ฐฅ์ด(๊ฐ€) ๋จน๊ณ  ์‹ถ์–ด์š”.'), '๋ฐฐ๊ฐ€ ๊ณ ํŒŒ์š”. ๋ฐฅ์ด ๋จน๊ณ  ์‹ถ์–ด์š”.'); // '๊ฐ€(์ด)' is not supported anymore because it conflicts with '(์ด)' //assert.strictEqual(hanp.translatePostpositions('๋ฐฐ๊ฐ€(์ด) ๊ณ ํŒŒ์š”. ๋ฐฅ๊ฐ€(์ด) ๋จน๊ณ  ์‹ถ์–ด์š”.'), '๋ฐฐ๊ฐ€ ๊ณ ํŒŒ์š”. ๋ฐฅ์ด ๋จน๊ณ  ์‹ถ์–ด์š”.'); assert.strictEqual(hanp.translatePostpositions('๋‘˜๋ฆฌ์•„(์•ผ)! ํฌ๋™์•„(์•ผ)!'), '๋‘˜๋ฆฌ์•ผ! ํฌ๋™์•„!'); assert.strictEqual(hanp.translatePostpositions('๋‘˜๋ฆฌ์•ผ(์•„)! ํฌ๋™์•ผ(์•„)!'), '๋‘˜๋ฆฌ์•ผ! ํฌ๋™์•„!'); assert.strictEqual(hanp.translatePostpositions('์ข…์ด์ด์–ด(์—ฌ)์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์ด์–ด(์—ฌ)์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'), '์ข…์ด์—ฌ์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์ด์–ด์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์ข…์ด์—ฌ(์ด์–ด)์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์—ฌ(์ด์–ด)์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'), '์ข…์ด์—ฌ์„œ ์ฐข์–ด์กŒ๋‹ค. ๋น„๋‹์ด์–ด์„œ ๋Š˜์–ด๋‚ฌ๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์ด์—(์˜ˆ)์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์ด์—(์˜ˆ)์š”.'), '์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์ด์—์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์˜ˆ์š”.'); assert.strictEqual(hanp.translatePostpositions('์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์˜ˆ(์ด์—)์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์˜ˆ(์ด์—)์š”.'), '์ € ์‚ฌ๋žŒ ๊น€ํƒœ๊ท ์ด์—์š”? ์•„๋‹ˆ์š”. ํ•˜๋‚˜์นด๋‚˜์˜ˆ์š”.'); assert.strictEqual(hanp.translatePostpositions('๊ทธ๋Š” ๊ณฐ์ด์—ˆ(์˜€)์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์ด์—ˆ(์˜€)๋‹ค.'), '๊ทธ๋Š” ๊ณฐ์ด์—ˆ์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์˜€๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('๊ทธ๋Š” ๊ณฐ์˜€(์ด์—ˆ)์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์˜€(์ด์—ˆ)๋‹ค.'), '๊ทธ๋Š” ๊ณฐ์ด์—ˆ์œผ๋ฉฐ, ๋™์‹œ์— ํ˜ธ๋ž‘์ด์˜€๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('๋ถˆ(์ด)์•ผ! ์†Œ๋ฐฉ์ฐจ(์ด)์•ผ!'), '๋ถˆ์ด์•ผ! ์†Œ๋ฐฉ์ฐจ์•ผ!'); assert.strictEqual(hanp.translatePostpositions('๋น„(์ด)๋‹ค. ์•„๋‹ˆ๋‹ค. ๋ˆˆ(์ด)๋‹ค.'), '๋น„๋‹ค. ์•„๋‹ˆ๋‹ค. ๋ˆˆ์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('์„œ์šธ(์œผ)๋กœ ์•ˆ ๊ฐ€๋‹ˆ?'), '์„œ์šธ๋กœ ์•ˆ ๊ฐ€๋‹ˆ?'); assert.strictEqual(hanp.translatePostpositions('๊ธฐ์ฐจ(์œผ)๋กœ ๋ถ€์‚ฐ(์œผ)๋กœ ๊ฐˆ ๊ฒƒ์ด๋‹ค.'), '๊ธฐ์ฐจ๋กœ ๋ถ€์‚ฐ์œผ๋กœ ๊ฐˆ ๊ฒƒ์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('4๊ณผ(์™€) 7์„(๋ฅผ) ๋”ํ•˜๋ฉด 11(์ด)๋‹ค.'), '4์™€ 7์„ ๋”ํ•˜๋ฉด 11์ด๋‹ค.'); assert.strictEqual(hanp.translatePostpositions('4์™€(๊ณผ) 7๋ฅผ(์„) ๋”ํ•˜๋ฉด 11(์ด)๋‹ค.'), '4์™€ 7์„ ๋”ํ•˜๋ฉด 11์ด๋‹ค.'); console.log('Test completed. No errors.');
import React from 'react'; import _ from 'lodash'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; import { getAuthenticatedUser, getFollowingList, getIsAuthFetching, getIsFetchingFollowingList, getIsAuthenticated, getIsLoaded, getFollowingFetched, getFetchFollowListError, } from '../reducers'; import HorizontalBarChart from '../components/HorizontalBarChart'; import LetsGetStartedIcon from './LetsGetStartedIcon'; import './LetsGetStarted.less'; @connect(state => ({ authenticatedUser: getAuthenticatedUser(state), followingList: getFollowingList(state), isAuthFetching: getIsAuthFetching(state), isFetchingFollowingList: getIsFetchingFollowingList(state), loaded: getIsLoaded(state), authenticated: getIsAuthenticated(state), followingFetched: getFollowingFetched(state), fetchFollowListError: getFetchFollowListError(state), })) class LetsGetStarted extends React.Component { static propTypes = { followingList: PropTypes.arrayOf(PropTypes.string).isRequired, isAuthFetching: PropTypes.bool.isRequired, isFetchingFollowingList: PropTypes.bool.isRequired, authenticated: PropTypes.bool.isRequired, authenticatedUser: PropTypes.shape().isRequired, loaded: PropTypes.bool.isRequired, followingFetched: PropTypes.bool.isRequired, fetchFollowListError: PropTypes.bool.isRequired, }; static getCurrentUserState(authenticatedUser, followingList) { const hasPost = authenticatedUser.last_root_post !== '1970-01-01T00:00:00'; const hasVoted = authenticatedUser.last_vote_time !== authenticatedUser.created; const jsonMetadata = _.attempt(JSON.parse, authenticatedUser.json_metadata); const hasProfile = _.has(jsonMetadata, 'profile.name') && _.has(jsonMetadata, 'profile.about') && _.has(jsonMetadata, 'profile.profile_image'); const hasFollowed = _.size(followingList) >= 5; return { hasProfile, hasPost, hasVoted, hasFollowed, }; } constructor(props) { super(props); this.state = LetsGetStarted.getCurrentUserState(props.authenticatedUser, props.followingList); } componentWillReceiveProps(nextProps) { const newState = {}; const newUserState = LetsGetStarted.getCurrentUserState( nextProps.authenticatedUser, nextProps.followingList, ); const diffHasProfile = this.state.hasProfile !== newUserState.hasProfile; const diffHasPost = this.state.hasPost !== newUserState.hasPost; const diffHasVoted = this.state.hasVoted !== newUserState.hasVoted; const diffHasFollowed = this.state.hasFollowed !== newUserState.hasFollowed; if (diffHasProfile) newState.hasProfile = newUserState.hasProfile; if (diffHasPost) newState.hasPost = newUserState.hasPost; if (diffHasVoted) newState.hasVoted = newUserState.hasVoted; if (diffHasFollowed) newState.hasFollowed = newUserState.hasFollowed; if (!_.isEmpty(newState)) { this.setState(newState); } } render() { const { authenticated, isFetchingFollowingList, isAuthFetching, loaded, followingFetched, fetchFollowListError, } = this.props; const { hasProfile, hasPost, hasVoted, hasFollowed } = this.state; const totalOptions = 4; const currentSelected = _.reduce( [hasProfile, hasPost, hasVoted, hasFollowed], (total, current) => { let newTotal = total; if (current) { newTotal = total + 1; } return newTotal; }, 0, ); const ready = followingFetched && loaded; const hide = !authenticated || currentSelected === totalOptions; if (!ready || hide || fetchFollowListError) return <div />; return ( <div className="LetsGetStarted"> <h4 className="LetsGetStarted__title"> <span className="LetsGetStarted__title__text"> <FormattedMessage id="lets_get_started" defaultMessage="Let's get started" /> </span> <HorizontalBarChart current={currentSelected} total={totalOptions} /> <span className="LetsGetStarted__title__description"> {`${currentSelected}/${totalOptions} `} <FormattedMessage id="completed" defaultMessage="Completed" /> </span> </h4> <div className="LetsGetStarted__content"> <div className="LetsGetStarted__action"> <LetsGetStartedIcon renderCheck={hasProfile} isLoading={isAuthFetching} iconClassName="icon-mine" /> <Link to="/edit-profile"> <span className={classNames('LetsGetStarted__action__text', { LetsGetStarted__action__completed: hasProfile, })} > <FormattedMessage id="complete_your_profile" defaultMessage="Complete your profile" /> </span> </Link> </div> <div className="LetsGetStarted__action"> <LetsGetStartedIcon renderCheck={hasFollowed} isLoading={isFetchingFollowingList} iconClassName="icon-addpeople" /> <Link to="/discover"> <span className={classNames('LetsGetStarted__action__text', { LetsGetStarted__action__completed: hasFollowed, })} > <FormattedMessage id="follow_steemians" defaultMessage="Follow {amount} steemians" values={{ amount: 5 }} /> </span> </Link> </div> <div className="LetsGetStarted__action"> <LetsGetStartedIcon renderCheck={hasVoted} isLoading={isAuthFetching} iconClassName="icon-praise" /> <Link to="/trending"> <span className={classNames('LetsGetStarted__action__text', { LetsGetStarted__action__completed: hasVoted, })} > <FormattedMessage id="like_good_posts" defaultMessage="Like some good posts" /> </span> </Link> </div> <div className="LetsGetStarted__action"> <LetsGetStartedIcon renderCheck={hasPost} isLoading={isAuthFetching} iconClassName="icon-order" /> <Link to="/editor"> <span className={classNames('LetsGetStarted__action__text', { LetsGetStarted__action__completed: hasPost, })} > <FormattedMessage id="write_first_post" defaultMessage="Write your first post" /> </span> </Link> </div> </div> </div> ); } } export default LetsGetStarted;
module.exports = { development: { baseUrl : "http://176.32.196.113:8000", secret: 'c6ddbf5047efc9s4e0d8ff9a87f4b5acb92abb8sdd26662ff2ddc74e33d1e24e0af7ssaa904825ae632e967418s98b1effd06531s15637cdca372bff0004f035', mongo_url: 'mongodb://127.0.0.1:27017/maeuticaAgenda', SENDGRID_API_KEY : "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", EMAIL_FROM : "purchase@ticket", http_port: 8000, http_host: '0.0.0.0' }, production: { baseUrl : "http://37.186.125.214:8080", secret: 'c6ddbf5047efc9s4e0d8ff9a87f4b5acb92abb8sdd26662ff2ddc74e33d1e24e0af7ssaa904825ae632e967418s98b1effd06531s15637cdca372bff0004f035', mongo_url: 'mongodb://localhost/brandsAndBusinessConference', SENDGRID_API_KEY : "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", EMAIL_FROM : "purchase@ticket", http_port: 8080, http_host: '0.0.0.0' } };
import express from 'express'; const app = express(); app.use('/', express.static('public')); app.listen(process.env.PORT || 3000);
import { types as t } from "@babel/core"; import nameFunction from "@babel/helper-function-name"; import splitExportDeclaration from "@babel/helper-split-export-declaration"; import { buildPrivateNamesNodes, buildPrivateNamesMap, transformPrivateNamesUsage, buildFieldsInitNodes, } from "./fields"; import { hasOwnDecorators, buildDecoratedClass, hasDecorators, } from "./decorators"; import { injectInitialization, extractComputedKeys } from "./misc"; import { enableFeature, verifyUsedFeatures, FEATURES, isLoose, } from "./features"; import pkg from "../package.json"; export { FEATURES, injectInitialization }; // Note: Versions are represented as an integer. e.g. 7.1.5 is represented // as 70000100005. This method is easier than using a semver-parsing // package, but it breaks if we release x.y.z where x, y or z are // greater than 99_999. const version = pkg.version.split(".").reduce((v, x) => v * 1e5 + +x, 0); const versionKey = "@babel/plugin-class-features/version"; export function createClassFeaturePlugin({ name, feature, loose, manipulateOptions, }) { return { name, manipulateOptions, pre() { enableFeature(this.file, feature, loose); if (!this.file.get(versionKey) || this.file.get(versionKey) < version) { this.file.set(versionKey, version); } }, visitor: { Class(path, state) { if (this.file.get(versionKey) !== version) return; verifyUsedFeatures(path, this.file); const loose = isLoose(this.file, feature); let constructor; let isDecorated = hasOwnDecorators(path.node); const props = []; const elements = []; const computedPaths = []; const privateNames = new Set(); const body = path.get("body"); for (const path of body.get("body")) { verifyUsedFeatures(path, this.file); if (path.node.computed) { computedPaths.push(path); } if (path.isPrivate()) { const { name } = path.node.key.id; const getName = `get ${name}`; const setName = `set ${name}`; if (path.node.kind === "get") { if ( privateNames.has(getName) || (privateNames.has(name) && !privateNames.has(setName)) ) { throw path.buildCodeFrameError("Duplicate private field"); } privateNames.add(getName).add(name); } else if (path.node.kind === "set") { if ( privateNames.has(setName) || (privateNames.has(name) && !privateNames.has(getName)) ) { throw path.buildCodeFrameError("Duplicate private field"); } privateNames.add(setName).add(name); } else { if ( (privateNames.has(name) && !privateNames.has(getName) && !privateNames.has(setName)) || (privateNames.has(name) && (privateNames.has(getName) || privateNames.has(setName))) ) { throw path.buildCodeFrameError("Duplicate private field"); } privateNames.add(name); } } if (path.isClassMethod({ kind: "constructor" })) { constructor = path; } else { elements.push(path); if (path.isProperty() || path.isPrivate()) { props.push(path); } } if (!isDecorated) isDecorated = hasOwnDecorators(path.node); } if (!props.length && !isDecorated) return; let ref; if (path.isClassExpression() || !path.node.id) { nameFunction(path); ref = path.scope.generateUidIdentifier("class"); } else { ref = t.cloneNode(path.node.id); } // NODE: These three functions don't support decorators yet, // but verifyUsedFeatures throws if there are both // decorators and private fields. const privateNamesMap = buildPrivateNamesMap(props); const privateNamesNodes = buildPrivateNamesNodes( privateNamesMap, loose, state, ); transformPrivateNamesUsage(ref, path, privateNamesMap, loose, state); let keysNodes, staticNodes, instanceNodes, wrapClass; if (isDecorated) { staticNodes = keysNodes = []; ({ instanceNodes, wrapClass } = buildDecoratedClass( ref, path, elements, this.file, )); } else { keysNodes = extractComputedKeys(ref, path, computedPaths, this.file); ({ staticNodes, instanceNodes, wrapClass } = buildFieldsInitNodes( ref, path.node.superClass, props, privateNamesMap, state, loose, )); } if (instanceNodes.length > 0) { injectInitialization( path, constructor, instanceNodes, (referenceVisitor, state) => { if (isDecorated) return; for (const prop of props) { if (prop.node.static) continue; prop.traverse(referenceVisitor, state); } }, ); } path = wrapClass(path); path.insertBefore([...privateNamesNodes, ...keysNodes]); path.insertAfter(staticNodes); }, PrivateName(path) { if (this.file.get(versionKey) !== version) return; throw path.buildCodeFrameError(`Unknown PrivateName "${path}"`); }, ExportDefaultDeclaration(path) { if (this.file.get(versionKey) !== version) return; const decl = path.get("declaration"); if (decl.isClassDeclaration() && hasDecorators(decl.node)) { if (decl.node.id) { // export default class Foo {} // --> // class Foo {} export { Foo as default } splitExportDeclaration(path); } else { // Annyms class declarations can be // transformed as if they were expressions decl.node.type = "ClassExpression"; } } }, }, }; }
var config = require('./webpack.base.config') var path = require( 'path' ) var webpack = require('webpack') module.exports = { // devtool: 'inline-source-map', module: { loaders:[ { test: /\.json$/, loader: "json-loader" }, { loader: 'babel-loader', babelrc: false, exclude: /(node_modules|bower_components)/, query: { presets: [/*"es2015",*/ 'react' ], "plugins": [ "transform-es2015-modules-commonjs", "transform-object-rest-spread", ["transform-runtime", { "polyfill": false, "regenerator": false }] ] } } ], postLoaders: [{ test: /\.(js|jsx)$/, include: [ path.resolve(__dirname, "../es2015")], exclude: /(\S*\.test\.js|node_modules)/, loader: 'istanbul-instrumenter' }] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"development"' } }) ] }
import BungieNet from "./BungieNet.js"; import request from "request"; /** * Plugin base class for plugins. Each plugin MUST define an update method. * * void update( String: eventName, args[] ) */ export default class Plugin { /** * Dummy function for inheriting classes * @param {String} eventName - name of the event being raised * @param {*} e - event object * @return {undefined} */ static update(eventName, e) { throw new Error("update method is undefined in subclass"); } } Plugin.CookieJarMemoryPlugin = class extends Plugin { /** * */ constructor() { super(); this.jar = request.jar(); } /** * @param {String} eventName - * @param {Object} e - * @return {undefined} */ update(eventName, e) { if(eventName === BungieNet.Platform.events.frameBeforeSend) { e.target.options.jar = this.jar; } } }; Plugin.OAuthPlugin = class extends Plugin { /** * @param {String} accessToken - oauth access token */ constructor(accessToken) { super(); this.accessToken = accessToken; } /** * @param {String} eventName - * @param {Object} e - * @return {undefined} */ update(eventName, e) { if(eventName === BungieNet.Platform.events.frameBeforeSend) { e.target.options.headers.Authorization = `Bearer ${ this.accessToken }`; } } };
// Axios API import axios from 'axios'; import { normalize } from 'normalizr'; import Immutable from 'seamless-immutable'; import { debug } from './utils/Messages'; // eslint-disable-next-line import/prefer-default-export export const api = (schema) => { const instance = axios.create({ headers: { responseType: 'json' }, }); // Intercept to apply schema and test unauthorized users instance.interceptors.response.use( (response) => { if (schema) { const toImmutable = response.config.responseType === undefined; //= == json const dataNormalize = normalize(response.data, schema); debug('api', { from: response.request.responseURL, data: { raw: response.data, normalize: dataNormalize }, }); response.data = toImmutable ? Immutable(dataNormalize) : dataNormalize; } return response; }, (err) => { const res = err.response; if ( res && res.status === 503 && err.config // eslint-disable-next-line no-underscore-dangle && !err.config.__isRetryRequest ) { // eslint-disable-next-line no-param-reassign,no-underscore-dangle err.config.__isRetryRequest = true; return axios(err.config); } if (res) { // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject({ status: res.status, ...res.data }); } // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject(false); }, ); return instance; };
'use strict'; /* Controllers */ var guideAchatApp = angular.module('guideAchatApp', []); guideAchatApp.controller('SectionListCtrl', function ($scope) { $scope.sections = [ { 'id' : 'fournisseurs', 'name' : 'Recherche par fournisseur', 'imageUrl' : 'img/accueil/fournisseur.png' }, { 'id' : 'univers', 'name' : 'Recherche par univers', 'imageUrl' : 'img/accueil/univers.png' }, { 'id' : 'article', 'name' : 'Recherche par article', 'imageUrl' : 'img/accueil/article.png' } ]; });
define([ "./../AbstractDevice", '../../../util/Class', '../../../util/DomEvent', '../Manager' ], function (AbstractDevice, Class, DomEvent, InputManager) { "use strict"; document.addEventListener('backbutton',function(){ DomEvent.emit('keydown',{ keyCode:27, el:document }); }); /** * @class com.sesamtv.core.engine.input.devices.Cordova * @extends com.sesamtv.core.engine.input.AbstractDevice * @requires com.sesamtv.core.util.DomEvent * @requires com.sesamtv.core.engine.input.Manager * @param {String} targetId */ var CordovaDevice = Class({ extend: AbstractDevice, constructor: function CordovaDevice() { this.name = "cordova"; this.eventNames = ['deviceready','pause','resume','online','offline','backbutton','batterycritical', 'batterylow','batterystatus','menubutton','searchbutton','startcallbutton','endcallbutton', 'volumedownbutton','volumeupbutton']; AbstractDevice.apply(this, arguments); }, /** * @method on * @param {String} query channelid/eventType * @param {Function} listener * @return {{id:String,remove:Function}} */ on: function (query, listener) { var self = this, channelInfo = this.parseChannelInfo(query), type = channelInfo.eventName, channel = channelInfo.channel, evtName; if (!(type in this.connect) && this.eventNames.indexOf(type) !== -1) { this.connect[type] = DomEvent.on(document, type, function (evt) { //evtName shouldn't be cached evtName = self.getEventName(type); if (self.evt.hasListeners(evtName)) { return self.evt.emit(evtName, evt); } /*self.connect[type].remove(); delete self.connect[type];*/ }, false); } return self.evt.on(self.getEventName(type, channel), listener); }, /** * @method once * @param {String} type * @param {Function} listener * @return {{id:String,remove:Function}} */ once: function (type, listener) { var h = this.on(type, function (evt) { listener(evt); h.remove(); }); return h; } }); InputManager.addDevice('cordova', CordovaDevice); return CordovaDevice; } );
export const shopDetailComponents = new Component({ element: '#shopDetail', render: (choice) => html` <li> <div> <div class='horizontal-panel'> <img src="${ choice.image }" alt="${ choice.name }"> <div> <h3>${ choice.name }</h3> <h4>${ choice.location }</h4> </div> </div> <p>${ choice.content }</p> </div> </li>` })
const { breaches } = require('hibp'); /** * Fetches all breached sites in the system. * * @param {string} domain a domain by which to filter the results (default: all * domains) * @returns {array} an array of breach objects (an empty array if no breaches * were found) */ module.exports = async (domain = '') => breaches({ domain });
function change(){ document.getElementById("granphoto").setAttribute("src",event.target.src); }
const webpack = require("webpack"); module.exports = { entry: "./node_modules/google-protobuf/google-protobuf.js", output: { filename: "jspb.inc.js", libraryTarget: "this", path: __dirname, }, optimization: { minimize: true }, mode: "production", };
search_result['1227']=["topic_00000000000002DC.html","tlece_ApplyPostVacancyVideos.CreatedUtc Property",""];
import alt from '../lib/AltInstance'; import GlucoseActions from '../actions/glucoseAction'; import ImmutableStore from 'alt/utils/ImmutableUtil'; import constants from '../constants/constants'; class GlucoseStore { constructor() { this.disconnected = this.disconnected.bind(this); this.connected = this.connected.bind(this); this.nodata = this.nodata.bind(this); this.bindListeners({ initialized: GlucoseActions.initialized, update: GlucoseActions.update }); this.state = {}; var self = this; var source = new EventSource(constants.apiroot + 'update'); source.addEventListener('update', function(e) { var j = JSON.parse(e.data); j.status = 'CONNECTED'; GlucoseActions.update(j); }, false); source.addEventListener('synch', function(e) { GlucoseActions.doInit(); }, false); source.addEventListener('open', function(e) { self.connected(); }, false); source.addEventListener('nodata', function(e) { self.nodata(); }, false); source.onerror = function(e) { console.log(e); if (source.readyState == 0) { self.disconnected(); } } } initialized(state) { state.data = true; this.setState(state); } update(state) { var currState = this.state; currState.data = true; if (currState.history) { var history = currState.history; history = _.sortBy(history, 'time').reverse().filter(function(g) { var unixTime = new Date(g.time).getTime(); if (unixTime > (Date.now() - (1000 * 60 * 60 * 3))) { return g; } }); currState.glucose = state.glucose; history.unshift({time: state.lastEntry, glucose: state.glucose}); currState.history = history; currState.lastEntry = state.lastEntry; currState.next = state.next; currState.trend = state.trend; } this.setState(currState); } disconnected() { console.log('disconnected'); var state = this.state; state.status = 'DISCONNECTED'; this.setState(state); } connected() { console.log('connected'); var state = this.state; state.status = 'CONNECTED'; this.setState(state); } nodata() { var state = this.state; state.data = false; this.setState(state); } } export default alt.createStore(ImmutableStore(GlucoseStore), 'GlucoseStore');
/*globals define, WebGMEGlobal*/ /*jshint browser: true*/ /** * @author rkereskenyi / https://github.com/rkereskenyi */ define(['js/logger'], function (Logger) { 'use strict'; var ConnectionRouteManagerBasic, DESIGNERITEM_SUBCOMPONENT_SEPARATOR = '_x_'; ConnectionRouteManagerBasic = function (options) { var loggerName = (options && options.loggerName) || 'gme:Widgets:DiagramDesigner:ConnectionRouteManagerBasic'; this.logger = (options && options.logger) || Logger.create(loggerName, WebGMEGlobal.gmeConfig.client.log); this.diagramDesigner = options ? options.diagramDesigner : null; if (this.diagramDesigner === undefined || this.diagramDesigner === null) { this.logger.error('Trying to initialize a ConnectionRouteManagerBasic without a canvas...'); throw ('ConnectionRouteManagerBasic can not be created'); } this.logger.debug('ConnectionRouteManagerBasic ctor finished'); }; ConnectionRouteManagerBasic.prototype.initialize = function () { }; ConnectionRouteManagerBasic.prototype.destroy = function () { }; ConnectionRouteManagerBasic.prototype.redrawConnections = function (idList) { var i; this.logger.debug('Redraw connection request: ' + idList.length); //NOTE: here it is not enough to update the connections the canvas asked for //because updating one connections' endpoint (connection area switch) can cause //other connections to be redrawn that was originally not requested to do so idList = this.diagramDesigner.connectionIds.slice(0); //1 - update all the connection endpoint connectable area information this._updateEndpointInfo(idList); //2 - we have each connection end connectability info //find the closest areas for each connection for (i = 0; i < idList.length; i += 1) { this._updateConnectionCoordinates(idList[i]); } //need to return the IDs of the connections that was really //redrawn or any other visual property chenged (width, etc) return idList; }; ConnectionRouteManagerBasic.prototype._updateEndpointInfo = function (idList) { var i = idList.length, connId, canvas = this.diagramDesigner, srcObjId, srcSubCompId, dstObjId, dstSubCompId, connectionMetaInfo; this.endpointConnectionAreaInfo = {}; //first update the available connection endpoint coordinates while (i--) { connId = idList[i]; srcObjId = canvas.connectionEndIDs[connId].srcObjId; srcSubCompId = canvas.connectionEndIDs[connId].srcSubCompId; dstObjId = canvas.connectionEndIDs[connId].dstObjId; dstSubCompId = canvas.connectionEndIDs[connId].dstSubCompId; connectionMetaInfo = canvas.items[connId].getMetaInfo(); this._getEndpointConnectionAreas(srcObjId, srcSubCompId, false, connectionMetaInfo); this._getEndpointConnectionAreas(dstObjId, dstSubCompId, true, connectionMetaInfo); } }; ConnectionRouteManagerBasic.prototype._getEndpointConnectionAreas = function (objId, subCompId, isEnd, connectionMetaInfo) { var longid = subCompId ? objId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + subCompId : objId, res, canvas = this.diagramDesigner, j, designerItem; if (this.endpointConnectionAreaInfo.hasOwnProperty(longid) === false) { this.endpointConnectionAreaInfo[longid] = []; if (subCompId === undefined || (subCompId !== undefined && this.diagramDesigner._itemSubcomponentsMap[objId] && this.diagramDesigner._itemSubcomponentsMap[objId].indexOf(subCompId) !== -1)) { designerItem = canvas.items[objId]; res = designerItem.getConnectionAreas(subCompId, isEnd, connectionMetaInfo) || []; j = res.length; while (j--) { this.endpointConnectionAreaInfo[longid].push({ x: res[j].x1 + (res[j].x2 - res[j].x1) / 2, y: res[j].y1 + (res[j].y2 - res[j].y1) / 2 }); } } } }; ConnectionRouteManagerBasic.prototype._updateConnectionCoordinates = function (connectionId) { var canvas = this.diagramDesigner, srcObjId = canvas.connectionEndIDs[connectionId].srcObjId, srcSubCompId = canvas.connectionEndIDs[connectionId].srcSubCompId, dstObjId = canvas.connectionEndIDs[connectionId].dstObjId, dstSubCompId = canvas.connectionEndIDs[connectionId].dstSubCompId, sId = srcSubCompId ? srcObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + srcSubCompId : srcObjId, tId = dstSubCompId ? dstObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + dstSubCompId : dstObjId, segmentPoints = canvas.items[connectionId].segmentPoints, sourceConnectionPoints = this.endpointConnectionAreaInfo[sId] || [], targetConnectionPoints = this.endpointConnectionAreaInfo[tId] || [], sourceCoordinates = null, targetCoordinates = null, closestConnPoints, connectionPathPoints = [], len, i; if (sourceConnectionPoints.length > 0 && targetConnectionPoints.length > 0) { closestConnPoints = this._getClosestPoints(sourceConnectionPoints, targetConnectionPoints, segmentPoints); if (srcObjId === dstObjId && srcSubCompId === dstSubCompId && closestConnPoints[0] === closestConnPoints[1]) { // Same source and destination point - try to scoot it over.. if (closestConnPoints[0] === closestConnPoints[1]) { closestConnPoints[1] = (closestConnPoints[0] + 1) % sourceConnectionPoints.length; } } sourceCoordinates = sourceConnectionPoints[closestConnPoints[0]]; targetCoordinates = targetConnectionPoints[closestConnPoints[1]]; //source point connectionPathPoints.push(sourceCoordinates); //segment points if (segmentPoints && segmentPoints.length > 0) { len = segmentPoints.length; for (i = 0; i < len; i += 1) { connectionPathPoints.push({ x: segmentPoints[i][0], y: segmentPoints[i][1] }); } } else { if (srcObjId === dstObjId && srcSubCompId === dstSubCompId) { //self connection, insert fake points connectionPathPoints.push({ x: sourceCoordinates.x + 100, y: sourceCoordinates.y - 100 }); connectionPathPoints.push({ x: sourceCoordinates.x + 200, y: sourceCoordinates.y }); connectionPathPoints.push({ x: sourceCoordinates.x + 100, y: sourceCoordinates.y + 100 }); } } //end point connectionPathPoints.push(targetCoordinates); } canvas.items[connectionId].setConnectionRenderData(connectionPathPoints); }; //figure out the shortest side to choose between the two ConnectionRouteManagerBasic.prototype._getClosestPoints = function (srcConnectionPoints, tgtConnectionPoints, segmentPoints) { var i, j, dx, dy, srcP, tgtP, minLength = -1, cLength; if (segmentPoints && segmentPoints.length > 0) { for (i = 0; i < srcConnectionPoints.length; i += 1) { for (j = 0; j < tgtConnectionPoints.length; j += 1) { dx = { src: Math.abs(srcConnectionPoints[i].x - segmentPoints[0][0]), tgt: Math.abs(tgtConnectionPoints[j].x - segmentPoints[segmentPoints.length - 1][0]) }; dy = { src: Math.abs(srcConnectionPoints[i].y - segmentPoints[0][1]), tgt: Math.abs(tgtConnectionPoints[j].y - segmentPoints[segmentPoints.length - 1][1]) }; cLength = Math.sqrt(dx.src * dx.src + dy.src * dy.src) + Math.sqrt(dx.tgt * dx.tgt + dy.tgt * dy.tgt); if (minLength === -1 || minLength > cLength) { minLength = cLength; srcP = i; tgtP = j; } } } } else { for (i = 0; i < srcConnectionPoints.length; i += 1) { for (j = 0; j < tgtConnectionPoints.length; j += 1) { dx = Math.abs(srcConnectionPoints[i].x - tgtConnectionPoints[j].x); dy = Math.abs(srcConnectionPoints[i].y - tgtConnectionPoints[j].y); cLength = Math.sqrt(dx * dx + dy * dy); if (minLength === -1 || minLength > cLength) { minLength = cLength; srcP = i; tgtP = j; } } } } return [srcP, tgtP]; }; return ConnectionRouteManagerBasic; });
var mqttLayer = require('./mqtt-layer'); class MqttStack { constructor() { this.request = {}; // inherited from the router this.options = {}; // all layers EXCEPT DEFAULT HANDLER this.stack = []; // handle all remaining errors at the end of stack // default behavior can be modified at router instanciation this.defaultHandler = (error, request) => { if (error) { console.log('Error in ', request.path, ': ', error.stack); } }; } /** * Goes through stack then calls handle on matching route, if any * @private */ execute() { var index = 0; var next = (err) => { var layerError = err; // find the next route var match, layer; while ( index < this.stack.length && match !== true) { layer = this.stack[index]; match = this.matchLayer(layer, this.request); index ++; if (match !== true) { continue; } if (layerError && layer.handle.length !== 3) { // if error, skip all non error handlers; match = false; continue; } } if (match !== true) { // no matching path left in stack if (layerError) { // handle remaining errors this.defaultHandler(layerError, this.request); return; } // done return; } // store last path for dispatch on error this.request.path = layer.path; if (layerError) { layer.handleRequest_error(layerError, this.request, next) } else { layer.handleRequest(this.request, next) } } this.request.next = next; //is that useful? next(); } /** * Tests for compatibility between a Layer and a topic * @param {Layer} layer * @param {MQTTRequest} request * @private */ matchLayer(layer, request) { try { return layer.match(request.topic); } catch (err) { return err; } } /** * Adds the specified function to the mqtt router, at a given path (path '#' matches to all) * @param {Path} path * @param {function} fn * @public */ add(path, handle) { var layer = new mqttLayer(path, handle, this.options); this.stack.push(layer); } /** * Adds default path to stack (will be performed if a channel is subscribed outside the router) * @param {function} fn * @public */ addDefaultHandler(handle) { if (handle.length < 2) { throw new TypeError('A default handler must have an error argument!') } this.defaultHandler = handle; } /** * Uses the stack for the given request * Builds a custom MQTTRequest request object, containing topic & payload * @param {MQTTTopic} topic * @param {MQTTPayload} payload * @public */ use(topic, payload) { this.request.topic = topic; this.request.payload = payload; this.execute(); } } /** * Module export * @public */ module.exports = MqttStack;
var path = require('path') var _ = require('lodash') var byMatcher = require('./db-generated/by-matcher.js') /** * Determine the index of a language specifiation in the languages-array. * @param filename * @returns {*} */ var langIndex = function (filename) { // Look for whole filename and for extension ("Makefile" is not an extesion, // but should be matched to the appropriate language) var index = byMatcher[filename] if (_.isUndefined(index)) { index = byMatcher[path.extname(filename)] } if (_.isUndefined(index)) { throw new Error("Cannot find language definition for '" + filename + "'") } return index } /** * Load the comment-pattern for a given file. * The file-language is determined by the file-extension. * @param {string} `filename` the name of the file * @returns {object} the comment-patterns * @api public */ function commentPattern (filename) { var base = require('./db-generated/base.js') var clone = _.cloneDeep(base[langIndex(filename)]) delete clone.srcFile return clone } /** * Load the comment-regex for a given file. * The result contains a regex that matches the comments * in the specification. It also has information about * which the different capturing groups of an object. * * @param {string} `filename` the name of the file * @returns {object} an object containing regular expressions and capturing-group metadata, * see usage example for details * @api public * @name commentPattern.regex */ commentPattern.regex = function commentRegex (filename) { var regex = require('./db-generated/regexes.js') return _.cloneDeep(regex[langIndex(filename)]) } /** * Returns the code-context detector for a given filename * (based on the name or the file-extension * @param {string} filename the name of the file that will be evaluated. * @return {function(string,number)} a function that detects the code-context * based on a line of code (and a line-number) */ commentPattern.codeContext = function codeContext (filename) { var base = require('./db-generated/base.js') var langFile = base[langIndex(filename)].srcFile return require('./languages/code-context/' + langFile) } module.exports = commentPattern
'use strict'; module.exports = function(gulp, config) { var OPTIONS = config; var rimraf = require('rimraf'); //////////////////////////////////////////////////////////////////// // CLEAN DESTINATION FILES //////////////////////////////////////////////////////////////////// gulp.task('clean:dest', function(cb) { rimraf(OPTIONS.DIR.DEST, cb); }); //////////////////////////////////////////////////////////////////// // CLEAN DOCS/API FOLDER //////////////////////////////////////////////////////////////////// gulp.task('clean:docs:api', function(cb) { rimraf(OPTIONS.DIR.DOCS_API, cb); }); //////////////////////////////////////////////////////////////////// // CLEAN DOCS/COVERAGE FOLDER //////////////////////////////////////////////////////////////////// gulp.task('clean:docs:coverage', function(cb) { rimraf(OPTIONS.DIR.DOCS_COVERAGE, cb); }); //////////////////////////////////////////////////////////////////// // CLEAN TEMP FOLDERS //////////////////////////////////////////////////////////////////// gulp.task('clean:temp', function(cb) { rimraf(OPTIONS.DIR.TEMP_FOLDER, cb); }); //////////////////////////////////////////////////////////////////// // COPY MEDIA FILES //////////////////////////////////////////////////////////////////// // gulp.task('copy:media', ['clean:client'], function() { // return gulp // .src(paths.GLOB.SRC_MEDIA, { base: paths.DIR.SRC_MEDIA }) // .pipe(gulp.dest(paths.DIR.DEST_MEDIA)); // }); //////////////////////////////////////////////////////////////////// // TASKS //////////////////////////////////////////////////////////////////// gulp.task('clean', ['clean:dest']); }
Ext.application({ name: 'MyApp', launch: function() { Ext.define('User', { extend: 'Ext.data.Model', fields: ['id', 'name', 'education'] }); var userStore = Ext.create('Ext.data.Store', { model: 'User', autoSync: true, proxy: { // load using HTTP type: 'ajax', url: '/app_dev.php/ajaxgetdata', reader: { type: 'json' // model: 'User' }, writer: { type: 'json' } } }); userStore.load(); var Editing = Ext.create('Ext.grid.plugin.RowEditing'); Ext.create('Ext.grid.Panel', { plugins: [Editing], renderTo: Ext.getBody(), store: userStore, width: 400, height: 200, title: 'Application Users', columns: { defaults: { editor: 'textfield' }, items: [ { text: 'Id', width: 100, dataIndex: 'id' }, { text: 'Name', width: 100, dataIndex: 'name'//, //hidden: true }, { text: 'Education', width: 100, dataIndex: 'education' } ] } }); } });
/*! * Stylus - Return * Copyright (c) Automattic <developer.wordpress.com> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node') , nodes = require('./'); /** * Initialize a new `Return` node with the given `expr`. * * @param {Expression} expr * @api public */ var Return = module.exports = function Return(expr){ this.expr = expr || nodes.null; }; /** * Inherit from `Node.prototype`. */ Return.prototype.__proto__ = Node.prototype; /** * Return a clone of this node. * * @return {Node} * @api public */ Return.prototype.clone = function(parent){ var clone = new Return(); clone.expr = this.expr.clone(parent, clone); clone.lineno = this.lineno; clone.column = this.column; clone.filename = this.filename; return clone; }; /** * Return a JSON representation of this node. * * @return {Object} * @api public */ Return.prototype.toJSON = function(){ return { __type: 'Return', expr: this.expr, lineno: this.lineno, column: this.column, filename: this.filename }; };
/* * Mixin that inject to user model object consumer set of methods necessary for * dealing with abcenses. * * */ 'use strict'; var _ = require('underscore'), Promise = require("bluebird"), CalendarMonth = require('../../calendar_month'), moment = require('moment'); module.exports = function(sequelize){ this._get_calendar_months_to_show = function(args){ var year = args.year, show_full_year = args.show_full_year; if (show_full_year) { return _.map([1,2,3,4,5,6,7,8,9,10,11,12], function(i){ return moment(year.format('YYYY')+'-'+i+'-01'); }); } return _.map([0,1,2,3], function(delta){ return moment().add(delta, 'months').startOf('month'); }) }; this.promise_calendar = function(args) { var year = args.year || moment(), show_full_year = args.show_full_year || false, model = sequelize.models, this_user = this, // Find or if we need to show multi year calendar is_multi_year = moment().month() > 8; var months_to_show = this_user._get_calendar_months_to_show({ year : year.clone(), show_full_year : show_full_year }); return Promise.join( Promise.try(function(){ return this_user.getDepartment(); }), Promise.try(function(){ return this_user.getCompany({ include:[ { model : model.BankHoliday, as : 'bank_holidays' }, { model : model.LeaveType, as : 'leave_types' }, ] }); }), Promise.try(function(){ return this_user.getMy_leaves({ where : { status : { $ne : sequelize.models.Leave.status_rejected()}, $or : { date_start : { $between : [ moment(year).startOf('year').format('YYYY-MM-DD'), moment( year.clone().add((is_multi_year ? 1 : 0), 'years') ).endOf('year').format('YYYY-MM-DD'), ] }, date_end : { $between : [ moment( year ).startOf('year').format('YYYY-MM-DD'), moment( year.clone().add((is_multi_year ? 1 : 0), 'years') ).endOf('year').format('YYYY-MM-DD'), ] } } }, }); }), function(department, company, leaves){ var leave_days = _.flatten( _.map(leaves, function(leave){ return _.map( leave.get_days(), function(leave_day){ leave_day.leave = leave; return leave_day; }); })); return Promise.resolve( _.map(months_to_show, function(month){ return new CalendarMonth( month, { bank_holidays : department.include_public_holidays ? _.map( company.bank_holidays, function(day){return day.date} ) : [], leave_days : leave_days, } ); }) ); } ); // End of join }; this.validate_overlapping = function(new_leave_attributes) { var this_user = this; var days_filter = { $between : [ new_leave_attributes.from_date, moment(new_leave_attributes.to_date) .add(1,'days').format('YYYY-MM-DD'), ], }; return this_user.getMy_leaves({ where : { status : { $ne : sequelize.models.Leave.status_rejected()}, $or : { date_start : days_filter, date_end : days_filter, }, }, }) .then(function(overlapping_leaves){ // Check there are overlapping leaves if (overlapping_leaves.length === 0){ return Promise.resolve(1); } var overlapping_leave = overlapping_leaves[0]; if (overlapping_leave.fit_with_leave_request( new_leave_attributes )){ return Promise.resolve(1); } // Otherwise it is overlapping! var error = new Error('Overlapping booking!'); error.user_message = 'Overlapping booking!'; throw error; }); }; // end of validate_overlapping // Promise all leaves requested by current user, regardless // their statuses // this.promise_my_leaves = function(args){ var where_clause = {}, year = args.year || moment(); if (args && args.filter_status) { where_clause = { status : args.filter_status }; } if (args && ! args.ignore_year) { where_clause['$or'] = { date_start : { $between : [ moment(year).startOf('year').format('YYYY-MM-DD'), moment(year).endOf('year').format('YYYY-MM-DD'), ] }, date_end : { $between : [ moment(year).startOf('year').format('YYYY-MM-DD'), moment(year).endOf('year').format('YYYY-MM-DD'), ] } }; } var promise_my_leaves = this.getMy_leaves({ // TODO here is cartesian product between leave types and users, // needs to be split include : [{ model : sequelize.models.LeaveType, as : 'leave_type', },{ model : sequelize.models.User, as : 'user', include : [{ model : sequelize.models.Company, as : 'company', include : [{ model : sequelize.models.BankHoliday, as : 'bank_holidays', }], }], }], where : where_clause, }) // Fetch approvers for each leave in separate query, to avoid cartesian // products. .then(function(leaves){ return Promise.resolve(leaves) .map( function(leave){ return leave.promise_approver() .then(function(approver){ leave.approver = approver; return Promise.resolve(leave); }); }, { concurrency : 10, } ); }) return promise_my_leaves; }; this.promise_my_active_leaves = function(args) { var year = args.year || moment(); return this.promise_my_leaves({ year : year, filter_status : [ sequelize.models.Leave.status_approved(), sequelize.models.Leave.status_new(), sequelize.models.Leave.status_pended_revoke(), ], }); }; // Promises leaves ever booked for current user this.promise_my_active_leaves_ever = function(args) { return this.promise_my_leaves({ ignore_year : true, filter_status : [ sequelize.models.Leave.status_approved(), sequelize.models.Leave.status_new(), sequelize.models.Leave.status_pended_revoke(), ], }); }; // Promise leaves that are needed to be Approved/Rejected // this.promise_leaves_to_be_processed = function(){ return this.getSupervised_leaves({ include : [{ model : sequelize.models.LeaveType, as : 'leave_type', },{ model : sequelize.models.User, as : 'user', include : [{ model : sequelize.models.Company, as : 'company', include : [{ model : sequelize.models.BankHoliday, as : 'bank_holidays', }], },{ model : sequelize.models.Department, as : 'department', }], }], where : { status : [ sequelize.models.Leave.status_new(), sequelize.models.Leave.status_pended_revoke() ] }, }); }; // END of promise_leaves_to_be_processed this.calculate_number_of_days_taken_from_allowence = function(args){ var leave_type = args ? args.leave_type : null, leaves_to_traverse = this.my_leaves || []; // If leave_type was provided, we care only about leaves of that type if (leave_type) { leaves_to_traverse = _.filter( leaves_to_traverse, function(leave){ return leave.leaveTypeId === leave_type.id; } ); } return _.reduce( _.map( _.filter( leaves_to_traverse, function (leave){ return leave.is_approved_leave(); } ), function(leave){ return leave.get_deducted_days_number(args); } ), function(memo, num){ return memo + num }, 0 ) || 0; }; // Based on leaves attached to the current user object, // the method does not perform any additional queries // this.get_leave_statistics_by_types = function(args){ if (! args ) args = {}; var statistics = {}, limit_by_top = args.limit_by_top || false; this.company.leave_types.forEach(function(leave_type){ var initial_stat = { leave_type : leave_type, days_taken : 0, }; if (leave_type.limit && leave_type.limit > 0) { initial_stat.limit = leave_type.limit; } statistics[leave_type.id] = initial_stat; }); // Calculate statistics as an object _.filter( this.my_leaves, function (leave){ return leave.is_approved_leave() } ) .forEach( function(leave){ var stat_obj = statistics[leave.leave_type.id]; stat_obj.days_taken = stat_obj.days_taken + leave.get_deducted_days_number({ ignore_allowance : true, }); } ); var statistic_arr = _.map( _.pairs(statistics), function(pair){ return pair[1]; } ); statistic_arr = _.sortBy( statistic_arr, 'days_taken' ) .reverse(); if (limit_by_top) { statistic_arr = _.first(statistic_arr, 4); } return _.sortBy(statistic_arr, function(rec){ return rec.leave_type.name; }); }, this.get_automatic_adjustment = function(args) { var now = (args && args.now) ? moment(args.now) : moment(); if ( now.year() !== moment(this.start_date).year() && ( ! this.end_date || moment(this.end_date).year() > now.year() ) ){ return 0; } var start_date = moment(this.start_date).year() === now.year() ? moment(this.start_date) : now.startOf('year'), end_date = this.end_date && moment(this.end_date).year() <= now.year() ? moment(this.end_date) : moment().endOf('year'); return -1*(this.department.allowence - Math.round( this.department.allowence * end_date.diff(start_date, 'days') / 365 )); }; this.calculate_total_number_of_days_n_allowence = function(year) { // If optional paramater year was provided we need to calculate allowance // for that year, and if it is something other then current year, // adjustment should be made, return nominal setting from department if (year && year != moment().year()) { return this.department.allowence } // Get general allowence based on department return this.department.allowence + this.get_automatic_adjustment() // Adjust it based on current user + this.adjustment; }; this.promise_my_leaves_for_calendar = function(args){ var year = args.year || moment(); return this.getMy_leaves({ where : { status : { $ne : sequelize.models.Leave.status_rejected()}, $or : { date_start : { $between : [ moment(year).startOf('year').format('YYYY-MM-DD'), moment(year).endOf('year').format('YYYY-MM-DD'), ] }, date_end : { $between : [ moment(year).startOf('year').format('YYYY-MM-DD'), moment(year).endOf('year').format('YYYY-MM-DD'), ] } } }, }); // End of MyLeaves }; // For given leave object (not necessary one with corresponding record in DB) // check if current user is capable to have it, that is if user's remaining // vacation allowance is big enough to accommodate the leave. // // If validation fails an exceptionis thrown. // this.validate_leave_fits_into_remaining_allowance = function(args){ var self = this, leave_type = args.leave_type, leave = args.leave, // Derive year from Leave object year = args.year || moment(leave.date_start); // Make sure object contain all necessary data for that check return self.reload_with_leave_details({ year : year.clone(), }) .then(function(employee){ return employee.reload_with_session_details(); }) .then(function(employee){ return employee.company.reload_with_bank_holidays() .then(function(){ return Promise.resolve(employee); }); }) .then(function(employee){ // Throw an exception when less than zero vacation would remain // if we add currently requested absence if ( employee.calculate_number_of_days_available_in_allowence( year.format('YYYY') ) - leave.get_deducted_days_number({ year : year.format('YYYY'), user : employee, leave_type : leave_type, }) < 0 ) { var error = new Error('Requested absence is longer than remaining allowance'); error.user_message = error.toString(); throw error; } return Promise.resolve(employee); }) // Check that adding new leave of this type will not exceed maximum limit of // that type (if it is defined) .then(function(employee){ if ( // There is a limit for current type leave_type.limit // ... and lemit is bigger than zero && leave_type.limit > 0 ) { // ... sum of used dayes for this limit is going to be bigger then limit var would_be_used = employee.calculate_number_of_days_taken_from_allowence({ year : year.format('YYYY'), leave_type : leave_type, ignore_allowance : true, }) + leave.get_deducted_days_number({ year : year.format('YYYY'), user : employee, leave_type : leave_type, ignore_allowance : true, }); if (would_be_used > leave_type.limit) { var error = new Error('Adding requested '+leave_type.name +" absense would exceed maximum allowed for such type by " +(would_be_used - leave_type.limit) ); error.user_message = error.toString(); throw error; } } }); }; };
const { regexMatchLocs } = require('../lib/matching/regexMatch'); const { mergeLocMatchGroups } = require('../lib/matching/utils'); const allSetSrc = { type: 'website', url: 'https://resources.allsetlearning.com/chinese/grammar/ASG1QB4K', name: 'AllSet Chinese Grammar Wiki', }; module.exports = { id: 'yimian', structures: ['ไธ€้ข + Verb + ไธ€้ข + Verb'], description: 'ไธ€้ข (yรฌmiร n) is a more formal than ไธ€่พน, but is used in the same way to express two simultaneous actions. It is used in the following way:', sources: [allSetSrc], match: sentence => { const text = sentence.original; return mergeLocMatchGroups([regexMatchLocs(text, /(ไธ€้ข)[^ไธ€้ข]+(ไธ€้ข)/)]); }, examples: [ { zh: 'ไป–ๅ–œๆฌขไธ€้ขๅƒไธœ่ฅฟ๏ผŒไธ€้ข็œ‹็”ตๅฝฑใ€‚', en: 'He likes to eat and watch movies at the same time.', src: allSetSrc, }, { zh: 'ๆˆ‘ๅ‘Š่ฏ‰ไฝ ๅคšๅฐ‘ๆฌกไบ†๏ผŒๅˆซไธ€้ข่บบๅœจๅบŠไธŠไธ€้ขๅƒ้›ถ้ฃŸ๏ผๅผ„ๅพ—ๅบŠไธŠ้ƒฝๆ˜ฏ็ขŽๅฑ‘!', en: 'I told you so many times, don\'t eat while laying on the bed. The "clean" bed now has crumbs all over it!', src: allSetSrc, }, { zh: 'ไป–ไปฌไธ€ๅฎถไบบไธ€้ข่ตๆœˆไธ€้ขๅƒๆœˆ้ฅผใ€‚', en: 'They enjoy the moon and eat mooncakes together as a family.', src: allSetSrc, }, { zh: 'ไฝ ไผšไธ€้ขๆ‹ๅคดไธ€้ขๆ‰่‚šๅญๅ—๏ผŸ', en: 'Can you pat your head and rub your belly at the same time?', src: allSetSrc, }, { zh: 'ๆ”ฟๅบœไธ€้ข่ฆๆŽงๅˆถ้€š่ดง่†จ่ƒ€๏ผŒไธ€้ขไนŸ่ฆไฟ่ฏไธ€ๅฎš็š„็ปๆตŽๅขž้•ฟ้€Ÿๅบฆใ€‚', en: "On one hand, the government is going to control inflation, but on the other hand, it's definitely going to protect economic growth.", src: allSetSrc, }, ], };
'use strict'; angular.module('carpoolBuddyApp.directives', []). directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
var request = require("request"); module.exports = { "exampleEndPoint": { get: function(req, res){ res.status(200).send("hi"); }, post: function(req, res){ res.status(200).send("justPosted"); } }, "sfCrimeData": { get: function(req, res){ var count = 100; // Get Crime data from 3 months back var date = new Date(); date.setMonth(date.getMonth() - 3); date = date.toISOString().split("").slice(0,-5); date.push("Z"); date = date.join(""); // Build a bounding box req.body.coordinates = [37.783409, -122.409176]; // Hack Reactor's coordinates var bbox = [req.body.coordinates[1]-0.01, req.body.coordinates[0]-0.01, req.body.coordinates[1]+0.01, req.body.coordinates[0]+0.01]; bbox = bbox.join(","); // Build API query var crimeSpotEndPoint = "http://sanfrancisco.crimespotting.org/crime-data?format=json"; crimeSpotEndPoint = crimeSpotEndPoint + "&count=" + count; crimeSpotEndPoint = crimeSpotEndPoint + "&dtstart=" + date; crimeSpotEndPoint = crimeSpotEndPoint + "&bbox=" + bbox; request.get(crimeSpotEndPoint, function(error, crimeData){ if (error) { console.error(error); res.status(400).send(error); } else { res.status(200).send(crimeData.body); } }); } } }
var gulp = require('gulp'), less = require('gulp-less'), clean = require('gulp-clean'), concatJs = require('gulp-concat'), minifyJs = require('gulp-uglify'); gulp.task('less', function() { return gulp.src(['web-src/less/*.less']) .pipe(less({compress: true})) .pipe(gulp.dest('web/css/')); }); gulp.task('images', function () { return gulp.src([ 'web-src/images/*' ]) .pipe(gulp.dest('web/images/')) }); gulp.task('fonts', function () { return gulp.src(['bower_components/bootstrap/fonts/*']) .pipe(gulp.dest('web/fonts/')) }); gulp.task('clean', function () { return gulp.src(['web/css/*', 'web/js/*', 'web/images/*', 'web/fonts/*']) .pipe(clean()); }); gulp.task('default', ['clean'], function () { var tasks = ['images', 'fonts', 'less', 'lib-js', 'pages-js']; tasks.forEach(function (val) { gulp.start(val); }); }); gulp.task('watch', function () { var less = gulp.watch('web-src/less/*.less', ['less']), js = gulp.watch('web-src/js/*.js', ['pages-js']); }); gulp.task('lib-js', function() { return gulp.src([ 'bower_components/jquery/dist/jquery.js', 'bower_components/bootstrap/dist/js/bootstrap.js' ]) .pipe(concatJs('app.js')) .pipe(minifyJs()) .pipe(gulp.dest('web/js/')); }); gulp.task('pages-js', function() { return gulp.src([ 'web-src/js/*.js' ]) .pipe(minifyJs()) .pipe(gulp.dest('web/js/')); });
import React, {PureComponent} from "react"; import {FillView} from "../shared/fill-view"; import {CodeView} from "../shared/code-view"; const sourceCode = ` export const simpleHoc = () => { return (WrappedComponent) => { return (props) => { const componentProps = { message: "Wrapped Component", ...props }; return ( <WrappedComponent {...componentProps} /> ); }; }; }; `; export class SimpleHocSlide extends PureComponent { render() { return ( <FillView> <CodeView sourceCode={sourceCode} language="javascript" /> </FillView> ) } }
export function showModal(id) { return { type: 'MODAL/SHOW', id: id } } export function closeModal() { return { type: 'MODAL/CLOSE' } } export function showScreen(id) { return { type: 'SCREEN/SHOW', id: id } }
angular.module('seagame',[]) .directive('shop',function (Ships){ return { restrict:'EA', templateUrl:'shop.html', link:function(scope){ scope.Ships=Ships } } }) .directive('ship',function ($timeout,Game){ return { restrict:'EA', templateUrl : 'ship.html', scope:{ data:'=' }, controller:function($interval,$scope){ var c=$scope; var data= c.data; c.start=function(){ if(data.current>= data.capacity)return; data.state='running'; c.timer=$interval(function (){ if(!data.timeleft){ c.resetTime(); } data.timeleft--; if(data.timeleft<=0){ c.harvest(); c.resetTime(); } },1000); } c.sell=function (){ if(Game.ships.length==1){ alert("ๆ‚จๅฐฑไธ€ๆก่ˆนไบ†๏ผŒไธ่ƒฝๅ†ๅ–ไบ†ๅ•Šใ€‚ใ€‚"); return; }; Game.sell(data); } c.resetTime=function (){ data.timeleft=data.needtime; } c.harvest=function(){ data.current+=data.harvestamount; if(data.current>=data.capacity){ data.current=data.capacity; c.stop(); } } c.get=function (){ if(data.current<=0)return; Game.get(data.current); data.current=0; } c.stop=function (){ $interval.cancel(c.timer); delete c.timer; data.state='idle'; } if(data.state=='running') c.start(); } } }) .value('Utils',{ timeunit: function (time){ var days,hours,minutes,seconds; seconds = time % 60; time-=seconds; time/=60;//ๅˆ†้’Ÿ minutes = time % 60; time-=minutes; time/=60; //ๅฐๆ—ถ hours = time % 24; time-=hours; days=time/24; var str=''; if(days>0){ str=days+'ๅคฉ'; } if(hours>0){ str+=hours+'ๅฐๆ—ถ'; }else{ if(str.length>0 & (minutes>0 || seconds>0)){ str+='้›ถ'; } } if(minutes>0){ str+=minutes+'ๅˆ†้’Ÿ'; }else{ if(str.length>0 && str[str.length-1]!='้›ถ' && seconds>0){ str+='้›ถ'; } } if(seconds>0){ str+=seconds+'็ง’'; } return str; } }) .filter('timeunit',function(Utils){ return Utils.timeunit; }) .service('Game',function (Ships,$interval,Utils,$timeout){ var Game=this; Game.money=0; Game.fish=0; Game.fishPrice=2; function Ship(index){ var ship=this; angular.extend(ship,Ships[index]); if(ship.timeleft==undefined){ ship.timeleft=ship.needtime; } } Game.ships=[new Ship(0)]; $interval(function(){ Game.save(); },1000); Game.buy=function (shipIndex){ if(Game.ships.length>=12){ alert('ๆœ€ๅคšๅช่ƒฝๆ‹ฅๆœ‰12ๆก่ˆน'); return; } var ship=Ships[shipIndex]; if(!ship || !ship.price){ alert('ๆ‰พไธๅˆฐ่ฆไนฐ็š„่ˆน!'); return; } if(Game.money<ship.price){ alert('้‡‘้’ฑไธ่ถณ!'); return; }; Game.money-=ship.price; Game.ships.push(new Ship(shipIndex)); if(Game.ships.length>=12){ var win=true; for(var i=0;i<Game.ships.length;i++){ if(Game.ships[i].title!='ๅผ‚ๆฌกๅ…ƒๆ•้ฑผ่ˆน'){ win=false; break; } } if(win){ var nowTime=new Date().getTime(); var lastSaveTime=angular.fromJson(localStorage.getItem('startTime')) || nowTime; var period=Math.floor((nowTime-lastSaveTime)/1000); $timeout(function(){ alert('ๆญๅ–œๆ‚จ!!!!\n\nๆ‚จๆˆๅŠŸๆ”ถ้›†ไบ†12ๆกๅผ‚ๆฌกๅ…ƒๆ•้ฑผ่ˆน๏ผŒ่Žทๅพ—ไบ†ๅคงๆ•้ฑผๅฎถ็งฐๅท๏ผๆ‚จ้€šๅ…ณๆ‰€็”จ็š„ๆธธๆˆๆ—ถ้—ดไธบ๏ผš' + Utils.timeunit(period)); },0); } } } Game.sell=function (ship){ for(var i=0;i<Game.ships.length;i++){ if(ship==Game.ships[i]){ if(confirm('่ฆไปฅ'+Math.floor(ship.price/2)+'ๅ…ƒๅ–ๆމ'+ship.title+'ๅ—?')){ Game.money+=Math.floor(ship.price/2); Game.ships.splice(i,1); return; } } } } Game.save=function(key){ localStorage.setItem('lastSaveTime',new Date().getTime()); if(key){ if(typeof Game[key]!='function'){ localStorage.setItem(key,angular.toJson(Game[key])); } return; } if(!localStorage.getItem('startTime')){ localStorage.setItem('startTime',new Date().getTime()); } for(var key in Game){ Game.save(key); } } Game.load=function(){ for(var i=0;i<localStorage.length;i++){ Game[localStorage.key(i)]=angular.fromJson(localStorage.getItem(localStorage.key(i))); } var nowTime=new Date().getTime(); var lastSaveTime=angular.fromJson(localStorage.getItem('lastSaveTime')) || nowTime; var period=Math.floor((nowTime-lastSaveTime)/1000); Game.consume(period); Game.save(); }; //for debug use window.reset=function(){ if(confirm('็กฎๅฎš่ฆ้‡ๆ–ฐ็Žฉๅ—๏ผŸ')){ localStorage.clear(); location.reload(); } } Game.consume=function(period){ function consumeShip(ship,period){ if(ship.state=='idle')return; var times=Math.floor(period / ship.needtime); ship.current+=ship.harvestamount*times; if(ship.current>=ship.capacity){ ship.current=ship.capacity; ship.state='idle'; } period=period % ship.needtime; ship.timeleft-=period; if(ship.timeleft<0)ship.timeleft=0; } if(period==0)return; for(var i=0;i<Game.ships.length;i++){ consumeShip(Game.ships[i],period); } } Game.load(); Game.get=function (fish){ Game.fish+=fish; } Game.sellFish=function (){ Game.money+=Math.floor(Game.fish*Game.fishPrice); Game.fish=0; } !function FishPriceAdjust(){ var step=0.05-Math.random()/10; Game.fishPrice+=step; if(Game.fishPrice<1)Game.fishPrice=1; if(Game.fishPrice>5)Game.fishPrice=5; setTimeout(FishPriceAdjust,1000); }(); }) .value('Ships',[ { title:'ๅฐๆธ”่ˆน', harvestamount:1000, needtime:6, capacity:2000, current:0, state:'idle', price:2000, imgClass:'ship1' } ,{ title:'ๅคงๅธ†่ˆน', harvestamount:5000, needtime:30, capacity:10000, current:0, state:'idle', price:50000, imgClass:'ship2' } ,{ title:'่ฑชๅŽๅฟซ่‰‡', harvestamount:1500, needtime:2, capacity:20000, current:0, state:'idle', price:200000, imgClass:'ship3' } ,{ title:'ๅผ‚ๆฌกๅ…ƒๆ•้ฑผ่ˆน', harvestamount:20000, needtime:60, capacity:50000, current:0, state:'idle', price:500000, imgClass:'ship4' } ]).run(function (Game,$rootScope){ $rootScope.Game=Game; });
/* ============================ TOC ============================== 1. Magific Popup Script 2. Get Scrollbar Width 3. Check if Scrollbar Exists if true, add class to html 4. Remove title on hover restore on click 5. single image with the class .pop-image on the href 6. gallery of images 7. iframe content 8. inline content 9. ajax content 10. custom close button 11. inline content onload ================================================================ */ /*! ================== 1. MAGNIFIC POPUP ==================== */ /*! Magnific Popup - v1.0.0 - 2015-01-03 * http://dimsemenov.com/plugins/magnific-popup/ * Copyright (c) 2015 Dmitry Semenov; */ ! function(a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : window.jQuery || window.Zepto) }(function(a) { var b, c, d, e, f, g, h = "Close", i = "BeforeClose", j = "AfterClose", k = "BeforeAppend", l = "MarkupParse", m = "Open", n = "Change", o = "mfp", p = "." + o, q = "mfp-ready", r = "mfp-removing", s = "mfp-prevent-close", t = function() {}, u = !!window.jQuery, v = a(window), w = function(a, c) { b.ev.on(o + a + p, c) }, x = function(b, c, d, e) { var f = document.createElement("div"); return f.className = "mfp-" + b, d && (f.innerHTML = d), e ? c && c.appendChild(f) : (f = a(f), c && f.appendTo(c)), f }, y = function(c, d) { b.ev.triggerHandler(o + c, d), b.st.callbacks && (c = c.charAt(0).toLowerCase() + c.slice(1), b.st.callbacks[c] && b.st.callbacks[c].apply(b, a.isArray(d) ? d : [d])) }, z = function(c) { return c === g && b.currTemplate.closeBtn || (b.currTemplate.closeBtn = a(b.st.closeMarkup.replace("%title%", b.st.tClose)), g = c), b.currTemplate.closeBtn }, A = function() { a.magnificPopup.instance || (b = new t, b.init(), a.magnificPopup.instance = b) }, B = function() { var a = document.createElement("p").style, b = ["ms", "O", "Moz", "Webkit"]; if (void 0 !== a.transition) return !0; for (; b.length;) if (b.pop() + "Transition" in a) return !0; return !1 }; t.prototype = { constructor: t, init: function() { var c = navigator.appVersion; b.isIE7 = -1 !== c.indexOf("MSIE 7."), b.isIE8 = -1 !== c.indexOf("MSIE 8."), b.isLowIE = b.isIE7 || b.isIE8, b.isAndroid = /android/gi.test(c), b.isIOS = /iphone|ipad|ipod/gi.test(c), b.supportsTransition = B(), b.probablyMobile = b.isAndroid || b.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent), d = a(document), b.popupsCache = {} }, open: function(c) { var e; if (c.isObj === !1) { b.items = c.items.toArray(), b.index = 0; var g, h = c.items; for (e = 0; e < h.length; e++) if (g = h[e], g.parsed && (g = g.el[0]), g === c.el[0]) { b.index = e; break } } else b.items = a.isArray(c.items) ? c.items : [c.items], b.index = c.index || 0; if (b.isOpen) return void b.updateItemHTML(); b.types = [], f = "", b.ev = c.mainEl && c.mainEl.length ? c.mainEl.eq(0) : d, c.key ? (b.popupsCache[c.key] || (b.popupsCache[c.key] = {}), b.currTemplate = b.popupsCache[c.key]) : b.currTemplate = {}, b.st = a.extend(!0, {}, a.magnificPopup.defaults, c), b.fixedContentPos = "auto" === b.st.fixedContentPos ? !b.probablyMobile : b.st.fixedContentPos, b.st.modal && (b.st.closeOnContentClick = !1, b.st.closeOnBgClick = !1, b.st.showCloseBtn = !1, b.st.enableEscapeKey = !1), b.bgOverlay || (b.bgOverlay = x("bg").on("click" + p, function() { b.close() }), b.wrap = x("wrap").attr("tabindex", -1).on("click" + p, function(a) { b._checkIfClose(a.target) && b.close() }), b.container = x("container", b.wrap)), b.contentContainer = x("content"), b.st.preloader && (b.preloader = x("preloader", b.container, b.st.tLoading)); var i = a.magnificPopup.modules; for (e = 0; e < i.length; e++) { var j = i[e]; j = j.charAt(0).toUpperCase() + j.slice(1), b["init" + j].call(b) } y("BeforeOpen"), b.st.showCloseBtn && (b.st.closeBtnInside ? (w(l, function(a, b, c, d) { c.close_replaceWith = z(d.type) }), f += " mfp-close-btn-in") : b.wrap.append(z())), b.st.alignTop && (f += " mfp-align-top"), b.wrap.css(b.fixedContentPos ? { overflow: b.st.overflowY, overflowX: "hidden", overflowY: b.st.overflowY } : { top: v.scrollTop(), position: "absolute" }), (b.st.fixedBgPos === !1 || "auto" === b.st.fixedBgPos && !b.fixedContentPos) && b.bgOverlay.css({ height: d.height(), position: "absolute" }), b.st.enableEscapeKey && d.on("keyup" + p, function(a) { 27 === a.keyCode && b.close() }), v.on("resize" + p, function() { b.updateSize() }), b.st.closeOnContentClick || (f += " mfp-auto-cursor"), f && b.wrap.addClass(f); var k = b.wH = v.height(), n = {}; if (b.fixedContentPos && b._hasScrollBar(k)) { var o = b._getScrollbarSize(); o && (n.marginRight = o) } b.fixedContentPos && (b.isIE7 ? a("body, html").css("overflow", "hidden") : n.overflow = "hidden"); var r = b.st.mainClass; return b.isIE7 && (r += " mfp-ie7"), r && b._addClassToMFP(r), b.updateItemHTML(), y("BuildControls"), a("html").css(n), b.bgOverlay.add(b.wrap).prependTo(b.st.prependTo || a(document.body)), b._lastFocusedEl = document.activeElement, setTimeout(function() { b.content ? (b._addClassToMFP(q), b._setFocus()) : b.bgOverlay.addClass(q), d.on("focusin" + p, b._onFocusIn) }, 16), b.isOpen = !0, b.updateSize(k), y(m), c }, close: function() { b.isOpen && (y(i), b.isOpen = !1, b.st.removalDelay && !b.isLowIE && b.supportsTransition ? (b._addClassToMFP(r), setTimeout(function() { b._close() }, b.st.removalDelay)) : b._close()) }, _close: function() { y(h); var c = r + " " + q + " "; if (b.bgOverlay.detach(), b.wrap.detach(), b.container.empty(), b.st.mainClass && (c += b.st.mainClass + " "), b._removeClassFromMFP(c), b.fixedContentPos) { var e = { marginRight: "" }; b.isIE7 ? a("body, html").css("overflow", "") : e.overflow = "", a("html").css(e) } d.off("keyup" + p + " focusin" + p), b.ev.off(p), b.wrap.attr("class", "mfp-wrap").removeAttr("style"), b.bgOverlay.attr("class", "mfp-bg"), b.container.attr("class", "mfp-container"), !b.st.showCloseBtn || b.st.closeBtnInside && b.currTemplate[b.currItem.type] !== !0 || b.currTemplate.closeBtn && b.currTemplate.closeBtn.detach(), b._lastFocusedEl && a(b._lastFocusedEl).focus(), b.currItem = null, b.content = null, b.currTemplate = null, b.prevHeight = 0, y(j) }, updateSize: function(a) { if (b.isIOS) { var c = document.documentElement.clientWidth / window.innerWidth, d = window.innerHeight * c; b.wrap.css("height", d), b.wH = d } else b.wH = a || v.height(); b.fixedContentPos || b.wrap.css("height", b.wH), y("Resize") }, updateItemHTML: function() { var c = b.items[b.index]; b.contentContainer.detach(), b.content && b.content.detach(), c.parsed || (c = b.parseEl(b.index)); var d = c.type; if (y("BeforeChange", [b.currItem ? b.currItem.type : "", d]), b.currItem = c, !b.currTemplate[d]) { var f = b.st[d] ? b.st[d].markup : !1; y("FirstMarkupParse", f), b.currTemplate[d] = f ? a(f) : !0 } e && e !== c.type && b.container.removeClass("mfp-" + e + "-holder"); var g = b["get" + d.charAt(0).toUpperCase() + d.slice(1)](c, b.currTemplate[d]); b.appendContent(g, d), c.preloaded = !0, y(n, c), e = c.type, b.container.prepend(b.contentContainer), y("AfterChange") }, appendContent: function(a, c) { b.content = a, a ? b.st.showCloseBtn && b.st.closeBtnInside && b.currTemplate[c] === !0 ? b.content.find(".mfp-close").length || b.content.append(z()) : b.content = a : b.content = "", y(k), b.container.addClass("mfp-" + c + "-holder"), b.contentContainer.append(b.content) }, parseEl: function(c) { var d, e = b.items[c]; if (e.tagName ? e = { el: a(e) } : (d = e.type, e = { data: e, src: e.src }), e.el) { for (var f = b.types, g = 0; g < f.length; g++) if (e.el.hasClass("mfp-" + f[g])) { d = f[g]; break } e.src = e.el.attr("data-mfp-src"), e.src || (e.src = e.el.attr("href")) } return e.type = d || b.st.type || "inline", e.index = c, e.parsed = !0, b.items[c] = e, y("ElementParse", e), b.items[c] }, addGroup: function(a, c) { var d = function(d) { d.mfpEl = this, b._openClick(d, a, c) }; c || (c = {}); var e = "click.magnificPopup"; c.mainEl = a, c.items ? (c.isObj = !0, a.off(e).on(e, d)) : (c.isObj = !1, c.delegate ? a.off(e).on(e, c.delegate, d) : (c.items = a, a.off(e).on(e, d))) }, _openClick: function(c, d, e) { var f = void 0 !== e.midClick ? e.midClick : a.magnificPopup.defaults.midClick; if (f || 2 !== c.which && !c.ctrlKey && !c.metaKey) { var g = void 0 !== e.disableOn ? e.disableOn : a.magnificPopup.defaults.disableOn; if (g) if (a.isFunction(g)) { if (!g.call(b)) return !0 } else if (v.width() < g) return !0; c.type && (c.preventDefault(), b.isOpen && c.stopPropagation()), e.el = a(c.mfpEl), e.delegate && (e.items = d.find(e.delegate)), b.open(e) } }, updateStatus: function(a, d) { if (b.preloader) { c !== a && b.container.removeClass("mfp-s-" + c), d || "loading" !== a || (d = b.st.tLoading); var e = { status: a, text: d }; y("UpdateStatus", e), a = e.status, d = e.text, b.preloader.html(d), b.preloader.find("a").on("click", function(a) { a.stopImmediatePropagation() }), b.container.addClass("mfp-s-" + a), c = a } }, _checkIfClose: function(c) { if (!a(c).hasClass(s)) { var d = b.st.closeOnContentClick, e = b.st.closeOnBgClick; if (d && e) return !0; if (!b.content || a(c).hasClass("mfp-close") || b.preloader && c === b.preloader[0]) return !0; if (c === b.content[0] || a.contains(b.content[0], c)) { if (d) return !0 } else if (e && a.contains(document, c)) return !0; return !1 } }, _addClassToMFP: function(a) { b.bgOverlay.addClass(a), b.wrap.addClass(a) }, _removeClassFromMFP: function(a) { this.bgOverlay.removeClass(a), b.wrap.removeClass(a) }, _hasScrollBar: function(a) { return (b.isIE7 ? d.height() : document.body.scrollHeight) > (a || v.height()) }, _setFocus: function() { (b.st.focus ? b.content.find(b.st.focus).eq(0) : b.wrap).focus() }, _onFocusIn: function(c) { return c.target === b.wrap[0] || a.contains(b.wrap[0], c.target) ? void 0 : (b._setFocus(), !1) }, _parseMarkup: function(b, c, d) { var e; d.data && (c = a.extend(d.data, c)), y(l, [b, c, d]), a.each(c, function(a, c) { if (void 0 === c || c === !1) return !0; if (e = a.split("_"), e.length > 1) { var d = b.find(p + "-" + e[0]); if (d.length > 0) { var f = e[1]; "replaceWith" === f ? d[0] !== c[0] && d.replaceWith(c) : "img" === f ? d.is("img") ? d.attr("src", c) : d.replaceWith('<img src="' + c + '" class="' + d.attr("class") + '" />') : d.attr(e[1], c) } } else b.find(p + "-" + a).html(c) }) }, _getScrollbarSize: function() { if (void 0 === b.scrollbarSize) { var a = document.createElement("div"); a.style.cssText = "width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;", document.body.appendChild(a), b.scrollbarSize = a.offsetWidth - a.clientWidth, document.body.removeChild(a) } return b.scrollbarSize } }, a.magnificPopup = { instance: null, proto: t.prototype, modules: [], open: function(b, c) { return A(), b = b ? a.extend(!0, {}, b) : {}, b.isObj = !0, b.index = c || 0, this.instance.open(b) }, close: function() { return a.magnificPopup.instance && a.magnificPopup.instance.close() }, registerModule: function(b, c) { c.options && (a.magnificPopup.defaults[b] = c.options), a.extend(this.proto, c.proto), this.modules.push(b) }, defaults: { disableOn: 0, key: null, midClick: !1, mainClass: "", preloader: !0, focus: "", closeOnContentClick: !1, closeOnBgClick: !0, closeBtnInside: !0, showCloseBtn: !0, enableEscapeKey: !0, modal: !1, alignTop: !1, removalDelay: 0, prependTo: null, fixedContentPos: "auto", fixedBgPos: "auto", overflowY: "auto", closeMarkup: '<button title="%title%" type="button" class="mfp-close">&times;</button>', tClose: "Close (Esc)", tLoading: "Loading..." } }, a.fn.magnificPopup = function(c) { A(); var d = a(this); if ("string" == typeof c) if ("open" === c) { var e, f = u ? d.data("magnificPopup") : d[0].magnificPopup, g = parseInt(arguments[1], 10) || 0; f.items ? e = f.items[g] : (e = d, f.delegate && (e = e.find(f.delegate)), e = e.eq(g)), b._openClick({ mfpEl: e }, d, f) } else b.isOpen && b[c].apply(b, Array.prototype.slice.call(arguments, 1)); else c = a.extend(!0, {}, c), u ? d.data("magnificPopup", c) : d[0].magnificPopup = c, b.addGroup(d, c); return d }; var C, D, E, F = "inline", G = function() { E && (D.after(E.addClass(C)).detach(), E = null) }; a.magnificPopup.registerModule(F, { options: { hiddenClass: "hide", markup: "", tNotFound: "Content not found" }, proto: { initInline: function() { b.types.push(F), w(h + "." + F, function() { G() }) }, getInline: function(c, d) { if (G(), c.src) { var e = b.st.inline, f = a(c.src); if (f.length) { var g = f[0].parentNode; g && g.tagName && (D || (C = e.hiddenClass, D = x(C), C = "mfp-" + C), E = f.after(D).detach().removeClass(C)), b.updateStatus("ready") } else b.updateStatus("error", e.tNotFound), f = a("<div>"); return c.inlineElement = f, f } return b.updateStatus("ready"), b._parseMarkup(d, {}, c), d } } }); var H, I = "ajax", J = function() { H && a(document.body).removeClass(H) }, K = function() { J(), b.req && b.req.abort() }; a.magnificPopup.registerModule(I, { options: { settings: null, cursor: "mfp-ajax-cur", tError: '<a href="%url%">The content</a> could not be loaded.' }, proto: { initAjax: function() { b.types.push(I), H = b.st.ajax.cursor, w(h + "." + I, K), w("BeforeChange." + I, K) }, getAjax: function(c) { H && a(document.body).addClass(H), b.updateStatus("loading"); var d = a.extend({ url: c.src, success: function(d, e, f) { var g = { data: d, xhr: f }; y("ParseAjax", g), b.appendContent(a(g.data), I), c.finished = !0, J(), b._setFocus(), setTimeout(function() { b.wrap.addClass(q) }, 16), b.updateStatus("ready"), y("AjaxContentAdded") }, error: function() { J(), c.finished = c.loadError = !0, b.updateStatus("error", b.st.ajax.tError.replace("%url%", c.src)) } }, b.st.ajax.settings); return b.req = a.ajax(d), "" } } }); var L, M = function(c) { if (c.data && void 0 !== c.data.title) return c.data.title; var d = b.st.image.titleSrc; if (d) { if (a.isFunction(d)) return d.call(b, c); if (c.el) return c.el.attr(d) || "" } return "" }; a.magnificPopup.registerModule("image", { options: { markup: '<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>', cursor: "mfp-zoom-out-cur", titleSrc: "title", verticalFit: !0, tError: '<a href="%url%">The image</a> could not be loaded.' }, proto: { initImage: function() { var c = b.st.image, d = ".image"; b.types.push("image"), w(m + d, function() { "image" === b.currItem.type && c.cursor && a(document.body).addClass(c.cursor) }), w(h + d, function() { c.cursor && a(document.body).removeClass(c.cursor), v.off("resize" + p) }), w("Resize" + d, b.resizeImage), b.isLowIE && w("AfterChange", b.resizeImage) }, resizeImage: function() { var a = b.currItem; if (a && a.img && b.st.image.verticalFit) { var c = 0; b.isLowIE && (c = parseInt(a.img.css("padding-top"), 10) + parseInt(a.img.css("padding-bottom"), 10)), a.img.css("max-height", b.wH - c) } }, _onImageHasSize: function(a) { a.img && (a.hasSize = !0, L && clearInterval(L), a.isCheckingImgSize = !1, y("ImageHasSize", a), a.imgHidden && (b.content && b.content.removeClass("mfp-loading"), a.imgHidden = !1)) }, findImageSize: function(a) { var c = 0, d = a.img[0], e = function(f) { L && clearInterval(L), L = setInterval(function() { return d.naturalWidth > 0 ? void b._onImageHasSize(a) : (c > 200 && clearInterval(L), c++, void(3 === c ? e(10) : 40 === c ? e(50) : 100 === c && e(500))) }, f) }; e(1) }, getImage: function(c, d) { var e = 0, f = function() { c && (c.img[0].complete ? (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("ready")), c.hasSize = !0, c.loaded = !0, y("ImageLoadComplete")) : (e++, 200 > e ? setTimeout(f, 100) : g())) }, g = function() { c && (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("error", h.tError.replace("%url%", c.src))), c.hasSize = !0, c.loaded = !0, c.loadError = !0) }, h = b.st.image, i = d.find(".mfp-img"); if (i.length) { var j = document.createElement("img"); j.className = "mfp-img", c.el && c.el.find("img").length && (j.alt = c.el.find("img").attr("alt")), c.img = a(j).on("load.mfploader", f).on("error.mfploader", g), j.src = c.src, i.is("img") && (c.img = c.img.clone()), j = c.img[0], j.naturalWidth > 0 ? c.hasSize = !0 : j.width || (c.hasSize = !1) } return b._parseMarkup(d, { title: M(c), img_replaceWith: c.img }, c), b.resizeImage(), c.hasSize ? (L && clearInterval(L), c.loadError ? (d.addClass("mfp-loading"), b.updateStatus("error", h.tError.replace("%url%", c.src))) : (d.removeClass("mfp-loading"), b.updateStatus("ready")), d) : (b.updateStatus("loading"), c.loading = !0, c.hasSize || (c.imgHidden = !0, d.addClass("mfp-loading"), b.findImageSize(c)), d) } } }); var N, O = function() { return void 0 === N && (N = void 0 !== document.createElement("p").style.MozTransform), N }; a.magnificPopup.registerModule("zoom", { options: { enabled: !1, easing: "ease-in-out", duration: 300, opener: function(a) { return a.is("img") ? a : a.find("img") } }, proto: { initZoom: function() { var a, c = b.st.zoom, d = ".zoom"; if (c.enabled && b.supportsTransition) { var e, f, g = c.duration, j = function(a) { var b = a.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"), d = "all " + c.duration / 1e3 + "s " + c.easing, e = { position: "fixed", zIndex: 9999, left: 0, top: 0, "-webkit-backface-visibility": "hidden" }, f = "transition"; return e["-webkit-" + f] = e["-moz-" + f] = e["-o-" + f] = e[f] = d, b.css(e), b }, k = function() { b.content.css("visibility", "visible") }; w("BuildControls" + d, function() { if (b._allowZoom()) { if (clearTimeout(e), b.content.css("visibility", "hidden"), a = b._getItemToZoom(), !a) return void k(); f = j(a), f.css(b._getOffset()), b.wrap.append(f), e = setTimeout(function() { f.css(b._getOffset(!0)), e = setTimeout(function() { k(), setTimeout(function() { f.remove(), a = f = null, y("ZoomAnimationEnded") }, 16) }, g) }, 16) } }), w(i + d, function() { if (b._allowZoom()) { if (clearTimeout(e), b.st.removalDelay = g, !a) { if (a = b._getItemToZoom(), !a) return; f = j(a) } f.css(b._getOffset(!0)), b.wrap.append(f), b.content.css("visibility", "hidden"), setTimeout(function() { f.css(b._getOffset()) }, 16) } }), w(h + d, function() { b._allowZoom() && (k(), f && f.remove(), a = null) }) } }, _allowZoom: function() { return "image" === b.currItem.type }, _getItemToZoom: function() { return b.currItem.hasSize ? b.currItem.img : !1 }, _getOffset: function(c) { var d; d = c ? b.currItem.img : b.st.zoom.opener(b.currItem.el || b.currItem); var e = d.offset(), f = parseInt(d.css("padding-top"), 10), g = parseInt(d.css("padding-bottom"), 10); e.top -= a(window).scrollTop() - f; var h = { width: d.width(), height: (u ? d.innerHeight() : d[0].offsetHeight) - g - f }; return O() ? h["-moz-transform"] = h.transform = "translate(" + e.left + "px," + e.top + "px)" : (h.left = e.left, h.top = e.top), h } } }); var P = "iframe", Q = "//about:blank", R = function(a) { if (b.currTemplate[P]) { var c = b.currTemplate[P].find("iframe"); c.length && (a || (c[0].src = Q), b.isIE8 && c.css("display", a ? "block" : "none")) } }; a.magnificPopup.registerModule(P, { options: { markup: '<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>', srcAction: "iframe_src", patterns: { youtube: { index: "youtube.com", id: "v=", src: "//www.youtube.com/embed/%id%?autoplay=1" }, vimeo: { index: "vimeo.com/", id: "/", src: "//player.vimeo.com/video/%id%?autoplay=1" }, gmaps: { index: "//maps.google.", src: "%id%&output=embed" } } }, proto: { initIframe: function() { b.types.push(P), w("BeforeChange", function(a, b, c) { b !== c && (b === P ? R() : c === P && R(!0)) }), w(h + "." + P, function() { R() }) }, getIframe: function(c, d) { var e = c.src, f = b.st.iframe; a.each(f.patterns, function() { return e.indexOf(this.index) > -1 ? (this.id && (e = "string" == typeof this.id ? e.substr(e.lastIndexOf(this.id) + this.id.length, e.length) : this.id.call(this, e)), e = this.src.replace("%id%", e), !1) : void 0 }); var g = {}; return f.srcAction && (g[f.srcAction] = e), b._parseMarkup(d, g, c), b.updateStatus("ready"), d } } }); var S = function(a) { var c = b.items.length; return a > c - 1 ? a - c : 0 > a ? c + a : a }, T = function(a, b, c) { return a.replace(/%curr%/gi, b + 1).replace(/%total%/gi, c) }; a.magnificPopup.registerModule("gallery", { options: { enabled: !1, arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', preload: [0, 2], navigateByImgClick: !0, arrows: !0, tPrev: "Previous (Left arrow key)", tNext: "Next (Right arrow key)", tCounter: "%curr% of %total%" }, proto: { initGallery: function() { var c = b.st.gallery, e = ".mfp-gallery", g = Boolean(a.fn.mfpFastClick); return b.direction = !0, c && c.enabled ? (f += " mfp-gallery", w(m + e, function() { c.navigateByImgClick && b.wrap.on("click" + e, ".mfp-img", function() { return b.items.length > 1 ? (b.next(), !1) : void 0 }), d.on("keydown" + e, function(a) { 37 === a.keyCode ? b.prev() : 39 === a.keyCode && b.next() }) }), w("UpdateStatus" + e, function(a, c) { c.text && (c.text = T(c.text, b.currItem.index, b.items.length)) }), w(l + e, function(a, d, e, f) { var g = b.items.length; e.counter = g > 1 ? T(c.tCounter, f.index, g) : "" }), w("BuildControls" + e, function() { if (b.items.length > 1 && c.arrows && !b.arrowLeft) { var d = c.arrowMarkup, e = b.arrowLeft = a(d.replace(/%title%/gi, c.tPrev).replace(/%dir%/gi, "left")).addClass(s), f = b.arrowRight = a(d.replace(/%title%/gi, c.tNext).replace(/%dir%/gi, "right")).addClass(s), h = g ? "mfpFastClick" : "click"; e[h](function() { b.prev() }), f[h](function() { b.next() }), b.isIE7 && (x("b", e[0], !1, !0), x("a", e[0], !1, !0), x("b", f[0], !1, !0), x("a", f[0], !1, !0)), b.container.append(e.add(f)) } }), w(n + e, function() { b._preloadTimeout && clearTimeout(b._preloadTimeout), b._preloadTimeout = setTimeout(function() { b.preloadNearbyImages(), b._preloadTimeout = null }, 16) }), void w(h + e, function() { d.off(e), b.wrap.off("click" + e), b.arrowLeft && g && b.arrowLeft.add(b.arrowRight).destroyMfpFastClick(), b.arrowRight = b.arrowLeft = null })) : !1 }, next: function() { b.direction = !0, b.index = S(b.index + 1), b.updateItemHTML() }, prev: function() { b.direction = !1, b.index = S(b.index - 1), b.updateItemHTML() }, goTo: function(a) { b.direction = a >= b.index, b.index = a, b.updateItemHTML() }, preloadNearbyImages: function() { var a, c = b.st.gallery.preload, d = Math.min(c[0], b.items.length), e = Math.min(c[1], b.items.length); for (a = 1; a <= (b.direction ? e : d); a++) b._preloadItem(b.index + a); for (a = 1; a <= (b.direction ? d : e); a++) b._preloadItem(b.index - a) }, _preloadItem: function(c) { if (c = S(c), !b.items[c].preloaded) { var d = b.items[c]; d.parsed || (d = b.parseEl(c)), y("LazyLoad", d), "image" === d.type && (d.img = a('<img class="mfp-img" />').on("load.mfploader", function() { d.hasSize = !0 }).on("error.mfploader", function() { d.hasSize = !0, d.loadError = !0, y("LazyLoadError", d) }).attr("src", d.src)), d.preloaded = !0 } } } }); var U = "retina"; a.magnificPopup.registerModule(U, { options: { replaceSrc: function(a) { return a.src.replace(/\.\w+$/, function(a) { return "@2x" + a }) }, ratio: 1 }, proto: { initRetina: function() { if (window.devicePixelRatio > 1) { var a = b.st.retina, c = a.ratio; c = isNaN(c) ? c() : c, c > 1 && (w("ImageHasSize." + U, function(a, b) { b.img.css({ "max-width": b.img[0].naturalWidth / c, width: "100%" }) }), w("ElementParse." + U, function(b, d) { d.src = a.replaceSrc(d, c) })) } } } }), function() { var b = 1e3, c = "ontouchstart" in window, d = function() { v.off("touchmove" + f + " touchend" + f) }, e = "mfpFastClick", f = "." + e; a.fn.mfpFastClick = function(e) { return a(this).each(function() { var g, h = a(this); if (c) { var i, j, k, l, m, n; h.on("touchstart" + f, function(a) { l = !1, n = 1, m = a.originalEvent ? a.originalEvent.touches[0] : a.touches[0], j = m.clientX, k = m.clientY, v.on("touchmove" + f, function(a) { m = a.originalEvent ? a.originalEvent.touches : a.touches, n = m.length, m = m[0], (Math.abs(m.clientX - j) > 10 || Math.abs(m.clientY - k) > 10) && (l = !0, d()) }).on("touchend" + f, function(a) { d(), l || n > 1 || (g = !0, a.preventDefault(), clearTimeout(i), i = setTimeout(function() { g = !1 }, b), e()) }) }) } h.on("click" + f, function() { g || e() }) }) }, a.fn.destroyMfpFastClick = function() { a(this).off("touchstart" + f + " click" + f), c && v.off("touchmove" + f + " touchend" + f) } }(), A() }); $(document).ready(function() { /* --------------- 2. Get Scrollbar Width --------------- */ function getScrollbarWidth() { var outer = document.createElement("div"); outer.style.visibility = "hidden"; outer.style.width = "100px"; outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps document.body.appendChild(outer); var widthNoScroll = outer.offsetWidth; // force scrollbars outer.style.overflow = "scroll"; // add innerdiv var inner = document.createElement("div"); inner.style.width = "100%"; outer.appendChild(inner); var widthWithScroll = inner.offsetWidth; // remove divs outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; } /* --------------- 3. Check if Scrollbar Exists if true, add class to html --------------- */ if ($(document).height() > $(window).height()) { $('html').addClass('modal-scroll-fix'); } /* --------------- 4. Remove title on hover restore on click --------------- */ $(".pop-gallery-img, .pop-image, .pop-youtube, .pop-vimeo, .pop-gmaps").hover(function() { var title = $(this).attr("title"); $(this).attr("tmp_title", title); $(this).attr("title", ""); }, function() { var title = $(this).attr("tmp_title"); $(this).attr("title", title); }); $(".pop-gallery-img, .pop-image, .pop-youtube, .pop-vimeo, .pop-gmaps").click(function() { var title = $(this).attr("tmp_title"); $(this).attr("title", title); }); /* --------------- 5. single image with the class .pop-image on the href --------------- */ $('.pop-image').magnificPopup({ type: 'image', callbacks: { open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } } }); /* --------------- 6. gallery of images --------------- */ $('.pop-gallery').magnificPopup({ delegate: '.pop-gallery-img', // child items selector, by clicking on it popup will open type: 'image', gallery: { enabled: true }, callbacks: { open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } } }); /* --------------- 7. iframe content --------------- */ // ============ magnificPopup :: iframe content with specific url types for only youtube, vimeo, and google maps others can be added by you ======================== // /* ++++ vimeo, youtube, and google maps disabled on touch devices as native behavior is preferred ++++ */ if ($('html').hasClass('no-touch')) { $('.pop-youtube, .pop-vimeo, .pop-gmaps, .iframe-content').magnificPopup({ type: 'iframe', iframe: { markup: '<div class="mfp-iframe-scaler">' + '<div class="mfp-close"></div>' + '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>' + '<div class="mfp-title">Some caption</div>' + '</div>' }, callbacks: { markupParse: function(template, values, item) { values.title = item.el.attr('title'); }, open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } } }); } /* --------------- 8. inline content --------------- */ $('.pop-inline').magnificPopup({ type: 'inline', mainClass: 'my-mfp-slidein', removalDelay: 300, callbacks: { open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } }, midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href. }); /* --------------- 9. ajax content --------------- */ $('.pop-ajax').magnificPopup({ type: 'ajax', mainClass: 'my-mfp-slidein', removalDelay: 300, callbacks: { ajaxContentAdded: function() { this.content.find('.closeme').on('click', function(e) { e.preventDefault(); $.magnificPopup.close(); }); }, open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } } }); /* --------------- 10. custom close button --------------- */ $(".mfp-modal .closeme").click(function() { $.magnificPopup.close(); }); /* --------------- 11. inline content onload --------------- */ setTimeout(function() { if ($('#example-modal-3').length) { $.magnificPopup.open({ items: { src: '#example-modal-3' }, type: 'inline', mainClass: 'my-mfp-slidein', removalDelay: 300, callbacks: { open: function() { $('html').toggleClass('mfp-open'); $('.header').css({ 'padding-right': getScrollbarWidth }); }, close: function() { $('html').removeClass('mfp-open'); $('.header').css({ 'padding-right': '0' }); } }, midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href. }); } }, 1000); }); // end ready function
//loginService.js var userService = (function () { function getUser(id) { return $.ajax({ headers: common.getAjaxHeader(), method: "GET", url: "user/" + id, }); } function deleteUser (id) { return $.ajax({ headers: common.getAjaxHeader(), method: "DELETE", url: "user/" + id, }); } function updateUser(id, user) { return $.ajax({ headers: common.getAjaxHeader(), type: "PUT", url: "/user/" + id, data: user, }); } function getUsers() { return $.ajax({ headers: common.getAjaxHeader(), method: "GET", url: "user", }); } function login(loginData) { return $.ajax({ type: "POST", url: "/user/login", data: loginData, }); } function logout() { return $.ajax({ type: "POST", url: "/user/logout" }); } function saveUser(user) { return $.ajax({ headers: common.getAjaxHeader(), type: "POST", url: "/user", data: user, }); } return { login: login, getUser: getUser, deleteUser: deleteUser, updateUser: updateUser, getUsers: getUsers, logout: logout, saveUser: saveUser } })();
define(["agda.frp.taskqueue","agda.frp.signal"],function(queue,signal) { function getTime(now) { return now; } function every(delay) { var start = queue.singleton.time + delay - 1; start = start - (start % delay); return signal.heartbeat(start,delay,0).map(getTime).hold(start); } return { date: function(t) { return new Date(t); }, seconds: function() { return every(1000); }, minutes: function() { return every(60 * 1000); }, hours: function() { return every(60 * 60 * 1000); }, every: every }; });
import r from 'restructure'; import Entity from '../entity'; import StringRef from '../string-ref'; export default Entity({ id: r.uint32le, name: StringRef, unknowns: new r.Reserved(r.uint32le, 2), soundID: r.uint32le, flags: r.uint32le });
/** * description: It contains utility functions which is used through out the client side app. */ angular.module('angularTestApp').factory('appUtils',["$http",function ($http) { var utility={ "dateUtility":{ "defaultDateFormatTo":"ddmmyyyy", "defaultDateFormatFrom":"ddmmyyyy", "defaultDateSeperator":"/", "zeroPad":function(num){ return num<10?"0"+num:num; //appends zero to numbers less than 10 in dates }, "dd":function (date) { return utility.dateUtility.zeroPad(date.getDate()); //date day }, "mm":function (date) { return utility.dateUtility.zeroPad(date.getMonth()+1); //date month }, "yyyy":function (date) { return date.getFullYear(); // date year }, /* * @param convertFormat:string * @param seperator: string seperator e.g / or - etc. * @param date:Date/number * @return date string * @desc:converts date as per given format */ "convertDate":function(convertFormat,seperator,date){ var result=""; switch (convertFormat){ case 'timestampTommddyyyy': result= utility.dateUtility.mm(date) + seperator + utility.dateUtility.dd(date) + seperator + utility.dateUtility.yyyy(date); return result; break; case 'timestampToddmmyyyy': result= utility.dateUtility.dd(date) + seperator + utility.dateUtility.mm(date) + seperator + utility.dateUtility.yyyy(date); return result; break; case 'timestampToyyyymmdd': date=new Date(date); result= utility.dateUtility.yyyy(date) + seperator + utility.dateUtility.mm(date) + seperator + utility.dateUtility.dd(date); return result; break; case 'ddmmyyyyTommddyyyy': result= utility.dateUtility.mm(date) + seperator + utility.dateUtility.dd(date) + seperator + utility.dateUtility.yyyy(date); return result; break; } }, /* * @param dateValue:string * @param delimiter: string seperator e.g / or - etc. * @desc:converts ddmmyyyy string date to js Date * @return js date */ 'ddmmyyyyStrToDate':function (dateValue,delimiter){ var dateValueArr=dateValue.split(" "); var del=delimiter ||"/"; var returnDate=null; if(dateValueArr && dateValueArr.length>0){ var dateValue1=dateValueArr[0]; var dateValue1Arr1=dateValue1.split(del); var day,month,year; dateValue1Arr1.length>0?day=parseInt(dateValue1Arr1[0]):NaN; dateValue1Arr1.length>1?month=parseInt(dateValue1Arr1[1]):NaN; dateValue1Arr1.length>2?year=parseInt(dateValue1Arr1[2]):NaN; month--; var hrs=0,mins=0,secs=0; if(dateValueArr.length>1 && dateValueArr[1].length>1){ var timeArr=dateValueArr[1].split(":"); timeArr.length>0?hrs=timeArr[0]:0; timeArr.length>1?mins=timeArr[1]:0; timeArr.length>2?secs=timeArr[2]:0; } if(day!=NaN && month!=NaN && year!=NaN){ var returnDate=new Date(Date.UTC(year, month, day, hrs, mins, secs)); } } return returnDate; }, 'validateDateRange':function(startDateStr,endDateStr){ var startTimeStamp=Number(utility.dateUtility.ddmmyyyyStrToDate(startDateStr)); var endTimeStamp=Number(utility.dateUtility.ddmmyyyyStrToDate(endDateStr)); if(startTimeStamp && startTimeStamp && typeof(startTimeStamp)=='number' && typeof(endTimeStamp)=='number' && startTimeStamp<=endTimeStamp){ return true; }else{ return false } }, 'validateDateRangeStamp':function(startDateStr,endDateStr){ var startTimeStamp=Date.parse(startDateStr); var endTimeStamp=Date.parse(endDateStr); if(startTimeStamp && startTimeStamp && typeof(startTimeStamp)=='number' && typeof(endTimeStamp)=='number' && startTimeStamp<=endTimeStamp){ return true; }else{ return false } }, /* * @param dateValue:string * @param delimiter: string seperator e.g / or - etc. * @desc:converts yyyymmdd string date to js Date * @return js date */ 'yyyymmddStrToDate':function (dateValue,delimiter){ var dateValueArr=dateValue.split(" "); var del=delimiter ||"/"; var returnDate=null; if(dateValueArr && dateValueArr.length>0){ var dateValue1=dateValueArr[0]; var dateValue1Arr=dateValue1.split(delimiter); var day,month,year; dateValue1Arr.length>0?year=parseInt(dateValue1Arr[0]):NaN; dateValue1Arr.length>1?month=parseInt(dateValue1Arr[1]):NaN; dateValue1Arr.length>2?day=parseInt(dateValue1Arr[2]):NaN; month--; var hrs=0,mins=0,secs=0; if(dateValueArr.length>1 && dateValueArr[1].length>1){ var timeArr=dateValueArr[1].split(":"); timeArr.length>0?hrs=timeArr[0]:0; timeArr.length>1?mins=timeArr[1]:0; timeArr.length>2?secs=timeArr[2]:0; } if(day!=NaN && month!=NaN && year!=NaN){ var returnDate=new Date(Date.UTC(year, month, day, hrs, mins, secs)); } } return returnDate; } }, /* * @param obj:Object * @return Object * desc: makes clone of any type of js object */ "cloneJSObj":function (obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = utility.cloneJSObj(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = utility.cloneJSObj(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }, /* * desc: Utility methods to support cross browser issues */ "downloadFileUtil":{ /* * @param sUrl:string * desc: takes path of the file to be downloaded and downloads that file */ "downloadFile":function (sUrl) { //iOS devices do not support downloading. We have to inform user about this. if (/(iP)/g.test(navigator.userAgent)) { alert('Your device does not support files downloading. Please try again in desktop browser.'); return false; } //If in Chrome or Safari - download via virtual link click if (utility.downloadFileUtil.isChrome || utility.downloadFileUtil.isSafari) { //Creating new link node. var link = document.createElement('a'); link.href = sUrl; if (link.download !== undefined) { //Set HTML5 download attribute. This will prevent file from opening if supported. var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length); link.download = fileName; } //Dispatching click event. if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } // Force file download (whether supported by server). sUrl += '?download'; window.open(sUrl, '_self'); return true; }, "isChrome":function(){ return navigator.userAgent.toLowerCase().indexOf('chrome') > -1; }, "isSafari":function(){ return navigator.userAgent.toLowerCase().indexOf('safari') > -1; } }, /* * @param response:Object * @param callback:function * desc: Used to parse response and show error if any. It should be used as to work with any $http response */ "defaultParseResponse":function(response,callback){ if(!response.error){ callback(response); }else{ $('#errorModal').find('.modal-body').html(response.errorMsg); $('#errorModal').modal('show'); return; } }, "showError":function(msg){ $('#errorModal').find('.modal-body').html(msg); $('#errorModal').modal('show'); return; }, "showWarning":function(msg){ $('#warningModal').find('.modal-body').html(msg); $('#warningModal').modal('show'); return; }, "showSuccess":function(msg){ $('#successModal').find('.modal-body').html(msg); $('#successModal').modal('show'); return; }, "uploadCSV":function(element,url,callback){ console.log("app Util uploadCSV",element,url); var file = element.files[0]; if(!file){ $(element).val(""); appUtils.showError("Please choose a .csv file."); return; } var fileName = file.name; var check = file.name.indexOf("csv"); if (check < 0) { $(thisObj).val(""); utility.showError("Please choose a .csv file."); return; }else{ //Take the first selected file var uploadCSV = new FormData(); uploadCSV.append("upload", file); $http.post(url, uploadCSV, { withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity }).success(function(dataResponse,status,headers,config){ //success utility.defaultParseResponse(dataResponse,callback); }).error(function(data,status,headers,config){ //error console.log("Error",data,status,headers,config); }); } }, "lovMapToArr":function(map){ var arr=[]; for(var key in map){ var obj=map[key]; if(typeof obj=='object'){ obj.key=key; arr.push(obj); } } return arr; }, 'validateEmail':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); } }; return utility; }]);
export default { locale: 'en', messages: { siteTitle: 'Dronegames', addPost: 'Add Post', switchLanguage: 'Switch Language', userIdText: 'Hello ', email: 'Email', by: 'By', deletePost: 'Delete Post', createNewPost: 'Create new post', authorName: 'Author\'s Name', postTitle: 'Post Title', postContent: 'Post Content', submit: 'Submit', comment: `user {name} {value, plural, =0 {does not have any comments} =1 {has # comment} other {has # comments} }`, HTMLComment: `user <b style='font-weight: bold'>{name} </b> {value, plural, =0 {does not have <i style='font-style: italic'>any</i> comments} =1 {has <i style='font-style: italic'>#</i> comment} other {has <i style='font-style: italic'>#</i> comments} }`, nestedDateComment: `user {name} {value, plural, =0 {does not have any comments} =1 {has # comment} other {has # comments} } as of {date}`, }, };
var Logger = require('content-logger'); var contentLogger = Logger.create( { prototype: { init() { this.testStats = { failures: 0 }; this._errorStack = []; this.on( 'add', function(error) { if (error.type !== 'ignored') { this.testStats.failures++; } } ); }, filterFileErrors(file, fn) { var fileErrors; var errors = this.getErrors(file); this._errorStack.push(errors); var filteredErrors = fn(errors); filteredErrors.errorMap = {}; this.fileErrors[file] = filteredErrors; return fileErrors; } } } ); module.exports = new contentLogger();
export {default as PreLogin} from './PreLogin'; export {default as Login} from './Login'; export {default as RegisterMobile} from './RegisterMobile'; export {default as RegisterVerify} from './RegisterVerify'; export {default as AssociateXpy} from './AssociateXpy'; export {default as GenderPicker} from './GenderPicker'; export {default as EditProfile} from './EditProfile'; export {default as EditProfileNickname} from './EditProfileNickname'; export {default as EditProfilePassword} from './EditProfilePassword'; export {default as SplashImage} from './SplashImage';
const controller = {}; controller.get = function(req,res){ res.render('../views/bios.ejs'); } module.exports = controller;
const express = require('express') const multer = require('multer') const upload = multer({ dest: '.uploads/' }) const router = new express.Router() // Routes handlers const books = require('./books.js') const authors = require('./authors.js') const collections = require('./collections.js') const illustrators = require('./illustrators.js') // // Routing // // Frist path handled router.get('/api.homecomix', (request, response, next) => { response.status(200).json({ status: 200, success: true, message: 'Welcome to the HomeComix-API' }) }) router.get('/api.homecomix/authors', authors.getAll) router.get('/api.homecomix/author/:id', authors.getOne) router.post('/api.homecomix/author', authors.create) router.put('/api.homecomix/author/:id', authors.update) router.delete('/api.homecomix/author/:id', authors.delete) router.get('/api.homecomix/books', books.getAll) router.get('/api.homecomix/book/:id', books.getOne) router.get('/api.homecomix/book/:id/page/:pid', books.getPage) router.get('/api.homecomix/book/:id/thumbnail', books.thumbnail) router.post('/api.homecomix/book', upload.single('file'), books.create) router.put('/api.homecomix/book/:id', books.update) router.delete('/api.homecomix/book/:id', books.delete) router.get('/api.homecomix/collections', collections.getAll) router.get('/api.homecomix/collection/:id', collections.getOne) router.post('/api.homecomix/collection', collections.create) router.put('/api.homecomix/collection/:id', collections.update) router.delete('/api.homecomix/collection/:id', collections.delete) router.get('/api.homecomix/illustrators', illustrators.getAll) router.get('/api.homecomix/illustrator/:id', illustrators.getOne) router.post('/api.homecomix/illustrator', illustrators.create) router.put('/api.homecomix/illustrator/:id', illustrators.update) router.delete('/api.homecomix/illustrator/:id', illustrators.delete) // If no route is matched a '404 Not Found' error is returned. router.use(require('../middleware/error.js').notFound) // Error middleware to catch unexpected errors router.use(require('../middleware/error.js').errorHandler) module.exports = router
/** * Venobo App * * @author Marcus S. Abildskov */ import mongoose from 'mongoose' import loadClass from 'mongoose-class-wrapper' import MovieSchema from './schemas/movies' class MovieModel { static getByTmdb(id: String, callback: Function) { this.findOne({tmdb: id}, callback) } static quickSearch(keyword: String, callback: Function) { this.find({$text: {$search: keyword}}, callback) } static search(data: Object, callback: Function) { var query = {} if (data.genres !== 'all') { query.genres = new RegExp(`^${data.genres}$`, 'i') } if (data.quality !== 'all') { query.torrents = {$exists: data.quality} } if (data.rating !== '0') { query.rating = {$gt: data.rating} } if (data.keyword !== '') { query.$text = {$search: data.keyword} } var orderBy = { year: {year: 1}, rating: {rating: 1}, views: {views: 1}, likes: {likes: 1}, asc: {added: -1}, desc: {added: 1} } this.find(query, callback).sort(orderBy[data.orderBy]) } static getAll(callback: Function) { this.find({}, callback) } static sortByLatest(limit: Number = 20, callback: Function) { this.find(callback).sort({added: -1}).limit(limit) } } MovieSchema.plugin(loadClass, MovieModel) export default mongoose.model('Movies', MovieSchema)
(function ($, window, document, undefined) { 'use strict'; var settings = { container: '.main', animationMethod: 'replace', duration: 1000, preload: false, anchors: 'a', blacklist: '.no-fancyclick', whitelist: '', onLoadStart: function () { //$('body').addClass('fancy-in-transition'); }, onLoadEnd: function () { //$('body').addClass('fancy-in-transition'); } }; /** * Initilize plugin with specified options * @param opts */ function init(opts) { // initialize config for (var key in opts) { if (settings.hasOwnProperty(key)) { settings[key] = opts[key]; } } attachLoader(); history.pushState({}, '', window.location.href); $(window).on('popstate', stateChange); } /** * Manage state changes, if a user navigates back or forward * load the page from history * @param e */ function stateChange(e) { if (e.originalEvent.state !== null) { loadPage(e, true); } else { loadPage(e); } } /** * Determine if the url is local or external * As seen in Fastest way to detect external URLs * (http://stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls) * @param url * @returns {boolean} */ function isExternal(url) { var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/); if (typeof match[1] === 'string' && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) { return true; } if (typeof match[2] === 'string' && match[2].length > 0 && match[2].replace(new RegExp(':(' + {'http:': 80, 'https:': 443}[location.protocol] + ')?$'), '') !== location.host) { return true; } return false; } function attachLoader() { var links = $('a'); $.each(links, function (key, element) { var $element = $(element); if (!isExternal($element.attr('href'))) { $element.click(loadPage); } }); } function loadPage(e, changeBack) { e.preventDefault(); var durationFn = getComputedAnimationDuration(); var duration = durationFn() || settings.duration; var href = e.currentTarget.href || window.location.href; var element = $(settings.container); // fire loading start callback settings.onLoadStart(); $.ajax({ url: href, dataType: 'html' }).then(function (responseText) { if (responseText) { var dom = $('<div>').append($.parseHTML(responseText)); updateTitle(dom.find('title').text()); if (settings.animationMethod === 'replace') { var html = dom.find(settings.container).html(); element.html(html); setTimeout(function () { settings.onLoadEnd(); }, duration); } else { element.addClass('fancy-leave'); var afterElement = dom.find(settings.container).addClass('fancy-enter'); element.after(afterElement); setTimeout(function () { element.remove(); afterElement.removeClass('fancy-enter'); settings.onLoadEnd(); }, duration); } // if this is the initial page loaded add it to the history if (!changeBack) { history.pushState({}, '', href); } } }, function (error) { // fire the load end callback settings.onLoadEnd(); // log the error console.error(error); }); } /** * Update the title of the page * @param title */ function updateTitle(title) { $('title').text(title); } /** * Get the computed animation duration for an element */ function getComputedAnimationDuration() { var element = $('<div>') .css('visibility', 'hidden') .addClass('fancy-enter') .appendTo('body'); var time = 0; setTimeout(function() { time += (parseFloat(getComputedStyle(element[0]).animationDuration)); time += (parseFloat(getComputedStyle(element[0], ':after')));//.animationDuration)); time += (parseFloat(getComputedStyle(element[0], ':before').animationDuration)); element.remove(); },0); return function() { return time; }; } window.fancyClick = { init: init }; }(jQuery, window, document, undefined));
function ping(jq){ var img = new Image(); var ip = jq.text(); img.src = "http://"+ip+"/textinputassistant/tia.png"; img.onload = function(){ jq.addClass('green'); } } $(function(){ $('#ping_btn').click(function(){ $('#ping_btn').attr('value','Processing'); $('td > a').each(function(i){ var $this = $(this); var text = $this.text(); var array = text.split("."); if(array && array.length==4){ ping($this); } }); }); });
import React,{ Component } from 'react' import { View, TouchableOpacity, Modal, Text, DatePickerIOS, StyleSheet, Image, ActivityIndicator, }from 'react-native' import { Actions } from 'react-native-router-flux'; import GlobalSize from '../common/GlobalSize' export default class ModalLoading extends Component{ constructor(props){ super(props); // this.state={ // visible:false, // } } render(){ console.log('ๅŠ ่ฝฝmodalๆ˜ฏๅฆๆ˜พ็คบ'+this.props.visible); return( <Modal animationType='fade' transparent={true} visible={this.props.visible} onRequestClose={() => {}} > <View style={styles.container}> <View style={styles.contentContainer}> <ActivityIndicator animation={true} size='large' /> <Text style={{textAlign:'center'}}> {this.props.loadingText?this.props.loadingText :"ๆญฃๅœจๅŠ ่ฝฝ..."} </Text> </View> </View> </Modal> ); } } var styles=StyleSheet.create({ container:{ flex:1, justifyContent:'center', alignItems:'center', backgroundColor:'rgba(0,1,0,0.2)', }, contentContainer:{ height:60, }, })
import {inject} from 'aurelia-framework'; import {appData} from './appdata'; @inject(appData) export class meetinglist { constructor(appData) { this.appData = appData; } insert() { this.appData.insertMotion(); } }
module.exports = { namespace: 'todoDemo', state: { todos: [{ id: 1, text: 'Learn Choo', done: false }], visibility: 'SHOW_ALL' }, subscriptions: [], reducers: { add: (action, state) => ({ todos: state.todos.concat({ id: state.todos.length + 1, text: action.text, done: false }) }), toggle: (action, state) => ({ todos: state.todos.map(todo => todo.id === action.id ? Object.assign({}, todo, { done: !todo.done }) : todo ) }), visibilityFilter: ({visibility}) => ({ visibility }) } }
import Terminal from "./src/terminal.jsx"; export default Terminal; export { Terminal };
const Rivescript = require('rivescript') const AsyncMessenger = function(messenger, macros, onReady) { const self = this self.messenger = messenger self.rs = new Rivescript({ utf8: true, caseSensitive: true }) self.rs.unicodePunctuation = new RegExp(/[~]/) self.sendMessage = (message, messageText) => { const reply = self.rs.reply(message.user, messageText) if(reply.then){ /* eslint-disable no-console */ reply.then(replyStr => { self.messenger.sendMessage(replyStr, message.channel) }).catch(err => console.log(err)) }else{ self.messenger.sendMessage(reply, message.channel) } } self.rs.loadDirectory('./brain', () => { self.rs.sortReplies() onReady() }) Object.keys(macros).forEach(macro => { self.rs._objlangs[macro] = 'javascript' self.rs._handlers.javascript._objects[macro] = (rs, args) => { /* eslint-disable no-console */ console.log('args', args.join(' ')) const response = macros[macro](args.join(' ')) return response } }) } module.exports = AsyncMessenger
/** * Contact Form */ jQuery(document).ready(function ($) { var showErrors = true; //show text errors? var sendingMessage = 'Sending...'; var debug = false; //show system errors var $f = $('.contactForm'); var $submit = $f.find('input[type="submit"]'); $f.submit(function () { //prevent double click if ($submit.hasClass('disabled')) { return false; } $submit.attr('data-value', $submit.val()).val(sendingMessage).addClass('disabled'); $.ajax({ url: $f.attr('action'), method: 'post', data: $f.serialize(), dataType: 'json', success: function (data) { $('input.error', $f).removeClass('error'); $('div.error', $f).remove(); if (data.errors) { $.each(data.errors, function (i, k) { var input = $('input[name=' + i + ']', $f).addClass('error'); if (showErrors) { input.after('<div class="error">' + k + '</div>'); } }); } else { $f.slideUp(function () { if (data.msg) { $f.before(data.msg); } }); } $submit.val($submit.attr('data-value')).removeClass('disabled'); }, error: function (data) { if (debug) { alert(data.responseText); } $submit.val($submit.attr('data-value')).removeClass('disabled'); } }); return false; }); });
import { h, Component } from 'preact/preact'; import SVGIcon from 'com/svg-icon/icon'; import NavLink from 'com/nav-link/link'; export default class SidebarCountdown extends Component { constructor( props ) { super(props); this.countdown_interval = null; this.total_seconds = 0; this.$ = {}; this.values = {}; this.class = this.props.nc; this.setState({loaded: false}); //this.init(this.props.date); } init( countdownTo ) { let that = this; //document.addEventListener("DOMContentLoaded", function(event) { let n = new Date(); let diff = countdownTo.getTime() - n.getTime(); let ts = Math.abs(diff/1000); let s = ts % 60; let m = Math.floor(ts / 60) % 60; let h = Math.floor(ts / 60 / 60) % 24; let d = Math.floor(ts / 60 / 60 / 24); //let d = Math.floor(countdownTo / (1000 * 60 * 60 * 24)); that.values = { days: d, hours: h, minutes: m, seconds: s }; if(d > 0) { that.setState({"ShowDays": true}); } //that.total_seconds = (((that.values.days * 24) * 60) * 60) + that.values.hours * 60 * 60 + (that.values.minutes * 60) + that.values.seconds; that.total_seconds = ts; that.setState({'values': {'days': d, 'hours': h, 'minutes': m, 'seconds': s}, 'fvalues': {'d1': 0, 'd2': 0, 'h1': 0, 'h2': 0, 'm1': 0, 'm2': 0, 's1': 0, 's2': 0}, 'animate': false}); that.count(); //}); } componentDidMount() { this.init(this.props.date); } animateFigure($el, value) { let $top = $el.children[0]; let $bottom = $el.children[2]; let $back_top = $el.children[1]; let $back_bottom = $el.children[3]; $back_top.children[0].innerHTML = value; $back_bottom.children[0].innerHTML = value; $top.setAttribute('style', 'transition: 0.8s all ease-out; transform: rotateX(-180deg) perspective(300px)'); setTimeout(function() { $top.setAttribute('style', 'transition: 0.0s all ease-out; transform: rotateX(0deg) perspective(0px)'); $top.innerHTML = value; $bottom.innerHTML = value; }, 800); $back_top.setAttribute('style', 'transition: 0.8s all ease-out; transform: rotateX(0deg) perspective(300px)'); setTimeout(function() { $back_top.setAttribute('style', 'transition: 0.0s all ease-out; transform: rotateX(180deg) perspective(0px)'); }, 800); } checkHour(value, e1, elc) { let val_1 = value.toString().charAt(0); let val_2 = value.toString().charAt(1); let fig_1_value = arguments[1].children[0].innerHTML; let fig_2_value = arguments[2].children[0].innerHTML; if(value >= 10) { //Animate only if the figure has changed // Something weird is happening here, that's why I'm using arguments[1] rather than el... if(fig_1_value !== val_1) this.animateFigure( arguments[1], val_1 ); if(fig_2_value !== val_2) this.animateFigure( arguments[2], val_2 ); } else { // If we are under 10, replace first figure with 0 if(fig_1_value !== '0') this.animateFigure(arguments[1], 0); if(fig_2_value !== val_1) this.animateFigure(arguments[2], val_1); } } count() { let that = this; let d = that.daysblock.children[1]; let h = that.hoursblock.children[1]; let m = that.minutesblock.children[1]; let s = that.secondsblock.children[1]; this.countdown_interval = setInterval(function() { if(that.total_seconds > 0) { --that.values.seconds; if(that.values.minutes >= 0 && that.values.seconds < 0) { that.values.seconds = 59; --that.values.minutes; } if(that.values.hours >= 0 && that.values.minutes < 0) { that.values.minutes = 59; --that.values.hours; } if(that.values.days >= 0 && that.values.hours < 0) { that.values.hours = 23; --that.values.days; } if(that.values.days < 1 && that.state.ShowDays === true) { that.setState({"ShowDays": false}); } if(that.values.days < 1 && that.values.hours <= 6) { if(!that.state.Urgent) { that.setState({'Urgent': true}); } } // Update DOM values // Days if(!that.state.loaded) that.setState({loaded: true}); that.checkHour(that.values.days, d.children[0], d.children[1]); // Hours that.checkHour(that.values.hours, h.children[0], h.children[1]); // Minutes that.checkHour(that.values.minutes, m.children[0], m.children[1]); // Seconds that.checkHour(that.values.seconds, s.children[0], s.children[1]); --that.total_seconds; } else { clearInterval(that.countdown_interval); } }, 1000); } renderDigit( value, classname ) { let Digit1 = Math.floor(value / 10); let Digit2 = value % 10; return ( <div> <div class={ "figure " + classname + " " + classname + "-1" }> <span class="top">{ Digit1 }</span> <span class="top-back"> <span>{ Digit1 }</span> </span> <span class="bottom">{ Digit1 }</span> <span class="bottom-back"> <span >{ Digit1 }</span> </span> </div> <div class={ "figure " + classname + " " + classname + "-2" }> <span class="top">{ Digit2 }</span> <span class="top-back"> <span>{ Digit2 }</span> </span> <span class="bottom">{ Digit2 }</span> <span class="bottom-back"> <span >{ Digit2 }</span> </span> </div> </div> ); } render( props ) { let days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; let utcCode = (props.date.getTimezoneOffset()/60)*-1; let utcCodep = ""; if(utcCode > 0) utcCodep = "+"; if(utcCode % 1 !== 0) { utcCode = parseInt(utcCode)+":30"; } else { utcCode = parseInt(utcCode)+":00"; } let daysblock = "display: none"; let secondsblock = "display: inline-block"; if(this.state.ShowDays){ daysblock = "display: inline-block"; secondsblock = "display: none"; } utcCode = utcCodep+utcCode; let urgentclass = "-countdown"; if(this.state.Urgent && this.state.Urgent === true) urgentclass = "-countdown urgent"; if(!this.state.loaded) { let n = new Date(); let diff = props.date.getTime() - n.getTime(); let ts = Math.abs(diff/1000); let ss = String(parseInt(ts % 60)); let mm = String(Math.floor(ts / 60) % 60); let hh = String(Math.floor(ts / 60 / 60) % 24); let dd = String(Math.floor(ts / 60 / 60 / 24)); this.values = { days: dd, hours: hh, minutes: mm, seconds: ss }; } var LanguagePrefix = "["+navigator.language+"] "; if ( navigator.languages ) { LanguagePrefix += "["+navigator.languages.join(',')+"] "; } var Title = null; if ( props.to ) { Title = <h1 class="_font2">{ props.to } <strong>{ props.tt }</strong></h1>; } return ( <div class="sidebar-base sidebar-countdown"> <div class="-clock" id={ this.class }> {Title} <div class={ urgentclass }> <div class="bloc-time days" data-init-value="00" ref={c => this.daysblock=c} style={ daysblock }> <span class="count-title _font2">Days</span> { this.renderDigit(this.values.days, "days") } </div> <div class="bloc-time hours" data-init-value="00" ref={c => this.hoursblock=c}> <span class="count-title _font2">Hours</span> { this.renderDigit(this.values.hours, "hours") } </div> <div class="bloc-time min" data-init-value="0" ref={c => this.minutesblock=c} style={this.state.ShowDays ? "margin-right: 0px;" : ""}> <span class="count-title _font2">Minutes</span> { this.renderDigit(this.values.minutes, "minutes") } </div> <div class="bloc-time sec" data-init-value="0" style={ secondsblock } ref={c => this.secondsblock=c}> <span class="count-title _font2">Seconds</span> { this.renderDigit(this.values.seconds, "seconds") } </div> </div> </div> <div id={this.class} class="-info" title={LanguagePrefix+props.date.toString()}>{props.tt} {getLocaleDay(props.date)} at <strong>{getLocaleTime(props.date)} {getLocaleTimeZone(props.date)}</strong> <NavLink href="https://github.com/ludumdare/ludumdare/issues/589"><strong title="Adjusted for your local timezone. If this is not your timezone, click here and let us know!">*</strong></NavLink></div> </div> ); } // <div id={this.class} class="-info">{props.tt} {days[props.date.getDay()]} at <strong>{props.date.getHours()}:{(props.date.getMinutes()<10?'0':'') + props.date.getMinutes()} UTC{utcCode}</strong></div> }
import { createStore, applyMiddleware, compose } from 'redux' import rootReducer from '../reducers' import thunk from 'redux-thunk' import { syncHistory } from 'react-router-redux' export default function configureStore (initialState, history) { const reduxRouterMiddleware = syncHistory(history) const createStoreWithMiddleware = compose( applyMiddleware(thunk, reduxRouterMiddleware), typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f )(createStore) const store = createStoreWithMiddleware(rootReducer, initialState) if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers') store.replaceReducer(nextRootReducer) }) } return store }
/** * Created by yuxuan on 9/12/16. */ import React from 'react' import Paper from 'material-ui/Paper' import style from './chat.less' import {grey200, blue200} from 'material-ui/styles/colors' import Avatar from 'material-ui/Avatar' import FontIcon from 'material-ui/FontIcon' import UserList from '../../components/UserList' import ChatContent from '../../components/ChatContent' import InputBox from '../../components/InputBox' import pureRender from 'pure-render-decorator' @pureRender export default class Chat extends React.Component { render () { return ( <div style={{backgroundColor: grey200}} className={style.container}> <div className={style.left}> <Paper zDepth={1} style={{ flex: 'auto', margin: '5px' }}> <UserList /> </Paper> </div> <div className={style.middle}> <Paper zDepth={1} style={{ display: 'flex', flex: 'auto', margin: '5px', marginTop: '15px', flexDirection: 'column' }}> <ChatContent /> <InputBox /> </Paper> </div> <div className={style.right}> <Paper zDepth={2} circle={true} style={{ width: '50px', height: '50px', margin: '35px 15px 0 0', alignSelf: 'center' }}> <Avatar backgroundColor={blue200} size={50} icon={<FontIcon className="material-icons">border_color</FontIcon>}/> </Paper> </div> </div> ) } }
/** * @license Highstock JS v9.2.1 (2021-08-19) * * Indicator series type for Highcharts Stock * * (c) 2010-2021 Rafal Sebestjanski * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/indicators/trix', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'Mixins/IndicatorRequired.js', [_modules['Core/Utilities.js']], function (U) { /** * * (c) 2010-2021 Daniel Studencki * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var error = U.error; /* eslint-disable no-invalid-this, valid-jsdoc */ var requiredIndicatorMixin = { /** * Check whether given indicator is loaded, else throw error. * @private * @param {Highcharts.Indicator} indicator * Indicator constructor function. * @param {string} requiredIndicator * Required indicator type. * @param {string} type * Type of indicator where function was called (parent). * @param {Highcharts.IndicatorCallbackFunction} callback * Callback which is triggered if the given indicator is loaded. * Takes indicator as an argument. * @param {string} errMessage * Error message that will be logged in console. * @return {boolean} * Returns false when there is no required indicator loaded. */ isParentLoaded: function (indicator, requiredIndicator, type, callback, errMessage) { if (indicator) { return callback ? callback(indicator) : true; } error(errMessage || this.generateMessage(type, requiredIndicator)); return false; }, /** * @private * @param {string} indicatorType * Indicator type * @param {string} required * Required indicator * @return {string} * Error message */ generateMessage: function (indicatorType, required) { return 'Error: "' + indicatorType + '" indicator type requires "' + required + '" indicator loaded before. Please read docs: ' + 'https://api.highcharts.com/highstock/plotOptions.' + indicatorType; } }; return requiredIndicatorMixin; }); _registerModule(_modules, 'Stock/Indicators/TRIX/TRIXIndicator.js', [_modules['Mixins/IndicatorRequired.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (RequiredIndicatorMixin, SeriesRegistry, U) { /* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TEMAIndicator = SeriesRegistry.seriesTypes.tema; var correctFloat = U.correctFloat, merge = U.merge; /** * The TRIX series type. * * @private * @class * @name Highcharts.seriesTypes.trix * * @augments Highcharts.Series */ var TRIXIndicator = /** @class */ (function (_super) { __extends(TRIXIndicator, _super); function TRIXIndicator() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.data = void 0; _this.options = void 0; _this.points = void 0; return _this; } TRIXIndicator.prototype.init = function () { var args = arguments, ctx = this; RequiredIndicatorMixin.isParentLoaded(SeriesRegistry.seriesTypes.tema, 'tema', ctx.type, function (indicator) { indicator.prototype.init.apply(ctx, args); return; }); }; // TRIX is calculated using TEMA so we just extend getTemaPoint method. TRIXIndicator.prototype.getTemaPoint = function (xVal, tripledPeriod, EMAlevels, i) { if (i > tripledPeriod) { return [ xVal[i - 3], EMAlevels.prevLevel3 !== 0 ? correctFloat(EMAlevels.level3 - EMAlevels.prevLevel3) / EMAlevels.prevLevel3 * 100 : null ]; } }; /** * Triple exponential average (TRIX) oscillator. This series requires * `linkedTo` option to be set. * * Requires https://code.highcharts.com/stock/indicators/ema.js * and https://code.highcharts.com/stock/indicators/tema.js. * * @sample {highstock} stock/indicators/trix * TRIX indicator * * @extends plotOptions.tema * @since 7.0.0 * @product highstock * @excluding allAreas, colorAxis, compare, compareBase, joinBy, keys, * navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, * stacking * @optionparent plotOptions.trix */ TRIXIndicator.defaultOptions = merge(TEMAIndicator.defaultOptions); return TRIXIndicator; }(TEMAIndicator)); SeriesRegistry.registerSeriesType('trix', TRIXIndicator); /* * * * Default Export * * */ /** * A `TRIX` series. If the [type](#series.trix.type) option is not specified, it * is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.trix * @since 7.0.0 * @product highstock * @excluding allAreas, colorAxis, compare, compareBase, dataParser, dataURL, * joinBy, keys, navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, stacking * @apioption series.trix */ ''; // to include the above in the js output return TRIXIndicator; }); _registerModule(_modules, 'masters/indicators/trix.src.js', [], function () { }); }));
version https://git-lfs.github.com/spec/v1 oid sha256:de76871467d44f5276ea30a928632941637e184c23506ceb754a282a5d123ba2 size 6383
/** * Created by Gabriele on 23/08/2016. */ angular.module('gms') .config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/index'); $stateProvider .state('index',{ url: '/index', templateUrl: 'views/welcome.html' }) .state('login',{ url: '/login', templateUrl: 'views/login.html', controller: 'loginController' }) .state('welcome',{ url: '/welcome', templateUrl: 'views/welcome.html' }) .state('new-bank',{ url: '/new-bank', templateUrl: 'views/banks/new_bank.html', controller: 'banksController' }) })
import Provider from './models/provider'; import _ from 'lodash'; export default function () { Provider.find({}, {name: 1}).exec((err, exists) => { if (exists && exists.length === 5) { return; } let providers = []; _.forEach(['openweathermap', 'apixu', 'darksky', 'weatherunlocked', 'wunderground'], function (providerName) { let provider = _.find(exists, function (item) { return item.name === providerName; }); if (!provider) { if (providerName === 'openweathermap') { providers.push(new Provider({ name: 'openweathermap', displayName: 'OpenWeatherMap', link: 'https://openweathermap.org/' })); } else if (providerName === 'apixu') { providers.push(new Provider({name: 'apixu', displayName: 'APIXU', link: 'https://www.apixu.com/'})); } else if (providerName === 'darksky') { providers.push(new Provider({name: 'darksky', displayName: 'Dark Sky', link: 'https://darksky.net/'})); } else if (providerName === 'weatherunlocked') { providers.push(new Provider({ name: 'weatherunlocked', displayName: 'Weather Unlocked', link: 'https://weatherunlocked.com/' })); } else if (providerName === 'wunderground') { providers.push(new Provider({ name: 'wunderground', displayName: 'WUnderground', link: 'https://www.wunderground.com/' })); } } }); Provider.create(providers, (error) => { if (!error) { console.log('init data...'); } }); }); }
define(['jquery'], function($){ function Window(){} Window.prototype = { alert: function(content, handler){ var boundingBox = $( '<div class="window_boundingBox"></div>'); boundingBox.appendTo('body'); boundingBox.html(content); //ๅฐ†โ€œๅผน็ช—ๅ…ณ้—ญๆŒ‰้’ฎโ€้™„ๅŠ ๅˆฐboundingBoxๅผน็ช—ไธญ๏ผŒ่€Œไธๆ˜ฏ็›ดๆŽฅๅœจๅˆ›ๅปบboundingBox jQueryๅฏน่ฑกๆ—ถ็”จๅญ—็ฌฆไธฒ var alertBtn = $('<input type="button" value="็กฎๅฎš" >'); alertBtn.appendTo(boundingBox); alertBtn.click(function(){ handler && handler(); boundingBox.remove(); }); }, confirm: function(){ }, prompt: function(){ } }; return { Window: Window } });
/*! Waypoints Infinite Scroll Shortcut - 3.1.1 Copyright ยฉ 2011-2015 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/waypoints/blog/master/licenses.txt */ !function () { "use strict"; function t(n) { this.options = i.extend({}, t.defaults, n), this.container = this.options.element, "auto" !== this.options.container && (this.container = this.options.container), this.$container = i(this.container), this.$more = i(this.options.more), this.$more.length && (this.setupHandler(), this.waypoint = new o(this.options)) } var i = window.jQuery, o = window.Waypoint; t.prototype.setupHandler = function () { this.options.handler = i.proxy(function () { this.options.onBeforePageLoad(), this.destroy(), this.$container.addClass(this.options.loadingClass), i.get(i(this.options.more).attr("href"), i.proxy(function (t) { var n = i(i.parseHTML(t)), e = n.find(this.options.more), s = n.find(this.options.items); s.length || (s = n.filter(this.options.items)), this.$container.append(s), this.$container.removeClass(this.options.loadingClass), e.length || (e = n.filter(this.options.more)), e.length ? (this.$more.replaceWith(e), this.$more = e, this.waypoint = new o(this.options)) : this.$more.remove(), this.options.onAfterPageLoad() }, this)) }, this) }, t.prototype.destroy = function () { this.waypoint && this.waypoint.destroy() }, t.defaults = { container: "auto", items: ".infinite-item", more: ".infinite-more-link", offset: "bottom-in-view", loadingClass: "infinite-loading", onBeforePageLoad: i.noop, onAfterPageLoad: i.noop }, o.Infinite = t }();
/* PicturePolyfill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Andrea Verlicchi | License: MIT/GPLv2 */ var picturePolyfill = (function(w) { "use strict"; var _cacheArray, _cacheIndex, _resizeTimer, _timeAfterResize = 100, _areListenersActive = false; /** * Detects old browser checking if browser can append images to pictures * @returns {boolean} */ function _detectAppendImageSupport() { var newImg = document.createElement('img'), pictures, firstPicture; pictures = document.getElementsByTagName('picture'); firstPicture = pictures[0]; if (!pictures.length) { // Can't determine support if no pictures are in the page. Worst case will do. return false; } try { firstPicture.appendChild(newImg); firstPicture.removeChild(newImg); return true; } catch(e) { return false; } } return { /** * Appends an image element to a picture element * @param element * @param attributes * @private */ _appendImg: function(element, attributes) { var newImg = document.createElement('img'); this._setAttrs(newImg, attributes); element.appendChild(newImg); }, /** * Set all the "attributes" to an "element" * @param element * @param attributes * @private */ _setAttrs: function(element, attributes) { for (var attributeName in attributes) { element.setAttribute(attributeName, attributes[attributeName]); } }, /** * Get all the "attributes" from an "element" and returns them as a hash * @param element * @param attributes * @returns {{}} * @private */ _getAttrs: function(element, attributes) { var ret = {}, attributeName, attributeValue; for (var i=0, len=attributes.length; i<len; i+=1) { attributeName = attributes[i]; attributeValue = element.getAttribute(attributeName); if (attributeValue) { ret[attributeName] = attributeValue; } } return ret; }, /** * Gets the attributes list from an "element" * @param element * @returns {Array} * @private */ _getAttrsList: function(element) { var arr = []; for (var i=0, attributes=element.attributes, l=attributes.length; i<l; i++){ arr.push(attributes.item(i).nodeName); } return arr; }, /** * Replaces the existing picture element with another picture element containing an image with the imgSrc source * @param picture * @param attributes * @private */ _replacePicture: function(picture, attributes) { var newPicture = document.createElement("picture"), pictureAttributes = this._getAttrs(picture, this._getAttrsList(picture)); this._appendImg(newPicture, attributes); this._setAttrs(newPicture, pictureAttributes); picture.parentNode.replaceChild(newPicture, picture); }, /** * Returns a sorted array of object representing the elements of a srcset attribute, * where pxr is the pixel ratio and src is the source for that ratio * @param srcset * @returns {Array} * @private */ _getSrcsetArray: function(srcset) { var srcSetElement, source, density, ret = [], srcSetElements = srcset.split(','); for (var i=0, len=srcSetElements.length; i<len; i+=1) { srcSetElement = srcSetElements[i].trim().split(' '); if (srcSetElement.length === 1) { density = 1; } else { density = parseFloat(srcSetElement[srcSetElement.length-1], 10); } source = srcSetElement[0]; ret.push({pxr: density, src: source}); } return ret.sort(function(hash1, hash2) { var pxr1 = hash1.pxr, pxr2 = hash2.pxr; if (pxr1 < pxr2) { return -1; } if (pxr1 > pxr2) { return 1; } return 0; }); }, /** * Returns the proper src from the srcset array obtained by _getSrcsetArray * Get the first valid element from passed position to the left * @param array * @param pixelRatio * @returns string || null * @private */ _getSrcFromArray: function(array, pixelRatio) { var i=0, len = array.length, breakPoint=-1; if (!len) { return null; } do { if (array[i].pxr >= pixelRatio || i === len-1) { breakPoint = i; } i+=1; } while (!(breakPoint > -1 || i >= len)); return array[breakPoint].src; }, /** * Loop through every element of the sourcesData array, check if the media query applies and, * if so, get the src element from the srcSet property based depending on pixel ratio * @param sourcesData * @returns {string||undefined} * @private */ _getSrcFromData: function(sourcesData) { var matchedSrc, sourceData, media, srcset; for (var i=0, len=sourcesData.length; i<len; i+=1) { sourceData = sourcesData[i]; media = sourceData.media; srcset = sourceData.srcset; if (!media || w.matchMedia(media).matches) { matchedSrc = srcset ? this._getSrcFromArray(srcset, this._pxRatio) : sourceData.src; } } return matchedSrc; }, /** * Removes the image from the picture, when it doesn't have to be shown * @param pictureElement * @private */ _resetImg: function(pictureElement) { var imageElements = pictureElement.getElementsByTagName('img'); if (imageElements.length) { pictureElement.removeChild(imageElements[0]); } }, /** * Set the src attribute of the first image element inside passed pictureElement * if the image doesn't exist, creates it, sets its alt attribute, and appends it to pictureElement * @param pictureElement {Node} * @param attributes */ _setImg: function(pictureElement, attributes) { var pictureAttributesToCopy, attributeName, attributeValue, imgEl, imgSrc, imageElements = pictureElement.getElementsByTagName('img'); // If image already exists, use it if (imageElements.length) { imgSrc = attributes.src; imgEl = imageElements[0]; if (imgEl.getAttribute('src') !== imgSrc) { imgEl.setAttribute('src', imgSrc); } } // Else create the image else { // Adding picture's attributes to the image (e.g. width, height) pictureAttributesToCopy = ['width', 'height']; for (var i = 0, len = pictureAttributesToCopy.length; i<len; i+=1) { attributeName = pictureAttributesToCopy[i]; attributeValue = pictureElement.getAttribute(attributeName); if (attributeValue) { attributes[attributeName] = attributeValue; } } if (this._appendSupport) { this._appendImg(pictureElement, attributes); } else { this._replacePicture(pictureElement, attributes); } } }, /** * Parses the picture element looking for sources elements, then * generate the array or string for the SrcSetArray * @param {Array} pictureElement the starting element to parse DOM into. If not passed, it parses the whole document. */ _getSourcesData: function(pictureElement) { var sourcesData = [], sourceElement, sourceData, foundSources = pictureElement.getElementsByTagName('source'); for (var i=0, len = foundSources.length; i<len; i+=1) { sourceElement = foundSources[i]; sourceData = this._getAttrs(sourceElement, this._getAttrsList(sourceElement)); if (sourceData.srcset) { sourceData.srcset = this._getSrcsetArray(sourceData.srcset); } sourcesData.push(sourceData); } return sourcesData; }, /** * Adds listeners to load and resize event * @private */ _addListeners: function() { if (!this.isUseful || _areListenersActive) { return false; } function parseDocument() { picturePolyfill.parse(document); } // Manage resize event only if they've passed 100 milliseconds between a resize event and another // to avoid the script to slow down browsers that animate resize or when browser edge is being manually dragged function parseDocumentAfterTimeout() { clearTimeout(_resizeTimer); _resizeTimer = setTimeout(parseDocument, _timeAfterResize); } if (w.addEventListener) { w.addEventListener('resize', parseDocumentAfterTimeout); w.addEventListener('DOMContentLoaded', function(){ parseDocument(); w.removeEventListener('load', parseDocument); }); w.addEventListener('load', parseDocument); } else if (w.attachEvent) { w.attachEvent('onload', parseDocument); w.attachEvent('onresize', parseDocumentAfterTimeout); } _areListenersActive = true; }, /** * Initialize and resize event handlers */ initialize: function() { /** * The device pixel ratio. 1 for standard displays, 2+ for HD displays * @type {number} * @private */ this._pxRatio = w.devicePixelRatio || 1; /** * Detect if browser has media queries support * @type {boolean} * @private */ this._mqSupport = !!w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches; /** * Detect if append image to picture is possible * @type {boolean} * @private */ this._appendSupport = _detectAppendImageSupport(); /** * Detect if polyfill is necessary * @type {boolean} */ this.isUseful = !w.HTMLPictureElement; /** * Cache array, where all sources data is stored * @type {Array} * @private */ _cacheArray = []; /** * Cache index, incremental * @type {number} * @private */ _cacheIndex = 0; // Add listeners (listeners are added once) this._addListeners(); }, /** * Parses the DOM looking for elements containing the "data-picture" attribute, then * generate the images or updates their src attribute. * @param {Node} element (the starting element to parse DOM into. REQUIRED) */ parse: function(element) { var sourcesData, pictureElement, pictureElements, srcAttribute, mqSupport; if (!this.isUseful) { return 0; } pictureElements = (element || document).getElementsByTagName('picture'); mqSupport = this._mqSupport; for (var i=0, len=pictureElements.length; i<len; i+=1) { pictureElement = pictureElements[i]; // Try to read sources data from cache sourcesData = _cacheArray[pictureElement.getAttribute('data-cache-index')]; // If empty, try to read sources data from the picture element, then cache them if (!sourcesData) { sourcesData = this._getSourcesData(pictureElement); _cacheArray[_cacheIndex] = sourcesData; pictureElement.setAttribute('data-cache-index', _cacheIndex); _cacheIndex+=1; } // If no sourcesData retrieved or media queries are not supported, read from the default src srcAttribute = (sourcesData.length === 0 || !mqSupport) ? pictureElement.getAttribute('data-default-src') : this._getSrcFromData(sourcesData); // If there mustn't be any image, remove it, else set it (create/ update) if (!srcAttribute) { this._resetImg(pictureElement); } else { this._setImg(pictureElement, { src: srcAttribute, alt: pictureElement.getAttribute('data-alt') }); } } return i; } }; }(window)); picturePolyfill.initialize(); picturePolyfill.parse();
define([ 'app', 'backbone', 'modules/diary/router' ], function (App, Backbone, DiaryRouter) { var DiaryModule = App.module.extend({ initialize: function() { this.Router = new DiaryRouter('diary', {createTrailingSlashRoutes: true}); } }); // return the module return DiaryModule; });
/** * * Usage: * * var completeList = * [ * { * name: "Hillary Clinton", * bakingSkills: 5, * likesPets: true * }, * { * name: "Donald Trump", * bakingSkills: 0, * likesPets: false, * } * ]; * * var selectedOption = "bakingSkills"; * * filterAndSortList(completeList, selectedOption); * */ /** * @param {Array} - required * @param {String} - required * @return {Array} */ function filterAndSortList(completeList, selectedOption) { // using Array.filter function to filter the array and store the result into the filteredList // if the function inside returns true, it will store into filteredList // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter var filteredList = completeList.filter(function(person) { // get the value of the selectedOption. // eg. person['bakingSkills'] // see: http://www.w3schools.com/js/js_objects.asp var value = person[selectedOption]; // typeof will check the type of element // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof // it checks if the value is either a number or a boolean (ie true or false) if (typeof value == 'number') { // if the value is a number, it will check if the number is in between 4 and 5 var min = 4; var max = 5; return value >= min && value <= max; } if (typeof value == 'boolean') { return value; } }); // using the Array.sort function to sort the array and store the result in sortedList // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort var sortedList = filteredList.sort(function(personA, personB) { var valueA = personA[selectedOption]; var valueB = personB[selectedOption]; if (typeof valueA == 'number' && typeof valueB == 'number') { // this will sort results in descending order if the valueB - valueA is more than 0 // or it will sort results in ascending order if the valueB - valueA is less than 0 return valueB - valueA; } }); return sortedList; }
/* * Facebox (for jQuery) * version: 1.2 (05/05/2008) * @requires jQuery v1.2 or later * * Examples at http://famspam.com/facebox/ * * Licensed under the MIT: * http://www.opensource.org/licenses/mit-license.php * * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ] * * Usage: * * jQuery(document).ready(function() { * jQuery('a[rel*=facebox]').facebox() * }) * * <a href="#terms" rel="facebox">Terms</a> * Loads the #terms div in the box * * <a href="terms.html" rel="facebox">Terms</a> * Loads the terms.html page in the box * * <a href="terms.png" rel="facebox">Terms</a> * Loads the terms.png image in the box * * * You can also use it programmatically: * * jQuery.facebox('some html') * jQuery.facebox('some html', 'my-groovy-style') * * The above will open a facebox with "some html" as the content. * * jQuery.facebox(function($) { * $.get('blah.html', function(data) { $.facebox(data) }) * }) * * The above will show a loading screen before the passed function is called, * allowing for a better ajaxy experience. * * The facebox function can also display an ajax page, an image, or the contents of a div: * * jQuery.facebox({ ajax: 'remote.html' }) * jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style') * jQuery.facebox({ image: 'stairs.jpg' }) * jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style') * jQuery.facebox({ div: '#box' }) * jQuery.facebox({ div: '#box' }, 'my-groovy-style') * * Want to close the facebox? Trigger the 'close.facebox' document event: * * jQuery(document).trigger('close.facebox') * * Facebox also has a bunch of other hooks: * * loading.facebox * beforeReveal.facebox * reveal.facebox (aliased as 'afterReveal.facebox') * init.facebox * afterClose.facebox * * Simply bind a function to any of these hooks: * * $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... }) * */ (function($) { $.facebox = function(data, klass) { $.facebox.loading() if (data.ajax) fillFaceboxFromAjax(data.ajax, klass) else if (data.image) fillFaceboxFromImage(data.image, klass) else if (data.div) fillFaceboxFromHref(data.div, klass) else if ($.isFunction(data)) data.call($) else $.facebox.reveal(data, klass) } /* * Public, $.facebox methods */ $.extend($.facebox, { settings: { opacity : 0.2, overlay : true, loadingImage : '/assets/facebox/loading.gif', closeImage : '/assets/facebox/closelabel.png', imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ], faceboxHtml : '\ <div id="facebox" style="display:none;"> \ <div class="popup"> \ <div class="content"> \ </div> \ <a href="#" class="close"><img src="/assets/facebox/closelabel.png" title="close" class="close_image" /></a> \ </div> \ </div>' }, loading: function() { init() if ($('#facebox .loading').length == 1) return true showOverlay() $('#facebox .content').empty() $('#facebox .body').children().hide().end(). append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>') $('#facebox').css({ top: getPageScroll()[1] + (getPageHeight() / 10), left: $(window).width() / 2 - 205 }).show() $(document).bind('keydown.facebox', function(e) { if (e.keyCode == 27) $.facebox.close() return true }) $(document).trigger('loading.facebox') }, reveal: function(data, klass) { $(document).trigger('beforeReveal.facebox') if (klass) $('#facebox .content').addClass(klass) $('#facebox .content').append(data) $('#facebox .loading').remove() $('#facebox .body').children().fadeIn('normal') $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').width() / 2)) $(document).trigger('reveal.facebox').trigger('afterReveal.facebox') }, close: function() { $(document).trigger('close.facebox') return false } }) /* * Public, $.fn methods */ $.fn.facebox = function(settings) { if ($(this).length == 0) return init(settings) function clickHandler() { $.facebox.loading(true) // support for rel="facebox.inline_popup" syntax, to add a class // also supports deprecated "facebox[.inline_popup]" syntax var klass = this.rel.match(/facebox\[?\.(\w+)\]?/) if (klass) klass = klass[1] fillFaceboxFromHref(this.href, klass) return false } return this.bind('click.facebox', clickHandler) } /* * Private methods */ // called one time to setup facebox on this page function init(settings) { if ($.facebox.settings.inited) return true else $.facebox.settings.inited = true $(document).trigger('init.facebox') makeCompatible() var imageTypes = $.facebox.settings.imageTypes.join('|') $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i') if (settings) $.extend($.facebox.settings, settings) $('body').append($.facebox.settings.faceboxHtml) var preload = [ new Image(), new Image() ] preload[0].src = $.facebox.settings.closeImage preload[1].src = $.facebox.settings.loadingImage $('#facebox').find('.b:first, .bl').each(function() { preload.push(new Image()) preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1') }) $('#facebox .close').click($.facebox.close) $('#facebox .close_image').attr('src', $.facebox.settings.closeImage) } // getPageScroll() by quirksmode.com function getPageScroll() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return new Array(xScroll,yScroll) } // Adapted from getPageSize() by quirksmode.com function getPageHeight() { var windowHeight if (self.innerHeight) { // all except Explorer windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowHeight = document.body.clientHeight; } return windowHeight } // Backwards compatibility function makeCompatible() { var $s = $.facebox.settings $s.loadingImage = $s.loading_image || $s.loadingImage $s.closeImage = $s.close_image || $s.closeImage $s.imageTypes = $s.image_types || $s.imageTypes $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml } // Figures out what you want to display and displays it // formats are: // div: #id // image: blah.extension // ajax: anything else function fillFaceboxFromHref(href, klass) { // div if (href.match(/#/)) { var url = window.location.href.split('#')[0] var target = href.replace(url,'') if (target == '#') return $.facebox.reveal($(target).html(), klass) // image } else if (href.match($.facebox.settings.imageTypesRegexp)) { fillFaceboxFromImage(href, klass) // ajax } else { fillFaceboxFromAjax(href, klass) } } function fillFaceboxFromImage(href, klass) { var image = new Image() image.onload = function() { $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass) } image.src = href } function fillFaceboxFromAjax(href, klass) { $.get(href, function(data) { $.facebox.reveal(data, klass) }) } function skipOverlay() { return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null } function showOverlay() { if (skipOverlay()) return if ($('#facebox_overlay').length == 0) $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>') $('#facebox_overlay').hide().addClass("facebox_overlayBG") .css('opacity', $.facebox.settings.opacity) .click(function() { $(document).trigger('close.facebox') }) .fadeIn(200) return false } function hideOverlay() { if (skipOverlay()) return $('#facebox_overlay').fadeOut(200, function(){ $("#facebox_overlay").removeClass("facebox_overlayBG") $("#facebox_overlay").addClass("facebox_hide") $("#facebox_overlay").remove() }) return false } /* * Bindings */ $(document).bind('close.facebox', function() { $(document).unbind('keydown.facebox') $('#facebox').fadeOut(function() { $('#facebox .content').removeClass().addClass('content') $('#facebox .loading').remove() $(document).trigger('afterClose.facebox') }) hideOverlay() }) })(jQuery);
game.SpendGold = Object.extend({ init: function(x, y, settings){ this.now = new Date().getTime(); this.lastBuy = new Date().getTime(); this.paused = false; this.alwaysUpdate = true; this.updateWhenPaused = true; this.buying = false; }, update: function(){ this.now = new Date().getTime(); if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){ this.lastBuy = this.now; if(!this.buying){ this.startBuying(); }else{ this.stopBuying(); } } this.checkBuyKeys(); return true; }, startBuying: function(){ this.buying = true; me.state.pause(me.state.PLAY); game.data.pausePos = me.game.viewport.localToWorld(0, 0); game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen')); game.data.buyscreen.updateWhenPaused = true; game.data.buyscreen.setOpacity(0.8); me.game.world.addChild(game.data.buyscreen, 34); game.data.player.body.setVelocity(0,0); me.state.pause(me.state.PLAY); me.input.bindKey(me.input.KEY.F1, "F1", true); me.input.bindKey(me.input.KEY.F2, "F2", true); me.input.bindKey(me.input.KEY.F3, "F3", true); me.input.bindKey(me.input.KEY.F4, "F4", true); me.input.bindKey(me.input.KEY.F5, "F5", true); me.input.bindKey(me.input.KEY.F6, "F6", true); this.setBuyText(); }, setBuyText: function(){ game.data.buyText = new (me.Renderable.extend({ init:function(){ this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]); this.font = new me.Font("Arial",26, "white"); this.updateWhenPaused = true; this.alwaysUpdate = true; }, draw: function(renderer){ this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y); this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.exp1+1)*10),this.pos.x, this.pos.y + 40); this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.exp2+1)*10), this.pos.x, this.pos.y + 80); this.font.draw(renderer.getContext(), "Skill 3:Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.exp3+1)*10), this.pos.x, this.pos.y + 120); this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level " + game.data.ability1 + " Cost: " + ((game.data.exp4+1)*10), this.pos.x, this.pos.y + 160); this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + " Cost: " + ((game.data.exp5+1)*10), this.pos.x, this.pos.y + 200); this.font.draw(renderer.getContext(), "E Ability: Throw YOur Spear: " + game.data.ability3 + " Cost: " + ((game.data.exp6+1)*10), this.pos.x, this.pos.y + 240); } })); me.game.world.addChild(game.data.buyText, 35); ; }, stopBuying: function(){ this.buying = false; me.state.resume(me.state.PLAY); game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20); me.game.world.removeChild(game.data.buyscreen); me.input.unbindKey(me.input.KEY.F1, "F1", true); me.input.unbindKey(me.input.KEY.F2, "F2", true); me.input.unbindKey(me.input.KEY.F3, "F3", true); me.input.unbindKey(me.input.KEY.F4, "F4", true); me.input.unbindKey(me.input.KEY.F5, "F5", true); me.input.unbindKey(me.input.KEY.F6, "F6", true); me.game.world.removeChild(game.data.buyText); }, checkBuyKeys: function(){ if(me.input.isKeyPressed("F1")){ if(this.checkCost(1)){ this.makePurchase(1); } }else if(me.input.isKeyPressed("F2")){ if(this.checkCost(2)){ this.makePurchase(2); } }else if(me.input.isKeyPressed("F3")){ if(this.checkCost(3)){ this.makePurchase(3); } }else if(me.input.isKeyPressed("F4")){ if(this.checkCost(4)){ this.makePurchase(4); } }else if(me.input.isKeyPressed("F5")){ if(this.checkCost(5)){ this.makePurchase(5); } }else if(me.input.isKeyPressed("F6")){ if(this.checkCost(6)){ this.makePurchase(6); } } }, checkCost: function(skill){ if(skill===1 && (game.data.gold >= ((game.data.skill1+1)*10))){ return true; }else if(skill===2 && (game.data.gold >= ((game.data.skill2+1)*10))){ return true; }else if(skill===3 && (game.data.gold >= ((game.data.skill3+1)*10))){ return true; }else if(skill===4 && (game.data.gold >= ((game.data.ability1+1)*10))){ return true; }else if(skill===5 && (game.data.gold >= ((game.data.ability2+1)*10))){ return true; }else if(skill===6 && (game.data.gold >= ((game.data.ability3+1)*10))){ return true; }else{ return false; } }, makePurchase: function(skill){ if(skill === 1){ game.data.gold -= ((game.data.skill1 +1)* 10); game.data.skill1 += 1; game.data.playerAttack += 1; }else if(skill ===2){ game.data.gold -= ((game.data.skill2 +1)* 10); game.data.skill2 += 1; }else if(skill ===3){ game.data.gold -= ((game.data.skill3 +1)* 10); game.data.skill3 += 1; }else if(skill ===4){ game.data.gold -= ((game.data.ability1 +1)* 10); game.data.ability1 += 1; }else if(skill ===5){ game.data.gold -= ((game.data.ability2 +1)* 10); game.data.ability2 += 1; }else if(skill ===6){ game.data.gold -= ((game.data.ability3 +1)* 10); game.data.ability3 += 1; } } });
export default function($stateProvider) { 'ngInject'; return $stateProvider.state('root', { abstract: true, views: { '@': { template: `<ion-side-menus enable-menu-with-back-views="true"> <ion-side-menu-content> <ion-nav-bar class="bar-positive"> <ion-nav-back-button native-transitions native-transitions-options="{type: 'slide', direction:'right'}"></ion-nav-back-button> <ion-nav-buttons side="left"> <button menu-toggle="left" class="button button-clear"> <i class="icon ion-navicon-round"></i> </button> </ion-nav-buttons> </ion-nav-bar> <ion-nav-view name="content"></ion-nav-view> </ion-side-menu-content> <ion-side-menu side="left" ui-view="menu"></ion-side-menu> </ion-side-menus>` } } }); }
"use strict"; // Core // const FeedbackController = require("./controllers/feedback"); const APIServer = require("../api/server"); // ---- // // External // const Joi = require("joi"); // -------- // /** * Creates a new OpenFeedback instance. * @class */ class OpenFeedback { constructor() { this.schemaMap = new Map(); } addSchema(name, schema) { // Lowercase name name = name.toLowerCase(); // Create Controller let _controller = new FeedbackController(name, schema); // Store in map this.schemaMap.set(name, _controller); // Get a copy return this.schemaMap.get(name); } hasSchema(name) { // Lowercase name name = name.toLowerCase(); return this.schemaMap.has(name); } getSchema(name) { // Lowercase name name = name.toLowerCase(); return this.schemaMap.get(name); } listSchemas() { let schemaArray = []; for (let Schema of this.schemaMap) { schemaArray.push({ name: Schema[0], schema: Schema[1] }); } return schemaArray; } connect(options, server) { if (!server) server = APIServer; server(this, options || {}); } } module.exports = OpenFeedback;
/*! DataTables Bootstrap 4 integration ยฉ2011-2017 SpryMedia Ltd - datatables.net/license */ var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,b,c){a instanceof String&&(a=String(a));for(var e=a.length,d=0;d<e;d++){var k=a[d];if(b.call(c,k,d,a))return{i:d,v:k}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1; $jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)};$jscomp.getGlobal=function(a){return"undefined"!=typeof window&&window===a?a:"undefined"!=typeof global&&null!=global?global:a};$jscomp.global=$jscomp.getGlobal(this); $jscomp.polyfill=function(a,b,c,e){if(b){c=$jscomp.global;a=a.split(".");for(e=0;e<a.length-1;e++){var d=a[e];d in c||(c[d]={});c=c[d]}a=a[a.length-1];e=c[a];b=b(e);b!=e&&null!=b&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})}};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(a,c){return $jscomp.findInternal(this,a,c).v}},"es6","es3"); (function(a){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(b){return a(b,window,document)}):"object"===typeof exports?module.exports=function(b,c){b||(b=window);c&&c.fn.dataTable||(c=require("datatables.net")(b,c).$);return a(c,b,b.document)}:a(jQuery,window,document)})(function(a,b,c,e){var d=a.fn.dataTable;a.extend(!0,d.defaults,{dom:"<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>", renderer:"bootstrap"});a.extend(d.ext.classes,{sWrapper:"dataTables_wrapper dt-bootstrap4",sFilterInput:"form-control form-control-sm",sLengthSelect:"custom-select custom-select-sm form-control form-control-sm",sProcessing:"dataTables_processing card",sPageButton:"paginate_button page-item"});d.ext.renderer.pageButton.bootstrap=function(b,l,v,w,m,r){var k=new d.Api(b),x=b.oClasses,n=b.oLanguage.oPaginate,y=b.oLanguage.oAria.paginate||{},g,h,t=0,u=function(c,d){var e,l=function(b){b.preventDefault(); a(b.currentTarget).hasClass("disabled")||k.page()==b.data.action||k.page(b.data.action).draw("page")};var q=0;for(e=d.length;q<e;q++){var f=d[q];if(a.isArray(f))u(c,f);else{h=g="";switch(f){case "ellipsis":g="&#x2026;";h="disabled";break;case "first":g=n.sFirst;h=f+(0<m?"":" disabled");break;case "previous":g=n.sPrevious;h=f+(0<m?"":" disabled");break;case "next":g=n.sNext;h=f+(m<r-1?"":" disabled");break;case "last":g=n.sLast;h=f+(m<r-1?"":" disabled");break;default:g=f+1,h=m===f?"active":""}if(g){var p= a("<li>",{"class":x.sPageButton+" "+h,id:0===v&&"string"===typeof f?b.sTableId+"_"+f:null}).append(a("<a>",{href:"#","aria-controls":b.sTableId,"aria-label":y[f],"data-dt-idx":t,tabindex:b.iTabIndex,"class":"page-link"}).html(g)).appendTo(c);b.oApi._fnBindAction(p,{action:f},l);t++}}}};try{var p=a(l).find(c.activeElement).data("dt-idx")}catch(z){}u(a(l).empty().html('<ul class="pagination"/>').children("ul"),w);p!==e&&a(l).find("[data-dt-idx="+p+"]").focus()};return d});
(function () { var module; module = angular.module('cabin.scrolling', []); module.factory('windowScrollY', [ '$window', function ($window) { if ($window.pageYOffset != null) { return function () { return $window.pageYOffset; }; } else { return function () { return $window.document.documentElement.scrollTop; }; } } ]); module.value('absoluteOffsetTop', function (node) { var offset; if (!node) { return 0; } if (node.bind && node.find) { node = node[0]; } offset = node.offsetTop; while (node = node.offsetParent) { offset += node.offsetTop; } return offset; }); module.directive('cbStickyPos', [ 'absoluteOffsetTop', 'windowScrollY', '$window', function (absoluteOffsetTop, windowScrollY, $window) { return { restrict: 'A', link: function (scope, elm, attrs) { var container, node, setClass, setup, stickyMax, stickyMin; node = elm[0]; container = node.offsetParent; stickyMin = stickyMax = null; setClass = function () { var scroll; scroll = windowScrollY(); elm.toggleClass('cb-stick', scroll >= stickyMin); return elm.toggleClass('cb-stick--bottom', scroll >= stickyMax); }; setup = function () { var extraTop, height, nodeMarginTop; nodeMarginTop = parseInt(getComputedStyle(node).marginTop, 10); extraTop = parseInt(attrs.cbStickyPos || 0, 10); height = node.clientHeight + nodeMarginTop + extraTop; stickyMin = absoluteOffsetTop(node) - nodeMarginTop - extraTop; stickyMax = absoluteOffsetTop(container) + container.clientHeight - height; angular.element($window).bind('scroll', setClass); return setClass(); }; return angular.element($window).bind('load', setup); } }; } ]); }.call(this));
'use strict'; angular.module('myApp.notes', ['ngRoute'] ) .config(['$routeProvider', function($scope) { $scope.when('/notes', { templateUrl: 'notes/notes.html', controller: 'NotesController' }); }]) .controller('NotesController', [function($scope) { $scope.categories = [ {"id": 0, "name": "Development"}, {"id": 1, "name": "Design"}, {"id": 2, "name": "Exercise"}, {"id": 3, "name": "Humor"} ]; $scope.bookmarks = [ {"id": 0, "title": "AngularJS", "url": "http://angularjs.org", "category": "Development" }, {"id": 1, "title": "Egghead.io", "url": "http://angularjs.org", "category": "Development" }, {"id": 2, "title": "A List Apart", "url": "http://alistapart.com/", "category": "Design" }, {"id": 3, "title": "One Page Love", "url": "http://onepagelove.com/", "category": "Design" }, {"id": 4, "title": "MobilityWOD", "url": "http://www.mobilitywod.com/", "category": "Exercise" }, {"id": 5, "title": "Robb Wolf", "url": "http://robbwolf.com/", "category": "Exercise" }, {"id": 6, "title": "Senor Gif", "url": "http://memebase.cheezburger.com/senorgif", "category": "Humor" }, {"id": 7, "title": "Wimp", "url": "http://wimp.com", "category": "Humor" }, {"id": 8, "title": "Dump", "url": "http://dump.com", "category": "Humor" } ]; }]);
import test from 'ava'; import fn from '../'; test('expects string parameters', t => { t.plan(2); t.throws(() => { fn({}, ['usd', 'eur']); }, 'ccoin expects two string parameters, got object, object'); t.throws(() => { fn('btc'); }, 'ccoin expects two string parameters, got string, undefined'); }); test('allows more than one from', async t => { const prices = await fn('btc,eth', 'eth,usd,ltc'); // const expected = { // BTC: [ // 'ETH: 8.22', // 'USD: 2733.23', // 'LTC: 58.62' // ], // ETH: [ // 'USD: 327.94', // 'LTC: 7.12' // ] // }; t.is(typeof prices, 'object'); t.is(Object.keys(prices).length, 2); t.is(Array.isArray(prices.BTC), true); t.is(prices.BTC.length, 3); t.is(Array.isArray(prices.ETH), true); t.is(prices.ETH.length, 2); }); test('forgives whitespace in currency list', async t => { const prices = await fn('btc', 'eth, usd, ltc'); t.is(typeof prices, 'object'); t.is(Object.keys(prices).length, 1); t.is(Array.isArray(prices.BTC), true); t.is(prices.BTC.length, 3); });
"use strict"; var a = 1; let b = 1; console.log("after global declaration", a, b); function asdf() { var a = 2; let b = 2; console.log("in method asdf", a, b); } console.log("after function declaration", a, b); asdf(); console.log("after function call", a, b) if(true) { var a = 3; let b = 3; console.log("in if block", a, b); } console.log("after if block", a, b); console.log("---"); var items = [1,2,3,4] for (var i = 0; i < items.length; i++) { setTimeout(function () { console.log("logging item with index %d using var, %s: %s", i, items, items[i]); }, 10); } // the same sample with let for (let i = 0; i < items.length; i++) { setTimeout(function () { console.log("logging item with index %d using let, %s: %s", i, items, items[i]); }, 10); }
define(function(require) { 'use strict'; const $ = require('jquery'); const _ = require('underscore'); require('bootstrap'); const BaseView = require('oroui/js/app/views/base/view'); const ExpressionEditorUtil = require('oroform/js/expression-editor-util'); const Typeahead = $.fn.typeahead.Constructor; const ExpressionEditorView = BaseView.extend({ optionNames: BaseView.prototype.optionNames.concat([ 'dataSource', 'delay' ]), /** * {Object} ExpressionEditorUtil */ util: null, /** * {Object} Typeahead */ typeahead: null, /** * {Object} Autocomplete data provided by ExpressionEditorUtil.getAutocompleteData */ autocompleteData: null, /** * {Object} List of data source widgets */ dataSource: null, /** * {Object} List of data source widget instances */ dataSourceInstances: null, /** * {Integer} Validation and autocomplete delay in milliseconds */ delay: 50, /** * @inheritDoc */ constructor: function ExpressionEditorView(options) { ExpressionEditorView.__super__.constructor.call(this, options); }, /** * @inheritDoc */ initialize: function(options) { this.util = new ExpressionEditorUtil(options); this.autocompleteData = this.autocompleteData || {}; this.dataSource = this.dataSource || {}; this.dataSourceInstances = this.dataSourceInstances || {}; this.initAutocomplete(); return ExpressionEditorView.__super__.initialize.call(this, options); }, /** * Initialize autocomplete widget */ initAutocomplete: function() { this.$el.typeahead({ minLength: 0, items: 20, select: _.bind(this._typeaheadSelect, this), source: _.bind(this._typeaheadSource, this), lookup: _.bind(this._typeaheadLookup, this), highlighter: _.bind(this._typeaheadHighlighter, this), updater: _.bind(this._typeaheadUpdater, this) }); this.typeahead = this.$el.data('typeahead'); this.typeahead.$menu.addClass('expression-editor-autocomplete'); }, /** * @inheritDoc */ dispose: function() { if (this.disposed) { return; } _.each(this.dataSourceInstances, function(dataSource) { dataSource.$widget.remove(); }); delete this.util; delete this.typeahead; delete this.autocompleteData; delete this.dataSource; delete this.dataSourceInstances; return ExpressionEditorView.__super__.dispose.call(this); }, /** * @inheritDoc */ delegateEvents: function(events) { const result = ExpressionEditorView.__super__.delegateEvents.call(this, events); const self = this; const namespace = this.eventNamespace(); const autocomplete = _.debounce(function(e) { if (!self.disposed) { self.autocomplete(e); } }, this.delay); const validate = _.debounce(function(e) { if (!self.disposed) { self.validate(e); } }, this.delay); this.$el .on('focus' + namespace, autocomplete) .on('click' + namespace, autocomplete) .on('input' + namespace, autocomplete) .on('keyup' + namespace, validate) .on('change' + namespace, validate) .on('blur' + namespace, validate) .on('paste' + namespace, validate); return result; }, /** * Show autocomplete list */ autocomplete: function() { this.typeahead.lookup(); }, /** * Validate expression */ validate: function() { const isValid = this.util.validate(this.$el.val()); this.$el.toggleClass('error', !isValid); this.$el.parent().toggleClass('validation-error', !isValid); }, /** * Override Typeahead.source function * * @return {Array} * @private */ _typeaheadSource: function() { const expression = this.el.value; const position = this.el.selectionStart; this.autocompleteData = this.util.getAutocompleteData(expression, position); this._toggleDataSource(); this.typeahead.query = this.autocompleteData.itemLastChild; return _.sortBy(_.keys(this.autocompleteData.items)); }, /** * Override Typeahead.lookup function * * @return {Typeahead} * @private */ _typeaheadLookup: function() { return this.typeahead.process(this.typeahead.source()); }, /** * Override Typeahead.select function * * @return {Typeahead} * @private */ _typeaheadSelect: function() { const original = Typeahead.prototype.select; const result = original.call(this.typeahead); this.typeahead.lookup(); return result; }, /** * Override Typeahead.highlighter function * * @param {String} item * @return {String} * @private */ _typeaheadHighlighter: function(item) { const original = Typeahead.prototype.highlighter; const hasChild = !!this.autocompleteData.items[item].child; const suffix = hasChild ? '&hellip;' : ''; return original.call(this.typeahead, item) + suffix; }, /** * Override Typeahead.updater function * * @param {String} item * @return {String} * @private */ _typeaheadUpdater: function(item) { this.util.updateAutocompleteItem(this.autocompleteData, item); const position = this.autocompleteData.position; this.$el.one('change', function() { // set correct position after typeahead call change event this.selectionStart = this.selectionEnd = position; }); return this.autocompleteData.expression; }, /** * Return data source instance by key * * @param {String} dataSourceKey * @return {Object} */ getDataSource: function(dataSourceKey) { const dataSource = this.dataSourceInstances[dataSourceKey]; if (!dataSource) { return this._initializeDataSource(dataSourceKey); } return dataSource; }, /** * Create data source instance * * @param {String} dataSourceKey * @return {Object} * @private */ _initializeDataSource: function(dataSourceKey) { const dataSource = this.dataSourceInstances[dataSourceKey] = {}; dataSource.$widget = $('<div>').addClass('expression-editor-data-source') .html(this.dataSource[dataSourceKey]); dataSource.$field = dataSource.$widget.find(':input[name]:first'); dataSource.active = false; this._hideDataSource(dataSource); this.$el.after(dataSource.$widget).trigger('content:changed'); dataSource.$field.on('change', _.bind(function() { if (!dataSource.active) { return; } this.util.updateDataSourceValue(this.autocompleteData, dataSource.$field.val()); this.$el.val(this.autocompleteData.expression) .change().focus(); this.el.selectionStart = this.el.selectionEnd = this.autocompleteData.position; }, this)); return dataSource; }, /** * Hide all data sources and show active * * @private */ _toggleDataSource: function() { this._hideDataSources(); const dataSourceKey = this.autocompleteData.dataSourceKey; const dataSourceValue = this.autocompleteData.dataSourceValue; if (_.isEmpty(dataSourceKey) || !_.has(this.dataSource, dataSourceKey)) { return; } this.autocompleteData.items = {};// hide autocomplete list const dataSource = this.getDataSource(dataSourceKey); dataSource.$field.val(dataSourceValue).change(); this._showDataSource(dataSource); }, /** * Hide all data sources * * @private */ _hideDataSources: function() { _.each(this.dataSourceInstances, this._hideDataSource, this); }, /** * Hide data source * * @param {Object} dataSource * @private */ _hideDataSource: function(dataSource) { dataSource.active = false; dataSource.$widget.hide().removeClass('active'); }, /** * Show data source * * @param {Object} dataSource * @private */ _showDataSource: function(dataSource) { dataSource.$widget.show().addClass('active'); dataSource.active = true; } }); return ExpressionEditorView; });
class QrAPI { constructor(apiUrl, apiPassword) { this.apiUrl = apiUrl; this.apiPassword = apiPassword; } setPassword(password) { this.apiPassword = password; } getHistory() { return this.scanRequest(""); } scanRequest(barcode) { 'use strict'; return Promise.resolve($.post( this.apiUrl, { "qrcode": barcode, "password": this.apiPassword }, null, 'json' )) } }
Ext.define('Signout.store.History', { extend: 'Ext.data.Store', storeId: 'history', model: 'Signout.model.LatestSignout' //fields: ['name', 'email', 'phone'], });
// Authors: Valery Bogdanov $(document).ready(function () { searchBox(); fancyboxInit(); }); $(window).resize(function () { }); $(window).load(function () { }); function searchBox() { $('.js-searchShow, .js-searchHide').on('click', function(e){ e.preventDefault(); $('.js-searchForm').fadeToggle('fast', 'linear'); if ($(this).hasClass('js-searchShow')) { $('.js-searchForm').find('input[name="s"]').trigger('focus'); } }); } function fancyboxInit() { $('.b-text a[href$=".jpg"], .b-text a[href$=".jpeg"], .b-text a[href$=".png"]').fancybox({ openEffect : 'none', closeEffect : 'none', beforeShow : function() { var alt = this.element.find('img').attr('alt'); this.inner.find('img').attr('alt', alt); this.title = alt; } }); $('.js-fancybox').fancybox({ type : 'iframe' }); }
$('.single-datepicker').daterangepicker({ singleDatePicker: true, calender_style: "picker_3", showDropdowns: true, format: 'YYYY-MM-DD' }, function (start, end, label) { //console.log(start.toISOString(), end.toISOString(), label); });
import React, { Component } from 'react'; import { ComposedChart, Line, Area, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts'; export default class extends Component { render() { const { datas, width, height, colors } = this.props; return (<div className="isoChartWrapper"> <ComposedChart width={width} height={height} data={datas} margin={{top: 20, right: 20, bottom: 20, left: 20}}> <XAxis dataKey="name" stroke={colors[3]}/> <YAxis stroke={colors[3]} /> <Tooltip/> <Legend/> <CartesianGrid stroke='#f5f5f5'/> <Area type='monotone' dataKey='amt' fill={colors[0]} stroke={colors[0]}/> <Bar dataKey='pv' barSize={20} fill={colors[1]} /> <Line type='monotone' dataKey='uv' stroke={colors[3]} /> </ComposedChart></div>); } };
function instrumentChange(instr){ midiMsg[0] = randID ; midiMsg[1] = '3' ; midiMsg[2] = instr ; loadInstrument(0, instr) for (var i = 1 ; i < userLimit ; i++) { if (user[i] != 0){ user[i].send(midiMsg); console.log('I sent the instrument change: ' + midiMsg[2] + " to " + user[i].peer); } } } // end function
!function (e) { "use strict"; var t = function (e, i, n) { var o, a, s = document.createElement("img"); if (s.onerror = i, s.onload = function () { !a || n && n.noRevoke || t.revokeObjectURL(a), i && i(t.scale(s, n)) }, t.isInstanceOf("Blob", e) || t.isInstanceOf("File", e))o = a = t.createObjectURL(e), s._type = e.type; else { if ("string" != typeof e)return!1; o = e, n && n.crossOrigin && (s.crossOrigin = n.crossOrigin) } return o ? (s.src = o, s) : t.readFile(e, function (e) { var t = e.target; t && t.result ? s.src = t.result : i && i(e) }) }, i = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL && webkitURL; t.isInstanceOf = function (e, t) { return Object.prototype.toString.call(t) === "[object " + e + "]" }, t.transformCoordinates = function (e, t) { var i = e.getContext("2d"), n = e.width, o = e.height; switch (t > 4 && (e.width = o, e.height = n), t) { case 2: i.translate(n, 0), i.scale(-1, 1); break; case 3: i.translate(n, o), i.rotate(Math.PI); break; case 4: i.translate(0, o), i.scale(1, -1); break; case 5: i.rotate(.5 * Math.PI), i.scale(1, -1); break; case 6: i.rotate(.5 * Math.PI), i.translate(0, -o); break; case 7: i.rotate(.5 * Math.PI), i.translate(n, -o), i.scale(-1, 1); break; case 8: i.rotate(-.5 * Math.PI), i.translate(-n, 0) } }, t.renderImageToCanvas = function (e, t, i, n, o, a, s, l, r, d) { return e.getContext("2d").drawImage(t, i, n, o, a, s, l, r, d), e }, t.scale = function (e, i) { i = i || {}; var n, o, a, s, l, r, d, h = document.createElement("canvas"), c = e.getContext || (i.canvas || i.crop || i.orientation) && h.getContext, g = e.width, m = e.height, f = g, u = m, w = 0, p = 0, v = 0, y = 0; return c && i.orientation > 4 ? (n = i.maxHeight, o = i.maxWidth, a = i.minHeight, s = i.minWidth) : (n = i.maxWidth, o = i.maxHeight, a = i.minWidth, s = i.minHeight), c && n && o && i.crop ? (l = n, r = o, n / o > g / m ? (u = o * g / n, p = (m - u) / 2) : (f = n * m / o, w = (g - f) / 2)) : (l = g, r = m, d = Math.max((a || l) / l, (s || r) / r), d > 1 && (l = Math.ceil(l * d), r = Math.ceil(r * d)), d = Math.min((n || l) / l, (o || r) / r), 1 > d && (l = Math.ceil(l * d), r = Math.ceil(r * d))), c ? (h.width = l, h.height = r, t.transformCoordinates(h, i.orientation), t.renderImageToCanvas(h, e, w, p, f, u, v, y, l, r)) : (e.width = l, e.height = r, e) }, t.createObjectURL = function (e) { return i ? i.createObjectURL(e) : !1 }, t.revokeObjectURL = function (e) { return i ? i.revokeObjectURL(e) : !1 }, t.readFile = function (e, t, i) { if (window.FileReader) { var n = new FileReader; if (n.onload = n.onerror = t, i = i || "readAsDataURL", n[i])return n[i](e), n } return!1 }, "function" == typeof define && define.amd ? define(function () { return t }) : e.loadImage = t }(this), function (e) { "use strict"; "function" == typeof define && define.amd ? define(["jquery", "load-image", "bootstrap"], e) : e(window.jQuery, window.loadImage) }(function (e, t) { "use strict"; e.extend(e.fn.modal.defaults, {delegate: document, selector: null, filter: "*", index: 0, href: null, preloadRange: 2, offsetWidth: 100, offsetHeight: 200, canvas: !1, slideshow: 0, imageClickDivision: .5}); var i = e.fn.modal.Constructor.prototype.show, n = e.fn.modal.Constructor.prototype.hide; e.extend(e.fn.modal.Constructor.prototype, {initLinks: function () { var t = this, i = this.options, n = i.selector || "a[data-target=" + i.target + "]"; this.$links = e(i.delegate).find(n).filter(i.filter).each(function (e) { t.getUrl(this) === i.href && (i.index = e) }), this.$links[i.index] || (i.index = 0) }, getUrl : function (t) { return t.href || e(t).data("href") }, getDownloadUrl : function (t) { return e(t).data("download") }, startSlideShow : function () { var e = this; this.options.slideshow && (this._slideShow = window.setTimeout(function () { e.next() }, this.options.slideshow)) }, stopSlideShow : function () { window.clearTimeout(this._slideShow) }, toggleSlideShow : function () { var e = this.$element.find(".modal-slideshow"); this.options.slideshow ? (this.options.slideshow = 0, this.stopSlideShow()) : (this.options.slideshow = e.data("slideshow") || 5e3, this.startSlideShow()), e.find("i").toggleClass("icon-play icon-pause") }, preloadImages : function () { var t, i, n = this.options, o = n.index + n.preloadRange + 1; for (i = n.index - n.preloadRange; o > i; i += 1)t = this.$links[i], t && i !== n.index && e("<img>").prop("src", this.getUrl(t)) }, loadImage : function () { var e, i = this, n = this.$element, o = this.options.index, a = this.getUrl(this.$links[o]), s = this.getDownloadUrl(this.$links[o]); this.abortLoad(), this.stopSlideShow(), n.trigger("beforeLoad"), this._loadingTimeout = window.setTimeout(function () { n.addClass("modal-loading") }, 100), e = n.find(".modal-image").children().removeClass("in"), window.setTimeout(function () { e.remove() }, 3e3), n.find(".modal-title").text(this.$links[o].title), n.find(".modal-download").prop("href", s || a), this._loadingImage = t(a, function (e) { i.img = e, window.clearTimeout(i._loadingTimeout), n.removeClass("modal-loading"), n.trigger("load"), i.showImage(e), i.startSlideShow() }, this._loadImageOptions), this.preloadImages() }, showImage : function (t) { var i, n, o = this.$element, a = e.support.transition && o.hasClass("fade"), s = a ? o.animate : o.css, l = o.find(".modal-image"); l.css({width: t.width, height: t.height}), o.find(".modal-title").css({width: Math.max(t.width, 380)}), a && (i = o.clone().hide().appendTo(document.body)), e(window).width() > 767 ? s.call(o.stop(), {"margin-top": -((i || o).outerHeight() / 2), "margin-left": -((i || o).outerWidth() / 2)}) : o.css({top: (e(window).height() - (i || o).outerHeight()) / 2}), i && i.remove(), l.append(t), n = t.offsetWidth, o.trigger("display"), a ? o.is(":visible") ? e(t).on(e.support.transition.end,function (i) { i.target === t && (e(t).off(e.support.transition.end), o.trigger("displayed")) }).addClass("in") : (e(t).addClass("in"), o.one("shown", function () { o.trigger("displayed") })) : (e(t).addClass("in"), o.trigger("displayed")) }, abortLoad : function () { this._loadingImage && (this._loadingImage.onload = this._loadingImage.onerror = null), window.clearTimeout(this._loadingTimeout) }, prev : function () { var e = this.options; e.index -= 1, e.index < 0 && (e.index = this.$links.length - 1), this.loadImage() }, next : function () { var e = this.options; e.index += 1, e.index > this.$links.length - 1 && (e.index = 0), this.loadImage() }, keyHandler : function (e) { switch (e.which) { case 37: case 38: e.preventDefault(), this.prev(); break; case 39: case 40: e.preventDefault(), this.next() } }, wheelHandler : function (e) { e.preventDefault(), e = e.originalEvent, this._wheelCounter = this._wheelCounter || 0, this._wheelCounter += e.wheelDelta || e.detail || 0, e.wheelDelta && this._wheelCounter >= 120 || !e.wheelDelta && this._wheelCounter < 0 ? (this.prev(), this._wheelCounter = 0) : (e.wheelDelta && this._wheelCounter <= -120 || !e.wheelDelta && this._wheelCounter > 0) && (this.next(), this._wheelCounter = 0) }, initGalleryEvents : function () { var t = this, i = this.$element; i.find(".modal-image").on("click.modal-gallery", function (i) { var n = e(this); 1 === t.$links.length ? t.hide() : (i.pageX - n.offset().left) / n.width() < t.options.imageClickDivision ? t.prev(i) : t.next(i) }), i.find(".modal-prev").on("click.modal-gallery", function (e) { t.prev(e) }), i.find(".modal-next").on("click.modal-gallery", function (e) { t.next(e) }), i.find(".modal-slideshow").on("click.modal-gallery", function (e) { t.toggleSlideShow(e) }), e(document).on("keydown.modal-gallery",function (e) { t.keyHandler(e) }).on("mousewheel.modal-gallery, DOMMouseScroll.modal-gallery", function (e) { t.wheelHandler(e) }) }, destroyGalleryEvents : function () { var t = this.$element; this.abortLoad(), this.stopSlideShow(), t.find(".modal-image, .modal-prev, .modal-next, .modal-slideshow").off("click.modal-gallery"), e(document).off("keydown.modal-gallery").off("mousewheel.modal-gallery, DOMMouseScroll.modal-gallery") }, show : function () { if (!this.isShown && this.$element.hasClass("modal-gallery")) { var t = this.$element, n = this.options, o = e(window).width(), a = e(window).height(); t.hasClass("modal-fullscreen") ? (this._loadImageOptions = {maxWidth: o, maxHeight: a, canvas: n.canvas}, t.hasClass("modal-fullscreen-stretch") && (this._loadImageOptions.minWidth = o, this._loadImageOptions.minHeight = a)) : this._loadImageOptions = {maxWidth: o - n.offsetWidth, maxHeight: a - n.offsetHeight, canvas: n.canvas}, o > 767 ? t.css({"margin-top": -(t.outerHeight() / 2), "margin-left": -(t.outerWidth() / 2)}) : t.css({top: (e(window).height() - t.outerHeight()) / 2}), this.initGalleryEvents(), this.initLinks(), this.$links.length && (t.find(".modal-slideshow, .modal-prev, .modal-next").toggle(1 !== this.$links.length), t.toggleClass("modal-single", 1 === this.$links.length), this.loadImage()) } i.apply(this, arguments) }, hide : function () { this.isShown && this.$element.hasClass("modal-gallery") && (this.options.delegate = document, this.options.href = null, this.destroyGalleryEvents()), n.apply(this, arguments) }}), e(function () { e(document.body).on("click.modal-gallery.data-api", '[data-toggle="modal-gallery"]', function (t) { var i, n = e(this), o = n.data(), a = e(o.target), s = a.data("modal"); s || (o = e.extend(a.data(), o)), o.selector || (o.selector = "a[data-gallery=gallery]"), i = e(t.target).closest(o.selector), i.length && a.length && (t.preventDefault(), o.href = i.prop("href") || i.data("href"), o.delegate = i[0] !== this ? this : document, s && e.extend(s.options, o), a.modal(o)) }) }) });
import React from 'react'; export default class CardSkip extends React.Component{ render(){ const colour = this.props.card.colour ? this.props.card.colour : 'gray'; return( <svg className="card-skip-component" onClick={this.props.onClick} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 158.7 243.8"> <g id="Layer_3"> <path id="XMLID_5_" className="c0" d="M146.7 243.8H12c-6.6 0-12-5.4-12-12V12C0 5.4 5.4 0 12 0h134.7c6.6 0 12 5.4 12 12v219.8c0 6.6-5.4 12-12 12z"/> </g> <g id="Layer_1"> <path id="XMLID_19_" className={colour} d="M147.5 79.1c0-37.6-30.4-68-68-68h-68v153.2c0 37.6 30.4 68 68 68h68V79.1z"/> </g> <g id="Layer_8"> <g id="XMLID_43_"> <g id="XMLID_38_"> <text id="XMLID_42_" transform="translate(13.747 35.452)" className="skip2 skip3 skip4">S</text> </g> <g id="XMLID_32_"> <text id="XMLID_36_" transform="translate(15.165 34.035)" className="skip5 skip3 skip4">S</text> </g> </g> </g> <g id="Layer_9"> <g id="XMLID_45_"> <g id="XMLID_33_"> <text id="XMLID_35_" transform="rotate(180 72.547 104.114)" className="skip2 skip3 skip4">S</text> </g> <g id="XMLID_29_"> <text id="XMLID_31_" transform="rotate(180 71.84 104.823)" className="skip5 skip3 skip4">S</text> </g> </g> </g> <g id="Layer_11"> <path id="XMLID_50_" className="skip6" d="M116.5 121.7c0 20.6-16.7 37.3-37.3 37.3s-37.3-16.7-37.3-37.3 16.7-37.3 37.3-37.3 37.3 16.7 37.3 37.3zm-76 38.6l38.6-38.6 39.1-42.5"/> </g> <g id="Layer_11_copy"> <g id="XMLID_52_"> <g id="XMLID_122_"> <path id="XMLID_123_" className="skip7" d="M119.3 124.5c0 20.6-16.7 37.3-37.3 37.3s-37.3-16.7-37.3-37.3S61.4 87.2 82 87.2s37.3 16.7 37.3 37.3zm-75.9 38.6L82 124.5 121 82"/> </g> <g id="XMLID_115_"> <path id="XMLID_116_" className="skip8" d="M116.5 121.7c0 20.6-16.7 37.3-37.3 37.3s-37.3-16.7-37.3-37.3 16.7-37.3 37.3-37.3 37.3 16.7 37.3 37.3zm-76 38.6l38.6-38.6 39.1-42.5"/> </g> </g> </g> </svg> ); } }
// +---------------------------------------------------------------------- // | ThinkJS-RABC [ ้€š็”จๆƒ้™็ฎก็†็ณป็ปŸ ] // +---------------------------------------------------------------------- // | Nanjing Digital Technology Co., Ltd. // +---------------------------------------------------------------------- // | Copyright (c) 2021 http://www.51-health.com All rights reserved. // +---------------------------------------------------------------------- // | Author: devlincms <devlincms@163.com> // +---------------------------------------------------------------------- // | Create: 2021-02-25 // +---------------------------------------------------------------------- 'use strict'; /** * model */ export default class extends think.model.base { /** * ๆŸฅๆ‰พ็”จๆˆทๆˆ–่€…็”จๆˆท็ป„ๆƒ้™ * @param {*} rid ็”จๆˆท็ป„ๆˆ–่€…็”จๆˆทID * @param {*} gstatus ็”จๆˆท่ฟ˜ๆ˜ฏ็”จๆˆท็ป„ */ async getRabcByGid(rid,gstatus){ let rabc = await this.model("rabc").where({rid:rid,gstatus:gstatus}).find(); let menu = []; if(!think.isEmpty(rabc)&&!think.isEmpty(rabc.mid)){ let u_rabc = rabc.mid.split(","); menu = await this.model("menu").findMenuByIdArr(u_rabc); } return menu; } /** * ๆŸฅๆ‰พ็”จๆˆทๆƒ้™๏ผˆๅŒ…ๅซๆ‰€ๅœจ็”จๆˆท็ป„๏ผ‰ * @param {*} uid */ async getUserRabc(uid){ let userGroup = await this.model("usergroup").getGroupByUserId(uid); let group_rabc_arr = []; if(!think.isEmpty(userGroup)){ let group_rabc = await this.model("rabc").where({rid:userGroup.id,gstatus:1}).find(); if(!think.isEmpty(group_rabc)&&!think.isEmpty(group_rabc.mid)){ group_rabc_arr = group_rabc.mid.split(","); } } let user_rabc = await this.model("rabc").where({rid:uid,gstatus:0}).find(); let user_rabc_arr = []; if(!think.isEmpty(user_rabc)&&!think.isEmpty(user_rabc.mid)){ user_rabc_arr = user_rabc.mid.split(","); } let all_rabc = group_rabc_arr.concat(user_rabc_arr); removeEmptyArrayEle(all_rabc); //ๆ•ฐ็ป„ๅŽป็ฉบ arr_unique(all_rabc); //ๆ•ฐ็ป„ๅŽป้‡ๅค //ๆŸฅๆ‰พๅฏนๅบ”่œๅ•ๆƒ้™ let menu = await this.model("menu").findMenuByIdArr(all_rabc); return menu; } /** * ๆƒ้™ๅˆ†้… * @param {*} rid ๅ…ณ่”็š„็”จๆˆทๆˆ–่€…็”จๆˆท็ป„ID * @param {*} mid ่œๅ•ID * @param {*} gstatus ็”จๆˆท่ฟ˜ๆ˜ฏ็”จๆˆท็ป„ */ async allocRabc(rid,mid,gstatus){ let rabc = await this.model("rabc").where({rid:rid,gstatus:gstatus}).find(); if(!think.isEmpty(rabc)){ return await this.model("rabc").where({rid:rid,gstatus:gstatus}).update({mid:mid}); } else{ return await this.model("rabc").add({ rid:rid, mid:mid, gstatus:gstatus }) } } }
/*eslint-env node, mocha */ /*eslint handle-callback-err:0, max-nested-callbacks:[2, 4], no-unused-expressions:0 */ 'use strict' var chai = require('chai') chai.use(require('chai-spies')) var expect = chai.expect var Promise = GLOBAL.Promise || require('es6-promise').Promise var net = require('net') var utils = require('../lib/utils') var TimeoutError = utils.TimeoutError var Pool = require('../lib/').Pool suite('Pool', function() { var Resource = function() {} test('instantiation', function(done) { var pool = new Pool({ create: function() { return new Resource } }) expect(pool.size).to.equal(2) var spy = chai.spy() pool.on('create', spy) setTimeout(function() { expect(spy).to.have.been.called.twice() expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.pool.forEach(function(resource) { expect(resource).to.be.an.instanceOf(Resource) }) done() }) }) test('instantiation with Promises', function(done) { var pool = new Pool({ create: function() { return new Promise(function(resolve) { setTimeout(function() { resolve(new Resource) }, 50) }) } }) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) done() }, 200) }) suite('Creation', function() { test('promise', function(done) { var pool = new Pool({ create: function() { return new Promise(function(resolve) { resolve(new Resource) }) } }) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) done() }, 300) }) test('callback', function(done) { var pool = new Pool({ create: function(callback) { callback(null, new Resource) } }) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) done() }, 300) }) test('retry', function(done) { var count = 0 var pool = new Pool({ create: function() { return new Promise(function(resolve, reject) { if (++count < 6) return reject() resolve(new Resource) }) } }) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) done() }, 300) }) }) suite('Destruction', function() { test('promise', function(done) { var pool = new Pool({ create: function() { return new Resource }, destroy: function() { return new Promise(function(resolve) { setTimeout(resolve, 50) }) } }) pool.opts.min = 1 setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.destroyResource(pool.pool[0]) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) done() }, 100) }) }) test('callback', function(done) { var pool = new Pool({ create: function() { return new Resource }, destroy: function(resource, callback) { callback() } }) pool.opts.min = 1 setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.destroyResource(pool.pool[0]) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) done() }, 100) }) }) test('reject', function(done) { var pool = new Pool({ create: function() { return new Resource }, destroy: function() { return new Promise(function(resolve, reject) { reject() }) } }) pool.opts.min = 1 setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.destroyResource(pool.pool[0]) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(2) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) done() }) }) }) test('timeout', function(done) { var pool = new Pool({ create: function() { return new Resource }, destroy: function() { return new Promise(function() {}) } }) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.on('fail', function onerror(err) { expect(err).to.be.an.instanceof(TimeoutError) pool.removeListener('fail', onerror) done() }) pool.destroyResource(pool.pool[0]) }) }) test('create after destroy if #resources < opts.min', function(done) { var pool = new Pool({ create: function() { return new Resource }, destroy: function() { return new Promise(function(resolve, reject) { reject() }) } }) setTimeout(function() { pool.destroyResource(pool.pool[0]) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(2) pool.on('create', function oncreate() { pool.removeListener('create', oncreate) expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) done() }) }) }) }) suite('Acquisition', function() { test('passing check', function(done) { var checked = 0 var pool = new Pool({ leakDetectionThreshold: 0, create: function() { return new Resource }, check: function() { checked++ return true } }) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) var acquire = pool.acquire() acquire.then(function(resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(2) expect(checked).to.equal(1) pool.acquire(function(err, resource) { expect(err).to.be.not.exist expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(2) expect(checked).to.equal(2) // pool.drain() done() }) }) .catch(done) }) }) test('failing check', function(done) { var checked = 0 var pool = new Pool({ leakDetectionThreshold: 0, create: function() { return new Resource }, check: function() { return ++checked > 1 } }) setTimeout(function() { expect(pool.pool.length).to.equal(2) expect(pool.size).to.equal(2) pool.opts.min = 0 pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) done() }) }) }) test('create if #resources < opts.max', function(done) { var pool = new Pool({ leakDetectionThreshold: 0, create: function() { return new Resource }, min: 0 }) setTimeout(function() { expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(0) pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) done() }) }) }) test('wait', function(done) { var pool = new Pool({ create: function() { return new Resource }, leakDetectionThreshold: 0, acquisitionTimeout: 0, min: 1, max: 1 }) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) pool.acquire(function() {}) expect(pool.queue).to.have.lengthOf(1) done() }) }) }) test('timeout', function(done) { var pool = new Pool({ create: function() { return new Promise(function() { // never ... }) }, min: 0, leakDetectionThreshold: 0, acquisitionTimeout: 500 }) pool.acquire() .catch(function(err) { expect(err).to.be.an.instanceOf(TimeoutError) // with callback pool.acquire(function(err, resource) { expect(err).to.be.an.instanceOf(TimeoutError) expect(resource).to.not.exist pool.drain() done() }) }) }) }) suite('Releasing', function() { test('add back', function(done) { var pool = new Pool({ create: function() { return new Resource }, min: 1, max: 1 }) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) pool.release(resource) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) done() }) }) }) }) test('forward', function(done) { var pool = new Pool({ create: function() { return new Resource }, min: 1, max: 1, leakDetectionThreshold: 0 }) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) pool.acquire(function(err, res) { expect(resource).to.equal(res) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) done() }) expect(pool.queue).to.have.lengthOf(1) pool.release(resource) }) }) }) test('return', function(done) { var pool = new Pool({ create: function() { return new Resource }, min: 1, max: 1 }) setTimeout(function() { expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) pool.acquire(function(err, resource) { expect(resource).to.be.an.instanceOf(Resource) expect(pool.pool.length).to.equal(0) expect(pool.size).to.equal(1) pool.release(resource) expect(pool.pool.length).to.equal(1) expect(pool.size).to.equal(1) done() }) }) }) }) }) var Balancer = require('../lib/').Balancer suite('Balancer', function() { var first, second, third var balancer, a, b, c suiteSetup(function(done) { var count = 3, cb = function() { if (--count === 0) done() } function handler(socket) { socket.setEncoding('utf8') socket.on('data', function(data) { expect(data).to.equal('ping') socket.write('pong') }) } first = net.createServer(handler) first.listen(4001, cb) second = net.createServer(handler) second.listen(4002, cb) third = net.createServer(handler) third.listen(4003, cb) }) suiteTeardown(function() { balancer.shutdown() first.close() second.close() third.close() }) var opts = { min: 0, max: 2, leakDetectionThreshold: 0, create: function(port) { return new Promise(function(resolve) { var socket = net.connect(port, function() { resolve(socket) }) socket.setEncoding('utf8') socket.setTimeout(300000) }) }, destroy: function(socket) { return new Promise(function(resolve) { if (!socket.localPort) resolve() else socket.end(resolve) }) }, check: function(socket) { return !!socket.localPort } } test('instantiation', function() { balancer = new Balancer balancer.add(a = new Pool('4001', opts, 4001), 1) balancer.add(b = new Pool('4002', opts, 4002), 2) balancer.add(c = new Pool('4003', opts, 4003), 2) }) test('balancing', function() { expect(balancer.next()).to.equal(a) expect(balancer.next()).to.equal(a) expect(balancer.next()).to.equal(a) a.healthy = false expect(balancer.next()).to.equal(b) expect(balancer.next()).to.equal(c) expect(balancer.next()).to.equal(b) expect(balancer.next()).to.equal(c) expect(balancer.next()).to.equal(b) expect(balancer.next()).to.equal(c) a.healthy = true expect(balancer.next()).to.equal(a) }) test('acquire', function(done) { balancer.acquire(function(err, resource) { expect(err).to.not.exist expect(resource).to.be.an.instanceOf(net.Socket) balancer.release(resource) done() }) }) test('release', function(done) { expect(a.size).to.equal(1) expect(a.pool).to.have.lengthOf(1) a.pool[0].end() setTimeout(done, 500) }) test('fail create -> mark pool as unhealthy', function(done) { a.opts.create = function() { return new Promise(function(resolve, reject) { reject() }) } balancer.opts.check = function() { return false } balancer.acquire(function(err, resource) { expect(resource.remotePort).to.equal(4002) expect(a.size).to.equal(0) expect(a.pool).to.have.lengthOf(0) expect(a.healthy).to.be.not.ok balancer.release(resource) done() }) }) test('monitor unhealthy pool', function(done) { balancer.opts.check = function() { return true } setTimeout(function() { expect(a.healthy).to.be.ok done() }, 100) }) test('acquire timeout', function(done) { var b = new Balancer({ acquisitionTimeout: 500 }) b.add(new Pool('4001', { create: function() { return new Promise(function() { }) } }, 4001), 1) b.acquire() .catch(function(err) { expect(err).to.be.an.instanceOf(TimeoutError) // with callback b.acquire(function(err, resource) { expect(err).to.be.an.instanceOf(TimeoutError) expect(resource).to.not.exist b.shutdown() done() }) }) }) test('all down', function(done) { a.healthy = b.healthy = c.healthy = false balancer.opts.check = function() { return false } balancer.acquire(function(err, resource) { expect(err).to.exist expect(err).to.be.an.instanceof(Balancer.UnavailableError) expect(err.message).to.equal('All servers are down') expect(resource).to.not.exist done() }) }) test('acquire with no pool', function(done) { var b = new Balancer b.acquire(function(err, resource) { expect(err).to.exist expect(err.message).to.equal('Balancer is empty - add pools first: `balancer.add(new Pool(...))`') expect(resource).to.not.exist done() }) }) })
'use strict'; import behaviour from './behaviour.js'; /** * Mixin Delegate * @type {object} */ export default { /** * Provides mixin behaviours for `object` * @param {object} object * @returns {*} */ provide: function(object) { return Object.assign(object, behaviour); }, /** * Creates mixin applier * @param {object} mixinObject * @param {string} initMethod * @returns {Function} */ create: function(mixinObject, initMethod = null) { return function(object, call = true) { Object.assign(object, mixinObject); if (call && initMethod) object[initMethod](); return object; } } };
/* * Iterable is used internally to provide functional style methods to indexed collections. * The contract a collection must follow to inherit from Iterable is: * - Exposing a property named items, the Array representation of the collection. * - Either specify a fromArray method or override _createNew so that new collections * can be built from an existing instance. * * None of the Iterable methods mutates the collection. * * For any method accepting a callback or predicate as a parameter, you need to ensure * the value of 'this' inside the method is either bound or not used. */ var Iterable = function() {}; /* * The current Array representation of the collection. * It should be considered read-only and never modified directly. */ Iterable.prototype.items = null; /* * Returns the number of items in this collection. */ Iterable.prototype.size = function() { return this.items.length; }; /* * Indicates whether this collection is empty. */ Iterable.prototype.isEmpty = function() { return this.size() == 0; }; /* * Returns the item located at the specified index. */ Iterable.prototype.itemAt = function(index) { return this.items[index]; }; /* * Returns the first item of this collection. */ Iterable.prototype.first = function() { return this.items[0]; }; /* * Returns the last item of this collection. */ Iterable.prototype.last = function() { return this.items[this.items.length - 1]; }; /* * Applies a function to all items of this collection. */ Iterable.prototype.each = function(callback) { for (var i = 0, length = this.items.length; i < length; i++) { this._invoke(callback, i, i); } }; /* * Builds a new collection by applying a function to all items of this collection. * * ArrayMap will require that you return [key, value] tuples to create a new ArrayMap. * * Note: If you intended to invoke filter and map in succession * you can merge these operations into just one map() call * by returning Collection.NOT_MAPPED for the items that shouldn't be in the final collection. */ Iterable.prototype.map = function(callback) { var result = []; for (var i = 0, length = this.items.length; i < length; i++) { var mapped = this._invoke(callback, i); if (mapped != Collection.NOT_MAPPED) result.push(mapped); } return this._createNew(result); }; Collection.NOT_MAPPED = {}; /* * Builds a List of the extracted properties of this collection of objects. * This is a special case of map(). The property can be arbitrarily nested. */ Iterable.prototype.pluck = function(property) { var doPluck = getPluckFunction(property); var result = []; for (var i = 0, length = this.items.length; i < length; i++) { result.push(doPluck(this.items[i])); } return List.fromArray(result); } /* * Selects all items of this collection which satisfy a predicate. */ Iterable.prototype.filter = function(predicate) { var result = []; for (var i = 0, length = this.items.length; i < length; i++) { if (this._invoke(predicate, i)) result.push(this.items[i]); } return this._createNew(result); }; /* * Counts the number of items in this collection which satisfy a predicate. */ Iterable.prototype.count = function(predicate) { var count = 0; for (var i = 0, length = this.items.length; i < length; i++) { if (this._invoke(predicate, i)) count++; } return count; }; /* * Finds the first item of the collection satisfying a predicate, if any. */ Iterable.prototype.find = function(predicate) { for (var i = 0, length = this.items.length; i < length; i++) { if (this._invoke(predicate, i)) return this.items[i]; } return undefined; }; /* * Finds the first item of this collection of objects that owns a property set to a given value. * This is a special case of find(). The property can be arbitrarily nested. */ Iterable.prototype.findBy = function(property, value) { var doPluck = getPluckFunction(property); for (var i = 0, length = this.items.length; i < length; i++) { if (doPluck(this.items[i]) === value) return this.items[i]; } return undefined; }; /* * Tests whether a predicate holds for some of the items of this collection. */ Iterable.prototype.some = function(predicate) { for (var i = 0, length = this.items.length; i < length; i++) { if (this._invoke(predicate, i)) return true; } return false; }; /* * Tests whether a predicate holds for all items of this collection. */ Iterable.prototype.every = function(predicate) { for (var i = 0, length = this.items.length; i < length; i++) { if (!this._invoke(predicate, i)) return false; } return true; }; /* * Partitions items in fixed size collections. */ Iterable.prototype.grouped = function(size) { var groups = []; var current = []; for (var i = 0, length = this.items.length; i < length; i++) { current.push(this.items[i]); if ((current.length === size) || (i === length - 1)) { groups[groups.length] = this._createNew(current); current = []; } } return List.fromArray(groups); }; /* * Partitions this collection into a map of Lists according to a discriminator function. */ Iterable.prototype.groupBy = function(discriminator) { var groups = Map(); for (var i = 0, length = this.items.length; i < length; i++) { var item = this.items[i]; var itemGroup = this._invoke(discriminator, i); var group = groups.get(itemGroup); if (!group) groups.put(itemGroup, List()); groups.get(itemGroup).add(item); } return groups; }; /* * Folds the items of this collection using the specified operator. */ Iterable.prototype.fold = function(initialValue, operator) { var result = initialValue; for (var i = 0, length = this.items.length; i < length; i++) { result = this._invoke(operator, i, result); } return result; }; /* * Partitions this collection in two collections according to a predicate. * The first element of the returned Array contains the items that satisfied the predicate. */ Iterable.prototype.partition = function(predicate) { var yes = [], no = []; for (var i = 0, length = this.items.length; i < length; i++) { (this._invoke(predicate, i) ? yes : no).push(this.items[i]); } return [this._createNew(yes), this._createNew(no)]; }; /* * Selects all items except the first n ones. */ Iterable.prototype.drop = function(n) { n = Math.min(n, this.items.length); return this._createNew(this.items.slice(n)); }; /* * Selects all items except the last n ones. */ Iterable.prototype.dropRight = function(n) { n = Math.min(n, this.items.length); return this._createNew(this.items.slice(0, this.items.length - n)); }; /* * Drops items till the predicate no longer hold. */ Iterable.prototype.dropWhile = function(predicate) { var result = this.items.slice(); var index = 0; while (result.length && this._invoke(predicate, index)) { result.shift(); index++; } return this._createNew(result); }; /* * Selects the first n items. */ Iterable.prototype.take = function(n) { n = Math.min(n, this.items.length); return this._createNew(this.items.slice(0, n)); }; /* * Selects the last n items. */ Iterable.prototype.takeRight = function(n) { n = Math.min(n, this.items.length); return this._createNew(this.items.slice(-n)); }; /* * Selects items till the predicate no longer hold. */ Iterable.prototype.takeWhile = function(predicate) { var result = []; for (var i = 0, length = this.items.length; i < length; i++) { if (this._invoke(predicate, i)) result.push(this.items[i]); else break; } return this._createNew(result); }; /* * Returns a new collection with the items in reversed order. */ Iterable.prototype.reverse = function() { return this._createNew(this.items.slice().reverse()); }; /* * Selects an interval of items. */ Iterable.prototype.slice = function(start, end) { return this._createNew(this.items.slice(start, end)); }; /* * Returns a new sorted collection. * The sort is stable. * * An option Object can be passed to modify the sort behavior. * All options are compatible with each other. * The supported options are: * * ignoreCase: Assuming strings are going to be sorted, ignore their cases. Defaults to false. * * localCompare: Assuming strings are going to be sorted, * handle locale-specific characters correctly at the cost of reduced sort speed. Defaults to false. * * by: Assuming objects are being sorted, a String (See pluck) or Function either pointing to or computing the value * that should be used for the sort. Defaults to null. * * reverse: Reverse the sort. Defaults to false. */ Iterable.prototype.sorted = function(options) { var o = options || {}, by = o.by !== undefined ? o.by : null, localeCompare = o.localeCompare !== undefined ? o.localeCompare : false, ignoreCase = o.ignoreCase !== undefined ? o.ignoreCase : false, reverse = o.reverse !== undefined ? o.reverse : false, result = [], mapped = [], missingData = [], sortFunction, item; if (isString(by)) by = getPluckFunction(by); for (var i = 0, length = this.items.length; i < length; i++) { item = this.items[i]; if (by && item) item = by(item); if (item === null || item === undefined || item === '') { missingData.push(item); continue; } if (ignoreCase) item = item.toUpperCase(); mapped.push({ index: i, value: item }); } if (localeCompare) { sortFunction = function(a, b) { if (a.value !== b.value) { return a.value.localeCompare(b.value); } return a.index < b.index ? -1 : 1; }; } else { sortFunction = function(a, b) { if (a.value !== b.value) { return (a.value < b.value) ? -1 : 1; } return a.index < b.index ? -1 : 1; }; } mapped.sort(sortFunction); for (var i = 0, length = mapped.length; i < length; i++) { result.push(this.items[mapped[i].index]); } if (missingData.length) result = result.concat(missingData); if (reverse) result.reverse(); return this._createNew(result); }; /* * Displays all items of this collection as a string. */ Iterable.prototype.mkString = function(start, sep, end) { return start + this.items.join(sep) + end; }; /* * Converts this collection to a List. */ Iterable.prototype.toList = function() { return List.fromArray(this.items); }; /* * Converts this collection to an Array. * If you do not require a new Array instance, consider using the items property instead. */ Iterable.prototype.toArray = function() { return cloneArray(this.items); }; /* * Creates a (shallow) copy of this collection. */ Iterable.prototype.clone = function() { return this._createNew(this.items.slice()); }; Iterable.prototype.toString = function() { return this.constructor.typeName + '(' + this.items.join(', ') + ')'; }; /** * Creates a new Iterable of the same kind but with a specific set of items. * The default implementation simply delegates to the type constructor's fromArray factory method. * Some iterables may override this method to better prepare the newly created instance. */ Iterable.prototype._createNew = function(array) { return this.constructor.fromArray(array); }; /** * Invokes a function for a particular item index. * This indirection is required as different clients of Iterable may require * the callbacks and predicates to be called with a specific signature. For instance, * an associative collection would invoke the function with a key and a value as parameters. * This default implementation simply call the function with the current item. */ Iterable.prototype._invoke = function(func, forIndex, extraParam) { return func(this.items[forIndex], extraParam); }; var getPluckFunction = function(property) { var propertyChain = property.split('.'); if (propertyChain.length == 1) return function(item) { return item[propertyChain[0]]; }; else return function(item) { var i = 0, currentContext = item, length = propertyChain.length; while (i < length) { if (currentContext == null && i != length) return undefined; currentContext = currentContext[propertyChain[i]]; i++; } return currentContext; }; }; Collection.Iterable = Iterable;
/** * @file ็Ÿฉๅฝข่ฝฌๆขๆˆ่ฝฎๅป“ * @author mengke01(kekee000@gmail.com) */ /** * ็Ÿฉๅฝข่ฝฌๆขๆˆ่ฝฎๅป“ * * @param {number} x ๅทฆไธŠ่ง’x * @param {number} y ๅทฆไธŠ่ง’y * @param {number} width ๅฎฝๅบฆ * @param {number} height ้ซ˜ๅบฆ * @return {Array} ่ฝฎๅป“ๆ•ฐ็ป„ */ export default function rect2contour(x, y, width, height) { x = +x; y = +y; width = +width; height = +height; return [ { x, y, onCurve: true }, { x: x + width, y, onCurve: true }, { x: x + width, y: y + height, onCurve: true }, { x, y: y + height, onCurve: true } ]; }