code
stringlengths
2
1.05M
import React from 'react'; const Footer = () => <p>Footer</p>; export default Footer;
/* License: MIT. * Copyright (C) 2013, 2014, Uri Shaked. */ 'use strict'; module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'angular-moment.js', 'tests.js' ] }, uglify: { dist: { files: { 'angular-moment.min.js': 'angular-moment.js' } } } }); grunt.registerTask('test', [ 'jshint', 'karma' ]); grunt.registerTask('build', [ 'jshint', 'uglify' ]); grunt.registerTask('default', ['build']); };
'use strict' const { lt, inRange } = require('lodash') module.exports = boardSize => { if (lt(boardSize, 70)) return '<70l' if (inRange(boardSize, 70, 80)) return '70l to 80l' if (inRange(boardSize, 80, 90)) return '80l to 90l' if (inRange(boardSize, 90, 100)) return '90l to 100l' if (inRange(boardSize, 100, 110)) return '100l to 110l' if (inRange(boardSize, 110, 120)) return '110l to 120l' if (inRange(boardSize, 120, 130)) return '120l to 130l' return '>130l' }
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Choices', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, QuestionId: { type: Sequelize.UUID }, text: { type: Sequelize.TEXT }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Choices'); } };
#!/usr/bin/env node var express = require('express'), package = require('./package.json'), program = require('commander'), _ = require('underscore'), Assets = require('./lib/assets.js'); program .version(package.version) .option('-s, --store <store>', 'Location of storage') .option('-u, --url <url>', 'Base url', '/store') .parse(process.argv); if (!program.store) program.help(); var assets = new Assets(program.store), app = express(); app.get(program.url + '/:id', /** * GET asset meta information * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {json} Meta information about asset */ function(req, res) { assets .get(req.params.id) .done(function(asset) { res.json(asset); }, function() { res.json(404, {error: 'Asset not found'}); }); } ); app.get(program.url + '/data/:id', /** * GET asset data * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {file|redirect} File associated with asset or redirect to server * that has the file */ function(req, res) { assets .getData(req.params.id) .done(function(file) { res.download(file.path, file.name); }, function() { res.json(404, {error: 'Asset not found'}); }); } ); app.post(program.url, [express.json(), express.multipart()], /** * POST asset meta information and data * * @param {Object} req * @prop {Object} files Uploaded files * * @returns {json} Meta information about asset */ function(req, res) { assets .fromUploads(req.files) .done(function() { res.send(''); }, function(err) { res.send(500, {error: 'Upload failed', raw_error: err}); }); } ); app.put(program.url + '/:id', [express.json(), express.multipart()], /** * PUT asset meta information * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * @prop {Object} files Uploaded files * * @returns {json} Meta information about asset */ function(req, res) { assets.put(req.params.id, file); } ); app.delete(program.url + '/:id', /** * DELETE asset * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {json} Meta information about asset */ function(req, res) { assets.delete(req.params.id); } ); assets .init(true) .then(function() { app.listen(3001); console.log('Listening on port 3001'); });
export default { data () { return { selected: null, options: [ { id: 1, label: 'Richard Hendricks' }, { id: 2, label: 'Bertram Gilfoyle' }, { id: 3, label: 'Dinesh Chugtai' }, { id: 4, label: 'Jared Dunn', disabled: true }, { id: 5, label: 'Erlich Bachman', disabled: true } ] }; } };
'use strict'; describe('Service: mainService', function () { // load the service's module beforeEach(module('catsGoApp')); // instantiate service var mainService; beforeEach(inject(function (_mainService_) { mainService = _mainService_; })); it('randomArray testing', function () { var a=mainService.randomArray(4,5,1); expect(a).not.toBe(null) expect(!!mainService).toBe(true); }); });
export default { props: { things: [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 5, name: 'e' } ] }, html: ` <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div>e</div> `, test({ assert, component, raf }) { let divs = document.querySelectorAll('div'); divs.forEach(div => { div.getBoundingClientRect = function() { const index = [...this.parentNode.children].indexOf(this); const top = index * 30; return { left: 0, right: 100, top, bottom: top + 20 }; }; }); component.things = [ { id: 5, name: 'e' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 1, name: 'a' } ]; divs = document.querySelectorAll('div'); assert.equal(divs[0].dy, 120); assert.equal(divs[4].dy, -120); raf.tick(50); assert.equal(divs[0].dy, 60); assert.equal(divs[4].dy, -60); raf.tick(100); assert.equal(divs[0].dy, 0); assert.equal(divs[4].dy, 0); } };
import React, {Component} from 'react'; import { Router, IndexRoute, Route, browserHistory } from 'react-router'; import UserCard from './UserCard'; import firebase from './firebase'; import NewContact from './NewContact'; class UserCards extends Component { constructor() { super(); this.state = { contacts: [] }; this.contactsArray = []; } get baseContactReference() { return firebase.database().ref(`baseContact/${firebase.auth().currentUser.uid}/`); } componentDidMount() { this.baseContactReference.on('child_added', (snapshot) => { const newContactCard = snapshot.val(); var contactArr = { fullName: newContactCard.fullName, company:newContactCard.company, id: newContactCard.id, email: newContactCard.email, followUp: newContactCard.followUp }; this.contactsArray.push(contactArr); this.setState({ contacts: this.contactsArray }); }); } componentWillUnmount() { this.baseContactReference.off(); } loadCards() { return this.state.contacts.map(contact => { return( <div className="contactInfoCard hello" key={contact.id}> <UserCard contact={contact} email={contact.email}/> </div> ) }) } render(){ return( <div className="user-cards"> {this.loadCards()} </div> ) } } export default UserCards
var urls = [ "https://vk.com/igor.suvorov", "https://twitter.com/suvorovigor", "https://telegram.me/skillbranch", "@skillbranch", "https://vk.com/skillbranch?w=wall-117903599_1076",]; function getName(url) { const reg = /(@|\/)?[\w\9.]+/ig; const reg1 = /[\w\9.]+/ig; const matches = url.match(reg); console.log(matches); // return "@"+matches[matches.length-1]; return "@"+matches[matches.length-1].match(reg1); } export default function canonize(url) { return getName(url); }
version https://git-lfs.github.com/spec/v1 oid sha256:8a773d7f07d6a2ce3c6379427f1a5aa12f7545b4da9579eae9b6a31ec13a11b7 size 43336
import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import fetchMock from 'fetch-mock'; import { fetchLogin, testing, } from './login'; const mockStore = configureMockStore([thunk]); beforeEach(() => { fetchMock.restore(); }); test('fetch login with success', done => { fetchMock.post(`${testing.base_url}/auth/login/`, { status: 200, body: {success: true}, }); const store = mockStore(); const expectedActions = [ testing.fetchLoginSuccess(), ]; const email = "[email protected]"; const password = "pippo"; return store.dispatch(fetchLogin(email, password)) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); }); test('fetch login failure', done => { fetchMock.post(`${testing.base_url}/auth/login/`, { status: 401, body: {}, }); const store = mockStore(); const expectedActions = [ testing.fetchLoginFailure(), ]; const email = "[email protected]"; const password = "pippo"; return store.dispatch(fetchLogin(email, password)) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('keyboard-navigable-list', 'Integration | Component | keyboard navigable list', { integration: true }); test('if passed in an array it renders the items in a list.', function(assert) { //this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.set('theArray', [1, 2, 3]); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{keyboard-navigable-list contentArray=theArray}}`); assert.equal(this.$('ul[data-parent-ul] > li').length, 3, 'it renders the proper number of items'); assert.equal(this.$('ul[data-parent-ul] > li').first().text().trim(), 1, 'the first item is 1'); assert.equal(this.$('ul[data-parent-ul] > li').last().text().trim(), 3, 'the last item is 3'); }); test('if passed in an array contains an object key it displays that property on the object.', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name"}}`); assert.equal(this.$('ul[data-parent-ul] > li').first().text().trim(), 'hello', 'the first item is hello'); assert.equal(this.$('ul[data-parent-ul] > li').last().text().trim(), 'third item', 'the last item is third item'); }); test('after the component loads no li item has the class of active', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name"}}`); assert.equal(this.$('li.active').length, 0, 'by default no one is active'); }); test('if linkDirection is set, hasLink is true and a link is present', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name" linkDirection='people.show'}}`); assert.equal(this.$('ul[data-parent-ul] > li:eq(0) > a').length, 1, 'if there is a linkDirection there is a link'); }); test('if used as a block level component it gives you access to the individual items in the array', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{#keyboard-navigable-list contentArray=theArray as |person|}} {{person.name}} {{/keyboard-navigable-list}}`); assert.equal(this.$('ul[data-parent-ul] > li:eq(0)').text().trim(), 'hello', 'we have access to the items from the yield'); });
define(['knockout', 'Q', 'model', 'css!mediaelement-css', 'css!dataTables-bootstrap-css', 'css!datatables-scroller-css', 'text!./mim-video-playlist.html', 'datatables', 'knockout.punches', 'mediaelement', 'datatables-bootstrap', 'datatables-scroller'], function (ko, Q, model, css, dataTablesBootstrapCss,datatablesScrollerCss, templateMarkup) { function MimVideoPlaylist(params) { var self = this; self.urlBaseVideo = 'videoDirectory/'; self.urlApi = 'Api/'; self.videoSuffix = '.mp4'; self.videoSuffix = '.jpg'; self.isVideoDataLoaded = ko.observable(false); self.url = { getVideoList: self.urlApi + 'video' }; self.list = ko.observableArray([]); self.list0 = ko.observableArray([]); self.fileName = ko.observable(); self.posterFileName = ko.observable(); self.isVideoVisible = ko.observable(false); self.mustPlay = ko.observable(false); self.playOnRender = ko.observable(false); self.playerAssign = function () { delete self.player; self.player = $('#videoContent').mediaelementplayer({ alwaysShowControls: false, features: ['playpause', 'volume'], success: function (mediaElement, domObject) { if (self.mustPlay()) mediaElement.play(); }, error: function (data) { } }); }; self.playlistClick = function (data) { self.isVideoVisible(false); self.fileName(data.video); ko.utils.arrayForEach(self.list(), function (item) { item.isPlaying(false) }); data.isPlaying(true); self.posterFileName(data.poster); self.mustPlay(true); self.isVideoVisible(true); return true; } self.player = null; self.mapping = { create: function (options) { var vmCreate = ko.mapping.fromJS(options.data, { 'ignore': ['Video','Title'] }); vmCreate.isPlaying = ko.observable(false); vmCreate.isNotPlaying = ko.pureComputed(function () { return !vmCreate.isPlaying(); }); vmCreate.poster = self.urlBaseVideo+ options.data.Video + self.posterSuffix vmCreate.video = self.urlBaseVideo + options.data.Video + self.videoSuffix; vmCreate.title = options.data.Title; return vmCreate; } }; self.initModel = function () { Q(model.post(self.url.getVideoList)) .then(function (data) { ko.mapping.fromJS(data.d, self.mapping, self.list); self.fileName(self.list()[0].video); self.posterFileName(self.list()[0].poster); self.isVideoDataLoaded(true); }); } self.initView = function () { $('#mim-playlist-innner').DataTable( { responsive: true, "deferRender": true, "jQueryUI": false, "sDom": 't', dom: "S", "sScrollY": "360px", scrollCollapse: true, "deferRender": true, "autoWidth": true, "autoHigh": false, searching: false, ordering: false, "info": false, }); $('#mim-playlist-innner').removeClass('display').addClass('table table-striped table-bordered'); $('.dataTables_scrollBody').css('height', 360); $('.dataTables_scrollBody').css('width', '100%'); }; ko.punches.enableAll(); self.initModel(); self.initView(); self.isVideoVisible(true); } MimVideoPlaylist.prototype.dispose = function() { }; return { viewModel: MimVideoPlaylist, template: templateMarkup }; });
import { encode } from 'vlq'; function Chunk ( start, end, content ) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; // we make these non-enumerable, for sanity while debugging Object.defineProperties( this, { previous: { writable: true, value: null }, next: { writable: true, value: null } }); } Chunk.prototype = { appendLeft: function appendLeft ( content ) { this.outro += content; }, appendRight: function appendRight ( content ) { this.intro = this.intro + content; }, clone: function clone () { var chunk = new Chunk( this.start, this.end, this.original ); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; }, contains: function contains ( index ) { return this.start < index && index < this.end; }, eachNext: function eachNext ( fn ) { var chunk = this; while ( chunk ) { fn( chunk ); chunk = chunk.next; } }, eachPrevious: function eachPrevious ( fn ) { var chunk = this; while ( chunk ) { fn( chunk ); chunk = chunk.previous; } }, edit: function edit ( content, storeName, contentOnly ) { this.content = content; if ( !contentOnly ) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; }, prependLeft: function prependLeft ( content ) { this.outro = content + this.outro; }, prependRight: function prependRight ( content ) { this.intro = content + this.intro; }, split: function split ( index ) { var sliceIndex = index - this.start; var originalBefore = this.original.slice( 0, sliceIndex ); var originalAfter = this.original.slice( sliceIndex ); this.original = originalBefore; var newChunk = new Chunk( index, this.end, originalAfter ); newChunk.outro = this.outro; this.outro = ''; this.end = index; if ( this.edited ) { // TODO is this block necessary?... newChunk.edit( '', false ); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if ( newChunk.next ) { newChunk.next.previous = newChunk; } newChunk.previous = this; this.next = newChunk; return newChunk; }, toString: function toString () { return this.intro + this.content + this.outro; }, trimEnd: function trimEnd ( rx ) { this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return true; } var trimmed = this.content.replace( rx, '' ); if ( trimmed.length ) { if ( trimmed !== this.content ) { this.split( this.start + trimmed.length ).edit( '', false ); } return true; } else { this.edit( '', false ); this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return true; } } }, trimStart: function trimStart ( rx ) { this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return true; } var trimmed = this.content.replace( rx, '' ); if ( trimmed.length ) { if ( trimmed !== this.content ) { this.split( this.end - trimmed.length ); this.edit( '', false ); } return true; } else { this.edit( '', false ); this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return true; } } } }; var _btoa; if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) { _btoa = window.btoa; } else if ( typeof Buffer === 'function' ) { _btoa = function (str) { return new Buffer( str ).toString( 'base64' ); }; } else { _btoa = function () { throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' ); }; } var btoa = _btoa; function SourceMap ( properties ) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = properties.mappings; } SourceMap.prototype = { toString: function toString () { return JSON.stringify( this ); }, toUrl: function toUrl () { return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() ); } }; function guessIndent ( code ) { var lines = code.split( '\n' ); var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } ); var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } ); if ( tabbed.length === 0 && spaced.length === 0 ) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if ( tabbed.length >= spaced.length ) { return '\t'; } // Otherwise, we need to guess the multiple var min = spaced.reduce( function ( previous, current ) { var numSpaces = /^ +/.exec( current )[0].length; return Math.min( numSpaces, previous ); }, Infinity ); return new Array( min + 1 ).join( ' ' ); } function getRelativePath ( from, to ) { var fromParts = from.split( /[\/\\]/ ); var toParts = to.split( /[\/\\]/ ); fromParts.pop(); // get dirname while ( fromParts[0] === toParts[0] ) { fromParts.shift(); toParts.shift(); } if ( fromParts.length ) { var i = fromParts.length; while ( i-- ) { fromParts[i] = '..'; } } return fromParts.concat( toParts ).join( '/' ); } var toString$1 = Object.prototype.toString; function isObject ( thing ) { return toString$1.call( thing ) === '[object Object]'; } function getLocator ( source ) { var originalLines = source.split( '\n' ); var start = 0; var lineRanges = originalLines.map( function ( line, i ) { var end = start + line.length + 1; var range = { start: start, end: end, line: i }; start = end; return range; }); var i = 0; function rangeContains ( range, index ) { return range.start <= index && index < range.end; } function getLocation ( range, index ) { return { line: range.line, column: index - range.start }; } return function locate ( index ) { var range = lineRanges[i]; var d = index >= range.end ? 1 : -1; while ( range ) { if ( rangeContains( range, index ) ) { return getLocation( range, index ); } i += d; range = lineRanges[i]; } }; } function Mappings ( hires ) { var this$1 = this; var offsets = { generatedCodeColumn: 0, sourceIndex: 0, sourceCodeLine: 0, sourceCodeColumn: 0, sourceCodeName: 0 }; var generatedCodeLine = 0; var generatedCodeColumn = 0; this.raw = []; var rawSegments = this.raw[ generatedCodeLine ] = []; var pending = null; this.addEdit = function ( sourceIndex, content, original, loc, nameIndex ) { if ( content.length ) { rawSegments.push([ generatedCodeColumn, sourceIndex, loc.line, loc.column, nameIndex ]); } else if ( pending ) { rawSegments.push( pending ); } this$1.advance( content ); pending = null; }; this.addUneditedChunk = function ( sourceIndex, chunk, original, loc, sourcemapLocations ) { var originalCharIndex = chunk.start; var first = true; while ( originalCharIndex < chunk.end ) { if ( hires || first || sourcemapLocations[ originalCharIndex ] ) { rawSegments.push([ generatedCodeColumn, sourceIndex, loc.line, loc.column, -1 ]); } if ( original[ originalCharIndex ] === '\n' ) { loc.line += 1; loc.column = 0; generatedCodeLine += 1; this$1.raw[ generatedCodeLine ] = rawSegments = []; generatedCodeColumn = 0; } else { loc.column += 1; generatedCodeColumn += 1; } originalCharIndex += 1; first = false; } pending = [ generatedCodeColumn, sourceIndex, loc.line, loc.column, -1 ]; }; this.advance = function (str) { if ( !str ) { return; } var lines = str.split( '\n' ); var lastLine = lines.pop(); if ( lines.length ) { generatedCodeLine += lines.length; this$1.raw[ generatedCodeLine ] = rawSegments = []; generatedCodeColumn = lastLine.length; } else { generatedCodeColumn += lastLine.length; } }; this.encode = function () { return this$1.raw.map( function (segments) { var generatedCodeColumn = 0; return segments.map( function (segment) { var arr = [ segment[0] - generatedCodeColumn, segment[1] - offsets.sourceIndex, segment[2] - offsets.sourceCodeLine, segment[3] - offsets.sourceCodeColumn ]; generatedCodeColumn = segment[0]; offsets.sourceIndex = segment[1]; offsets.sourceCodeLine = segment[2]; offsets.sourceCodeColumn = segment[3]; if ( ~segment[4] ) { arr.push( segment[4] - offsets.sourceCodeName ); offsets.sourceCodeName = segment[4]; } return encode( arr ); }).join( ',' ); }).join( ';' ); }; } var Stats = function Stats () { Object.defineProperties( this, { startTimes: { value: {} } }); }; Stats.prototype.time = function time ( label ) { this.startTimes[ label ] = process.hrtime(); }; Stats.prototype.timeEnd = function timeEnd ( label ) { var elapsed = process.hrtime( this.startTimes[ label ] ); if ( !this[ label ] ) { this[ label ] = 0; } this[ label ] += elapsed[0] * 1e3 + elapsed[1] * 1e-6; }; var warned = { insertLeft: false, insertRight: false, storeName: false }; function MagicString$1 ( string, options ) { if ( options === void 0 ) options = {}; var chunk = new Chunk( 0, string.length, string ); Object.defineProperties( this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: {} }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: guessIndent( string ) } }); this.byStart[ 0 ] = chunk; this.byEnd[ string.length ] = chunk; } MagicString$1.prototype = { addSourcemapLocation: function addSourcemapLocation ( char ) { this.sourcemapLocations[ char ] = true; }, append: function append ( content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); } this.outro += content; return this; }, appendLeft: function appendLeft ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byEnd[ index ]; if ( chunk ) { chunk.appendLeft( content ); } else { this.intro += content; } return this; }, appendRight: function appendRight ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byStart[ index ]; if ( chunk ) { chunk.appendRight( content ); } else { this.outro += content; } return this; }, clone: function clone () { var cloned = new MagicString$1( this.original, { filename: this.filename }); var originalChunk = this.firstChunk; var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); while ( originalChunk ) { cloned.byStart[ clonedChunk.start ] = clonedChunk; cloned.byEnd[ clonedChunk.end ] = clonedChunk; var nextOriginalChunk = originalChunk.next; var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if ( nextClonedChunk ) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if ( this.indentExclusionRanges ) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } Object.keys( this.sourcemapLocations ).forEach( function (loc) { cloned.sourcemapLocations[ loc ] = true; }); return cloned; }, generateMap: function generateMap ( options ) { var this$1 = this; options = options || {}; var sourceIndex = 0; var names = Object.keys( this.storedNames ); var mappings = new Mappings( options.hires ); var locate = getLocator( this.original ); if ( this.intro ) { mappings.advance( this.intro ); } this.firstChunk.eachNext( function (chunk) { var loc = locate( chunk.start ); if ( chunk.intro.length ) { mappings.advance( chunk.intro ); } if ( chunk.edited ) { mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 ); } else { mappings.addUneditedChunk( sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations ); } if ( chunk.outro.length ) { mappings.advance( chunk.outro ); } }); var map = new SourceMap({ file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ), sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ], sourcesContent: options.includeContent ? [ this.original ] : [ null ], names: names, mappings: mappings.encode() }); return map; }, getIndentString: function getIndentString () { return this.indentStr === null ? '\t' : this.indentStr; }, indent: function indent ( indentStr, options ) { var this$1 = this; var pattern = /^[^\r\n]/gm; if ( isObject( indentStr ) ) { options = indentStr; indentStr = undefined; } indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' ); if ( indentStr === '' ) { return this; } // noop options = options || {}; // Process exclusion ranges var isExcluded = {}; if ( options.exclude ) { var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude; exclusions.forEach( function (exclusion) { for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) { isExcluded[i] = true; } }); } var shouldIndentNextCharacter = options.indentStart !== false; var replacer = function (match) { if ( shouldIndentNextCharacter ) { return ("" + indentStr + match); } shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace( pattern, replacer ); var charIndex = 0; var chunk = this.firstChunk; while ( chunk ) { var end = chunk.end; if ( chunk.edited ) { if ( !isExcluded[ charIndex ] ) { chunk.content = chunk.content.replace( pattern, replacer ); if ( chunk.content.length ) { shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n'; } } } else { charIndex = chunk.start; while ( charIndex < end ) { if ( !isExcluded[ charIndex ] ) { var char = this$1.original[ charIndex ]; if ( char === '\n' ) { shouldIndentNextCharacter = true; } else if ( char !== '\r' && shouldIndentNextCharacter ) { shouldIndentNextCharacter = false; if ( charIndex === chunk.start ) { chunk.prependRight( indentStr ); } else { var rhs = chunk.split( charIndex ); rhs.prependRight( indentStr ); this$1.byStart[ charIndex ] = rhs; this$1.byEnd[ charIndex ] = chunk; chunk = rhs; } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace( pattern, replacer ); return this; }, insert: function insert () { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' ); }, insertLeft: function insertLeft ( index, content ) { if ( !warned.insertLeft ) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned.insertLeft = true; } return this.appendLeft( index, content ); }, insertRight: function insertRight ( index, content ) { if ( !warned.insertRight ) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned.insertRight = true; } return this.prependRight( index, content ); }, move: function move ( start, end, index ) { if ( index >= start && index <= end ) { throw new Error( 'Cannot move a selection inside itself' ); } this._split( start ); this._split( end ); this._split( index ); var first = this.byStart[ start ]; var last = this.byEnd[ end ]; var oldLeft = first.previous; var oldRight = last.next; var newRight = this.byStart[ index ]; if ( !newRight && last === this.lastChunk ) { return this; } var newLeft = newRight ? newRight.previous : this.lastChunk; if ( oldLeft ) { oldLeft.next = oldRight; } if ( oldRight ) { oldRight.previous = oldLeft; } if ( newLeft ) { newLeft.next = first; } if ( newRight ) { newRight.previous = last; } if ( !first.previous ) { this.firstChunk = last.next; } if ( !last.next ) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight; if ( !newLeft ) { this.firstChunk = first; } if ( !newRight ) { this.lastChunk = last; } return this; }, overwrite: function overwrite ( start, end, content, options ) { var this$1 = this; if ( typeof content !== 'string' ) { throw new TypeError( 'replacement content must be a string' ); } while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } if ( end > this.original.length ) { throw new Error( 'end is out of bounds' ); } if ( start === end ) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); } this._split( start ); this._split( end ); if ( options === true ) { if ( !warned.storeName ) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console warned.storeName = true; } options = { storeName: true }; } var storeName = options !== undefined ? options.storeName : false; var contentOnly = options !== undefined ? options.contentOnly : false; if ( storeName ) { var original = this.original.slice( start, end ); this.storedNames[ original ] = true; } var first = this.byStart[ start ]; var last = this.byEnd[ end ]; if ( first ) { if ( end > first.end && first.next !== this.byStart[ first.end ] ) { throw new Error( 'Cannot overwrite across a split point' ); } first.edit( content, storeName, contentOnly ); if ( last ) { first.next = last.next; } else { first.next = null; this.lastChunk = first; } first.original = this.original.slice( start, end ); first.end = end; } else { // must be inserting at the end var newChunk = new Chunk( start, end, '' ).edit( content, storeName ); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; }, prepend: function prepend ( content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); } this.intro = content + this.intro; return this; }, prependLeft: function prependLeft ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byEnd[ index ]; if ( chunk ) { chunk.prependLeft( content ); } else { this.intro = content + this.intro; } return this; }, prependRight: function prependRight ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byStart[ index ]; if ( chunk ) { chunk.prependRight( content ); } else { this.outro = content + this.outro; } return this; }, remove: function remove ( start, end ) { var this$1 = this; while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } if ( start === end ) { return this; } if ( start < 0 || end > this.original.length ) { throw new Error( 'Character is out of bounds' ); } if ( start > end ) { throw new Error( 'end must be greater than start' ); } this._split( start ); this._split( end ); var chunk = this.byStart[ start ]; while ( chunk ) { chunk.intro = ''; chunk.outro = ''; chunk.edit( '' ); chunk = end > chunk.end ? this$1.byStart[ chunk.end ] : null; } return this; }, slice: function slice ( start, end ) { var this$1 = this; if ( start === void 0 ) start = 0; if ( end === void 0 ) end = this.original.length; while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } var result = ''; // find start chunk var chunk = this.firstChunk; while ( chunk && ( chunk.start > start || chunk.end <= start ) ) { // found end chunk before start if ( chunk.start < end && chunk.end >= end ) { return result; } chunk = chunk.next; } if ( chunk && chunk.edited && chunk.start !== start ) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } var startChunk = chunk; while ( chunk ) { if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) { result += chunk.intro; } var containsEnd = chunk.start < end && chunk.end >= end; if ( containsEnd && chunk.edited && chunk.end !== end ) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } var sliceStart = startChunk === chunk ? start - chunk.start : 0; var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice( sliceStart, sliceEnd ); if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) { result += chunk.outro; } if ( containsEnd ) { break; } chunk = chunk.next; } return result; }, // TODO deprecate this? not really very useful snip: function snip ( start, end ) { var clone = this.clone(); clone.remove( 0, start ); clone.remove( end, clone.original.length ); return clone; }, _split: function _split ( index ) { var this$1 = this; if ( this.byStart[ index ] || this.byEnd[ index ] ) { return; } var chunk = this.lastSearchedChunk; var searchForward = index > chunk.end; while ( true ) { if ( chunk.contains( index ) ) { return this$1._splitChunk( chunk, index ); } chunk = searchForward ? this$1.byStart[ chunk.end ] : this$1.byEnd[ chunk.start ]; } }, _splitChunk: function _splitChunk ( chunk, index ) { if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements) var loc = getLocator( this.original )( index ); throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") ); } var newChunk = chunk.split( index ); this.byEnd[ index ] = chunk; this.byStart[ index ] = newChunk; this.byEnd[ newChunk.end ] = newChunk; if ( chunk === this.lastChunk ) { this.lastChunk = newChunk; } this.lastSearchedChunk = chunk; return true; }, toString: function toString () { var str = this.intro; var chunk = this.firstChunk; while ( chunk ) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; }, trimLines: function trimLines () { return this.trim('[\\r\\n]'); }, trim: function trim ( charType ) { return this.trimStart( charType ).trimEnd( charType ); }, trimEnd: function trimEnd ( charType ) { var this$1 = this; var rx = new RegExp( ( charType || '\\s' ) + '+$' ); this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return this; } var chunk = this.lastChunk; do { var end = chunk.end; var aborted = chunk.trimEnd( rx ); // if chunk was trimmed, we have a new lastChunk if ( chunk.end !== end ) { this$1.lastChunk = chunk.next; this$1.byEnd[ chunk.end ] = chunk; this$1.byStart[ chunk.next.start ] = chunk.next; } if ( aborted ) { return this$1; } chunk = chunk.previous; } while ( chunk ); return this; }, trimStart: function trimStart ( charType ) { var this$1 = this; var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' ); this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return this; } var chunk = this.firstChunk; do { var end = chunk.end; var aborted = chunk.trimStart( rx ); if ( chunk.end !== end ) { // special case... if ( chunk === this$1.lastChunk ) { this$1.lastChunk = chunk.next; } this$1.byEnd[ chunk.end ] = chunk; this$1.byStart[ chunk.next.start ] = chunk.next; } if ( aborted ) { return this$1; } chunk = chunk.next; } while ( chunk ); return this; } }; var hasOwnProp = Object.prototype.hasOwnProperty; function Bundle ( options ) { if ( options === void 0 ) options = {}; this.intro = options.intro || ''; this.separator = options.separator !== undefined ? options.separator : '\n'; this.sources = []; this.uniqueSources = []; this.uniqueSourceIndexByFilename = {}; } Bundle.prototype = { addSource: function addSource ( source ) { if ( source instanceof MagicString$1 ) { return this.addSource({ content: source, filename: source.filename, separator: this.separator }); } if ( !isObject( source ) || !source.content ) { throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' ); } [ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) { if ( !hasOwnProp.call( source, option ) ) { source[ option ] = source.content[ option ]; } }); if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up source.separator = this.separator; } if ( source.filename ) { if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) { this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length; this.uniqueSources.push({ filename: source.filename, content: source.content.original }); } else { var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ]; if ( source.content.original !== uniqueSource.content ) { throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") ); } } } this.sources.push( source ); return this; }, append: function append ( str, options ) { this.addSource({ content: new MagicString$1( str ), separator: ( options && options.separator ) || '' }); return this; }, clone: function clone () { var bundle = new Bundle({ intro: this.intro, separator: this.separator }); this.sources.forEach( function (source) { bundle.addSource({ filename: source.filename, content: source.content.clone(), separator: source.separator }); }); return bundle; }, generateMap: function generateMap ( options ) { var this$1 = this; if ( options === void 0 ) options = {}; var names = []; this.sources.forEach( function (source) { Object.keys( source.content.storedNames ).forEach( function (name) { if ( !~names.indexOf( name ) ) { names.push( name ); } }); }); var mappings = new Mappings( options.hires ); if ( this.intro ) { mappings.advance( this.intro ); } this.sources.forEach( function ( source, i ) { if ( i > 0 ) { mappings.advance( this$1.separator ); } var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[ source.filename ] : -1; var magicString = source.content; var locate = getLocator( magicString.original ); if ( magicString.intro ) { mappings.advance( magicString.intro ); } magicString.firstChunk.eachNext( function (chunk) { var loc = locate( chunk.start ); if ( chunk.intro.length ) { mappings.advance( chunk.intro ); } if ( source.filename ) { if ( chunk.edited ) { mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 ); } else { mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations ); } } else { mappings.advance( chunk.content ); } if ( chunk.outro.length ) { mappings.advance( chunk.outro ); } }); if ( magicString.outro ) { mappings.advance( magicString.outro ); } }); return new SourceMap({ file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ), sources: this.uniqueSources.map( function (source) { return options.file ? getRelativePath( options.file, source.filename ) : source.filename; }), sourcesContent: this.uniqueSources.map( function (source) { return options.includeContent ? source.content : null; }), names: names, mappings: mappings.encode() }); }, getIndentString: function getIndentString () { var indentStringCounts = {}; this.sources.forEach( function (source) { var indentStr = source.content.indentStr; if ( indentStr === null ) { return; } if ( !indentStringCounts[ indentStr ] ) { indentStringCounts[ indentStr ] = 0; } indentStringCounts[ indentStr ] += 1; }); return ( Object.keys( indentStringCounts ).sort( function ( a, b ) { return indentStringCounts[a] - indentStringCounts[b]; })[0] ) || '\t'; }, indent: function indent ( indentStr ) { var this$1 = this; if ( !arguments.length ) { indentStr = this.getIndentString(); } if ( indentStr === '' ) { return this; } // noop var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n'; this.sources.forEach( function ( source, i ) { var separator = source.separator !== undefined ? source.separator : this$1.separator; var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) ); source.content.indent( indentStr, { exclude: source.indentExclusionRanges, indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) }); // TODO this is a very slow way to determine this trailingNewline = source.content.toString().slice( 0, -1 ) === '\n'; }); if ( this.intro ) { this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) { return index > 0 ? indentStr + match : match; }); } return this; }, prepend: function prepend ( str ) { this.intro = str + this.intro; return this; }, toString: function toString () { var this$1 = this; var body = this.sources.map( function ( source, i ) { var separator = source.separator !== undefined ? source.separator : this$1.separator; var str = ( i > 0 ? separator : '' ) + source.content.toString(); return str; }).join( '' ); return this.intro + body; }, trimLines: function trimLines () { return this.trim('[\\r\\n]'); }, trim: function trim ( charType ) { return this.trimStart( charType ).trimEnd( charType ); }, trimStart: function trimStart ( charType ) { var this$1 = this; var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' ); this.intro = this.intro.replace( rx, '' ); if ( !this.intro ) { var source; var i = 0; do { source = this$1.sources[i]; if ( !source ) { break; } source.content.trimStart( charType ); i += 1; } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source? } return this; }, trimEnd: function trimEnd ( charType ) { var this$1 = this; var rx = new RegExp( ( charType || '\\s' ) + '+$' ); var source; var i = this.sources.length - 1; do { source = this$1.sources[i]; if ( !source ) { this$1.intro = this$1.intro.replace( rx, '' ); break; } source.content.trimEnd( charType ); i -= 1; } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source? return this; } }; export { Bundle };export default MagicString$1; //# sourceMappingURL=magic-string.es.js.map
export * from './PostProcessor.js'; export * from './EffectComposer.js'; export * from './pass/index.js'; export * from './shader/index.js';
'use strict'; module.exports = function intervalTime(startIntervalTime){ return function(done){ var endTime = Date.now(); var runTime = endTime - startIntervalTime; done(null,{'intervalTime': runTime}); }; };
/** * description * Author: Oded Sagir * @param Object require for adding dependencies * @return Object Class Object */ define(function(require) { var database = { posts: require("text!api/posts.json") }; return database; });
/* http://prismjs.com/download.html?themes=prism&languages=git&plugins=line-numbers */ self = (typeof window !== 'undefined') ? window // if in browser : ( (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self // if in worker : {} // if in node js ); /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */ var Prism = (function(){ // Private helper vars var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i; var _ = self.Prism = { util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); } else if (_.util.type(tokens) === 'Array') { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]; }, // Deep clone a language definition (e.g. to extend it) clone: function (o) { var type = _.util.type(o); switch (type) { case 'Object': var clone = {}; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = _.util.clone(o[key]); } } return clone; case 'Array': return o.map(function(v) { return _.util.clone(v); }); } return o; } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need anobject and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. If not provided, the function appends instead. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; }, // Traverse a language definition with Depth First Search DFS: function(o, callback, type) { for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); if (_.util.type(o[i]) === 'Object') { _.languages.DFS(o[i], callback); } else if (_.util.type(o[i]) === 'Array') { _.languages.DFS(o[i], callback, i); } } } } }, highlightAll: function(async, callback) { var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'); for (var i=0, element; element = elements[i++];) { _.highlightElement(element, async === true, callback); } }, highlightElement: function(element, async, callback) { // Find language var language, grammar, parent = element; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (parent.className.match(lang) || [,''])[1]; grammar = _.languages[language]; } if (!grammar) { return; } // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; // Set language on the parent, for styling parent = element.parentNode; if (/pre/i.test(parent.nodeName)) { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } var code = element.textContent; if(!code) { return; } code = code.replace(/^(?:\r?\n|\r)/,''); var env = { element: element, language: language, grammar: grammar, code: code }; _.hooks.run('before-highlight', env); if (async && self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function(evt) { env.highlightedCode = Token.stringify(JSON.parse(evt.data), language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(env.element); _.hooks.run('after-highlight', env); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code })); } else { env.highlightedCode = _.highlight(env.code, env.grammar, env.language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(element); _.hooks.run('after-highlight', env); } }, highlight: function (text, grammar, language) { var tokens = _.tokenize(text, grammar); return Token.stringify(_.util.encode(tokens), language); }, tokenize: function(text, grammar, language) { var Token = _.Token; var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } tokenloop: for (var token in grammar) { if(!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } var patterns = grammar[token]; patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, lookbehindLength = 0, alias = pattern.alias; pattern = pattern.pattern || pattern; for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! break tokenloop; } if (str instanceof Token) { continue; } pattern.lastIndex = 0; var match = pattern.exec(str); if (match) { if(lookbehind) { lookbehindLength = match[1].length; } var from = match.index - 1 + lookbehindLength, match = match[0].slice(lookbehindLength), len = match.length, to = from + len, before = str.slice(0, from + 1), after = str.slice(to + 1); var args = [i, 1]; if (before) { args.push(before); } var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); } } } } return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i=0, callback; callback = callbacks[i++];) { callback(env); } } } }; var Token = _.Token = function(type, content, alias) { this.type = type; this.content = content; this.alias = alias; }; Token.stringify = function(o, language, parent) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function(element) { return Token.stringify(element, language, o); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language, parent), tag: 'span', classes: ['token', o.type], attributes: {}, language: language, parent: parent }; if (env.type == 'comment') { env.attributes['spellcheck'] = 'true'; } if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = ''; for (var name in env.attributes) { attributes += name + '="' + (env.attributes[name] || '') + '"'; } return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>'; }; if (!self.document) { if (!self.addEventListener) { // in Node.js return self.Prism; } // In worker self.addEventListener('message', function(evt) { var message = JSON.parse(evt.data), lang = message.language, code = message.code; self.postMessage(JSON.stringify(_.util.encode(_.tokenize(code, _.languages[lang])))); self.close(); }, false); return self.Prism; } // Get current script and highlight var script = document.getElementsByTagName('script'); script = script[script.length - 1]; if (script) { _.filename = script.src; if (document.addEventListener && !script.hasAttribute('data-manual')) { document.addEventListener('DOMContentLoaded', _.highlightAll); } } return self.Prism; })(); if (typeof module !== 'undefined' && module.exports) { module.exports = Prism; } ; Prism.languages.git = { /* * A simple one line comment like in a git status command * For instance: * $ git status * # On branch infinite-scroll * # Your branch and 'origin/sharedBranches/frontendTeam/infinite-scroll' have diverged, * # and have 1 and 2 different commits each, respectively. * nothing to commit (working directory clean) */ 'comment': /^#.*$/m, /* * a string (double and simple quote) */ 'string': /("|')(\\?.)*?\1/m, /* * a git command. It starts with a random prompt finishing by a $, then "git" then some other parameters * For instance: * $ git add file.txt */ 'command': { pattern: /^.*\$ git .*$/m, inside: { /* * A git command can contain a parameter starting by a single or a double dash followed by a string * For instance: * $ git diff --cached * $ git log -p */ 'parameter': /\s(--|-)\w+/m } }, /* * Coordinates displayed in a git diff command * For instance: * $ git diff * diff --git file.txt file.txt * index 6214953..1d54a52 100644 * --- file.txt * +++ file.txt * @@ -1 +1,2 @@ * -Here's my tetx file * +Here's my text file * +And this is the second line */ 'coord': /^@@.*@@$/m, /* * Regexp to match the changed lines in a git diff output. Check the example above. */ 'deleted': /^-(?!-).+$/m, 'inserted': /^\+(?!\+).+$/m, /* * Match a "commit [SHA1]" line in a git log output. * For instance: * $ git log * commit a11a14ef7e26f2ca62d4b35eac455ce636d0dc09 * Author: lgiraudel * Date: Mon Feb 17 11:18:34 2014 +0100 * * Add of a new line */ 'commit_sha1': /^commit \w{40}$/m }; ; Prism.hooks.add('after-highlight', function (env) { // works only for <code> wrapped inside <pre data-line-numbers> (not inline) var pre = env.element.parentNode; if (!pre || !/pre/i.test(pre.nodeName) || pre.className.indexOf('line-numbers') === -1) { return; } var linesNum = (1 + env.code.split('\n').length); var lineNumbersWrapper; var lines = new Array(linesNum); lines = lines.join('<span></span>'); lineNumbersWrapper = document.createElement('span'); lineNumbersWrapper.className = 'line-numbers-rows'; lineNumbersWrapper.innerHTML = lines; if (pre.hasAttribute('data-start')) { pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1); } env.element.appendChild(lineNumbersWrapper); });;
const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const { validateSignInForm, isLoggedIn } = require('../middlewares/validation'); const { signOutUser } = require('../../models/helper-functions'); const user = require('../../models/users'); const reviews = require('../../models/reviews'); const urlEncodedParser = bodyParser.urlencoded({ extended: false }); router.get('/sign-up', (req, res) => { res.render('sign-up', { error: false }); }); router.route('/sign-in') .get((req, res) => { res.render('sign-in', { error: false }); }) .post(urlEncodedParser, validateSignInForm, (req, res, next) => { const credentials = req.body; user.loginByEmail(credentials, req) .then((user) => { res.redirect(`users/${user.id}`); }) .catch((error) => { console.log('An error occured while logging in user::', error); next(new Error('incorrect email and/or password')); }) }); router.get('/sign-out', (req, res) => { signOutUser(req); res.redirect('/?isloggedIn=false'); }) module.exports = router;
define(function(require,exports,module){"use strict";var PreferencesManager=brackets.getModule("preferences/PreferencesManager");PreferencesManager.set("openSVGasXML",true)});
define(function () { return { registerExtenders: registerExtenders }; function registerExtenders() { registerDateBinding(); registerMoneyExtension(); } function registerDateBinding () { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow.com/questions/17001303/date-formatting-issues-with-knockout-and-syncing-to-breeze-js-entityaspect-modif init: function (element, valueAccessor) { //attach an event handler to our dom element to handle user input element.onchange = function () { var value = valueAccessor();//get our observable //set our observable to the parsed date from the input value(moment(element.value).toDate()); }; }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var value = valueAccessor(); var valueUnwrapped = ko.utils.unwrapObservable(value); if (valueUnwrapped) { element.value = moment(valueUnwrapped).format('L'); } } }; } function registerMoneyExtension() { //Credit to Josh Bush http://freshbrewedcode.com/joshbush/2011/12/27/knockout-js-observable-extensions/ var format = function (value) { toks = value.toFixed(2).replace('-', '').split('.'); var display = '$' + $.map(toks[0].split('').reverse(), function (elm, i) { return [(i % 3 === 0 && i > 0 ? ',' : ''), elm]; }).reverse().join('') + '.' + toks[1]; return value < 0 ? '(' + display + ')' : display; }; ko.subscribable.fn.money = function () { var target = this; var writeTarget = function (value) { target(parseFloat(value.replace(/[^0-9.-]/g, ''))); }; var result = ko.computed({ read: function () { return target(); }, write: writeTarget }); result.formatted = ko.computed({ read: function () { return format(target()); }, write: writeTarget }); return result; }; } });
'use strict'; /* * AngularJS Toaster * Version: 0.4.4 * * Copyright 2013 Jiri Kavulak. * All Rights Reserved. * Use, reproduction, distribution, and modification of this code is subject to the terms and * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php * * Author: Jiri Kavulak * Related to project of John Papa and Hans Fjällemark */ angular.module('toaster', ['ngAnimate']) .service('toaster', ['$rootScope', function ($rootScope) { this.pop = function (type, title, body, timeout, bodyOutputType) { this.toast = { type: type, title: title, body: body, timeout: timeout, bodyOutputType: bodyOutputType }; $rootScope.$broadcast('toaster-newToast'); }; this.clear = function () { $rootScope.$broadcast('toaster-clearToasts'); }; }]) .constant('toasterConfig', { 'limit': 0, // limits max number of toasts 'tap-to-dismiss': true, 'newest-on-top': true, //'fade-in': 1000, // done in css //'on-fade-in': undefined, // not implemented //'fade-out': 1000, // done in css // 'on-fade-out': undefined, // not implemented //'extended-time-out': 1000, // not implemented 'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky 'icon-classes': { error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' }, 'body-output-type': '', // Options: '', 'trustedHtml', 'template' 'body-template': 'toasterBodyTmpl.html', 'icon-class': 'toast-info', 'position-class': 'toast-bottom-left', 'title-class': 'toast-title', 'message-class': 'toast-message' }) .directive('toasterContainer', ['$compile', '$timeout', '$sce', 'toasterConfig', 'toaster', function ($compile, $timeout, $sce, toasterConfig, toaster) { return { replace: true, restrict: 'EA', link: function (scope, elm, attrs) { var id = 0; var mergedConfig = toasterConfig; if (attrs.toasterOptions) { angular.extend(mergedConfig, scope.$eval(attrs.toasterOptions)); } scope.config = { position: mergedConfig['position-class'], title: mergedConfig['title-class'], message: mergedConfig['message-class'], tap: mergedConfig['tap-to-dismiss'] }; scope.configureTimer = function configureTimer(toast) { var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out']; if (timeout > 0) setTimeout(toast, timeout); }; function addToast(toast) { toast.type = mergedConfig['icon-classes'][toast.type]; if (!toast.type) toast.type = mergedConfig['icon-class']; id++; angular.extend(toast, { id: id }); // Set the toast.bodyOutputType to the default if it isn't set toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']; switch (toast.bodyOutputType) { case 'trustedHtml': toast.html = $sce.trustAsHtml(toast.body); break; case 'template': toast.bodyTemplate = toast.body || mergedConfig['body-template']; break; } scope.configureTimer(toast); if (mergedConfig['newest-on-top'] === true) { scope.toasters.unshift(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.pop(); } } else { scope.toasters.push(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.shift(); } } } function setTimeout(toast, time) { toast.timeout = $timeout(function () { scope.removeToast(toast.id); }, time); } scope.toasters = []; scope.$on('toaster-newToast', function () { addToast(toaster.toast); }); scope.$on('toaster-clearToasts', function () { scope.toasters.splice(0, scope.toasters.length); }); }, controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { $scope.stopTimer = function (toast) { if (toast.timeout) { $timeout.cancel(toast.timeout); toast.timeout = null; } }; $scope.restartTimer = function (toast) { if (!toast.timeout) $scope.configureTimer(toast); }; $scope.removeToast = function (id) { var i = 0; for (i; i < $scope.toasters.length; i++) { if ($scope.toasters[i].id === id) break; } $scope.toasters.splice(i, 1); }; $scope.remove = function (id) { if ($scope.config.tap === true) { $scope.removeToast(id); } }; }], template: '<div id="toast-container" ng-class="config.position">' + '<div ng-repeat="toaster in toasters" class="toast" ng-class="toaster.type" ng-click="remove(toaster.id)" ng-mouseover="stopTimer(toaster)" ng-mouseout="restartTimer(toaster)">' + '<div ng-class="config.title">{{toaster.title}}</div>' + '<div ng-class="config.message" ng-switch on="toaster.bodyOutputType">' + '<div ng-switch-when="trustedHtml" ng-bind-html="toaster.html"></div>' + '<div ng-switch-when="template"><div ng-include="toaster.bodyTemplate"></div></div>' + '<div ng-switch-default >{{toaster.body}}</div>' + '</div>' + '</div>' + '</div>' }; }]);
/*! * Redback * Copyright(c) 2011 Chris O'Hara <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var Structure = require('../Structure'); /** * See https://gist.github.com/chriso/54dd46b03155fcf555adccea822193da * * Count the number of times a subject performs an action over an interval * in the immediate past - this can be used to rate limit the subject if * the count goes over a certain threshold. For example, you could track * how many times an IP (the subject) has viewed a page (the action) over * a certain time frame and limit them accordingly. * * Usage: * `redback.createRateLimit(action [, options]);` * * Options: * `bucket_interval` - default is 5 seconds * `bucket_span` - default is 10 minutes * `subject_expiry` - default is 20 minutes * * Reference: * https://gist.github.com/chriso/54dd46b03155fcf555adccea822193da * http://redis.io/topics/data-types#hash * * Redis Structure: * `(namespace:)action:<subject1> = hash(bucket => count)` * `(namespace:)action:<subject2> = hash(bucket => count)` * `(namespace:)action:<subjectN> = hash(bucket => count)` */ var RateLimit = exports.RateLimit = Structure.new(); /** * Setup the RateLimit structure. * * @param {Object} options (optional) * @api private */ RateLimit.prototype.init = function (options) { options = options || {}; this.bucket_span = options.bucket_span || 600; this.bucket_interval = options.bucket_interval || 5; this.subject_expiry = options.subject_expiry || 1200; this.bucket_count = Math.round(this.bucket_span / this.bucket_interval); } /** * Get the bucket associated with the current time. * * @param {int} time (optional) - default is the current time (ms since epoch) * @return {int} bucket * @api private */ RateLimit.prototype.getBucket = function (time) { time = (time || new Date().getTime()) / 1000; return Math.floor((time % this.bucket_span) / this.bucket_interval); } /** * Increment the count for the specified subject. * * @param {string} subject * @param {Function} callback (optional) * @return this * @api public */ RateLimit.prototype.add = function (subject, callback) { if (Array.isArray(subject)) { return this.addAll(subject, callback); } var bucket = this.getBucket(), multi = this.client.multi(); subject = this.key + ':' + subject; //Increment the current bucket multi.hincrby(subject, bucket, 1) //Clear the buckets ahead multi.hdel(subject, (bucket + 1) % this.bucket_count) .hdel(subject, (bucket + 2) % this.bucket_count) //Renew the key TTL multi.expire(subject, this.subject_expiry); multi.exec(function (err) { if (!callback) return; if (err) return callback(err); callback(null); }); return this; } /** * Count the number of times the subject has performed an action * in the last `interval` seconds. * * @param {string} subject * @param {int} interval * @param {Function} callback * @return this * @api public */ RateLimit.prototype.count = function (subject, interval, callback) { var bucket = this.getBucket(), multi = this.client.multi(), count = Math.floor(interval / this.bucket_interval); subject = this.key + ':' + subject; //Get the counts from the previous `count` buckets multi.hget(subject, bucket); while (count--) { multi.hget(subject, (--bucket + this.bucket_count) % this.bucket_count); } //Add up the counts from each bucket multi.exec(function (err, counts) { if (err) return callback(err, null); for (var count = 0, i = 0, l = counts.length; i < l; i++) { if (counts[i]) { count += parseInt(counts[i], 10); } } callback(null, count); }); return this; } /** * An alias for `ratelimit.add(subject).count(subject, interval);` * * @param {string} subject * @param {int} interval * @param {Function} callback * @return this * @api public */ RateLimit.prototype.addCount = function (subject, interval, callback) { var bucket = this.getBucket(), multi = this.client.multi(), count = Math.floor(interval / this.bucket_interval); subject = this.key + ':' + subject; //Increment the current bucket multi.hincrby(subject, bucket, 1) //Clear the buckets ahead multi.hdel(subject, (bucket + 1) % this.bucket_count) .hdel(subject, (bucket + 2) % this.bucket_count) //Renew the key TTL multi.expire(subject, this.subject_expiry); //Get the counts from the previous `count` buckets multi.hget(subject, bucket); while (count--) { multi.hget(subject, (--bucket + this.bucket_count) % this.bucket_count); } //Add up the counts from each bucket multi.exec(function (err, counts) { if (err) return callback(err, null); for (var count = 0, i = 4, l = counts.length; i < l; i++) { if (counts[i]) { count += parseInt(counts[i], 10); } } callback(null, count); }); return this; }
var _ = require('lodash') var assert = require('assert') var common = require('./common') module.exports = function() { var adapter = { wrap: column => `"${column}"` } adapter.createTimestamps = function(data, options) { options = options || {} var table = this.wrap(data.identity.name) var schema = options.schema || 'public' return this.db .query( 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE ' + "TABLE_NAME='" + data.identity.name + "' AND COLUMN_NAME='updated_at' AND " + "TABLE_CATALOG=current_database() AND TABLE_SCHEMA='" + schema + "'", null, options ) .then(recordset => { if (recordset.length === 0) { return this.db.execute( `ALTER TABLE ${table} ADD ${this.wrap( 'updated_at' )} TIMESTAMP(3) WITHOUT TIME ZONE`, null, options ) } }) } adapter.buildInsertCommand = function(data) { data.insertCommand = `INSERT INTO ${this.wrap( data.identity.name )} (<fields>${data.timestamps ? `,"updated_at"` : ''}) VALUES (<values>${ data.timestamps ? `,(now() at time zone 'utc')` : '' }) RETURNING *` } adapter.buildUpdateCommand = function(data) { data.updateCommand = `UPDATE ${this.wrap( data.identity.name )} SET <fields-values>${ data.timestamps ? `,"updated_at"=(now() at time zone 'utc')` : '' } WHERE <primary-keys> RETURNING *` } adapter.buildDeleteCommand = function(data) { data.deleteCommand = 'DELETE FROM ' + this.wrap(data.identity.name) + ' WHERE <find-keys> RETURNING *' } adapter.create = common.create adapter.update = common.update adapter.destroy = common.destroy adapter.extractRecordset = function(jsonset, coerce) { assert(_.isArray(jsonset), 'jsonset is not an array') _.forEach(jsonset, function(record) { coerce.map(function(coercion) { const value = record[coercion.property] if (value === void 0) { record[coercion.property] = null } else if (value !== null) { record[coercion.property] = coercion.fn(record[coercion.property]) } }) }) return jsonset } adapter.buildQuery = function buildQuery(data, options, isAssociation) { var fields = [] _.forEach( data.properties, function(property, name) { var fieldName = property.field || name var alias = name fields.push( this.wrap(fieldName) + (alias !== fieldName ? ' AS ' + this.wrap(alias) : '') ) if ( options.fetchExternalDescription && property.display && property.schema && property.schema.$ref && property.schema.key ) { let display = property.display const point = display.indexOf('.') if (point > -1) { display = display.substr(point + 1) } fields.push( `(select "${display}" FROM "${property.schema.$ref}" where "${ property.schema.key }"="${data.key}"."${fieldName}") as "${_.camelCase( `${data.identity.name} ${name} ${display}` )}"` ) } }.bind(this) ) if (data.timestamps) { fields.push(this.wrap('updated_at')) } _.forEach( data.associations, function(association) { if (!association.data.foreignKey) { return false } const query = this.buildQuery(association.data, options, true) var foreignKey = association.data.properties[association.data.foreignKey].field || association.data.foreignKey fields.push( '(select array_to_json(array_agg(row_to_json(t))) from (' + query + ' WHERE ' + this.wrap(foreignKey) + '=' + this.wrap(data.key) + '.' + this.wrap(data.primaryKeyFields[0]) + ' ORDER BY ' + ( association.data.primaryOrderFields || association.data.primaryKeyFields ) .map(this.wrap.bind(this)) .join() + ') t) AS ' + this.wrap(association.data.key) ) }.bind(this) ) let fetchCommand = 'SELECT ' + fields.join(',') + ' FROM ' + this.wrap(data.identity.name) + ' AS ' + this.wrap(data.key) if (options.schema && !isAssociation) { fetchCommand = fetchCommand.replace( /" FROM "/g, `" FROM ${options.schema}."` ) } return fetchCommand } adapter.getCoercionFunction = function(type, timezone) { switch (type) { case 'datetime': return function(value) { if (timezone === 'ignore') { var d = new Date(value + 'Z') return new Date(d.getTime() + d.getTimezoneOffset() * 60000) } else { return new Date(value) } } default: return function(value) { return value } } } return adapter }
module.exports = function( grunt ) { // Project configuration. grunt.initConfig( { pkg : grunt.file.readJSON( "bower.json" ), jshint : { options : { jshintrc : true }, src : { src : [ "src/*.js" ] } }, uglify : { js : { src : "src/<%= pkg.name %>.js", dest : "dist/<%= pkg.name %>.min.js" } }, watch : { files : [ "src/*.js" ], tasks : [ "jshint" ] } } ); grunt.loadNpmTasks( "grunt-contrib-jshint" ); grunt.loadNpmTasks( "grunt-contrib-uglify" ); grunt.loadNpmTasks( "grunt-contrib-watch" ); grunt.registerTask( "default", [ "jshint", "uglify" ] ); };
export function initialize(application) { application.inject('route', 'session', 'service:session'); application.inject('route', 'sessionAccount', 'service:session-account'); application.inject('controller', 'session', 'service:session'); application.inject('controller', 'sessionAccount', 'service:session-account'); application.inject('component', 'session', 'service:session'); application.inject('component', 'sessionAccount', 'service:session-account'); } export default { name: 'session', after: 'ember-simple-auth', initialize };
import Canvas from '../tool/Canvas.js'; import Animation from './Animation/Animation.js'; import Frame from './Animation/Frame.js'; import Player from '../engine/Player.js'; class Avatar { static radius = 360; static shakeTime = 300; constructor(player, direction) { this.player = player; this.idle = Avatar.createLozange('#FFFD1B', '#BCBB14', 1, direction, 0.5, 0.75, 0.25); this.idleShadow = Avatar.createLozange('#000000', '#000000', 0.1, direction, 0.5, 0.75, 0.25); this.thrust = Avatar.createLozange('#F5DF0E', '#AB9B0A', 1, direction, 0.25, 1, 0.25); this.thrustShadow = Avatar.createLozange('#000000', '#000000', 0.1, direction, 0.25, 1, 0.25); this.shake = 0; this.shakeTimout = null; this.startShake = this.startShake.bind(this); this.endShake = this.endShake.bind(this); this.player.setWallEventListener(this.startShake); } static createFrames(color, colorDark, direction) { const size = Avatar.radius * 2; const canvas = new Canvas(size, size); const context = canvas.context(); let frames = [ ]; } static createLozange(color, colorDark, alpha, direction, height, body, head) { const canvasWidth = 2; const canvasHeight = 2; const size = Avatar.radius * 2; const canvas = new Canvas(size * canvasWidth, size * canvasHeight); const context = canvas.context; const center = { x: canvasWidth / 2, y: canvasHeight / 2 }; const top = { x: center.x, y: center.y - (height / 2) }; const right = { x: center.x + head, y: center.y } const bottom = { x: center.x, y: top.y + height }; const left = { x: center.x - body, y: center.y }; if (direction) { canvas.reverse(); } context.scale(size, size); canvas.setAlpha(alpha); canvas.setFill(color); context.beginPath(); context.moveTo(left.x, left.y); context.lineTo(top.x, top.y); context.lineTo(right.x, right.y); context.fill(); canvas.setFill(colorDark); context.beginPath(); context.moveTo(left.x, left.y); context.lineTo(bottom.x, bottom.y); context.lineTo(right.x, right.y); context.fill(); if (direction) { canvas.reverse(); } return canvas; } startShake() { this.shake = Date.now(); this.shakeTimout = setTimeout(this.endShake, Avatar.shakeTime); } endShake() { this.shake = false; clearTimeout(this.shakeTimout); } getShake() { if (!this.shake) { return 0; } const time = (Date.now() - this.shake) / Avatar.shakeTime * 4 * Math.PI; return Math.cos(time) * Avatar.radius / 25; } draw() { return this.player.thrusting ? this.thrust.element : this.idle.element; } drawShadow() { return this.player.thrusting ? this.thrustShadow.element : this.idleShadow.element; } getSize() { const ratio = 1 + (this.player.getSpeedRatio() - 1) * 0.5; return Avatar.radius / devicePixelRatio * ratio; } getDropShadow() { return Avatar.radius * 0.1; } } export default Avatar;
const PlotCard = require('../../plotcard.js'); class TheSpidersWeb extends PlotCard { setupCardAbilities(ability) { this.reaction({ limit: ability.limit.perPhase(1), when: { onClaimApplied: event => event.player === this.controller && event.challenge.challengeType === 'intrigue' }, handler: () => { this.game.addMessage('{0} uses {1} to be able to initiate an additional {2} challenge with claim raised by 1', this.controller, this, 'intrigue'); this.untilEndOfPhase(ability => ({ targetController: 'current', effect: ability.effects.mayInitiateAdditionalChallenge('intrigue') })); this.untilEndOfPhase(ability =>({ condition: () => this.game.isDuringChallenge({ challengeType: 'intrigue' }), match: card => card === this.controller.activePlot, effect: ability.effects.modifyClaim(1) })); } }); } } TheSpidersWeb.code = '09049'; module.exports = TheSpidersWeb;
// All code points in the Buginese block as per Unicode v5.1.0: [ 0x1A00, 0x1A01, 0x1A02, 0x1A03, 0x1A04, 0x1A05, 0x1A06, 0x1A07, 0x1A08, 0x1A09, 0x1A0A, 0x1A0B, 0x1A0C, 0x1A0D, 0x1A0E, 0x1A0F, 0x1A10, 0x1A11, 0x1A12, 0x1A13, 0x1A14, 0x1A15, 0x1A16, 0x1A17, 0x1A18, 0x1A19, 0x1A1A, 0x1A1B, 0x1A1C, 0x1A1D, 0x1A1E, 0x1A1F ];
'use strict'; 'use strict'; angular.module('appModule', [ 'ngRoute', 'appControllers' ]) .config(function($routeProvider) { $routeProvider.when('/home', { controller : 'SettingCtrl', templateUrl : '/views/public/setting.html' }).when('/postcodes', { controller : 'PostCodeCtrl', templateUrl : '/views/postcode/list.html' }).when('/postcode/:id', { controller : 'PostCodeEditCtrl', templateUrl : '/views/postcode/detail.html' }).otherwise({ redirectTo : '/home' }); });
'use strict'; const assert = require('assert'); const context = require('../helpers/context'); describe('ctx.search=', () => { it('should replace the search', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.search, '?page=2&color=blue'); }); it('should update ctx.querystring and ctx.query', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.querystring, 'page=2&color=blue'); assert.equal(ctx.query.page, '2'); assert.equal(ctx.query.color, 'blue'); }); it('should change .url but not .originalUrl', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.originalUrl, '/store/shoes'); assert.equal(ctx.request.originalUrl, '/store/shoes'); }); describe('when missing', () => { it('should return ""', () => { const ctx = context({ url: '/store/shoes' }); assert.equal(ctx.search, ''); }); }); });
/* Thing > Intangible > Enumeration > WarrantyScope - A range of of services that will be provided to a customer free of charge in case of a defect or malfunction of a product. Commonly used values: http://purl.org/goodrelations/v1#Labor-BringIn http://purl.org/goodrelations/v1#PartsAndLabor-BringIn http://purl.org/goodrelations/v1#PartsAndLabor-PickUp. Generated automatically by the reactGenerator. */ var WarrantyScope= React.createClass({ getDefaultProps: function(){ return { } }, render: function(){ var props = this.props.props; var potentialAction; if( props.potentialAction ){ if( props.potentialAction instanceof Array ){ potentialAction = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] potentialAction = potentialAction.concat( props.potentialAction.map( function(result, index){ return ( <Action {...result} key={index} /> ) }) ); potentialAction.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { potentialAction = ( <Action props={ props.potentialAction } /> ); } } var description; if( props.description ){ if( props.description instanceof Array ){ description = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] description = description.concat( props.description.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. description is a Text.'></div> ) }) ); description.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { description = ( <div data-advice='Put your HTML here. description is a Text.'></div> ); } } var sameAs; if( props.sameAs ){ if( props.sameAs instanceof Array ){ sameAs = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sameAs = sameAs.concat( props.sameAs.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. sameAs is a URL.'></div> ) }) ); sameAs.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sameAs = ( <div data-advice='Put your HTML here. sameAs is a URL.'></div> ); } } var image; if( props.image ){ if( props.image instanceof Array ){ image = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] image = image.concat( props.image.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ) }) ); image.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { image = ( <div data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ); } } var url; if( props.url ){ if( props.url instanceof Array ){ url = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] url = url.concat( props.url.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. url is a URL.'></div> ) }) ); url.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { url = ( <div data-advice='Put your HTML here. url is a URL.'></div> ); } } var supersededBy; if( props.supersededBy ){ if( props.supersededBy instanceof Array ){ supersededBy = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] supersededBy = supersededBy.concat( props.supersededBy.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. supersededBy is a Class or Property or Enumeration.'></div> ) }) ); supersededBy.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { supersededBy = ( <div data-advice='Put your HTML here. supersededBy is a Class or Property or Enumeration.'></div> ); } } var mainEntityOfPage; if( props.mainEntityOfPage ){ if( props.mainEntityOfPage instanceof Array ){ mainEntityOfPage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntityOfPage = mainEntityOfPage.concat( props.mainEntityOfPage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ) }) ); mainEntityOfPage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntityOfPage = ( <div data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ); } } var additionalType; if( props.additionalType ){ if( props.additionalType instanceof Array ){ additionalType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] additionalType = additionalType.concat( props.additionalType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. additionalType is a URL.'></div> ) }) ); additionalType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { additionalType = ( <div data-advice='Put your HTML here. additionalType is a URL.'></div> ); } } var alternateName; if( props.alternateName ){ if( props.alternateName instanceof Array ){ alternateName = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternateName = alternateName.concat( props.alternateName.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternateName is a Text.'></div> ) }) ); alternateName.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternateName = ( <div data-advice='Put your HTML here. alternateName is a Text.'></div> ); } } var name; if( props.name ){ if( props.name instanceof Array ){ name = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] name = name.concat( props.name.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. name is a Text.'></div> ) }) ); name.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { name = ( <div data-advice='Put your HTML here. name is a Text.'></div> ); } } return (<div title='WarrantyScope' className='WarrantyScope entity'> { potentialAction } { description } { sameAs } { image } { url } { supersededBy } { mainEntityOfPage } { additionalType } { alternateName } { name } </div>); } });
/* pointbreak.js - PointBreak provides a friendly interface to matchMedia with named media queries and easy to create callbacks. Authors & copyright (c) 2013: WebLinc, David Knight. */ (function(win) { 'use strict'; var EVENT_TYPE_MATCH = 'match', EVENT_TYPE_UNMATCH = 'unmatch'; // Create a point object which contains the functionality to trigger events and name alias for the media query function createPoint() { return { name : null, media : '', mql : null, listeners : { once : { match : null, unmatch : null }, match : [], unmatch : [] }, trigger : function(type) { var listenerType = this.listeners[type]; for (var i = 0, len = listenerType.length; i < len; i++) { var listener = listenerType[i]; if (typeof(listener.callback) === 'function') { listener.callback.call(win, this, listener.data); } } }, handleListener: null, // Fires 'callback' that matches the 'type' immediately now : function(type, callback, data) { var matches = this.mql && this.mql.matches; if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) { callback.call(win, this, data || {}); } return this; }, // Fired the first time the conditions are matched or unmatched once : function(type, callback, data) { var matches = this.mql && this.mql.matches; if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) { this.once[type] = null; callback.call(win, this, data || {}); } else { this.once[type] = { callback : callback, data : data }; } return this; }, // Fired each time the conditions are matched or unmatched which could be multiple times during a session on : function(type, callback, data) { this.listeners[type].push({ callback : callback, data : data || {} }); return this; }, // Removes a specific callback or all callbacks if 'callback' is undefined for 'match' or 'unmatch' off : function(type, callback) { if (callback) { var listenerType = this.listeners[type]; for (var i = 0; i < listenerType.length; i++) { if (listenerType[i].callback === callback) { listenerType.splice(i, 1); i--; } } } else { this.listeners[type] = []; this.once[type] = null; } return this; } }; } // Interface for points that provides easy get/set methods and storage in the 'points' object win.PointBreak = { // Contains alias for media queries points: {}, // PointBreak.set('xsmall', '(min-width: 320px) and (max-width: 480px)') set: function (name, value) { var point = this.points[name]; // Reset 'listeners' and removeListener from 'mql' (MediaQueryList) // else create point object and add 'name' property if (point) { point.mql.removeListener(point.handleListener); point .off(EVENT_TYPE_MATCH) .off(EVENT_TYPE_UNMATCH); } else { point = this.points[name] = createPoint(); point.name = name; } // Set up listener function for 'mql' point.handleListener = function(mql) { var type = (mql.matches && EVENT_TYPE_MATCH) || EVENT_TYPE_UNMATCH, once = point.once[type]; // 'point' comes from the 'set' scope if (typeof(once) === 'function') { point.once[type] = null; once.call(win, point); } point.trigger(type); }; // Set up matchMedia and listener, requires matchMedia support or equivalent polyfill to evaluate media query // See https://github.com/weblinc/media-match or https://github.com/paulirish/matchMedia.js for matchMedia polyfill point.media = value || 'all'; point.mql = (win.matchMedia && win.matchMedia(point.media)) || { matches : false, media : point.media, addListener : function() {}, removeListener : function() {} }; point.mql.addListener(point.handleListener); return point; }, // PointBreak.get('xsmall') get: function(name) { return this.points[name] || null; }, // PointBreak.matches('xsmall') matches: function(name) { return (this.points[name] && this.points[name].mql.matches) || false; }, // PointBreak.lastMatch('xsmall small medium') lastMatch: function(nameList) { var list = nameList.indexOf(' ') ? nameList.split(' ') : [nameList], name = '', result = ''; for (var i = 0, len = list.length; i < len; i++) { name = list[i]; if (this.points[name] && this.points[name].mql.matches) { result = name; } } return result; } }; })(window);
var cc = require('closure-compiler'); var vinylTransform = require('vinyl-transform'); var mapStream = require('map-stream'); module.exports = function () { return vinylTransform(function () { return mapStream(function (data, next) { cc.compile(data, {}, function afterCompile (err, stdout) { if (err) { return next(err) } else { return next(null, stdout); } }); }); }); }
import { StaticResource } from 'iab-vast-model' export default ($staticResource) => { const res = new StaticResource() res.creativeType = $staticResource.creativeType res.uri = $staticResource._value return res }
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view'; class wsapp extends Component { render() { return <ScrollableTabView style={{marginTop: 20, }} initialPage={2} scrollWithoutAnimation={false} renderTabBar={() => <ScrollableTabBar />} ref={(tabView) => { this.tabView = tabView; }}> <Text tabLabel='Tab #1'>My</Text> <Text tabLabel='Tab #2'>favorite</Text> <Text tabLabel='Tab #3'>project</Text> <TouchableOpacity tabLabel='Back' onPress={() => this.tabView.goToPage(0)}> <Text>Lets go back!</Text> </TouchableOpacity> </ScrollableTabView> } } export default wsapp
'use strict'; var expect = require('chai').expect; var Config = require('../lib/dalek/config.js'); describe('dalek-internal-config', function () { it('should exist', function () { expect(Config).to.be.ok; }); it('can be initialized', function () { var config = new Config({}, {tests: []}, {}); expect(config).to.be.ok; }); it('can get a value', function () { var config = new Config({foo: 'bar'}, {tests: []}, {}); expect(config.get('foo')).to.equal('bar'); }); it('can read & parse a yaml file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readyml(__dirname + '/mock/Dalekfile.yml'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a json file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjson(__dirname + '/mock/Dalekfile.json'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a json5 file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjson5(__dirname + '/mock/Dalekfile.json5'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a js file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjs(__dirname + '/mock/Dalekfile.js'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can check the avilability of a config file', function () { var config = new Config({}, {tests: []}, {}); var path = __dirname + '/mock/Dalekfile.coffee'; expect(config.checkAvailabilityOfConfigFile(path)).to.equal(path); }); it('can verify a reporter', function () { var config = new Config({}, {tests: []}, {}); var reporter = { isReporter: function () { return true; } }; var reporters = ['foobar']; expect(config.verifyReporters(reporters, reporter)[0]).to.equal(reporters[0]); }); it('can verify a driver', function () { var config = new Config({}, {tests: []}, {}); var driver = { isDriver: function () { return true; } }; var drivers = ['foobar']; expect(config.verifyDrivers(drivers, driver)[0]).to.equal(drivers[0]); }); it('can return the previous filename if the _checkFile iterator foudn a file', function () { var config = new Config({}, {tests: []}, {}); expect(config._checkFile('foobarbaz', '', '', '')).to.equal('foobarbaz'); }); it('can check the existance of default config files', function () { var config = new Config({}, {tests: []}, {}); config.defaultFilename = __dirname + '/mock/Dalekfile'; expect(config._checkFile('js', 'coffee', 0, ['js', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.js'); }); it('can check the existance of default config files (1st in row doesnt exist, snd. does)', function () { var config = new Config({}, {tests: []}, {}); config.defaultFilename = __dirname + '/mock/Dalekfile'; expect(config._checkFile('txt', 'coffee', 0, ['txt', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.coffee'); }); });
SirTrevor.Locales = { en: { general: { 'delete': 'Delete?', 'drop': 'Drag __block__ here', 'paste': 'Or paste URL here', 'upload': '...or choose a file', 'close': 'close', 'position': 'Position', 'wait': 'Please wait...', 'link': 'Enter a link' }, errors: { 'title': "You have the following errors:", 'validation_fail': "__type__ block is invalid", 'block_empty': "__name__ must not be empty", 'type_missing': "You must have a block of type __type__", 'required_type_empty': "A required block type __type__ is empty", 'load_fail': "There was a problem loading the contents of the document" }, blocks: { text: { 'title': "Text" }, columns: { 'title': "Columns" }, list: { 'title': "List" }, quote: { 'title': "Quote", 'credit_field': "Credit" }, image: { 'title': "Image", 'upload_error': "There was a problem with your upload" }, video: { 'title': "Video" }, tweet: { 'title': "Tweet", 'fetch_error': "There was a problem fetching your tweet" }, embedly: { 'title': "Embedly", 'fetch_error': "There was a problem fetching your embed", 'key_missing': "An Embedly API key must be present" }, heading: { 'title': "Heading" } } } }; if (window.i18n === undefined || window.i18n.init === undefined) { // Minimal i18n stub that only reads the English strings SirTrevor.log("Using i18n stub"); window.i18n = { t: function(key, options) { var parts = key.split(':'), str, obj, part, i; obj = SirTrevor.Locales[SirTrevor.LANGUAGE]; for(i = 0; i < parts.length; i++) { part = parts[i]; if(!_.isUndefined(obj[part])) { obj = obj[part]; } } str = obj; if (!_.isString(str)) { return ""; } if (str.indexOf('__') >= 0) { _.each(options, function(value, opt) { str = str.replace('__' + opt + '__', value); }); } return str; } }; } else { SirTrevor.log("Using i18next"); // Only use i18next when the library has been loaded by the user, keeps // dependencies slim i18n.init({ resStore: SirTrevor.Locales, fallbackLng: SirTrevor.LANGUAGE, ns: { namespaces: ['general', 'blocks'], defaultNs: 'general' } }); }
// telegram.link // Copyright 2014 Enrico Stara '[email protected]' // Released under the MIT License // http://telegram.link // Dependencies: var api = require('../api'); var utility = require('../utility'); // *** // This module wraps API methods required to manage the session updates // See [Api Methods](https://core.telegram.org/methods#working-with-updates) // Access only via Client object (like client.updates) and `updates` instance property function Updates(client) { this.client = client; } // *** // **Event: **`'method name'` // Each of the following methods emits an event with the same name when done, an `error` event otherwise. // *** // updates.**getState([callback])** // Return a Promise to get the current state of updates. // [Click here for more details](https://core.telegram.org/method/updates.getState) // The code: Updates.prototype.getState = function (callback) { return utility.callService(api.service.updates.getState, this.client, this.client._channel, callback, arguments); }; // *** // updates.**getDifference(pts, date, qts, [callback])** // Return a Promise to get the difference between the current state of updates and transmitted. // [Click here for more details](https://core.telegram.org/method/updates.getDifference) // The code: Updates.prototype.getDifference = function (pts, date, qts, callback) { return utility.callService(api.service.updates.getDifference, this.client, this.client._channel, callback, arguments); }; // Export the class module.exports = exports = Updates;
(function() { function setUpTopLevelInteraction() { var TopLevelInteraction = new ITPHelper({ redirectUrl: document.body.dataset.redirectUrl, }); TopLevelInteraction.execute(); } document.addEventListener("DOMContentLoaded", setUpTopLevelInteraction); })();
/// <reference path="./typings/globals.d.ts"/> /// <reference path="./typings/lib.d.ts"/> var angular = require('angular'); var magics_scene_1 = require('./directives/magics-scene'); var magics_spy_1 = require('./directives/magics-spy'); var magics_stage_1 = require('./directives/magics-stage'); var constants_1 = require('./services/constants'); var magics_1 = require('./services/magics'); exports.__esModule = true; exports["default"] = angular.module('ngMagics', [ magics_scene_1["default"], magics_spy_1["default"], magics_stage_1["default"], constants_1["default"], magics_1["default"] ]) .name;
/** * Array.from ponyfill. * * @param {Object} iterable * * @returns {Array} */ export default function arrayFrom(iterable) { const arr = []; for (let i = 0; i < iterable.length; i += 1) { arr.push(iterable[i]); } return arr; }
import { expect } from 'chai' import _drop from '../../src/array/_drop2' describe('_drop', function(){ it('is a function', function(){ expect(_drop).to.be.a('function') }) it('returns an array', function(){ const droppedArray = _drop([5,7,2]) expect(droppedArray).to.be.a('array') }) it('returns [2] when given [5,7,2], 2', function(){ const droppedArray = _drop([5,7,2], 2) expect(droppedArray).to.be.deep.equal([2]) }) it('returns [7, 2] when given [5,7,2]', function(){ const droppedArray = _drop([5,7,2]) expect(droppedArray).to.be.deep.equal([7, 2]) }) it('returns [] when given [5,7,2], 17', function(){ const droppedArray = _drop([5,7,2], 17) expect(droppedArray).to.be.deep.equal([]) }) })
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react' import { Col, Row } from 'react-bootstrap' import WorkPageLayout from '../../components/work-page-layout' import './index.scss' export default class WorkPage extends Component { static title = 'walknote' static image = '/works/walknote_eyecatch.png' static description = 'Free music discovery player for iOS' render() { return ( <WorkPageLayout title={WorkPage.title} eyecatch="/works/walknote_eyecatch.png" > <Row> <Col sm={6}> <div> <img src="/works/walknote_01.png" className="image-screenshot" alt="image screenshot" /> </div> </Col> <Col sm={6}> <div> <img src="/works/walknote_02.png" className="image-screenshot" alt="image screenshot" /> </div> </Col> </Row> <div> <img src="/works/walknote_05.png" className="image-screenshot" alt="image screenshot" /> </div> <div> <img src="/works/walknote_03.png" className="image-screenshot" alt="image screenshot" /> </div> <div> <img src="/works/walknote_04.png" className="image-screenshot" alt="image screenshot" /> </div> <h3>walknote (2011-2016)</h3> <div className="work-description"> <div>好みを理解して推薦する無料で聴き放題な音楽プレーヤー</div> <div>Free music discovery player for iOS</div> </div> <div className="work-long-description"> <p> 13万人超が使う音楽アプリ。 あなたのiPhoneに入っている曲から好みを理解して、新しい曲を提示。 まるでラジオのように推薦曲を聴いて楽しめる! </p> <p> ※本サービスは終了しました。 詳細は <a href="http://blog.odoruinu.net/2016/09/06/farewell-from-walknote/"> こちら </a> 。 </p> </div> <div className="work-long-description"> <p> walknote recommends new music you may like based on your music preferences by recognizing your favorite songs stored in your device. You can listen to recommended music just like a radio! </p> <p> This service has been closed. Thank you for over 130,000 registered users! </p> </div> <h3>掲載実績</h3> <div className="work-description"> <ul> <li> <a href="http://renewal49.hateblo.jp/entry/20120710/1341925681" target="_blank" rel="noopener noreferrer" > 強力すぎて紹介しそびれていた音楽好きのための神アプリ『walknote』 - リニューアル式様 </a> </li> <li> <a href="http://www.appbank.net/2011/10/15/iphone-application/309349.php" target="_blank" rel="noopener noreferrer" > walknote: CD屋の試聴機が、自分向けになって手元に到着。そんな曲探しアプリ。無料。 - appbank様 </a> </li> <li> <a href="http://www.danshihack.com/2012/07/18/junp/iphoneapp-walknote.html" target="_blank" rel="noopener noreferrer" > おすすめの音楽をレコメンド!ストリーミング再生してくれるiPhoneアプリ「walknote」が素敵。 - 男子ハック様 </a> </li> <li> <a href="http://www.tabroid.jp/app/multimedia/2013/05/app.walknote.html" target="_blank" rel="noopener noreferrer" > 「YOU、これ聴いちゃいなよ」自分好みの曲が勝手に集まる音楽プレーヤー『walknote』 - タブロイド様 </a> </li> <li>その他、多数</li> </ul> </div> </WorkPageLayout> ) } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; 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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; import { CSSNavigation } from './cssNavigation.js'; import * as nodes from '../parser/cssNodes.js'; import { URI } from './../../vscode-uri/index.js'; import { startsWith } from '../utils/strings.js'; var SCSSNavigation = /** @class */ (function (_super) { __extends(SCSSNavigation, _super); function SCSSNavigation(fileSystemProvider) { return _super.call(this, fileSystemProvider) || this; } SCSSNavigation.prototype.isRawStringDocumentLinkNode = function (node) { return (_super.prototype.isRawStringDocumentLinkNode.call(this, node) || node.type === nodes.NodeType.Use || node.type === nodes.NodeType.Forward); }; SCSSNavigation.prototype.resolveRelativeReference = function (ref, documentUri, documentContext, isRawLink) { return __awaiter(this, void 0, void 0, function () { function toPathVariations(uri) { // No valid path if (uri.path === '') { return undefined; } // No variation for links that ends with suffix if (uri.path.endsWith('.scss') || uri.path.endsWith('.css')) { return undefined; } // If a link is like a/, try resolving a/index.scss and a/_index.scss if (uri.path.endsWith('/')) { return [ uri.with({ path: uri.path + 'index.scss' }).toString(), uri.with({ path: uri.path + '_index.scss' }).toString() ]; } // Use `uri.path` since it's normalized to use `/` in all platforms var pathFragments = uri.path.split('/'); var basename = pathFragments[pathFragments.length - 1]; var pathWithoutBasename = uri.path.slice(0, -basename.length); // No variation for links such as _a if (basename.startsWith('_')) { if (uri.path.endsWith('.scss')) { return undefined; } else { return [uri.with({ path: uri.path + '.scss' }).toString()]; } } var normalizedBasename = basename + '.scss'; var documentUriWithBasename = function (newBasename) { return uri.with({ path: pathWithoutBasename + newBasename }).toString(); }; var normalizedPath = documentUriWithBasename(normalizedBasename); var underScorePath = documentUriWithBasename('_' + normalizedBasename); var indexPath = documentUriWithBasename(normalizedBasename.slice(0, -5) + '/index.scss'); var indexUnderscoreUri = documentUriWithBasename(normalizedBasename.slice(0, -5) + '/_index.scss'); var cssPath = documentUriWithBasename(normalizedBasename.slice(0, -5) + '.css'); return [normalizedPath, underScorePath, indexPath, indexUnderscoreUri, cssPath]; } var target, parsedUri, pathVariations, j, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (startsWith(ref, 'sass:')) { return [2 /*return*/, undefined]; // sass library } return [4 /*yield*/, _super.prototype.resolveRelativeReference.call(this, ref, documentUri, documentContext, isRawLink)]; case 1: target = _a.sent(); if (!(this.fileSystemProvider && target && isRawLink)) return [3 /*break*/, 8]; parsedUri = URI.parse(target); _a.label = 2; case 2: _a.trys.push([2, 7, , 8]); pathVariations = toPathVariations(parsedUri); if (!pathVariations) return [3 /*break*/, 6]; j = 0; _a.label = 3; case 3: if (!(j < pathVariations.length)) return [3 /*break*/, 6]; return [4 /*yield*/, this.fileExists(pathVariations[j])]; case 4: if (_a.sent()) { return [2 /*return*/, pathVariations[j]]; } _a.label = 5; case 5: j++; return [3 /*break*/, 3]; case 6: return [3 /*break*/, 8]; case 7: e_1 = _a.sent(); return [3 /*break*/, 8]; case 8: return [2 /*return*/, target]; } }); }); }; return SCSSNavigation; }(CSSNavigation)); export { SCSSNavigation };
angular.module('fishTank') .controller('PostsCtrl', [ '$scope', 'postsFactory', 'post', function($scope, postsFactory, post){ $("input.tags").tagsinput('items') // $("input.form-control").show() $scope.post = post; $scope.incrementUpvotes = function(comment) { postsFactory.upvoteComment(post, comment); }; $scope.decrementUpvotes = function(comment) { postsFactory.downvoteComment(post, comment); }; $scope.addComment = function(){ errors(); if($scope.body === ''){return;} postsFactory.addComment(post.id, { body: $scope.body, author: 'user' }).success(function(comment) { $scope.post.comments.push(comment) }); $scope.body = ''; }; var errors = function() { $scope.$on('devise:unauthorized', function(event, xhr, deferred) { $scope.error = xhr.data.error }); } }]);
export default [ { name: 'Types', examples: [ { name: 'List', description: 'A list groups related content', file: 'List', }, { description: 'You can also pass an array of items as props', file: 'ListShorthand', }, { file: 'ListIcon', }, { file: 'ListDivided', }, { file: 'ListTree', }, { name: 'Bulleted', description: 'A list can mark items with a bullet.', file: 'Bulleted', }, { file: 'BulletedHorizontal', }, { name: 'Ordered', description: 'A list can be ordered numerically.', file: 'Ordered', }, { description: 'You can also use an `ol` and `li` to render an ordered list.', file: 'OrderedNumber', }, { name: 'Link', description: 'A list can be specially formatted for navigation links.', file: 'Link', }, ], }, { name: 'Content', examples: [ { name: 'Item', description: 'A list item can contain a set of items.', file: 'Item', }, { name: 'Icon', description: 'A list item can contain an icon.', file: 'Icon', }, { name: 'Image', description: 'A list item can contain an image.', file: 'Image', }, { name: 'Link', description: 'A list can contain links.', file: 'LinkContent', }, { file: 'LinkDescription', }, { name: 'Header', description: 'A list item can contain a header.', file: 'Header', }, { name: 'Description', description: 'A list item can contain a description.', file: 'Description', }, ], }, { name: 'Variations', examples: [ { name: 'Inverted', description: 'A list can be inverted to appear on a dark background.', file: 'ListInverted', }, ], }, ];
/* * docs-mixin: used by any page under /docs path */ import { updateMetaTOC, scrollTo, offsetTop } from '~/utils' import { bvDescription, nav } from '~/content' const TOC_CACHE = {} // @vue/component export default { head() { return { title: this.headTitle, meta: this.headMeta } }, computed: { headTitle() { const routeName = this.$route.name let title = '' let section = '' if (this.meta && this.meta.title) { title = this.meta.title } if (/^docs-components/.test(routeName)) { section = 'Components' } else if (/^docs-directives/.test(routeName)) { section = 'Directives' } else if (/^docs-reference/.test(routeName)) { section = 'Reference' } return [title, section, 'BootstrapVue'].filter(Boolean).join(' | ') }, headMeta() { const section = this.$route.name.split('-')[1] const sectionMeta = section ? nav.find(n => n.base === `${section}/`) : null const description = this.meta && this.meta.description ? this.meta.description : sectionMeta && sectionMeta.description ? sectionMeta.description : bvDescription const meta = [ { hid: 'og:title', name: 'og:title', property: 'og:title', content: this.headTitle } ] if (description) { meta.push({ hid: 'description', name: 'description', content: description }) meta.push({ hid: 'og:description', name: 'og:description', property: 'og:description', content: description }) } return meta } }, created() { // Create private non-reactive props this.$_filterTimer = null // In a `$nextTick()` to ensure `toc.vue` is created first this.$nextTick(() => { const key = `${this.$route.name}_${this.$route.params.slug || ''}` const toc = TOC_CACHE[key] || (TOC_CACHE[key] = updateMetaTOC(this.baseTOC || {}, this.meta || null)) this.$root.$emit('docs-set-toc', toc) }) }, mounted() { this.clearScrollTimeout() this.focusScroll() }, updated() { this.clearScrollTimeout() this.focusScroll() }, beforeDestroy() { this.clearScrollTimeout() }, methods: { clearScrollTimeout() { clearTimeout(this.$_scrollTimeout) this.$_scrollTimeout = null }, focusScroll() { const hash = this.$route.hash this.$nextTick(() => { let el if (hash) { // We use an attribute `querySelector()` rather than `getElementByID()`, // as some auto-generated ID's are invalid or not unique el = this.$el.querySelector(`[id="${hash.replace('#', '')}"]`) this.scrollIntoView(el) } if (!el) { el = this.$el.querySelector('h1') } if (el) { el.tabIndex = -1 el.focus() } }) }, scrollIntoView(el) { if (el) { // Get the document scrolling element const scroller = document.scrollingElement || document.documentElement || document.body this.clearScrollTimeout() // Allow time for v-play to finish rendering this.$_scrollTimeout = setTimeout(() => { // Scroll heading into view (minus offset to account for nav top height) scrollTo(scroller, offsetTop(el) - 70, 100) }, 100) } } } }
/** * Data that contains a string. * @param {string} value * @param {boolean} [isValid=true] * @constructor */ function StringData(value, isValid) { Data.call(this, Data.types.string, value, isValid); } StringData.prototype = Object.create(Data.prototype); StringData.prototype.constructor = StringData; /** * If the value could represent a number, it is converted to valid NumData. Otherwise, invalid NumData(0) is returned * @return {NumData} */ StringData.prototype.asNum = function() { if (this.isNumber()) { return new NumData(parseFloat(this.getValue()), this.isValid); } else { return new NumData(0, false); } }; /** * The string is a valid boolean if it is "true" or "false" (any casing) * @return {BoolData} */ StringData.prototype.asBool = function() { if (this.getValue().toUpperCase() === "TRUE") { return new BoolData(true, this.isValid); } else if (this.getValue().toUpperCase() === "FALSE") { return new BoolData(false, this.isValid); } return new BoolData(false, false); }; /** * @return {StringData} */ StringData.prototype.asString = function() { return this; }; /** * Checks to see if the number can be converted to a valid number * @return {boolean} */ StringData.prototype.isNumber = function() { //from https://en.wikipedia.org/wiki/Regular_expression const numberRE = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/; return numberRE.test(this.getValue()); }; /** * Imports StringData from XML * @param {Node} dataNode * @return {StringData|null} */ StringData.importXml = function(dataNode) { const value = XmlWriter.getTextNode(dataNode, "value"); if (value == null) return null; return new StringData(value); };
$(document).ready(function(){ ///Declare variables var unitSwap = true; var latitude = $('#latitude'); var longitude = $('#longitude'); var location = $('#location'); var temperature = $('#temperature'); var weather = $('#weather'); var weatherIcon; var clock = $('#clock'); var day = $('#day'); ///Geolocation //Find the geolocation if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { ///Weather API //Setup for weather app var key = 'd160d975b9920be65fcf14313e95afb4'; var weatherNow = 'http://api.openweathermap.org/data/2.5/weather?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&APPID=' + key + '&units=metric'; //Get the weather $.getJSON(weatherNow, function(data) { location.html(data.name + ', ' + data.sys.country); temperature.html(data.main.temp + '<sup>o</sup>C'); weather.html(data.weather[0].main); //Weather icons https://openweathermap.org/weather-conditions if(data.weather[0].icon === '01d') { document.getElementById('weatherIcon').src = 'img/sun.png'; $('body').css("background-image", "url(img/02.jpeg)"); } else if (data.weather[0].icon === '01n') { document.getElementById('weatherIcon').src = 'img/moon.png'; $('body').css("background-image", "url(img/04.jpeg)"); } else if(data.weather[0].icon === '02d') { document.getElementById('weatherIcon').src = 'img/cloud.png'; $('body').css("background-image", "url(img/01.jpeg)"); } else if(data.weather[0].icon === '02n') { document.getElementById('weatherIcon').src = 'img/night.png'; $('body').css("background-image", "url(img/05.jpeg)"); } else if(data.weather[0].icon === '03d' || data.weather[0].icon === '03n') { document.getElementById('weatherIcon').src = 'img/cloud2.png'; $('body').css("background-image", "url(img/06.jpeg)"); } else if(data.weather[0].icon === '04d' || data.weather[0].icon === '04n') { document.getElementById('weatherIcon').src = 'img/cloudy.png'; $('body').css("background-image", "url(img/07.jpeg)"); } else if(data.weather[0].icon === '09d' || data.weather[0].icon === '90n' || data.weather[0].icon === '10d' || data.weather[0].icon === '10n') { document.getElementById('weatherIcon').src = 'img/rain.png'; $('body').css("background-image", "url(img/03.jpeg)"); } else if(data.weather[0].icon === '11d' || data.weather[0].icon === '11n') { document.getElementById('weatherIcon').src = 'img/flash.png'; $('body').css("background-image", "url(img/08.jpeg)"); } else if(data.weather[0].icon === '13d' || data.weather[0].icon === '13n') { document.getElementById('weatherIcon').src = 'img/snowflake.png'; $('body').css("background-image", "url(img/09.jpeg)"); } else if(data.weather[0].icon === '50d' || data.weather[0].icon === '50n') { document.getElementById('weatherIcon').src = 'img/fog.png'; $('body').css("background-image", "url(img/10.jpeg)"); } else { console.log('photo didn\'t load'); } //button to change between fahrenheit and celcius temperature.click(function() { if (unitSwap === true) { temperature.html(data.main.temp*9/5+32 + '<sup>o</sup>F'); unitSwap = false; }else { temperature.html(data.main.temp + '<sup>o</sup>C'); unitSwap = true; } }); }); //Get current time function time() { var currentTime = new Date (); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; //Formatting it to a nice string using ternary operators currentMinutes = ( currentMinutes < 10 ? '0' : '' ) + currentMinutes; //Formatting it to 12 hours and adding AM and PM var timeOfDay = ( currentHours < 12 ) ? 'AM' : 'PM'; currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours; currentHours = ( currentHours === 0 ) ? 12 : currentHours; //The last part to make the finished formatted string var currentTimeString = currentHours + ':' + currentMinutes + ' ' + timeOfDay; day.html(weekday[currentTime.getDay()]); clock.html(currentTimeString); } time(); }); } else { location.html('Geolocation is not supported by this browser'); } });
app.controller('ThumbnailCtrl', function($http, Upload, $timeout, $location, $anchorScroll, $stateParams, $cookies){ thumbnailCtrl = this; thumbnailCtrl.sendEmail = function(){ $http.get('/api/sendEmail').success(function(response){ console.log('Ok') }).catch(function(err){ console.log(err) }); }; thumbnailCtrl.getThumbnails = function(){ thumbnailCtrl.loading=true; $http.get('/api/thumbnails').success(function(response){ thumbnailCtrl.thumbnailData = response.thumbnailsFound; thumbnailCtrl.actualPage = response.actualPage; articleLoader(); paginatorCalculator(response); getLastPosts(); thumbnailCtrl.loading = false; }).catch(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.responseError = response; }); }; thumbnailCtrl.postThumbnail = function(myFile){ thumbnailCtrl.loading=true; if(myFile){ Upload.upload({ url: '/api/thumbnails', method: 'POST', data: { file: Upload.dataUrltoBlob(myFile), thumbnailTitle: thumbnailCtrl.thumbnailTitle, thumbnailBody: thumbnailCtrl.thumbnailBody, articleTitle: thumbnailCtrl.articleTitle, articleBody: thumbnailCtrl.articleBody } }).then(function(response){ $timeout(function(){ myFile.result = response.data; thumbnailCtrl.loading = false; thumbnailCtrl.response = response.data.message; thumbnailCtrl.credentials = response.data.credentials; }); }, function(responseError){ if(responseError) thumbnailCtrl.responseError = responseError; }); } }; thumbnailCtrl.removeThumbnail = function(myTitle){ $http.delete('/api/thumbnails/'+myTitle).success(function(response){ thumbnailCtrl.getThumbnails(); }).catch(function(response){ thumbnailCtrl.responseError = 'Something went wrong'; }); }; thumbnailCtrl.editThumbnail = function(myTitle, editTitle, editBody){ $http.put('/api/thumbnails/'+myTitle, { thumbnailTitle: editTitle, thumbnailBody: editBody }).success(function(response){ thumbnailCtrl.getThumbnails(); }).catch(function(response){ console.log(response); thumbnailCtrl.responseError = 'Something went wrong'; }); }; thumbnailCtrl.getPage = function(pageQuery){ $http.get('/api/thumbnails?page='+pageQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; thumbnailCtrl.actualPage = response.actualPage; }).catch(function(response){ alert('Something went wrong'); }); }; thumbnailCtrl.selectIndex = function(index){ thumbnailCtrl.loading = true; for (var i = 0; i < thumbnailCtrl.thumbnailData.length; i++) { if(thumbnailCtrl.thumbnailData[i] == thumbnailCtrl.thumbnailData[index]){ thumbnailCtrl.articleFound = thumbnailCtrl.thumbnailData[i]; thumbnailCtrl.loading = false; return thumbnailCtrl.thumbnailData[i]; } } }; thumbnailCtrl.editArticle = function(editedTitle, editedBody){ thumbnailCtrl.loading = true; var myTitle = thumbnailCtrl.thumbnailData[$stateParams.id].thumbnailTitle; $http.put('/api/article/'+myTitle, { articleTitle: editedTitle, articleBody: editedBody }).success(function(response){ console.log(response) thumbnailCtrl.getThumbnails(); thumbnailCtrl.loading = false; }).catch(function(error){ console.log(error) }); }; thumbnailCtrl.getThumbnailsLimit = function(limitQuery, pageQuery){ thumbnailCtrl.loading=true; if(pageQuery){ $http.get('/api/thumbnails/search?limit='+limitQuery+'&page='+pageQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; }).catch(function(response){ alert('Something went wrong'); }); }else{ $http.get('/api/thumbnails/search?limit='+limitQuery).success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.thumbnailData = response.thumbnailsFound; }).catch(function(response){ alert('Something went wrong'); }); } }; thumbnailCtrl.scrollToTop = function(){ $location.hash('scrollTop'); $anchorScroll(); }; thumbnailCtrl.currentParamsId = function(){ return $stateParams.id; }; thumbnailCtrl.isLogged = function(){ if($cookies.get('username')){ return true; }else{ return false; } } function paginatorCalculator(response){ //Paginator calculation var totalPages = Math.ceil(response.totalPages/18); var range = []; for (var i = 1; i <= totalPages; i++) { range.push(i); } thumbnailCtrl.pagesArray = range; } function articleLoader(){ if(Object.keys($stateParams).length != 0){ //the id object is defined in the routes app.js thumbnailCtrl.selectIndex($stateParams.id); } }; function getLastPosts(){ $http.get('/api/thumbnails?lastPosts=10').success(function(response){ thumbnailCtrl.loading = false; thumbnailCtrl.lastPosts = response.thumbnailsFound; }).catch(function(response){ console.log('error'+response.error); }); }; });
import Component from '@ember/component'; import layout from '../templates/components/google-docs'; import { computed, get } from '@ember/object'; import { capitalize } from '@ember/string'; const GoogleDocs = Component.extend({ layout, tagName: 'a', attributeBindings: ['href', 'rel', 'target'], type: 'reference', referenceUrl: 'https://developers.google.com/maps/documentation/javascript/reference#', guideUrl: 'https://developers.google.com/maps/documentation/javascript/', rel: 'noopener', target: '_blank', baseUrl: computed('type', function() { return (this.type === 'reference') ? this.referenceUrl : this.guideUrl; }), displayType: computed('type', function() { return capitalize(this.type); }), href: computed(function() { return get(this, 'baseUrl') + get(this, 'section'); }) }); GoogleDocs.reopenClass({ positionalParams: ['section'] }); export default GoogleDocs;
/* * Exemplo de Readline (Input via console) * * @author André Ferreira <[email protected]> */ const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Qual sua idade? ', (idade) => { console.log('Sua idade é :', idade); rl.close(); });
// For info about this file refer to webpack and webpack-hot-middleware documentation // For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import WebpackMd5Hash from 'webpack-md5-hash'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import autoprefixer from 'autoprefixer'; const GLOBALS = { 'process.env.NODE_ENV': JSON.stringify('production'), __DEV__: false }; export default { resolve: { extensions: ['', '.js', '.jsx'] }, debug: true, devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool noInfo: true, // set to false to see a list of every file being bundled. entry: './src/index', target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test output: { path: `${__dirname}/dist`, publicPath: '/', filename: '[name].[chunkhash].js' }, plugins: [ // Hash the files using MD5 so that their names change when the content changes. new WebpackMd5Hash(), // Optimize the order that items are bundled. This assures the hash is deterministic. new webpack.optimize.OccurenceOrderPlugin(), // Tells React to build in prod mode. https://facebook.github.io/react/downloads.html new webpack.DefinePlugin(GLOBALS), // Generate an external css file with a hash in the filename new ExtractTextPlugin('[name].[contenthash].css'), // Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage new HtmlWebpackPlugin({ template: 'src/index.ejs', minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true }, inject: true, // Note that you can add custom options here if you need to handle other custom logic in index.html // To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below. trackJSToken: '' }), // Eliminate duplicate packages when generating bundle new webpack.optimize.DedupePlugin(), // Minify JS new webpack.optimize.UglifyJsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]' }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff&name=[name].[ext]" }, { test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]' }, { test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]' }, { test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]' }, { test: /\.ico$/, loader: 'file?name=[name].[ext]' }, { test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap') } ] }, postcss: () => [autoprefixer] };
/* Set the width of the side navigation to 250px */ function openNav() { document.getElementById("mySidenav").style.width = "250px"; } /* Set the width of the side navigation to 0 */ function closeNav() { document.getElementById("mySidenav").style.width = "0"; }
var App = angular.module('validationApp', []); App.controller('mainController', function ($scope) { $scope.submitForm = function (isValid) { if (isValid) { alert('Our form is Amazing'); } else { alert('Please enter the values and click submit'); } }; });
var dikoServices = angular.module('diko.basic.service', []); dikoServices.factory('dikoShareObject', [dikoServicesFunction]); function dikoServicesFunction() { var tabActive= "planets"; return { setTabActive: function(name) { if(typeof name !== 'undefined') tabActive = name; return tabActive; }, getTabActive: function() { return tabActive; } }; }
/*global tarteaucitron */ tarteaucitron.lang = { "adblock": "Benvenuto! Questo sito ti permette di attivare i servizi di terzi di tua scelta.", "adblock_call": "Disabilita il tuo adblocker per iniziare la navigazione.", "reload": "Aggiorna la pagina", "alertBigScroll": "Continuando a scorrere,", "alertBigClick": "Continuando a navigare nel sito,", "alertBig": "autorizzi l’utilizzo dei cookies inviati da domini di terze parti", "alertBigPrivacy": "Questo sito fa uso di cookies e ti consente di decidere se accettarli o rifiutarli", "alertSmall": "Gestione dei servizi", "acceptAll": "Ok, accetta tutto", "personalize": "Personalizza", "close": "Chiudi", "all": "Preferenze per tutti i servizi", "info": "Tutela della privacy", "disclaimer": "Abilitando l'uso dei servizi di terze parti, accetti la ricezione dei cookies e l'uso delle tecnologie analitici necessarie al loro funzionamento.", "allow": "Consenti", "deny": "Blocca", "noCookie": "Questo servizio non invia nessun cookie", "useCookie": "Questo servizio puo' inviare", "useCookieCurrent": "Questo servizio ha inviato", "useNoCookie": "Questo servizio non ha inviato nessun cookie", "more": "Saperne di più", "source": "Vai al sito ufficiale", "credit": "Gestione dei cookies da tarteaucitron.js", "toggleInfoBox": "Show/hide informations about cookie storage", "title": "Cookies management panel", "cookieDetail": "Cookie detail for", "ourSite": "on our site", "newWindow": "(new window)", "allowAll": "Allow all cookies", "denyAll": "Deny all cookies", "fallback": "è disattivato", "ads": { "title": "Regie pubblicitarie", "details": "Le regie pubblicitarie producono redditi gestendo la commercializzazione degli spazi del sito dedicati alle campagne pubblicitarie" }, "analytic": { "title": "Misura del pubblico", "details": "I servizi di misura del pubblico permettono di raccogliere le statistiche utili al miglioramento del sito" }, "social": { "title": "Reti sociali", "details": "Le reti sociali permettono di migliorare l'aspetto conviviale del sito e di sviluppare la condivisione dei contenuti da parte degli utenti a fini promozionali." }, "video": { "title": "Video", "details": "I servizi di condivisione di video permettono di arricchire il sito di contenuti multimediali e di aumentare la sua visibilità" }, "comment": { "title": "Commenti", "details": "La gestione dei commenti utente aiuta a gestire la pubblicazione dei commenti e a lottare contro lo spamming" }, "support": { "title": "Supporto", "details": "I servizi di supporto ti consentono di contattare la team del sito e di contribuire al suo miglioramento" }, "api": { "title": "API", "details": "Le API permettono di implementare script diversi : geolocalizzazione, motori di ricerca, traduttori..." }, "other": { "title": "Altro", "details": "Servizi per visualizzare contenuti web." } };
// index.js import { LocalStateForm, SimpleValidation } from 'immutable-react-form'; import Form from './form'; import validation from './validation'; import {GetData,UpdateData} from './data'; export default LocalStateForm( props => (GetData()), validation, submit )(Form); async function submit(model,props){ await UpdateData(model); }
JsonRecordApp.contorller(getCtrl, ['$scope', '$http', function($scope, $http){ var testArray = new Array(); var errorChar = 1; for (var i = 10001; i < 10101; i++) { var query = jQuery.ajax({ url: jsonUrl + jsonName + i + ".json", type: "GET", async: false, dataType: 'json', success: function(result){ testArray.push(result); $scope.jsonData = testArray; } }); if (query.status=="404") { break;} // $http.get(jsonUrl + jsonName + i + ".json").then(function(data){ // testArray.push(data.data); // $scope.jsonData = testArray; // console.log(testArray); // }).catch(function(){ // errorChar = 0; // }); } var testJson ={ "id" : 100010, "Name" : "testsName" } // var postQuery=$http.post("http://localhost:8080" + jsonUrl + jsonName + "10001.json", testJson).then(function(data){ // // var postQuery=$http.post(jsonUrl + jsonName + "test.json", testJson).then(function(data){ // console.log(data); // }).catch(err => console.log(err)); jQuery.ajax({ url: jsonUrl + jsonName + "10001.json", type: "POST", context: testJson, contentType: "application/json", async: false, dataType: 'json', success: function(result){ console.log(result); } }) }]);
import React, { Component } from 'react'; import { View, TextInput, Text } from 'react-native'; const Input = ({ label, securetxt, maxlen, keytype, value, onChangeText, placeHolder }) => { return ( <View style={styles.containerStyle}> <Text style={styles.labelStyle}>{label}</Text> <TextInput secureTextEntry={securetxt} keyboardType={keytype} maxLength={maxlen} autoCorrect={false} placeholder={placeHolder} placeholderTextColor={'#e0e2e1'} multiline={false} value={value} onChangeText={onChangeText} style={styles.inputStyle} /> </View> ); }; const styles = { inputStyle: { color: '#000', paddingRight: 10, paddingLeft: 5, fontSize: 18, lineHeight: 23, flex: 2, width: 150 }, labelStyle: { paddingLeft: 5, fontSize: 18, flex: 2 }, containerStyle: { height: 40, flex: 1, flexDirection: 'row', alignItems: 'center' } }; export { Input }
import { RocketChat } from 'meteor/rocketchat:lib'; RocketChat.settings.addGroup('Logs', function() { this.add('Log_Exceptions_to_Channel', '', { type: 'string' }); });
const EventEmitter = require("events"); const ssh2 = require("ssh2"); const Client = ssh2.Client; class Connection extends EventEmitter { constructor (connectOptions, dimensions) { this.connectOptions = connectOptions; this.dimensions = dimensions; this.errorCallback = errorCallback; if (!this.errorCallback) { this.errorCallback = function () {}; } this.stream = null; this.connection = new Client(); } ready () { this.emit("info", "Client is ready"); connection.shell({ cols: this.dimensions.cols, rows: this.dimensions.rows }, this.onConnect); } connect (connectOptions = null) { if (connectOptions) this.connectOptions = connectOptions; this.connection.connect(this.connectOptions); } resize (cols, rows) { if (this.stream) { // Height and width are set to the defaults because their values don't seem to actually matter this.stream.setWindow(rows, cols, 480, 640); } else { this.emit("info", "Connection not established! (resize)"); console.warn("Connection not established! (resize)"); } } write (data) { if (this.stream !== null) { this.stream.write(data); } else { this.emit("info", "Connection not established! (write)"); console.warn("Connection not established! (write)"); } } // Events onConnect (err, stream) { if (err) return errorCallback(); this.emit("info", "Connection successful"); this.stream = stream; stream .on("close", this.onClose.bind(this)) .on("data", this.onData.bind(this)) .stderr.on("data", onErrorData.bind(this)); } onData (data) { this.emit("data", data); this.emit("stdout", data); } onErrorData (data) { this.emit("data", data); this.emit("stderr", data); } onClose () { this.emit("info", "Connection stream closed"); this.connection.end(); this.stream = null; } } module.exports = Connection;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ramda_1 = require("ramda"); var render_instance_1 = require("./render-instance"); var types_1 = require("./types"); function deepResolver(mapper, renderer) { return function (comp) { var resolve = deepResolver(mapper, renderer); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { var newComp = renderer(mapped.instance); // note that newComp might be shallow again, so we need to call // deepResolver on it to resolve the whole the tree return resolve(newComp); } if (types_1.isHtml(mapped)) return ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); return mapped; }; } exports.deepResolver = deepResolver; function shallowResolver(mapper, _) { return function (comp) { var resolve = shallowResolver(mapper, _); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { return render_instance_1.toArtificialHtml(mapped); } if (types_1.isHtml(mapped)) { return ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); } return mapped; }; } exports.shallowResolver = shallowResolver; function interleavedResolver(mapper, renderer, nonRoot) { return function (comp) { var resolve = interleavedResolver(mapper, renderer, true); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { var newComp = renderer(mapped.instance); // note that newComp might be shallow again, so we need to call // interleavedResolver on it to render the whole the tree var renderedComp = resolve(newComp); return render_instance_1.toArtificialHtml(mapped, renderedComp); } if (types_1.isHtml(mapped)) { var mappedWithChildren = ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); return nonRoot ? mappedWithChildren : render_instance_1.toArtificialHtml(mappedWithChildren, mappedWithChildren); } return mapped; }; } exports.interleavedResolver = interleavedResolver;
const express = require('express'); const mongodb = require('mongodb') const request = require('request'); const app = express(); const server = require('http').createServer(app) const io = require('socket.io').listen(server) const mongo_url = 'mongodb://localhost:27017/rally' const mongo = mongodb.MongoClient() app.set("port", process.env.PORT || 3001); // Express only serves static assets in production if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); } let is_live = function(event) { let today = new Date() let yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000); if ("start" in event) { if(event.start >= today) { let end = event.start if ("end" in event) { end = event.end } if(end <= yesterday) { return true } } } return false } let events_data; let updateEventsData = () => { try { mongo.connect(mongo_url, (err, db) => { if (err) { console.log('Unable to connect to database server', err); } else { let collection = db.collection('ra_events'); let results = collection.find({},{'sort': {'start':-1}}); results.toArray((err, data) => { if (err) { console.log('Unable to get events from database', err); } else if (data) { let parentEvents = {}; let years = new Set(); for (let event of data) { if (event['type'] === 'parent') { if (event.year in parentEvents) { if (is_live(event)) { event['live'] = 'LIVE event' } parentEvents[event.year].push(event) } else { parentEvents[event.year] = [event] } years.add(event.year) } } years = Array.from(years).sort(function(a, b){return b-a}); events_data = { "events": parentEvents, "years": years }; } }) } }); } catch (e) { console.log('exception thrown by mongo.connect', e); } } let updateRaEvent = (year, code) => { let evt = year + code; console.log(evt); console.log(evt + ': requesting to start update') // if (false) { if (evt in jobs) { return({ 'year': year, 'code': code, 'jobid': jobs[evt] }); console.log(evt + ': job already exists: ' + jobs[evt]) } else { // send the request to start the job for scrapyd request.post( 'http://localhost:6800/schedule.json', { form: { project: 'timecontrol', spider: 'ra_scores', year: year, event_code: code, } }, function (err, response, data) { if (!err && response.statusCode == 200) { data = JSON.parse(data) jobs[evt] = data.jobid return({year: year, code: code, 'jobid': data.jobid}) console.log(evt + ': starting the update: ' + jobs[evt]) } else { return({error: err}) } } ); } } app.get("/api/events", (req, res) => { if (!events_data) { updateEventsData(); } res.send(events_data); }); app.get('/api/ra/:year/:code', function(req, res, next) { try { var year = req.params.year var code = req.params.code mongo.connect(mongo_url, function(err, db) { if (err) { res.send({error: err}); console.log('Unable to connect to database server', err) } else { var collection = db.collection('ra_scores') collection.findOne({ 'year':year, 'event_code':code }, function(err, data) { if (err) { res.send({error: err}); } else if (data) { res.send(data); } else { res.send({no_data: 'There is no data for this event, please update.'}); } }); } }); } catch(e) { next(e) } }); var jobs = {}; app.get('/api/ra/update/:year/:code', function(req, res, next) { var year = req.params.year var code = req.params.code res.send(updateRaEvent(year,code)); }); var latestStatus = {}; var waitingClients = []; var checkStatus = function() { let srvSockets = io.sockets.sockets; if (Object.keys(srvSockets).length > 0) { request.get( 'http://localhost:6800/listjobs.json?project=timecontrol', function (err, response, data) { if (!err && response.statusCode == 200) { data = JSON.parse(data); latestStatus = data; } else { console.log(err) } } ); } const findInFinshed = (id, status) => { for (let i in status.finished) { if (id === status.finished[i].id) { return true; } } return false; } let finishedJobs = []; for (let evt in jobs) { if (jobs.hasOwnProperty(evt)) { let jobid = jobs[evt]; if (latestStatus.finished && findInFinshed(jobid, latestStatus)) { finishedJobs.push(evt); console.log(evt); } } } for (let i in finishedJobs) { let evt = finishedJobs[i]; console.log(evt + ': finished, removing from jobs'); delete jobs[evt]; } } // poll the status from scrapyd every 1 seconds setInterval(checkStatus, 1000); io.on('connection', function(client) { let srvSockets = io.sockets.sockets; console.log('number of connected clients: ' + Object.keys(srvSockets).length); client.on('subscribeToStatus', (interval) => { console.log('client is subscribing to status with interval ', interval); setInterval(() => { client.emit('status', latestStatus); }, interval); }); }); server.listen(app.get("port"), () => { console.log(`Find the server at: http://localhost:${app.get("port")}/`); // eslint-disable-line no-console });
import e3AnimatedChild from '../e3-animated-child'; export default e3AnimatedChild.extend({ shadowType: 'text', enterState: { x: 0, y: 0, text: '' }, activeState: { x: null, y: null, text: null } });
describe('my app', function() { it('should redirect `index.html` to `index.html#!/countries/countries', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toBe('/home'); }); describe('home', function() { beforeEach(function() { browser.get('index.html'); }); it('should filter the country list as a user types into the search box', function() { var countryList = element.all(by.repeater('country in $ctrl.countries')); var query = element(by.model('$ctrl.query')); expect(countryList.count()).toBe(11); query.sendKeys('vietnam'); expect(countryList.count()).toBe(1); query.clear(); query.sendKeys('Brunei'); expect(countryList.count()).toBe(1); query.clear(); query.sendKeys('Indien'); expect(countryList.count()).toBe(0); }); it('should render country specific links', function() { var query = element(by.model('$ctrl.query')); query.sendKeys('Brunei'); element.all(by.css('.thumbDescription a')).first().click(); expect(browser.getLocationAbsUrl()).toBe('/countries/countries/BN'); }); }); describe('View: Country details', function() { beforeEach(function() { browser.get('index.html#!/countries/countries/BN'); }); it('should display country with title `translations.de`', function() { expect(element(by.binding('$ctrl.country.translations.de')).getText()).toBe('Brunei'); }); }); });
var webpack = require('webpack'); var path = require('path'); var APP_DIR = path.resolve(__dirname, 'react'); var BUILD_DIR = path.resolve(__dirname, 'project/static/js'); var config = { entry: { public: APP_DIR + '/public.main.jsx', private: APP_DIR + '/private.main.jsx', }, output: { path: BUILD_DIR, filename: "[name].bundle.js", }, plugins: [ new webpack.optimize.CommonsChunkPlugin('init.js'), new webpack.EnvironmentPlugin(['NODE_ENV']), ], resolve: { extensions: ['', '.js', '.jsx'], moduleDirectories: ['node_modules', 'react'], }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { cacheDirectory: false, plugins: [ require.resolve('babel-plugin-transform-decorators-legacy'), ], presets: [ require.resolve('babel-preset-react'), require.resolve('babel-preset-es2015'), require.resolve('babel-preset-stage-0'), ], }, }, ], }, }; module.exports = config;
var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Task Schema * @type {Object} */ var TaskSchema = new Schema({ title: { type: String, default: '', trim: true }, project: { type: String, default: '', trim: true }, date: { type: Date }, created: { type: Date }, user: { type: String } }); /** * Validations */ TaskSchema.path('title').validate(function(title) { "use strict"; return title.length; }, 'Titulo em branco'); TaskSchema.path('project').validate(function(project) { "use strict"; return project.length; }, 'Projeto em branco'); /** * Statics */ TaskSchema.statics = { load: function(id, cb) { "use strict"; this.findOne({ _id: id }).populate('user', 'name username').exec(cb); } }; mongoose.model('Task', TaskSchema);
'use strict'; var Promise = require('bluebird'), git = require('../index'); describe('isClean command', function() { var command = git.isClean; it('should exists', function(){ expect(command).to.be.a('function'); }); it('should issue a git diff-index', function() { return command() .tap(function() { var call = mockSpawn.calls.pop(); expect(call.args).to.be.eql([ 'diff-index', '--quiet', 'HEAD', '.' ]); }); }); it('should return true when is clean', function() { mockSpawn.sequence.add(mockSpawn.simple(0)); return command() .tap(function(isClean) { expect(isClean).to.be.true; }); }); it('should return true when is dirty', function() { mockSpawn.sequence.add(mockSpawn.simple(1)); return command() .tap(function(isClean) { expect(isClean).to.be.false; }); }); it('should fail when git does', function() { mockSpawn.sequence.add(mockSpawn.simple(128)); return command() .then(Promise.reject) .catch(Promise.resolve); }); });
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite'; import {fmt} from 'ember-runtime/system/string'; var suite = SuiteModuleBuilder.create(); suite.module('objectAt'); suite.test('should return object at specified index', function() { var expected = this.newFixture(3); var obj = this.newObject(expected); var len = expected.length; var idx; for (idx=0;idx<len;idx++) { equal(obj.objectAt(idx), expected[idx], fmt('obj.objectAt(%@) should match', [idx])); } }); suite.test('should return undefined when requesting objects beyond index', function() { var obj; obj = this.newObject(this.newFixture(3)); equal(obj.objectAt(5), undefined, 'should return undefined for obj.objectAt(5) when len = 3'); obj = this.newObject([]); equal(obj.objectAt(0), undefined, 'should return undefined for obj.objectAt(0) when len = 0'); }); export default suite;
export var meanDocs = { name: 'mean', category: 'Statistics', syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'], description: 'Compute the arithmetic mean of a list of values.', examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'], seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance'] };
import InfiniteScroll from './directive'; import 'bh-mint-ui2/src/style/empty.css'; import Vue from 'vue'; const install = function(Vue) { Vue.directive('InfiniteScroll', InfiniteScroll); }; if (!Vue.prototype.$isServer && window.Vue) { window.infiniteScroll = InfiniteScroll; Vue.use(install); // eslint-disable-line } InfiniteScroll.install = install; export default InfiniteScroll;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const config_1 = require("../models/config"); const version_1 = require("../upgrade/version"); const common_tags_1 = require("common-tags"); const Command = require('../ember-cli/lib/models/command'); const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal(); const pollDefault = config.config.defaults && config.config.defaults.poll; // defaults for BuildOptions exports.baseBuildCommandOptions = [ { name: 'target', type: String, default: 'development', aliases: ['t', { 'dev': 'development' }, { 'prod': 'production' }], description: 'Defines the build target.' }, { name: 'environment', type: String, aliases: ['e'], description: 'Defines the build environment.' }, { name: 'output-path', type: 'Path', aliases: ['op'], description: 'Path where output will be placed.' }, { name: 'aot', type: Boolean, description: 'Build using Ahead of Time compilation.' }, { name: 'sourcemaps', type: Boolean, aliases: ['sm', 'sourcemap'], description: 'Output sourcemaps.' }, { name: 'vendor-chunk', type: Boolean, default: true, aliases: ['vc'], description: 'Use a separate bundle containing only vendor libraries.' }, { name: 'base-href', type: String, aliases: ['bh'], description: 'Base url for the application being built.' }, { name: 'deploy-url', type: String, aliases: ['d'], description: 'URL where files will be deployed.' }, { name: 'verbose', type: Boolean, default: false, aliases: ['v'], description: 'Adds more details to output logging.' }, { name: 'progress', type: Boolean, default: true, aliases: ['pr'], description: 'Log progress to the console while building.' }, { name: 'i18n-file', type: String, description: 'Localization file to use for i18n.' }, { name: 'i18n-format', type: String, description: 'Format of the localization file specified with --i18n-file.' }, { name: 'locale', type: String, description: 'Locale to use for i18n.' }, { name: 'extract-css', type: Boolean, aliases: ['ec'], description: 'Extract css from global styles onto css files instead of js ones.' }, { name: 'watch', type: Boolean, default: false, aliases: ['w'], description: 'Run build when files change.' }, { name: 'output-hashing', type: String, values: ['none', 'all', 'media', 'bundles'], description: 'Define the output filename cache-busting hashing mode.', aliases: ['oh'] }, { name: 'poll', type: Number, default: pollDefault, description: 'Enable and define the file watching poll time period (milliseconds).' }, { name: 'app', type: String, aliases: ['a'], description: 'Specifies app name or index to use.' }, { name: 'delete-output-path', type: Boolean, default: true, aliases: ['dop'], description: 'Delete output path before build.' }, { name: 'preserve-symlinks', type: Boolean, default: false, description: 'Do not use the real path when resolving modules.' }, { name: 'extract-licenses', type: Boolean, default: true, description: 'Extract all licenses in a separate file, in the case of production builds only.' } ]; const BuildCommand = Command.extend({ name: 'build', description: 'Builds your app and places it into the output path (dist/ by default).', aliases: ['b'], availableOptions: exports.baseBuildCommandOptions.concat([ { name: 'stats-json', type: Boolean, default: false, description: common_tags_1.oneLine `Generates a \`stats.json\` file which can be analyzed using tools such as: \`webpack-bundle-analyzer\` or https://webpack.github.io/analyse.` } ]), run: function (commandOptions) { // Check angular version. version_1.Version.assertAngularVersionIs2_3_1OrHigher(this.project.root); const BuildTask = require('../tasks/build').default; const buildTask = new BuildTask({ project: this.project, ui: this.ui, }); return buildTask.run(commandOptions); } }); BuildCommand.overrideCore = true; exports.default = BuildCommand; //# sourceMappingURL=/users/arick/angular-cli/commands/build.js.map
/* Add Fish Form */ import React from 'react'; import autobind from 'autobind-decorator'; class AddFishForm extends React.Component{ @autobind createFish(event){ //1. Stop the form from submitting event.preventDefault(); //2. Take the data from the form and create an object var fish = { name : this.refs.name.value, price : this.refs.price.value, status :this.refs.status.value, desc : this.refs.desc.value, image :this.refs.image.value } //3. Add the fish to the App State this.props.addFish(fish); //asdf this.refs.fishForm.reset(); } render(){ return( <form className="fish-edit" refs="fishForm" onSubmit={this.createFish}> <input type="text" ref="name" placeholder="Fish Name"/> <input type="text" ref="price" placeholder="Fish Price"/> <select ref="status"> <option value="available">Fresh!</option> <option value="unavailable">Sold Out!</option> </select> <textarea type="text" ref="desc" placeholder="Desc"></textarea> <input type="text" ref="image" placeholder="URL to image"/> <button type="submit">+ Add Item </button> </form> ) } } export default AddFishForm;
import Ember from 'ember'; export default Ember.Route.extend({ appState: Ember.inject.service('app-state'), actions: { toggleLeftSidebar(){ this.set('appState.isLeftSidebarOpen', !this.get('appState.isLeftSidebarOpen')); }, toggleRightSidebar(){ this.set('appState.isRightSidebarOpen', !this.get('appState.isRightSidebarOpen')); }, toggleScrollingX(){ this.set('appState.scrollingX', !this.get('appState.scrollingX')); }, toggleScrollingY(){ this.set('appState.scrollingY', !this.get('appState.scrollingY')); }, toggleAnimating(){ this.set('appState.animating', !this.get('appState.animating')); }, toggleBouncing(){ this.set('appState.bouncing', !this.get('appState.bouncing')); }, toggleLocking(){ this.set('appState.locking', !this.get('appState.locking')); }, togglePaging(){ this.set('appState.paging', !this.get('appState.paging')); }, toggleZooming(){ this.set('appState.zooming', !this.get('appState.zooming')); }, toggleUseNativeScroll(){ this.set('appState.useNativeScroll', !this.get('appState.useNativeScroll')); }, onSelectOption(value){ this.set('appState.selectValue',value); } }, renderTemplate(){ this._super(...arguments); /* this.render('dummy-sidebar', { outlet: 'left-sidebar', into: 'application' });*/ this.render('content', { outlet: 'content', into: 'application' }); this.render('header', { outlet: "header-content", into: 'application' }); /*this.render('dummy-right-sidebar', { outlet: 'right-sidebar', into: 'application' }); var self = this; this.render('nested-header-content', { outlet: "another-header-content", into: 'dummy-content' }); this.render('nested-right-sidebar-content', { outlet: "right-sidebar", into: 'dummy-content' }); this.render('nested-left-sidebar-content', { outlet: "left-sidebar", into: 'dummy-content' }); this.render('nested-content', { outlet: "content", into: 'dummy-content' });*/ } });
const Webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin') const package = require('./package.json') const { join } = require('path') const externals = () => { const dependencies = package.dependencies return Object .keys(dependencies) .reduce((modules, module) => Object.assign({}, modules, { [module]: `commonjs ${module}` }), {} ) } module.exports = { context: join(__dirname, './build'), entry: { boleto: './resources/boleto/index.js', database: './functions/database/index.js' }, output: { path: join(__dirname, './dist'), libraryTarget: 'commonjs2', filename: '[name].js' }, devtool: 'inline-source-map', target: 'node', externals: externals(), module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['source-map-loader'], enforce: 'pre' } ] }, plugins: [ new Webpack.DefinePlugin({ 'process.env.ENV': JSON.stringify('production'), 'process.env.NODE_ENV': JSON.stringify('production'), }), new Webpack.BannerPlugin({ banner: ` require("source-map-support").install(); require("core-js"); `, raw: true, entryOnly: false }), new CopyWebpackPlugin([{ from: './database/migrations', to: './migrations', context: join(__dirname, './build') }]) ] }
/** * todo service */ class Todo { // id = 0; // text = ''; // checked = false; constructor(id, text, checked) { this.id = id; this.text = text; this.checked = checked; } }
var mongoose = require('mongoose'); var urlSchema = require('../schemas/UrlSchema'); var Url = mongoose.model('Url', urlSchema); var insertUrl = function(url, urlMinifie) { var link = new Url({ url, urlMinifie }); link.save(function(err) { if (err) return handleError(err); }); }; var getUrls = function() { return Url.find().exec(); }; module.exports = {Url, insertUrl, getUrls};
Template.botanikaLogo.events({ 'click .botanika-logo' (evt) { evt.preventDefault(); Meteor.swiperV.slideTo(0); } });
const event = { on(element, type, listener, options) { element.addEventListener(type, listener, options); return () => event.off(element, type, listener, options); }, off(element, type, listener, options) { element.removeEventListener(type, listener, options); }, once(element, type, listener) { const fn = function (...args) { listener.apply(this, args); event.off(element, type, fn); }; event.on(element, type, fn); }, }; export default event;
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'iframe', 'bg', { border: 'Показва рамка на карето', noUrl: 'Моля въведете URL за iFrame', scrolling: 'Активира прелистване', title: 'IFrame настройки', toolbar: 'IFrame' } );
/* * y * * * Copyright (c) 2013 ssddi456 * Licensed under the MIT license. */ 'use strict'; var iconvLite = require('iconv-lite'); var _ = require('underscore'); var path = require('path'); module.exports = function(grunt) { function detectDestType (dest) { if (grunt.util._.endsWith(dest, path.sep)) { return 'directory'; } else { return 'file'; } }; function unixifyPath (filepath) { if (process.platform === 'win32') { return filepath.replace(/\\/g, '/'); } else { return filepath; } }; grunt.registerMultiTask('grunt-iconv-lite', 'trans encoding', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ fromEncoding : 'utf8', toEncoding : 'gb2312' }); // Iterate over all specified file groups. this.files.forEach(function(f) { var isExpandedPair = f.orig.expand || false; // Concat specified files. f.src.filter(function(src) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(src)) { grunt.log.warn('Source file "' + src + '" not found.'); return false; } else { return true; } }).forEach(function(src) { var dest; if (detectDestType(f.dest) === 'directory') { dest = (isExpandedPair) ? f.dest : unixifyPath(path.join(f.dest, src)); } else { dest = f.dest; } if (grunt.file.isDir(src)) { // grunt.log.writeln('Creating ' + dest.cyan); grunt.file.mkdir(dest); } else { // grunt.log.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan); // Read file source. grunt.file.copy(src, dest, { encoding : options.fromEncoding, process : function( content ){ return iconvLite.encode(new Buffer(content),options.toEncoding); } }); // Print a success message. grunt.log.writeln('File "' + f.dest + '" transed.'); } }); }); }); };
var Bluebird = require('bluebird'); var connection = require('./connection'); var errors = require('./errors'); var mockOptions = {}; var offlineMode = false; module.exports.errors = errors; module.exports.connect = function connect(options) { if (offlineMode) { throw new Error('Real connections to ' + options.host + ' are not allowed in offline mode'); } return new connection.Connection(options).connect(); }; module.exports.connectMock = function connectMock(options) { return new connection.MockConnection(options, mockOptions).connect(); }; module.exports.setMockOptions = function setMockOptions(options) { mockOptions = options; }; module.exports.setOfflineMode = function setOfflineMode(value) { offlineMode = !!value; };
"use strict"; const hamt = require('../hamt'); const assert = require('chai').assert; describe('entries', () => { it('should be empty for empty map', () => { const h = hamt.make(); const it = hamt.entries(h); let v = it.next(); assert.ok(v.done); for (let x of h) assert.isFalse(true); }); it('should visit single child', () => { const h = hamt.make().set('a', 3); const it = hamt.entries(h); let v = it.next(); assert.deepEqual(['a', 3], v.value); assert.notOk(v.done); v = it.next(); assert.ok(v.done); assert.deepEqual([['a', 3]], Array.from(h)); }); it('should visit all children', () => { const h = hamt.make() .set('a', 3) .set('b', 5) .set('c', 7); const expected = [['a', 3], ['b', 5], ['c', 7]]; { const it = h.entries(); const results = []; let v; for (var i = 0; i < h.count(); ++i) { v = it.next(); assert.notOk(v.done); results.push(v.value) } v = it.next(); assert.isTrue(v.done); assert.deepEqual(expected, results); } assert.deepEqual(expected, Array.from(h)); }); it('should handle collisions', () => { const h = hamt.make() .setHash(0, 'a', 3) .setHash(0, 'b', 5) .setHash(0, 'c', 7) const expected = [['b', 5], ['a', 3], ['c', 7]]; { const it = h.entries(); const results = []; let v; for (var i = 0; i < h.count(); ++i) { v = it.next(); assert.notOk(v.done); results.push(v.value) } v = it.next(); assert.isTrue(v.done); assert.deepEqual(expected, results); } assert.deepEqual(expected, Array.from(h)); }); it('should handle large map correctly', () => { let h = hamt.make(); let sum = 0; for (let i = 0; i < 20000; ++i) { h = h.set(i + '', i); sum += i; } let foundSum = 0; for (let x of h) foundSum += x[1]; assert.strictEqual(sum, foundSum); }); });
import { each } from "../helpers"; import TablesHandler from "../TablesHandler"; each("table", table => { const tables = new TablesHandler(table); tables.enable(); });
#!/usr/bin/env node 'use strict'; var program = require('commander'); var pluck = require('pluck-keys'); var credential = require('../credential'); var stdin = ''; program .command('hash [password]') .description('Hash password') .option('-w --work <work>', 'relative work load (0.5 for half the work)', Number) .option('-k --key-length <key-length>', 'length of salt', Number) .action(function (password, options){ var pw = credential(pluck([ 'keyLength', 'hashMethod', 'work' ], options)); pw.hash(stdin || password, function (err, result){ if (err){ return console.error(err); } console.log(result); }); }); program .command('verify [hash] <password>') .description('Verify password') .action(function (hash, password){ credential().verify(stdin || hash, password, function (err, valid){ if (err){ return console.error(err); } if (!valid){ throw new Error('Invalid'); } console.log('Verified'); }); }); if (process.stdin.isTTY) { program.parse(process.argv); } else { process.stdin.on('readable', function (){ stdin += this.read() || ''; }); process.stdin.on('end', function (){ program.parse(process.argv); }); }
var app = angular.module('app',[]); app.controller('adderController', function($scope) { $scope.firstNumber = 2; $scope.secondNumber = 2; $scope.lvalue = 2+2; $scope.thirdNumber = function () { if (!$scope.firstNumber || !$scope.secondNumber) { return $scope.lvalue; } else { $scope.lvalue=parseInt($scope.firstNumber)+ parseInt($scope.secondNumber); return $scope.lvalue; } }; });
var expect = require('expect.js'); var request = require('supertest'); var app = require(process.cwd() + '/app.js'); describe('GET /api/artists', function() { this.timeout(15000); it('should return a single JSON artist object', function(done) { request(app) .get('/api/artists') .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/artists/:slug', function() { this.timeout(15000); it('should return a JSON array of artists', function(done) { var slug = 'deserto-rosso'; request(app) .get('/api/artists/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.artist).to.be.an('object'); done(); }); }); }); describe('GET /api/artists/genre/:slug', function() { this.timeout(15000); it('should return a JSON array of artist within a specific genre', function(done) { var slug = 'rock'; request(app) .get('/api/artists/genre/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.genre.slug).to.be.equal(slug); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/artists/tag/:slug', function() { this.timeout(15000); it('should return a JSON array of artist within a specific tag', function(done) { var slug = 'pop'; request(app) .get('/api/artists/tag/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.tag.slug).to.be.equal(slug); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/genres/artists', function() { this.timeout(15000); it('should return a JSON array of all artists genre', function(done) { request(app) .get('/api/genres/artists') .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; done(); }); }); });
/* Copyright (c) 2012 Jacob Rus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. File-like objects that read from or write to a string buffer. A nearly direct port of Python’s StringIO module. f = StringIO() # ready for writing f = StringIO(buf) # ready for reading f.close() # explicitly release resources held pos = f.tell() # get current position f.seek(pos) # set current position f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF buf = f.read() # read until EOF buf = f.read(n) # read up to n bytes buf = f.readline() # read until end of line ('\n') or EOF list = f.readlines() # list of f.readline() results until EOF f.truncate([size]) # truncate file to at most size (default: current pos) f.write(buf) # write at current position f.writelines(list) # for line in list: f.write(line) f.getvalue() # return whole file's contents as a string Notes: - Seeking far beyond EOF and then writing will insert real null bytes that occupy space in the buffer. - There's a simple test set (see end of this file). */ var StringIO, _complain_ifclosed, _test, module_root; _complain_ifclosed = function(closed) { if (closed) { throw new Error('I/O operation on closed file'); } }; /* class StringIO([buffer]) When a StringIO object is created, it can be initialized to an existing string by passing the string to the constructor. If no string is given, the StringIO will start empty. */ StringIO = (function() { function StringIO(buf) { if (buf == null) { buf = ''; } this.buf = '' + buf; this.length = this.buf.length; this.buflist = []; this.pos = 0; this.closed = false; } /* Free the memory buffer. */ StringIO.prototype.close = function() { if (!this.closed) { this.closed = true; delete this.buf; delete this.pos; } }; StringIO.prototype._flush_buflist = function() { this.buf += this.buflist.join(''); return this.buflist = []; }; /* Set the file's current position. The mode argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value. */ StringIO.prototype.seek = function(pos, mode) { if (mode == null) { mode = 0; } _complain_ifclosed(this.closed); if (this.buflist.length) { this._flush_buflist(); } if (mode === 1) { pos += this.pos; } else if (mode === 2) { pos += this.length; } this.pos = Math.max(0, pos); }; /* Return the file's current position. */ StringIO.prototype.tell = function() { _complain_ifclosed(this.closed); return this.pos; }; /* Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. */ StringIO.prototype.read = function(n) { var newpos, r; if (n == null) { n = -1; } _complain_ifclosed(this.closed); if (this.buflist.length) { this._flush_buflist(); } if (n < 0) { newpos = this.length; } else { newpos = Math.min(this.pos + n, this.length); } r = this.buf.slice(this.pos, newpos); this.pos = newpos; return r; }; /* Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. */ StringIO.prototype.readline = function(length) { var i, newpos, r; if (length == null) { length = null; } _complain_ifclosed(this.closed); if (this.buflist.length) { this._flush_buflist(); } i = this.buf.indexOf('\n', this.pos); if (i < 0) { newpos = this.length; } else { newpos = i + 1; } if ((length != null) && this.pos + length < newpos) { newpos = this.pos + length; } r = this.buf.slice(this.pos, newpos); this.pos = newpos; return r; }; /* Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (or more to accommodate a final whole line). */ StringIO.prototype.readlines = function(sizehint) { var line, lines, total; if (sizehint == null) { sizehint = 0; } total = 0; lines = []; line = this.readline(); while (line) { lines.push(line); total += line.length; if ((0 < sizehint && sizehint <= total)) { break; } line = this.readline(); } return lines; }; /* Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed unless the position is beyond the new file size. If the specified size exceeds the file's current size, the file remains unchanged. */ StringIO.prototype.truncate = function(size) { if (size == null) { size = null; } _complain_ifclosed(this.closed); if (size == null) { size = this.pos; } else if (size < 0) { throw new Error('Negative size not allowed'); } else if (size < this.pos) { this.pos = size; } this.buf = this.getvalue().slice(0, size); this.length = size; }; /* Write a string to the file. There is no return value. */ StringIO.prototype.write = function(s) { var newpos, null_bytes, slen, spos; _complain_ifclosed(this.closed); if (!s) { return; } if (typeof s !== 'string') { s = s.toString(); } spos = this.pos; slen = this.length; if (spos === slen) { this.buflist.push(s); this.length = this.pos = spos + s.length; return; } if (spos > slen) { null_bytes = (Array(spos - slen + 1)).join('\x00'); this.buflist.push(null_bytes); slen = spos; } newpos = spos + s.length; if (spos < slen) { if (this.buflist.length) { this._flush_buflist(); } this.buflist.push(this.buf.slice(0, spos), s, this.buf.slice(newpos)); this.buf = ''; if (newpos > slen) { slen = newpos; } } else { this.buflist.push(s); slen = newpos; } this.length = slen; this.pos = newpos; }; /* Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.) */ StringIO.prototype.writelines = function(array) { var j, len, line; for (j = 0, len = array.length; j < len; j++) { line = array[j]; this.write(line); } }; /* Flush the internal buffer */ StringIO.prototype.flush = function() { _complain_ifclosed(this.closed); }; /* Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called. */ StringIO.prototype.getvalue = function() { if (this.buflist.length) { this._flush_buflist(); } return this.buf; }; return StringIO; })(); module_root = typeof exports !== "undefined" && exports !== null ? exports : typeof window !== "undefined" && window !== null ? window : this; module_root.StringIO = StringIO; _test = function() { var f, j, len, length, line, line2, lines, list, print, ref; print = function() { return console.log.apply(console, arguments); }; lines = ['This is a test,\n', 'Blah blah blah,\n', 'Wow does this work?\n', 'Okay, here are some lines\n', 'of text.\n']; f = new StringIO; ref = lines.slice(0, -2); for (j = 0, len = ref.length; j < len; j++) { line = ref[j]; f.write(line); } f.writelines(lines.slice(-2)); if (f.getvalue() !== lines.join('')) { throw new Error('write failed'); } length = f.tell(); print('File length =', length); f.seek(lines[0].length); f.write(lines[1]); f.seek(0); print("First line = " + (f.readline())); print("Position = " + (f.tell())); line = f.readline(); print("Second line = " + line); f.seek(-line.length, 1); line2 = f.read(line.length); if (line !== line2) { throw new Error('bad result after seek back'); } f.seek(-line2.length, 1); list = f.readlines(); line = list[list.length - 1]; f.seek(f.tell() - line.length); line2 = f.read(); if (line !== line2) { throw new Error('bad result after seek back from EOF'); } print("Read " + list.length + " more lines"); print("File length = " + (f.tell())); if (f.tell() !== length) { throw new Error('bad length'); } f.truncate((length / 2) | 0); f.seek(0, 2); print("Truncated length = " + (f.tell())); if (f.tell() !== ((length / 2) | 0)) { throw new Error('truncate did not adjust length'); } return f.close(); };
var searchData= [ ['upmixtype',['UpmixType',['../struct_upmix_type.html',1,'']]] ];
import { suite, test, equal, isUndefined, isFalse, isTrue } from "../assert"; import CompositeContext from "di/CompositeContext"; import Context from "di/Context"; suite("CompositeContext", () => { test("no contexts", () => { const composite = new CompositeContext(); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isFalse(hasFirst); isUndefined(firstValue); }); test("single context", () => { const context = new Context({ first: "first expected" }); const composite = new CompositeContext([context]); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isTrue(hasFirst); equal("first expected", firstValue); }); test("multiple contexts", () => { const primaryContext = new Context({ first: "first expected" }); const secondaryContext = new Context({ first: "nothing", second: "second expected" }); const composite = new CompositeContext([primaryContext, secondaryContext]); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isTrue(hasFirst); equal("first expected", firstValue); const hasSecond = composite.has("second"); const secondValue = composite.get("second"); isTrue(hasSecond); equal("second expected", secondValue); }); });
var xue =xue || {}; xue.formCheck = xue.formCheck || {}; var fCheck = xue.formCheck; /* 提示信息的css样式 */ fCheck.setTips = function(select, tips){ $(select).css({ 'display': 'block', }).html(tips); }; /* 输入正确时,清除提醒 */ fCheck.clearTips = function(select){ $(select).css({ 'display':'none' }).html(null); }; /* 边框样式 */ fCheck.bordercss = function(argument) { if($(argument).val() !== ''){ $(argument).css('border','1px solid #68c04a'); }else{$(argument).css('border','1px solid #d2d2d2');} } /* 验证昵称 */ $(function(){ var nickname = $('.nickname'); $(nickname).on('focus',function(){ nickname.data('lastVal', $.trim(nickname.val())); $('.prompt-empty').html('请输入不超过6个汉字、18个字母或18个数字').css({ color: '#999', display: 'block' }); $(".nickname-warning").css({ display: 'none', }); }); $(nickname).on('blur',function(){ fCheck.clearTips(".prompt-empty"); if (nickname.val() == '') { $(".nickname-warning").html('请输入昵称').css({ display: 'block', }); }else{ if(nickname.data('lastVal') != $.trim(nickname.val())) { $(".nickname").css('border','1px solid #d2d2d2'); fCheck.clearTips(".nickname-warning"); $.fn.nickname(); }else{ $(".nickname-warning").css({ display: 'block', }); } } }); }); var boxs = { nickname: '.nickname', school:'.school' } $.fn.nickname = function(){ var box = $(boxs.nickname), val = box.val(); if (val == '') { fCheck.setTips(".nickname-warning",'请输入昵称'); }else { var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,18}$/; if(reg.test(val)){ $.fn.nicknameajax(); }else{ fCheck.setTips(".nickname-warning",'只能输入数字、汉字和字母'); } } }; $.fn.nicknameajax = function(){ var box = $(boxs.nickname), val = box.val(), d_val = $.trim(box.data('lastVal')); if($.trim(val) != d_val){ $.ajax({ url : '/MyInfos/getNicknameUseful', type : 'GET', dataType : 'json', data : 'nickname=' + $('.nickname').val(), timeout: 7000, async: true, success : function(result){ if(result.sign == false){ fCheck.setTips(".nickname-warning",result.msg); return false; } else { fCheck.clearTips(".nickname-warning"); fCheck.bordercss('.nickname'); $(box).data('lastVal',val); return true; } if(result.sign === 2){ window.location.href = result.msg; } } }); } } /* 学校格式验证 */ $.fn.school = function(){ var box = $(boxs.school), val = box.val(); var text = box.next('.school-warning'), block = text.addClass('success'); if (val == '') { fCheck.clearTips(".school-warning"); }else { var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,50}$/; if(reg.test(val)){ fCheck.clearTips(".school-warning"); fCheck.bordercss('.school'); }else{ fCheck.setTips(".school-warning",'只能输入数字、汉字和字母'); $('.school').css('border','1px solid #d2d2d2'); return false; } } }; $('.school').on('blur',function(){ $.fn.school(); }); /* 点击提交按钮验证 */ function inforCheckform () { if ($(".nickname").val() == $(".nickname").data("nickname") && $(".school").val() == $(".school").data("school") && $("#year").find("option:selected").text() == $("#year").attr("rel") && $("#month").find("option:selected").text() == $("#month").attr("rel") && $("#day").find("option:selected").text() == $("#day").attr("rel")) { alert('您没有修改或新增任何资料'); return false; }else{ setTimeout($.fn.nickname(),200); $.fn.school(); } if ($('.nickname-warning').is(":empty") && $('.school-warning').is(":empty") && $('.date-warning').is(":empty")) { }else{ return false; }; } var messageError = $(".message-error span").is(":empty"); if (messageError == '0') { $('.message-error').css({ display: 'block' }); setTimeout("$('.message-error').css({display: 'none'});",6000); }
'use strict'; var chai = require('chai') , Sequelize = require('../../../index') , expect = chai.expect , Support = require(__dirname + '/../support') , DataTypes = require(__dirname + '/../../../lib/data-types') , datetime = require('chai-datetime') , async = require('async'); chai.use(datetime); chai.config.includeStack = true; var sortById = function(a, b) { return a.id < b.id ? -1 : 1; }; describe(Support.getTestDialectTeaser('Includes with schemas'), function() { describe('findAll', function() { this.timeout(30000); beforeEach(function() { var self = this; this.fixtureA = function(done) { self.sequelize.dropAllSchemas().success(function() { self.sequelize.createSchema('account').success(function() { var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'}) , Company = self.sequelize.define('Company', { name: DataTypes.STRING }, {schema: 'account'}) , Product = self.sequelize.define('Product', { title: DataTypes.STRING }, {schema: 'account'}) , Tag = self.sequelize.define('Tag', { name: DataTypes.STRING }, {schema: 'account'}) , Price = self.sequelize.define('Price', { value: DataTypes.FLOAT }, {schema: 'account'}) , Customer = self.sequelize.define('Customer', { name: DataTypes.STRING }, {schema: 'account'}) , Group = self.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , GroupMember = self.sequelize.define('GroupMember', { }, {schema: 'account'}) , Rank = self.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0 }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0 }, canPost: { type: DataTypes.INTEGER, defaultValue: 0 } }, {schema: 'account'}); self.models = { AccUser: AccUser, Company: Company, Product: Product, Tag: Tag, Price: Price, Customer: Customer, Group: Group, GroupMember: GroupMember, Rank: Rank }; AccUser.hasMany(Product); Product.belongsTo(AccUser); Product.hasMany(Tag); Tag.hasMany(Product); Product.belongsTo(Tag, {as: 'Category'}); Product.belongsTo(Company); Product.hasMany(Price); Price.belongsTo(Product); AccUser.hasMany(GroupMember, {as: 'Memberships'}); GroupMember.belongsTo(AccUser); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, {as: 'Memberships'}); self.sequelize.sync({force: true}).done(function() { var count = 4 , i = -1; async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'Developers'}, {name: 'Designers'}, {name: 'Managers'} ]).done(function() { Group.findAll().done(callback); }); }, companies: function(callback) { Company.bulkCreate([ {name: 'Sequelize'}, {name: 'Coca Cola'}, {name: 'Bonanza'}, {name: 'NYSE'}, {name: 'Coshopr'} ]).done(function(err) { if (err) return callback(err); Company.findAll().done(callback); }); }, ranks: function(callback) { Rank.bulkCreate([ {name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1}, {name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1}, {name: 'Member', canInvite: 1, canRemove: 0, canPost: 0} ]).done(function() { Rank.findAll().done(callback); }); }, tags: function(callback) { Tag.bulkCreate([ {name: 'A'}, {name: 'B'}, {name: 'C'}, {name: 'D'}, {name: 'E'} ]).done(function() { Tag.findAll().done(callback); }); }, loop: ['groups', 'ranks', 'tags', 'companies', function(done, results) { var groups = results.groups , ranks = results.ranks , tags = results.tags , companies = results.companies; async.whilst( function() { return i < count; }, function(callback) { i++; async.auto({ user: function(callback) { AccUser.create().done(callback); }, memberships: ['user', function(callback, results) { var groupMembers = [ {AccUserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id}, {AccUserId: results.user.id, GroupId: groups[1].id, RankId: ranks[2].id} ]; if (i < 3) { groupMembers.push({AccUserId: results.user.id, GroupId: groups[2].id, RankId: ranks[1].id}); } GroupMember.bulkCreate(groupMembers).done(callback); }], products: function(callback) { Product.bulkCreate([ {title: 'Chair'}, {title: 'Desk'}, {title: 'Bed'}, {title: 'Pen'}, {title: 'Monitor'} ]).done(function(err) { if (err) return callback(err); Product.findAll().done(callback); }); }, userProducts: ['user', 'products', function(callback, results) { results.user.setProducts([ results.products[(i * 5) + 0], results.products[(i * 5) + 1], results.products[(i * 5) + 3] ]).done(callback); }], productTags: ['products', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.products[(i * 5) + 0].setTags([ tags[0], tags[2] ])); chainer.add(results.products[(i * 5) + 1].setTags([ tags[1] ])); chainer.add(results.products[(i * 5) + 0].setCategory(tags[1])); chainer.add(results.products[(i * 5) + 2].setTags([ tags[0] ])); chainer.add(results.products[(i * 5) + 3].setTags([ tags[0] ])); chainer.run().done(callback); }], companies: ['products', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); results.products[(i * 5) + 0].setCompany(companies[4]); results.products[(i * 5) + 1].setCompany(companies[3]); results.products[(i * 5) + 2].setCompany(companies[2]); results.products[(i * 5) + 3].setCompany(companies[1]); results.products[(i * 5) + 4].setCompany(companies[0]); chainer.run().done(callback); }], prices: ['products', function(callback, results) { Price.bulkCreate([ {ProductId: results.products[(i * 5) + 0].id, value: 5}, {ProductId: results.products[(i * 5) + 0].id, value: 10}, {ProductId: results.products[(i * 5) + 1].id, value: 5}, {ProductId: results.products[(i * 5) + 1].id, value: 10}, {ProductId: results.products[(i * 5) + 1].id, value: 15}, {ProductId: results.products[(i * 5) + 1].id, value: 20}, {ProductId: results.products[(i * 5) + 2].id, value: 20}, {ProductId: results.products[(i * 5) + 3].id, value: 20} ]).done(callback); }] }, callback); }, function(err) { expect(err).not.to.be.ok; done(); } ); }] }, done.bind(this)); }).error(done); }); }); }; }); it('should support an include with multiple different association types', function(done) { var self = this; self.sequelize.dropAllSchemas().success(function() { self.sequelize.createSchema('account').success(function() { var AccUser = self.sequelize.define('AccUser', {}, {schema: 'account'}) , Product = self.sequelize.define('Product', { title: DataTypes.STRING }, {schema: 'account'}) , Tag = self.sequelize.define('Tag', { name: DataTypes.STRING }, {schema: 'account'}) , Price = self.sequelize.define('Price', { value: DataTypes.FLOAT }, {schema: 'account'}) , Customer = self.sequelize.define('Customer', { name: DataTypes.STRING }, {schema: 'account'}) , Group = self.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , GroupMember = self.sequelize.define('GroupMember', { }, {schema: 'account'}) , Rank = self.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0 }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0 } }, {schema: 'account'}); AccUser.hasMany(Product); Product.belongsTo(AccUser); Product.hasMany(Tag); Tag.hasMany(Product); Product.belongsTo(Tag, {as: 'Category'}); Product.hasMany(Price); Price.belongsTo(Product); AccUser.hasMany(GroupMember, {as: 'Memberships'}); GroupMember.belongsTo(AccUser); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, {as: 'Memberships'}); self.sequelize.sync({force: true}).done(function() { var count = 4 , i = -1; async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'Developers'}, {name: 'Designers'} ]).done(function() { Group.findAll().done(callback); }); }, ranks: function(callback) { Rank.bulkCreate([ {name: 'Admin', canInvite: 1, canRemove: 1}, {name: 'Member', canInvite: 1, canRemove: 0} ]).done(function() { Rank.findAll().done(callback); }); }, tags: function(callback) { Tag.bulkCreate([ {name: 'A'}, {name: 'B'}, {name: 'C'} ]).done(function() { Tag.findAll().done(callback); }); }, loop: ['groups', 'ranks', 'tags', function(done, results) { var groups = results.groups , ranks = results.ranks , tags = results.tags; async.whilst( function() { return i < count; }, function(callback) { i++; async.auto({ user: function(callback) { AccUser.create().done(callback); }, memberships: ['user', function(callback, results) { GroupMember.bulkCreate([ {AccUserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id}, {AccUserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id} ]).done(callback); }], products: function(callback) { Product.bulkCreate([ {title: 'Chair'}, {title: 'Desk'} ]).done(function() { Product.findAll().done(callback); }); }, userProducts: ['user', 'products', function(callback, results) { results.user.setProducts([ results.products[(i * 2) + 0], results.products[(i * 2) + 1] ]).done(callback); }], productTags: ['products', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.products[(i * 2) + 0].setTags([ tags[0], tags[2] ])); chainer.add(results.products[(i * 2) + 1].setTags([ tags[1] ])); chainer.add(results.products[(i * 2) + 0].setCategory(tags[1])); chainer.run().done(callback); }], prices: ['products', function(callback, results) { Price.bulkCreate([ {ProductId: results.products[(i * 2) + 0].id, value: 5}, {ProductId: results.products[(i * 2) + 0].id, value: 10}, {ProductId: results.products[(i * 2) + 1].id, value: 5}, {ProductId: results.products[(i * 2) + 1].id, value: 10}, {ProductId: results.products[(i * 2) + 1].id, value: 15}, {ProductId: results.products[(i * 2) + 1].id, value: 20} ]).done(callback); }] }, callback); }, function(err) { expect(err).not.to.be.ok; AccUser.findAll({ include: [ {model: GroupMember, as: 'Memberships', include: [ Group, Rank ]}, {model: Product, include: [ Tag, {model: Tag, as: 'Category'}, Price ]} ], order: [ [AccUser.rawAttributes.id, 'ASC'] ] }).done(function(err, users) { expect(err).not.to.be.ok; users.forEach(function(user) { expect(user.Memberships).to.be.ok; user.Memberships.sort(sortById); expect(user.Memberships.length).to.equal(2); expect(user.Memberships[0].Group.name).to.equal('Developers'); expect(user.Memberships[0].Rank.canRemove).to.equal(1); expect(user.Memberships[1].Group.name).to.equal('Designers'); expect(user.Memberships[1].Rank.canRemove).to.equal(0); user.Products.sort(sortById); expect(user.Products.length).to.equal(2); expect(user.Products[0].Tags.length).to.equal(2); expect(user.Products[1].Tags.length).to.equal(1); expect(user.Products[0].Category).to.be.ok; expect(user.Products[1].Category).not.to.be.ok; expect(user.Products[0].Prices.length).to.equal(2); expect(user.Products[1].Prices.length).to.equal(4); done(); }); }); } ); }] }, done); }); }); }); }); it('should support many levels of belongsTo', function(done) { var A = this.sequelize.define('a', {}, {schema: 'account'}) , B = this.sequelize.define('b', {}, {schema: 'account'}) , C = this.sequelize.define('c', {}, {schema: 'account'}) , D = this.sequelize.define('d', {}, {schema: 'account'}) , E = this.sequelize.define('e', {}, {schema: 'account'}) , F = this.sequelize.define('f', {}, {schema: 'account'}) , G = this.sequelize.define('g', {}, {schema: 'account'}) , H = this.sequelize.define('h', {}, {schema: 'account'}); A.belongsTo(B); B.belongsTo(C); C.belongsTo(D); D.belongsTo(E); E.belongsTo(F); F.belongsTo(G); G.belongsTo(H); var b, singles = [ B, C, D, E, F, G, H ]; this.sequelize.sync().done(function() { async.auto({ as: function(callback) { A.bulkCreate([ {}, {}, {}, {}, {}, {}, {}, {} ]).done(function() { A.findAll().done(callback); }); }, singleChain: function(callback) { var previousInstance; async.eachSeries(singles, function(model, callback) { model.create({}).done(function(err, instance) { if (previousInstance) { previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function() { previousInstance = instance; callback(); }); } else { previousInstance = b = instance; callback(); } }); }, callback); }, abs: ['as', 'singleChain', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); results.as.forEach(function(a) { chainer.add(a.setB(b)); }); chainer.run().done(callback); }] }, function() { A.findAll({ include: [ {model: B, include: [ {model: C, include: [ {model: D, include: [ {model: E, include: [ {model: F, include: [ {model: G, include: [ {model: H} ]} ]} ]} ]} ]} ]} ] }).done(function(err, as) { expect(err).not.to.be.ok; expect(as.length).to.be.ok; as.forEach(function(a) { expect(a.b.c.d.e.f.g.h).to.be.ok; }); done(); }); }); }); }); it('should support ordering with only belongsTo includes', function(done) { var User = this.sequelize.define('SpecialUser', {}, {schema: 'account'}) , Item = this.sequelize.define('Item', {'test': DataTypes.STRING}, {schema: 'account'}) , Order = this.sequelize.define('Order', {'position': DataTypes.INTEGER}, {schema: 'account'}); User.belongsTo(Item, {'as': 'itemA', foreignKey: 'itemA_id'}); User.belongsTo(Item, {'as': 'itemB', foreignKey: 'itemB_id'}); User.belongsTo(Order); this.sequelize.sync().done(function() { async.auto({ users: function(callback) { User.bulkCreate([{}, {}, {}]).done(function() { User.findAll().done(callback); }); }, items: function(callback) { Item.bulkCreate([ {'test': 'abc'}, {'test': 'def'}, {'test': 'ghi'}, {'test': 'jkl'} ]).done(function() { Item.findAll({order: ['id']}).done(callback); }); }, orders: function(callback) { Order.bulkCreate([ {'position': 2}, {'position': 3}, {'position': 1} ]).done(function() { Order.findAll({order: ['id']}).done(callback); }); }, associate: ['users', 'items', 'orders', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); var user1 = results.users[0]; var user2 = results.users[1]; var user3 = results.users[2]; var item1 = results.items[0]; var item2 = results.items[1]; var item3 = results.items[2]; var item4 = results.items[3]; var order1 = results.orders[0]; var order2 = results.orders[1]; var order3 = results.orders[2]; chainer.add(user1.setItemA(item1)); chainer.add(user1.setItemB(item2)); chainer.add(user1.setOrder(order3)); chainer.add(user2.setItemA(item3)); chainer.add(user2.setItemB(item4)); chainer.add(user2.setOrder(order2)); chainer.add(user3.setItemA(item1)); chainer.add(user3.setItemB(item4)); chainer.add(user3.setOrder(order1)); chainer.run().done(callback); }] }, function() { User.findAll({ 'include': [ {'model': Item, 'as': 'itemA', where: {test: 'abc'}}, {'model': Item, 'as': 'itemB'}, Order], 'order': [ [Order, 'position'] ] }).done(function(err, as) { expect(err).not.to.be.ok; expect(as.length).to.eql(2); expect(as[0].itemA.test).to.eql('abc'); expect(as[1].itemA.test).to.eql('abc'); expect(as[0].Order.position).to.eql(1); expect(as[1].Order.position).to.eql(2); done(); }); }); }); }); it('should include attributes from through models', function(done) { var Product = this.sequelize.define('Product', { title: DataTypes.STRING }, {schema: 'account'}) , Tag = this.sequelize.define('Tag', { name: DataTypes.STRING }, {schema: 'account'}) , ProductTag = this.sequelize.define('ProductTag', { priority: DataTypes.INTEGER }, {schema: 'account'}); Product.hasMany(Tag, {through: ProductTag}); Tag.hasMany(Product, {through: ProductTag}); this.sequelize.sync({force: true}).done(function() { async.auto({ products: function(callback) { Product.bulkCreate([ {title: 'Chair'}, {title: 'Desk'}, {title: 'Dress'} ]).done(function() { Product.findAll().done(callback); }); }, tags: function(callback) { Tag.bulkCreate([ {name: 'A'}, {name: 'B'}, {name: 'C'} ]).done(function() { Tag.findAll().done(callback); }); }, productTags: ['products', 'tags', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.products[0].addTag(results.tags[0], {priority: 1})); chainer.add(results.products[0].addTag(results.tags[1], {priority: 2})); chainer.add(results.products[1].addTag(results.tags[1], {priority: 1})); chainer.add(results.products[2].addTag(results.tags[0], {priority: 3})); chainer.add(results.products[2].addTag(results.tags[1], {priority: 1})); chainer.add(results.products[2].addTag(results.tags[2], {priority: 2})); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; Product.findAll({ include: [ {model: Tag} ], order: [ ['id', 'ASC'], [Tag, 'id', 'ASC'] ] }).done(function(err, products) { expect(err).not.to.be.ok; expect(products[0].Tags[0].ProductTag.priority).to.equal(1); expect(products[0].Tags[1].ProductTag.priority).to.equal(2); expect(products[1].Tags[0].ProductTag.priority).to.equal(1); expect(products[2].Tags[0].ProductTag.priority).to.equal(3); expect(products[2].Tags[1].ProductTag.priority).to.equal(1); expect(products[2].Tags[2].ProductTag.priority).to.equal(2); done(); }); }); }); }); it('should support a required belongsTo include', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', {}, {schema: 'account'}); User.belongsTo(Group); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([{}, {}]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}, {}]).done(function() { User.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { results.users[2].setGroup(results.groups[1]).done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, required: true} ] }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); expect(users[0].Group).to.be.ok; done(); }); }); }); }); it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setGroup(results.groups[1])); chainer.add(results.users[1].setGroup(results.groups[0])); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, where: {name: 'A'}} ] }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); expect(users[0].Group).to.be.ok; expect(users[0].Group.name).to.equal('A'); done(); }); }); }); }); it('should be possible to extend the on clause with a where option on a belongsTo include', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setGroup(results.groups[1])); chainer.add(results.users[1].setGroup(results.groups[0])); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, required: true} ] }).done(function(err, users) { expect(err).not.to.be.ok; users.forEach(function(user) { expect(user.Group).to.be.ok; }); done(); }); }); }); }); it('should be possible to define a belongsTo include as required with child hasMany with limit', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , Category = this.sequelize.define('Category', { category: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group); Group.hasMany(Category); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, categories: function(callback) { Category.bulkCreate([{}, {}]).done(function() { Category.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setGroup(results.groups[1])); chainer.add(results.users[1].setGroup(results.groups[0])); chainer.run().done(callback); }], groupCategories: ['groups', 'categories', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); results.groups.forEach(function(group) { chainer.add(group.setCategories(results.categories)); }); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, required: true, include: [ {model: Category} ]} ], limit: 1 }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); users.forEach(function(user) { expect(user.Group).to.be.ok; expect(user.Group.Categories).to.be.ok; }); done(); }); }); }); }); it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , Category = this.sequelize.define('Category', { category: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group, {as: 'Team'}); Group.hasMany(Category, {as: 'Tags'}); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, categories: function(callback) { Category.bulkCreate([{}, {}]).done(function() { Category.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setTeam(results.groups[1])); chainer.add(results.users[1].setTeam(results.groups[0])); chainer.run().done(callback); }], groupCategories: ['groups', 'categories', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); results.groups.forEach(function(group) { chainer.add(group.setTags(results.categories)); }); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, required: true, as: 'Team', include: [ {model: Category, as: 'Tags'} ]} ], limit: 1 }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); users.forEach(function(user) { expect(user.Team).to.be.ok; expect(user.Team.Tags).to.be.ok; }); done(); }); }); }); }); it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , Category = this.sequelize.define('Category', { category: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group); Group.hasMany(Category); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, categories: function(callback) { Category.bulkCreate([{}, {}]).done(function() { Category.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setGroup(results.groups[1])); chainer.add(results.users[1].setGroup(results.groups[0])); chainer.run().done(callback); }], groupCategories: ['groups', 'categories', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); results.groups.forEach(function(group) { chainer.add(group.setCategories(results.categories)); }); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, required: true, include: [ {model: Category, required: false} ]} ], limit: 1 }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); users.forEach(function(user) { expect(user.Group).to.be.ok; expect(user.Group.Categories).to.be.ok; }); done(); }); }); }); }); it('should be possible to extend the on clause with a where option on a hasOne include', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Project = this.sequelize.define('Project', { title: DataTypes.STRING }, {schema: 'account'}); User.hasOne(Project, {as: 'LeaderOf'}); this.sequelize.sync({force: true}).done(function() { async.auto({ projects: function(callback) { Project.bulkCreate([ {title: 'Alpha'}, {title: 'Beta'} ]).done(function() { Project.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}]).done(function() { User.findAll().done(callback); }); }, userProjects: ['users', 'projects', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[1].setLeaderOf(results.projects[1])); chainer.add(results.users[0].setLeaderOf(results.projects[0])); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Project, as: 'LeaderOf', where: {title: 'Beta'}} ] }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(1); expect(users[0].LeaderOf).to.be.ok; expect(users[0].LeaderOf.title).to.equal('Beta'); done(); }); }); }); }); it('should be possible to extend the on clause with a where option on a hasMany include with a through model', function(done) { var Product = this.sequelize.define('Product', { title: DataTypes.STRING }, {schema: 'account'}) , Tag = this.sequelize.define('Tag', { name: DataTypes.STRING }, {schema: 'account'}) , ProductTag = this.sequelize.define('ProductTag', { priority: DataTypes.INTEGER }, {schema: 'account'}); Product.hasMany(Tag, {through: ProductTag}); Tag.hasMany(Product, {through: ProductTag}); this.sequelize.sync({force: true}).done(function() { async.auto({ products: function(callback) { Product.bulkCreate([ {title: 'Chair'}, {title: 'Desk'}, {title: 'Dress'} ]).done(function() { Product.findAll().done(callback); }); }, tags: function(callback) { Tag.bulkCreate([ {name: 'A'}, {name: 'B'}, {name: 'C'} ]).done(function() { Tag.findAll().done(callback); }); }, productTags: ['products', 'tags', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.products[0].addTag(results.tags[0], {priority: 1})); chainer.add(results.products[0].addTag(results.tags[1], {priority: 2})); chainer.add(results.products[1].addTag(results.tags[1], {priority: 1})); chainer.add(results.products[2].addTag(results.tags[0], {priority: 3})); chainer.add(results.products[2].addTag(results.tags[1], {priority: 1})); chainer.add(results.products[2].addTag(results.tags[2], {priority: 2})); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; Product.findAll({ include: [ {model: Tag, where: {name: 'C'}} ] }).done(function(err, products) { expect(err).not.to.be.ok; expect(products.length).to.equal(1); expect(products[0].Tags.length).to.equal(1); done(); }); }); }); }); it('should be possible to extend the on clause with a where option on nested includes', function(done) { var User = this.sequelize.define('User', { name: DataTypes.STRING }, {schema: 'account'}) , Product = this.sequelize.define('Product', { title: DataTypes.STRING }, {schema: 'account'}) , Tag = this.sequelize.define('Tag', { name: DataTypes.STRING }, {schema: 'account'}) , Price = this.sequelize.define('Price', { value: DataTypes.FLOAT }, {schema: 'account'}) , Customer = this.sequelize.define('Customer', { name: DataTypes.STRING }, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}) , GroupMember = this.sequelize.define('GroupMember', { }, {schema: 'account'}) , Rank = this.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0 }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0 } }, {schema: 'account'}); User.hasMany(Product); Product.belongsTo(User); Product.hasMany(Tag); Tag.hasMany(Product); Product.belongsTo(Tag, {as: 'Category'}); Product.hasMany(Price); Price.belongsTo(Product); User.hasMany(GroupMember, {as: 'Memberships'}); GroupMember.belongsTo(User); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, {as: 'Memberships'}); this.sequelize.sync({force: true}).done(function() { var count = 4 , i = -1; async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'Developers'}, {name: 'Designers'} ]).done(function() { Group.findAll().done(callback); }); }, ranks: function(callback) { Rank.bulkCreate([ {name: 'Admin', canInvite: 1, canRemove: 1}, {name: 'Member', canInvite: 1, canRemove: 0} ]).done(function() { Rank.findAll().done(callback); }); }, tags: function(callback) { Tag.bulkCreate([ {name: 'A'}, {name: 'B'}, {name: 'C'} ]).done(function() { Tag.findAll().done(callback); }); }, loop: ['groups', 'ranks', 'tags', function(done, results) { var groups = results.groups , ranks = results.ranks , tags = results.tags; async.whilst( function() { return i < count; }, function(callback) { i++; async.auto({ user: function(callback) { User.create({name: 'FooBarzz'}).done(callback); }, memberships: ['user', function(callback, results) { GroupMember.bulkCreate([ {UserId: results.user.id, GroupId: groups[0].id, RankId: ranks[0].id}, {UserId: results.user.id, GroupId: groups[1].id, RankId: ranks[1].id} ]).done(callback); }], products: function(callback) { Product.bulkCreate([ {title: 'Chair'}, {title: 'Desk'} ]).done(function() { Product.findAll().done(callback); }); }, userProducts: ['user', 'products', function(callback, results) { results.user.setProducts([ results.products[(i * 2) + 0], results.products[(i * 2) + 1] ]).done(callback); }], productTags: ['products', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.products[(i * 2) + 0].setTags([ tags[0], tags[2] ])); chainer.add(results.products[(i * 2) + 1].setTags([ tags[1] ])); chainer.add(results.products[(i * 2) + 0].setCategory(tags[1])); chainer.run().done(callback); }], prices: ['products', function(callback, results) { Price.bulkCreate([ {ProductId: results.products[(i * 2) + 0].id, value: 5}, {ProductId: results.products[(i * 2) + 0].id, value: 10}, {ProductId: results.products[(i * 2) + 1].id, value: 5}, {ProductId: results.products[(i * 2) + 1].id, value: 10}, {ProductId: results.products[(i * 2) + 1].id, value: 15}, {ProductId: results.products[(i * 2) + 1].id, value: 20} ]).done(callback); }] }, callback); }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: GroupMember, as: 'Memberships', include: [ Group, {model: Rank, where: {name: 'Admin'}} ]}, {model: Product, include: [ Tag, {model: Tag, as: 'Category'}, {model: Price, where: { value: { gt: 15 } }} ]} ], order: [ ['id', 'ASC'] ] }).done(function(err, users) { expect(err).not.to.be.ok; users.forEach(function(user) { expect(user.Memberships.length).to.equal(1); expect(user.Memberships[0].Rank.name).to.equal('Admin'); expect(user.Products.length).to.equal(1); expect(user.Products[0].Prices.length).to.equal(1); }); done(); }); } ); }] }, done); }); }); it('should be possible to use limit and a where with a belongsTo include', function(done) { var User = this.sequelize.define('User', {}, {schema: 'account'}) , Group = this.sequelize.define('Group', { name: DataTypes.STRING }, {schema: 'account'}); User.belongsTo(Group); this.sequelize.sync({force: true}).done(function() { async.auto({ groups: function(callback) { Group.bulkCreate([ {name: 'A'}, {name: 'B'} ]).done(function() { Group.findAll().done(callback); }); }, users: function(callback) { User.bulkCreate([{}, {}, {}, {}]).done(function() { User.findAll().done(callback); }); }, userGroups: ['users', 'groups', function(callback, results) { var chainer = new Sequelize.Utils.QueryChainer(); chainer.add(results.users[0].setGroup(results.groups[0])); chainer.add(results.users[1].setGroup(results.groups[0])); chainer.add(results.users[2].setGroup(results.groups[0])); chainer.add(results.users[3].setGroup(results.groups[1])); chainer.run().done(callback); }] }, function(err) { expect(err).not.to.be.ok; User.findAll({ include: [ {model: Group, where: {name: 'A'}} ], limit: 2 }).done(function(err, users) { expect(err).not.to.be.ok; expect(users.length).to.equal(2); users.forEach(function(user) { expect(user.Group.name).to.equal('A'); }); done(); }); }); }); }); it('should be possible use limit, attributes and a where on a belongsTo with additional hasMany includes', function(done) { var self = this; this.fixtureA(function() { self.models.Product.findAll({ attributes: ['title'], include: [ {model: self.models.Company, where: {name: 'NYSE'}}, {model: self.models.Tag}, {model: self.models.Price} ], limit: 3, order: [ ['id', 'ASC'] ] }).done(function(err, products) { expect(err).not.to.be.ok; expect(products.length).to.equal(3); products.forEach(function(product) { expect(product.Company.name).to.equal('NYSE'); expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; }); done(); }); }); }); it('should be possible to use limit and a where on a hasMany with additional includes', function(done) { var self = this; this.fixtureA(function() { self.models.Product.findAll({ include: [ {model: self.models.Company}, {model: self.models.Tag}, {model: self.models.Price, where: { value: {gt: 5} }} ], limit: 6, order: [ ['id', 'ASC'] ] }).done(function(err, products) { expect(err).not.to.be.ok; expect(products.length).to.equal(6); products.forEach(function(product) { expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; product.Prices.forEach(function(price) { expect(price.value).to.be.above(5); }); }); done(); }); }); }); it('should be possible to use limit and a where on a hasMany with a through model with additional includes', function(done) { var self = this; this.fixtureA(function() { self.models.Product.findAll({ include: [ {model: self.models.Company}, {model: self.models.Tag, where: {name: ['A', 'B', 'C']}}, {model: self.models.Price} ], limit: 10, order: [ ['id', 'ASC'] ] }).done(function(err, products) { expect(err).not.to.be.ok; expect(products.length).to.equal(10); products.forEach(function(product) { expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; product.Tags.forEach(function(tag) { expect(['A', 'B', 'C']).to.include(tag.name); }); }); done(); }); }); }); it.skip('should support including date fields, with the correct timeszone', function(done) { var User = this.sequelize.define('user', { dateField: Sequelize.DATE }, {timestamps: false, schema: 'account'}) , Group = this.sequelize.define('group', { dateField: Sequelize.DATE }, {timestamps: false, schema: 'account'}); User.hasMany(Group); Group.hasMany(User); this.sequelize.sync().success(function() { User.create({ dateField: Date.UTC(2014, 1, 20) }).success(function(user) { Group.create({ dateField: Date.UTC(2014, 1, 20) }).success(function(group) { user.addGroup(group).success(function() { User.findAll({ where: { id: user.id }, include: [Group] }).success(function(users) { expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); done(); }); }); }); }); }); }); }); describe('findOne', function() { it('should work with schemas', function() { var self = this; var UserModel = this.sequelize.define('User', { Id: { type: DataTypes.INTEGER, primaryKey: true }, Name: DataTypes.STRING, UserType: DataTypes.INTEGER, Email: DataTypes.STRING, PasswordHash: DataTypes.STRING, Enabled: { type: DataTypes.BOOLEAN }, CreatedDatetime: DataTypes.DATE, UpdatedDatetime: DataTypes.DATE }, { schema: 'hero', tableName: 'User', timestamps: false }); var ResumeModel = this.sequelize.define('Resume', { Id: { type: Sequelize.INTEGER, primaryKey: true }, UserId: { type: Sequelize.INTEGER, references: UserModel, referencesKey: 'Id' }, Name: Sequelize.STRING, Contact: Sequelize.STRING, School: Sequelize.STRING, WorkingAge: Sequelize.STRING, Description: Sequelize.STRING, PostType: Sequelize.INTEGER, RefreshDatetime: Sequelize.DATE, CreatedDatetime: Sequelize.DATE }, { schema: 'hero', tableName: 'resume', timestamps: false }); UserModel.hasOne(ResumeModel, { foreignKey: 'UserId', as: 'Resume' }); ResumeModel.belongsTo(UserModel, { foreignKey: 'UserId' }); return self.sequelize.dropAllSchemas().then(function() { return self.sequelize.createSchema('hero'); }).then(function() { return self.sequelize.sync({force: true}).then(function() { return UserModel.find({ where: { Id: 1 }, include: [{ model: ResumeModel, as: 'Resume' }] }).on('sql', function(sql) { console.log(sql); }); }); }); }); }); });
webpackJsonp([2,3],[function(n,c){}]);
import React, { Component, PropTypes } from 'react'; import ReactDOM from 'react-dom'; export default class TaskForm extends Component { constructor(props, context) { super(props, context); this.state = { text: this.props.text || '' }; } componentWillReceiveProps(nextProps) { this.state = { text: nextProps.text || '' }; } handleSubmit() { const text = this.refs.taskInput.value.trim(); this.props.onAddClick(text); } handlePressEnter(e) { const text = e.target.value.trim(); if (e.which === 13) { this.props.onAddClick(text); } } handleChange(e) { const text = e.target.value.trim(); this.setState({text: text}); } render() { const style = { btn: { margin: "0 5px", backgroundColor: "#dfe", paddingLeft: "5px", paddingRight: "5px" } }; const { addTodo } = this.props; return ( <div style={{float: 'right', display: 'inline'}}> <input type="text" size="20" ref="taskInput" value={this.state.text} onChange={this.handleChange.bind(this)} onKeyDown={this.handlePressEnter.bind(this)}/> <button className="btn btn-sm" style={style.btn} onClick={ () => this.handleSubmit()} >add</button> </div> ); } } TaskForm.propTypes = { text: PropTypes.string, onAddClick: PropTypes.func.isRequired };
export default class Storage { constructor(type, storageItemName) { this.type = type || 'localStorage'; this.itemName = storageItemName || 'document'; this.available = Storage.storageAvailable(this.type); } static storageAvailable(type) { try { let storage = window[type]; let x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch(e) { console.warn(`${type} is not available`); return false; } } saveDoc(document) { if (!this.available) return; let storage = window[this.type]; storage.setItem(this.itemName, JSON.stringify(document)); } loadDoc() { if (!this.available) return; const storage = window[this.type]; const item = storage.getItem(this.itemName); if (item) return JSON.parse(item) return item; } }
import TriggerableMixin from '../Common/TriggerableMixin.js'; import Introspectable from '../Common/Introspectable.js'; class GenericWrapper extends TriggerableMixin(Introspectable) { constructor (options) { super(); this.index = options.index; this.table = options.table; if (this.index === undefined || !this.table) { throw new Error(`index and table are required`); } this.classObj = options.classObj || null; this.row = options.row || {}; this.connectedItems = options.connectedItems || {}; this.duplicateItems = options.duplicateItems || []; } registerDuplicate (item) { this.duplicateItems.push(item); } connectItem (item) { this.connectedItems[item.table.tableId] = this.connectedItems[item.table.tableId] || []; if (this.connectedItems[item.table.tableId].indexOf(item) === -1) { this.connectedItems[item.table.tableId].push(item); } for (const dup of this.duplicateItems) { item.connectItem(dup); dup.connectItem(item); } } disconnect () { for (const itemList of Object.values(this.connectedItems)) { for (const item of itemList) { const index = (item.connectedItems[this.table.tableId] || []).indexOf(this); if (index !== -1) { item.connectedItems[this.table.tableId].splice(index, 1); } } } this.connectedItems = {}; } get instanceId () { return `{"classId":"${this.classObj.classId}","index":"${this.index}"}`; } get exportId () { return `${this.classObj.classId}_${this.index}`; } get label () { return this.classObj.annotations.labelAttr ? this.row[this.classObj.annotations.labelAttr] : this.index; } equals (item) { return this.instanceId === item.instanceId; } async * handleLimit (options, iterators) { let limit = Infinity; if (options.limit !== undefined) { limit = options.limit; delete options.limit; } let i = 0; for (const iterator of iterators) { for await (const item of iterator) { yield item; i++; if (item === null || i >= limit) { return; } } } } async * iterateAcrossConnections (tableIds) { // First make sure that all the table caches have been fully built and // connected await Promise.all(tableIds.map(tableId => { return this.classObj.model.tables[tableId].buildCache(); })); yield * this._iterateAcrossConnections(tableIds); } * _iterateAcrossConnections (tableIds) { if (this.reset) { return; } const nextTableId = tableIds[0]; if (tableIds.length === 1) { yield * (this.connectedItems[nextTableId] || []); } else { const remainingTableIds = tableIds.slice(1); for (const item of this.connectedItems[nextTableId] || []) { yield * item._iterateAcrossConnections(remainingTableIds); } } } } Object.defineProperty(GenericWrapper, 'type', { get () { return /(.*)Wrapper/.exec(this.name)[1]; } }); export default GenericWrapper;
'use strict'; var getSubplotCalcData = require('../get_data').getSubplotCalcData; var counterRegex = require('../../lib').counterRegex; var createPolar = require('../polar/polar'); var constants = require('./constants'); var attr = constants.attr; var name = constants.name; var counter = counterRegex(name); var attributes = {}; attributes[attr] = { valType: 'subplotid', dflt: name, editType: 'calc', description: [ 'Sets a reference between this trace\'s data coordinates and', 'a smith subplot.', 'If *smith* (the default value), the data refer to `layout.smith`.', 'If *smith2*, the data refer to `layout.smith2`, and so on.' ].join(' ') }; function plot(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var subplotIds = fullLayout._subplots[name]; for(var i = 0; i < subplotIds.length; i++) { var id = subplotIds[i]; var subplotCalcData = getSubplotCalcData(calcData, name, id); var subplot = fullLayout[id]._subplot; if(!subplot) { subplot = createPolar(gd, id, true); fullLayout[id]._subplot = subplot; } subplot.plot(subplotCalcData, fullLayout, gd._promises); } } function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldIds = oldFullLayout._subplots[name] || []; for(var i = 0; i < oldIds.length; i++) { var id = oldIds[i]; var oldSubplot = oldFullLayout[id]._subplot; if(!newFullLayout[id] && !!oldSubplot) { oldSubplot.framework.remove(); for(var k in oldSubplot.clipPaths) { oldSubplot.clipPaths[k].remove(); } } } } module.exports = { attr: attr, name: name, idRoot: name, idRegex: counter, attrRegex: counter, attributes: attributes, layoutAttributes: require('./layout_attributes'), supplyLayoutDefaults: require('./layout_defaults'), plot: plot, clean: clean, toSVG: require('../cartesian').toSVG };