code
stringlengths
2
1.05M
function createQueryLookup ({ name = 'locale' } = {}) { const noNameError = new Error('A query string parameter name is required for query string locale lookup'); if (typeof name !== 'string' || name.trim().length <= 0) { throw noNameError; } return function lookupQuery (req) { if (!(name in req.query)) { return; } return req.query[name]; }; }; module.exports = createQueryLookup;
import Ember from 'ember'; import _ from 'lodash'; /** Live Filtering component Filter channels using tags @class LiveFilteringComponent */ export default Ember.Component.extend({ /** Normalized object of message strings @property messages @type Object */ messages: { noMatch: 'Sorry, there are no channels that match that criteria. Try un-checking some filters or adding more channels.' }, /** Alias for collection of filters @property filters @type Class */ filters: Ember.computed.alias('buildFilters'), /** Alias for categorized groups of filters @property filtersGroupGenres @type Class */ filtersGroupGenres: Ember.computed.filterBy('filtersArr', 'group', 'genres'), /** Signal if any of the filters in this group are on @property genresFilterOn @type Bool */ genresFilterOn: function() { return this.get('filtersGroupGenres').isAny('on'); }.property('filtersArr.@each.on'), /** Alias for categorized groups of filters @property filtersGroupGenres @type Class */ filtersGroupAvailability: Ember.computed.filterBy('filtersArr', 'group', 'availablity'), /** Signal if any of the filters in this group are on @property availabilityFilterOn @type Bool */ availabilityFilterOn: function() { return this.get('filtersGroupAvailability').isAny('on'); }.property('filtersArr.@each.on'), /** Alias for categorized groups of filters @property filtersGroupContent @type Class */ filtersGroupContent: Ember.computed.filterBy('filtersArr', 'group', 'content'), /** Signal if any of the filters in this group are on @property contentFilterOn @type Bool */ contentFilterOn: function() { return this.get('filtersGroupContent').isAny('on'); }.property('filtersArr.@each.on'), /* Allfilters array within filters object @property filtersArr @type Array */ sortAlpha: ['name'], filtersArr: Ember.computed.sort('filters.allfilters', 'sortAlpha'), /** Create model for filters collection @property buildFilters @type Class */ buildFilters: function() { var currentContext = this.get('controller').get('model'), currentModel = currentContext.get('model'), library = currentModel.get('library'), cachedFilters = currentContext.get('cachedFilters'); //Breakdown of filters model /* Filters: { allfilters: [ filter: { name: Display name, tag: App readable name to compare against channel tags, on: Bool signifiy filter/unfilter channel } ] } */ //Template for filters model var FiltersModel = Ember.Object.extend({ init: function() { this._super(); this.set("allfilters", []); } }), _filters = FiltersModel.create(); var libtags = [], allTags = _.uniq(library.getEach('tags')); allTags.filter(function(tags) { tags.filter(function(tag) { if (!_.contains(libtags, tag)) { libtags.push(tag); } }); }); //plain old array of filters var poarr = [ //Price { name: 'Free', tag: 'free', group: 'availablity' }, { name: 'Subscription', tag: 'subscription', group: 'availablity' }, { name: 'Rent', tag: 'alacarte', group: 'availablity' }, { name: 'Cable Provider', tag: 'cable provider', group: 'availablity' }, { name: 'Cast-ready', tag: 'castready', group: 'availablity' }, //Content { name: 'Full Episodes', tag: 'tv', group: 'content' }, { name: 'Movies', tag: 'movies', group: 'content' }, { name: 'Music', tag: 'music', group: 'content' }, { name: 'Radio', tag: 'radio', group: 'content' }, { name: 'P2P', tag: 'p2p', group: 'content' }, //Genres { name: 'Kids', tag: 'kids', group: 'genres' }, { name: 'Sports', tag: 'sports', group: 'genres' }, { name: 'News', tag: 'news', group: 'genres' }, { name: 'Fitness', tag: 'exercise', group: 'genres' }, { name: 'Latino', tag: 'latino', group: 'genres' }, { name: 'Documentaries', tag: 'documentaries', group: 'genres' }, { name: 'Comedy', tag: 'comedy', group: 'genres' }, { name: 'Drama', tag: 'drama', group: 'genres' }, { name: 'SciFi / Fantasy', tag: 'scifi/fantasy', group: 'genres' }, { name: 'Concerts', tag: 'concerts', group: 'genres' }, { name: 'Horror', tag: 'horror', group: 'genres' }, { name: 'Action/Adventure', tag: 'action/adventure', group: 'genres' }, { name: 'Reality', tag: 'reality', group: 'genres' }, { name: 'Animation', tag: 'animation', group: 'genres' }, { name: 'DIY', tag: 'diy', group: 'genres' }, { name: 'Food', tag: 'food', group: 'genres' }, { name: 'Tech', tag: 'tech', group: 'genres' }, { name: 'Premium', tag: 'premium', group: 'genres' }, { name: 'Social', tag: 'social', group: 'genres' }, { name: 'Independent', tag: 'independent', group: 'genres' } ]; poarr.filter(function(item) { var a = FiltersModel.create(); a.setProperties({ name: item.name, on: false, tag: item.tag, group: item.group }); if (_.contains(libtags, item.tag)) { _filters.get('allfilters').push(a); } }); //if filters have already been cached, return cached filters if (!cachedFilters) { currentContext.set('cachedFilters', _filters); return _filters; } else { return cachedFilters; } }.property(), /** Compare channel's tags with selected filters @method applyFilters */ applyFilters: function() { var context = this.get('model'), model = context.model, lib = model.get('library'), useFilters = this.get('filters.allfilters'), onFilters = useFilters.filterBy('on', true), shouldApplyFilters = []; //reset messaging this.set('error', false); this.set('message', null); //Isolate filters that are turn on into an array var sameGroup = _.uniq(onFilters.getEach('group')).length === 1; onFilters.filter(function(item) { shouldApplyFilters.push(item.tag); }); //Iterate channels lib, toggle isfiltered property lib.setEach('isfiltered', true); lib.filter(function(item) { //todo: filter groups should be allowed to compound if (!sameGroup) { //show only channels with this combination of filters if (_.difference(shouldApplyFilters, item.tags).length === 0) { item.toggleProperty('isfiltered'); } } else { //aggregate channels within this group shouldApplyFilters.filter(function(should) { if (_.contains(item.tags, should)) { item.set('isfiltered', false); } }); } }); var visibleLib = lib.filterBy('visible', true); if (visibleLib.isEvery('isfiltered')) { var controllerContext = this.get('controller').get('model'); if (controllerContext.get('showFilterMessaging')) { return controllerContext.get('controllers.application').addInfoMessage(this.get('messages.noMatch')); } } }, actions: { /** Designate filter on or off @method toggleFilter */ toggleFilter: function(filter) { var filtersObj = this.get('filters'), currentFilter = filtersObj.get('allfilters'), foundFilter = currentFilter.findBy('name', filter); foundFilter.toggleProperty('on'); this.applyFilters(); }, /** Designate entire filter group on or off @method toggleFilterGroup */ toggleFiltersGroup: function(group) { var filtersGroup = this.get('filtersArr').filterBy('group', group), status = filtersGroup.isAny('on'); filtersGroup.setEach('on', !status); this.applyFilters(); }, /** Save filter choices in local storage @method saveFilters */ saveFilters: function() { //to do } } });
'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"', AUTH0_REDIRECTURI: '"http://localhost:8080/auth0callback"', })
var osmosis = require('../index'); var server = require('./server'); var URL = require('url'); var url = server.host + ':' + server.port; module.exports.link = function (assert) { var count = 0; osmosis.get(url + '/paginate') .paginate('a[rel="next"]', 3) .set('page', 'div') .then(function (context, data) { var page = context.request.params.page || 1; assert.equal(page, data.page); assert.equal(page, ++count); }) .done(function () { assert.ok(count > 1); assert.done(); }); }; module.exports.param = function (assert) { var count = 0; osmosis.get(url + '/paginate', { page: 1 }) .paginate({ page: +1 }, 3) .set('page', 'div') .then(function (context, data) { var page = context.request.params.page || 1; assert.equal(page, data.page); assert.equal(page, ++count); }) .done(function () { assert.ok(count > 1); assert.done(); }); }; module.exports.form = function (assert) { var count = 0; osmosis.get(url + '/paginate') .paginate('form', 3) .set('page', 'div') .then(function (context, data) { var page = context.request.params.page || 1; assert.ok(page == data.page); assert.ok(page == ++count); }) .done(function () { assert.ok(count > 1); assert.done(); }); }; server('/paginate', function (url, req, res, data) { res.setHeader("Content-Type", "text/html"); var page = 1; if (data && data.page) page = data.page; else if (url.query.page) page = url.query.page; res.write('<div>' + page + '</div><a href="?page=' + (parseInt(page) + 1) + '" rel="next">Next</a>\ <form method="POST"><input type="hidden" name="page" value="' + (parseInt(page) + 1) + '"></form>'); res.end(); });
(function($, DataTables){ $.extend( true, DataTables.Buttons.defaults, { dom: { container: { className: 'dt-buttons ui-buttonset' }, button: { className: 'dt-button ui-button ui-state-default ui-button-text-only', disabled: 'ui-state-disabled', active: 'ui-state-active' }, buttonLiner: { tag: 'span', className: 'ui-button-text' } } } ); DataTables.ext.buttons.collection.text = function ( dt ) { return dt.i18n('buttons.collection', 'Collection <span class="ui-button-icon-primary ui-icon ui-icon-triangle-1-s"/>'); }; })(jQuery, jQuery.fn.dataTable);
import React from 'react' import { Image } from 'cloudinary-react' export default () => ( <div style={{ marginBottom: '40px' }}> <Image style={{ margin: '20px 0' }} cloudName='ziro' width='40' publicId='ok-icon_bskbxm' version='1508212647' format='png' secure='true' /> <p>Seu CNPJ foi validado com sucesso!</p> <p>Agora, termine de preencher o formulรกrio abaixo para acessar o aplicativo. ร‰ rapidinho ;)</p> </div> )
var seek = require('../'); seek(process.cwd(), 'cwd console', { dotFiles: false }, function(file, matches) { console.log('\nMatched: '+file+'\nMatches:'); console.log(matches); console.log(); });
/* globals require, module, console */ /* jshint -W097 */ 'use strict'; /****************************** * 3 - Join, Leave, Disconnect ******************************/ var view = require('./view.js'), q = require('Q'), Firebase = require('firebase'), Settings = require('./settings.js'); function FireChat() { var fullName; var userId; var firebase; function onEnter(name) { fullName = name; view.addMember(name, userId); view.setUsername(name); firebase.child('chatroom') .child('members') .child(userId) .set({ dateAdded: Firebase.ServerValue.TIMESTAMP }); // Make sure we remove ourselves // if the connection dies firebase.child('chatroom') .child('members') .child(userId) .onDisconnect() .remove(); } function onLeave() { view.removeMember(userId); view.clearMessages(); firebase.child('chatroom') .child('members') .child(userId) .set(null); } function onAddMessage(message) { view.addMessage(fullName, message); } function onChangeTopic(newTopic) { view.setTopic(newTopic); } function initialiseFirebase() { var deferred = q.defer(); // Initialise firebase firebase = new Firebase(Settings.firebaseUrl); // Do anonymous auth firebase.authAnonymously(function(error, context) { if (error) { deferred.reject(error, context); } else { deferred.resolve(context.uid); } }); return deferred.promise; } // public API this.initialise = function() { // Rig up the events view.onEnter = onEnter; view.onLeave = onLeave; view.onAddMessage = onAddMessage; view.onChangeTopic = onChangeTopic; // Initialise the view view.initialise() .then(initialiseFirebase) .then(function initialised(uid) { userId = uid; console.log('Initialised'); view.enableLoginBox(); }); }; } module.exports = new FireChat();
(function () { 'use strict'; /** * * @ngdoc directive * @module __modulename__ * @name __directivename___ * * @requires $q * * @description * A generic angular directive */ angular .module('gen') .directive('gridBase', grid); //grid.$inject = ['']; function grid() { var directive = { link: link, restrict: 'EA', scope: { directivename: "@", parentdirective: "@", gridClass: "@", }, transclude: true, templateUrl: "/app/gen/components/grid/grid.html", bindToController: true, controllerAs: "vm", controller: Controller, }; return directive; function link(scope, element, attrs) { if (!attrs.directivename) { scope.vm.directivename = "gridBase"; } var ctrl = {}; if (!attrs.hasOwnProperty("parentdirective")) { ctrl = element.parent().controller(); } else { ctrl = element.parent().controller(attrs.parentdirective); } if (ctrl.hasOwnProperty("_registerDirective")) { ctrl._registerDirective(scope.vm, scope.vm.directivename); } initControl(scope, attrs); } function initControl(scope, attrs){ scope.vm.tabExclusive = (attrs.tabExclusive !== undefined || attrs.tabExclusive == '') ? true : false; scope.vm.hasPaging = false; scope.vm.hasSearch = false; } } Controller.$inject = ['lodash', '$scope'] function Controller(_, $scope) { var vm = this; /** * vm.parentdirective * vm.directivename * vm.gridClass */ vm.cellTemplates = []; vm.headerTemplates = []; vm.data = []; vm.addCellTemplate = function(templateConfig){ //we make a temp copy so as not to trigger the watcher on vm.cellTemplates //more than we have to // var temp = angular.copy(vm.cellTemplates); //angular copy of an object // temp.push(templateString); // vm.cellTemplates = temp; vm.cellTemplates.push(templateConfig); } vm.addHeaderTemplate = function(templateConfig){ vm.headerTemplates.push(templateConfig); } vm.setData = function(data){ vm.data = data; } var sortOrder = []; vm.sort = function(sortBy){ var dex = _.findIndex(sortOrder, { 'name': sortBy }); console.log(dex); if(dex > -1){ if(sortOrder[dex].rule == "desc"){ sortOrder = _.pullAt(sortOrder, dex); } else{ sortOrder[dex].rule = "desc"; } } else{ sortOrder.push({ name: sortBy, rule: "asc" }); } console.log(sortOrder) vm.data = _.sortByOrder(vm.data, _.map(sortOrder, 'name'), _.map(sortOrder, 'rule')); console.log(vm.data); $scope.$digest(); } function init(){ } init(); } })();
import 'react-native'; import React from 'react'; import Board from '../build/common/board/Board'; import * as boardUtil from '../build/common/board/util'; import * as fenUtil from '../build/common/board/fen'; import { defaults as boardDefaultConf } from '../build/common/board/config' // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; jest.mock('react-native-svg', () => { const React = require('react') // eslint-disable-next-line no-undef const ReactNativeSvg = jest.genMockFromModule('react-native-svg') const svgElementMockGenerator = (name, propTypes) => { function SvgMock() { return ( React.createElement(name, null, null) ) } SvgMock.displayName = name SvgMock.propTypes = propTypes return SvgMock } const Svg = svgElementMockGenerator('Svg', ReactNativeSvg.Svg.propTypes) Svg.Rect = svgElementMockGenerator('Rect', ReactNativeSvg.Rect.propTypes) Svg.G = svgElementMockGenerator('G', ReactNativeSvg.G.propTypes) Svg.LinearGradient = svgElementMockGenerator( 'LinearGradient', ReactNativeSvg.LinearGradient.propTypes ) Svg.Path = svgElementMockGenerator('Path', ReactNativeSvg.Path.propTypes) Svg.Circle = svgElementMockGenerator('Circle', ReactNativeSvg.Circle.propTypes) Svg.Symbol = svgElementMockGenerator('Symbol', ReactNativeSvg.Symbol.propTypes) Svg.Use = svgElementMockGenerator('Use', ReactNativeSvg.Use.propTypes) Svg.Stop = svgElementMockGenerator('Stop', ReactNativeSvg.Stop.propTypes) Svg.Defs = svgElementMockGenerator('Defs', ReactNativeSvg.Defs.propTypes) return Svg }) it('renders correctly', () => { const uidGen = boardUtil.uidGenFactory() const state = { orientation: 'white', turnColor: 'white', pieces: fenUtil.initialBoard(fenUtil.initial, uidGen), selected: null, moveDests: null, check: null, } const boardHandlers = { onSelectSquare: () => {}, onMove: () => {} } const tree = renderer.create( <Board state={state} handlers={boardHandlers} config={boardDefaultConf} size={400} /> ); });
var fs = require('fs'); module.exports = function meminfo(callback) { var result = {}; fs.readFile('/proc/meminfo', 'utf8', function (err, str) { if (err) { return callback(err); } str.split('\n').forEach(function (line) { var parts = line.split(':'); if (parts.length === 2) { result[parts[0]] = parts[1].trim().split(' ', 1)[0]; } }); callback(null, result); }); };
module.exports = 'โœจ ๐Ÿข ๐Ÿš€ โœจ'
import styled from "styled-components" import media from "styled-media-query" import AniLink from "gatsby-plugin-transition-link/AniLink" export const MenuLinksWrapper = styled.nav` ${media.lessThan("large")` display: none; `} ` export const MenuLinksList = styled.ul` font-size: 1.2rem; font-weight: 300; ` export const MenuLinksItem = styled.li` padding: 0.5rem 0; .active { color: var(--highlight); } ` export const MenuLinksLink = styled(AniLink)` color: var(--texts); text-decoration: none; transition: color 0.5s; &:hover { color: var(--highlight); } `
var ResourceServerActionCreators = require('actions/ResourceServerActionCreators'); module.exports = { createResource: function(fields) { window.setTimeout(function() { ResourceServerActionCreators.recieveRawCreatedResource(fields); }); } };
export default { props: { struct: { type: Function, default () { return {}; }, }, }, };
'use strict'; import React, { Component } from 'react' import { connect } from 'react-redux' import { PageNavigator, actions } from 'kn-react-native-router' import * as types from '../../router' import LoginContainer from './login' import RegisterContainer from './register' const { navigationPop, navigationPush, navigationLoginReset } = actions class LoginNavigator extends PageNavigator { constructor(props) { super(props) this.name = 'login' this.container = { LoginPage: { routeKey: 'LoginPage', component: LoginContainer }, RegisterPage: { routeKey: 'RegisterPage', component: RegisterContainer } } //this.showHeader = false } } function mapStateToProps(state) { return { navigationState: state.navigation.navigationStates[types.NAVIGATOR_NAME_LOGIN] } } export default connect(mapStateToProps, { navigationPop, navigationPush, navigationLoginReset } )(LoginNavigator)
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // import // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ import React from 'react'; import { graphql } from 'gatsby'; import PropTypes from 'prop-types'; import sample from 'lodash/sample'; import { RootContainer, SEOContainer } from '~containers'; import { Main, Section, Aside, View, Button, H1, Ul, Ol, Li } from '~components'; import { renderBlocks, pagePropTypes } from '~utils'; // Hexapawn was first described in an article by Martin Gardner in Scientific American in 1962 // http://cs.williams.edu/~freund/cs136-073/GardnerHexapawn.pdf // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // query // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ export const query = graphql` { page: mdx(frontmatter: { meta: { permalink: { eq: "/lab/hexapawn/" } } }) { frontmatter { ...MetaFragment blocks { title codeLink type } } } } `; // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // helpers // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ function Pawn({ pawn, isSelected, onSelect, ...rest }) { return ( <Button css={` position: absolute; width: var(--grid); height: var(--grid); transform: translateX(calc(100% * ${pawn.x - 1})) translateY(calc(100% * ${pawn.y - 1})) !important; line-height: 2rem; transition: transform 250ms; display: grid; place-items: center; font-size: 8rem; cursor: ${onSelect && 'pointer'}; color: ${isSelected && 'var(--color-primary)'}; pointer-events: ${pawn.figure === 'โ™Ÿ' && 'none'}; `} onClick={() => onSelect(pawn.id)} {...rest} > {`${pawn.figure}\u{fe0e}`} </Button> ); } Pawn.propTypes = { pawn: PropTypes.shape({ id: PropTypes.number.isRequired, x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, figure: PropTypes.string.isRequired, }).isRequired, isSelected: PropTypes.bool, onSelect: PropTypes.func, }; Pawn.defaultProps = { isSelected: false, onSelect: () => {}, }; function Move({ move, onMove, ...rest }) { return ( <Button css={` grid-column: ${move.x}; grid-row: ${move.y}; z-index: 1; cursor: pointer; box-shadow: inset 0 0 0 2px hsla(var(--hsl-primary), 0.5); `} onClick={() => onMove(move)} {...rest} /> ); } Move.propTypes = { move: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, }).isRequired, onMove: PropTypes.func, }; Move.defaultProps = { onMove: () => {}, }; const enemyDefault = [ { id: 1, x: 1, y: 1, figure: 'โ™Ÿ' }, { id: 2, x: 2, y: 1, figure: 'โ™Ÿ' }, { id: 3, x: 3, y: 1, figure: 'โ™Ÿ' }, ]; const playerDefault = [ { id: 4, x: 1, y: 3, figure: 'โ™™' }, { id: 5, x: 2, y: 3, figure: 'โ™™' }, { id: 6, x: 3, y: 3, figure: 'โ™™' }, ]; const AIdefault = [ // 1 { id: 0, board: 'eeep...pp', move: [2, '12'] }, { id: 1, board: 'eeep...pp', move: [2, '22'] }, { id: 2, board: 'eeep...pp', move: [3, '32'] }, { id: 3, board: 'eee..ppp.', move: [1, '12'] }, { id: 4, board: 'eee..ppp.', move: [2, '22'] }, { id: 5, board: 'eee..ppp.', move: [2, '32'] }, // 2 { id: 6, board: 'eee.p.p.p', move: [1, '12'] }, { id: 7, board: 'eee.p.p.p', move: [1, '22'] }, { id: 8, board: 'eee.p.p.p', move: [3, '22'] }, { id: 9, board: 'eee.p.p.p', move: [3, '32'] }, // 3 { id: 10, board: 'e.eep...p', move: [1, '22'] }, { id: 11, board: 'e.eep...p', move: [3, '22'] }, { id: 12, board: 'e.eep...p', move: [3, '32'] }, { id: 13, board: 'e.eep...p', move: [2, '13'] }, { id: 14, board: 'e.e.pep..', move: [1, '12'] }, { id: 15, board: 'e.e.pep..', move: [1, '22'] }, { id: 16, board: 'e.e.pep..', move: [3, '22'] }, { id: 17, board: 'e.e.pep..', move: [2, '33'] }, // 4 { id: 18, board: '.eepe...p', move: [2, '12'] }, { id: 19, board: '.eepe...p', move: [3, '32'] }, { id: 20, board: '.eepe...p', move: [1, '23'] }, { id: 21, board: '.eepe...p', move: [1, '33'] }, { id: 22, board: 'ee..epp..', move: [1, '12'] }, { id: 23, board: 'ee..epp..', move: [2, '32'] }, { id: 24, board: 'ee..epp..', move: [3, '13'] }, { id: 25, board: 'ee..epp..', move: [3, '23'] }, // 5 { id: 26, board: 'e.epp..p.', move: [1, '22'] }, { id: 27, board: 'e.epp..p.', move: [3, '22'] }, { id: 28, board: 'e.epp..p.', move: [3, '32'] }, { id: 29, board: 'e.e.pp.p.', move: [1, '12'] }, { id: 30, board: 'e.e.pp.p.', move: [1, '22'] }, { id: 31, board: 'e.e.pp.p.', move: [3, '22'] }, // 6 { id: 32, board: 'ee.p.p..p', move: [2, '12'] }, { id: 33, board: 'ee.p.p..p', move: [2, '22'] }, { id: 34, board: 'ee.p.p..p', move: [2, '32'] }, { id: 35, board: '.eep.pp..', move: [2, '32'] }, { id: 36, board: '.eep.pp..', move: [2, '32'] }, { id: 37, board: '.eep.pp..', move: [2, '32'] }, // 7 { id: 38, board: '.ee.epp..', move: [2, '32'] }, { id: 39, board: '.ee.epp..', move: [1, '13'] }, { id: 40, board: '.ee.epp..', move: [1, '23'] }, { id: 41, board: 'ee.pe...p', move: [2, '12'] }, { id: 42, board: 'ee.pe...p', move: [3, '23'] }, { id: 43, board: 'ee.pe...p', move: [3, '33'] }, // 8 { id: 44, board: '.eeeppp..', move: [2, '32'] }, { id: 45, board: '.eeeppp..', move: [3, '22'] }, { id: 46, board: 'ee.ppe..p', move: [1, '22'] }, { id: 47, board: 'ee.ppe..p', move: [2, '12'] }, // 9 { id: 48, board: 'e.ee.p.p.', move: [2, '13'] }, { id: 49, board: 'e.ee.p.p.', move: [2, '23'] }, { id: 50, board: 'e.ep.e.p.', move: [2, '23'] }, { id: 51, board: 'e.ep.e.p.', move: [2, '33'] }, // 10 { id: 52, board: '.ee.p...p', move: [3, '22'] }, { id: 53, board: '.ee.p...p', move: [3, '32'] }, { id: 54, board: 'ee..p.p..', move: [1, '12'] }, { id: 55, board: 'ee..p.p..', move: [1, '22'] }, // 11 { id: 56, board: '.ee.p.p..', move: [3, '22'] }, { id: 57, board: '.ee.p.p..', move: [3, '32'] }, { id: 58, board: 'ee..p...p', move: [1, '12'] }, { id: 59, board: 'ee..p...p', move: [1, '22'] }, // 12 { id: 60, board: 'e.ep....p', move: [3, '32'] }, { id: 61, board: 'e.e..pp..', move: [1, '12'] }, // 13 { id: 62, board: '..eeep...', move: [2, '13'] }, { id: 63, board: '..eeep...', move: [1, '23'] }, { id: 64, board: 'e..pee...', move: [3, '23'] }, { id: 65, board: 'e..pee...', move: [2, '33'] }, // 14 { id: 66, board: 'e..ppp...', move: [1, '22'] }, { id: 67, board: '.eeppp...', move: [3, '22'] }, // 15 { id: 68, board: '.e.epp...', move: [2, '32'] }, { id: 69, board: '.e.epp...', move: [1, '13'] }, { id: 70, board: '.e.ppe...', move: [2, '12'] }, { id: 71, board: '.e.ppe...', move: [3, '33'] }, // 16 { id: 72, board: 'e..eep...', move: [2, '13'] }, { id: 73, board: 'e..eep...', move: [3, '23'] }, { id: 74, board: '..epee...', move: [1, '23'] }, { id: 75, board: '..epee...', move: [2, '33'] }, // 17 { id: 76, board: '..eep....', move: [3, '22'] }, { id: 77, board: '..eep....', move: [3, '32'] }, { id: 78, board: '..eep....', move: [2, '13'] }, { id: 79, board: 'e..pe....', move: [1, '12'] }, { id: 80, board: 'e..pe....', move: [1, '22'] }, { id: 81, board: 'e..pe....', move: [2, '33'] }, // 18 { id: 82, board: '.e.pe....', move: [2, '12'] }, { id: 83, board: '.e.pe....', move: [1, '23'] }, // TODO: test if 1 exists here { id: 84, board: '.e..ep...', move: [2, '32'] }, { id: 85, board: '.e..ep...', move: [1, '23'] }, // TODO: test if 1 exists here // 19 { id: 86, board: 'e..ep....', move: [1, '22'] }, { id: 87, board: 'e..ep....', move: [2, '13'] }, { id: 88, board: '..e.pe...', move: [3, '22'] }, { id: 89, board: '..e.pe...', move: [2, '33'] }, ]; function Hexapawn() { const [AI, setAI] = React.useState(AIdefault); const [lastMoveId, setLastMoveId] = React.useState(-1); const [player, setPlayer] = React.useState(playerDefault); const [enemy, setEnemy] = React.useState(enemyDefault); const [selectedId, setSelectedId] = React.useState(-1); const [validMoves, setValidMoves] = React.useState([]); const [stats, setStats] = React.useState({ victories: 0, defeats: 0, lastVictory: '', }); const [turn, setTurn] = React.useState('player'); const getValidMoves = (id) => { const { x, y } = player.find((pawn) => pawn.id === id); const isAhead = enemy.find((pawn) => pawn.x === x && pawn.y === y - 1); const isAheadLeft = enemy.find((pawn) => pawn.x === x - 1 && pawn.y === y - 1); const isAheadRight = enemy.find((pawn) => pawn.x === x + 1 && pawn.y === y - 1); return [ ...(isAhead ? [] : [{ x, y: y - 1 }]), ...(isAheadLeft ? [{ x: x - 1, y: y - 1 }] : []), ...(isAheadRight ? [{ x: x + 1, y: y - 1 }] : []), ]; }; const handleSelect = (id) => { setSelectedId(id); if (id > -1) setValidMoves(getValidMoves(id)); }; const handleMove = (move) => { setPlayer((prev) => prev.map((pawn) => (pawn.id === selectedId ? { ...pawn, ...move } : pawn))); setValidMoves([]); setSelectedId(-1); setEnemy((prev) => prev.filter((pawn) => pawn.x !== move.x || pawn.y !== move.y)); setTurn('enemy'); }; const handleReset = () => { setPlayer(playerDefault); setEnemy(enemyDefault); setTurn('player'); }; const handleWin = () => { setAI((prev) => prev.filter((move) => move.id !== lastMoveId)); setStats((prev) => ({ ...prev, victories: prev.victories + 1, lastVictory: 'Player' })); setTurn('end'); }; const handleDefeat = () => { setStats((prev) => ({ ...prev, defeats: prev.defeats + 1, lastVictory: 'AI' })); setTurn('end'); }; const handleEnemy = () => { const currentBoard = [...player, ...enemy] .reduce( (acc, item) => { acc[item.x - 1 + 3 * (item.y - 1)] = item.id < 4 ? 'e' : 'p'; return acc; }, Array.from({ length: 9 }, () => '.'), ) .join(''); const moves = AI.filter(({ board }) => board === currentBoard); if (moves.length === 0) { return handleWin(); } const { id: moveId, move: [id, xy], } = sample(moves); setLastMoveId(moveId); setEnemy((prev) => prev.map((pawn) => (pawn.id === id ? { ...pawn, x: +xy.charAt(0), y: +xy.charAt(1) } : pawn)), ); setPlayer((prev) => prev.filter((pawn) => pawn.x !== +xy.charAt(0) || pawn.y !== +xy.charAt(1)), ); return setTurn('player'); }; React.useEffect(() => { if (turn === 'enemy') { if (player.some((pawn) => pawn.y === 1) || enemy.length === 0) { handleWin(); return; } setTimeout(() => handleEnemy(), 250); } if (turn === 'player') { if ( enemy.some((pawn) => pawn.y === 3) || player.length === 0 || player.every((pawn) => getValidMoves(pawn.id).length === 0) ) { handleDefeat(); } } }, [turn]); // eslint-disable-line react-hooks/exhaustive-deps return ( <Section css={` grid-area: hexapawn; display: grid; grid-template-columns: repeat(auto-fit, minmax(30rem, 1fr)); grid-gap: 4rem 0; `} > <Section> <View css={` --grid: 10rem; position: relative; display: grid; grid-template-columns: repeat(3, var(--grid)); grid-template-rows: repeat(3, var(--grid)); max-width: calc(var(--grid) * 3); background-position: 0px 0px, calc(var(--grid) / 1) calc(var(--grid) / 1); background-size: calc(var(--grid) * 2) calc(var(--grid) * 2); background-image: linear-gradient( 45deg, hsla(var(--hsl-text), 0.1) 25%, transparent 25%, transparent 75%, hsla(var(--hsl-text), 0.1) 75%, hsla(var(--hsl-text), 0.1) 100% ), linear-gradient( 45deg, hsla(var(--hsl-text), 0.1) 25%, transparent 25%, transparent 75%, hsla(var(--hsl-text), 0.1) 75%, hsla(var(--hsl-text), 0.1) 100% ); `} > {enemy.map((pawn) => ( <Pawn key={pawn.id} pawn={pawn} /> ))} {player.map((pawn) => ( <Pawn key={pawn.id} pawn={pawn} isSelected={selectedId === pawn.id} onSelect={handleSelect} disabled={turn === 'end'} /> ))} {validMoves.map((move) => ( <Move key={`${move.x}${move.y}`} move={move} onMove={handleMove} disabled={turn === 'end'} /> ))} </View> {__DEV__ && <p>{__DEV__ && `${AI.length} / ${AIdefault.length}`}</p>} <p> {stats.victories} / {stats.victories + stats.defeats} victories </p> <p>Last victory: {stats.lastVictory}</p> {turn === 'end' && ( <Button look="primary" disabled={turn !== 'end'} onClick={handleReset}> Next round </Button> )} {__DEV__ && ( <> <Button onClick={() => { handleDefeat(); handleReset(); }} > Give up </Button> <Button onClick={() => { handleWin(); handleReset(); }} > Win </Button> </> )} </Section> <Aside css={` font-size: 1.75rem; line-height: 3rem; `} > <H1>How to play</H1> <Ul css="list-style: disc; padding: 0 0 2rem 1em;"> <Li>You play white, the AI plays black</Li> <Li>White always starts</Li> <Li> On your turn, there are two types of valid moves:{' '} <Ol css="list-style: lower-roman; padding: 0 0 0 1em;"> <Li>Move one of your pawns 1 square straight ahead if free</Li> <Li> Move one of your pawns 1 square diagonally ahead if occupied by the opponent and capture the piece </Li> </Ol> </Li> <Li> The game is won in one of three ways:{' '} <Ol css="list-style: lower-roman; padding: 0 0 0 1em;"> <Li>Moving a pawn to the opposite end of the board</Li> <Li>Capturing all enemy pawns</Li> <Li>Achieving a position in which the enemy can&apos;t move</Li> </Ol> </Li> </Ul> <H1>About the AI</H1> <Ul css="list-style: disc; padding: 0 0 0 1em;"> <Li>The AI makes random (valid) moves in response to yours</Li> <Li>These moves feel silly and wrong in the beginning</Li> <Li> When making a move that leads to losing, the AI won&apos;t do it again (until you refresh the browser) </Li> <Li>Very quickly, the AI becomes scarily good at the game</Li> </Ul> </Aside> </Section> ); } // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // component // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ export default function HexapawnPage({ data: { page: { frontmatter: { meta, blocks }, }, }, }) { return ( <RootContainer> <SEOContainer meta={meta} /> <Main css={` grid-template: 'hero' 'hexapawn'; grid-gap: 10vh 1rem; `} > {renderBlocks(blocks)} <Hexapawn /> </Main> </RootContainer> ); } HexapawnPage.propTypes = pagePropTypes;
var Parser = require("../wrapping"), _ = require("../../utils"), EventualParser; /** * EventualParser * * @class EventualParser * @extends Parser * @author Sergey Kamardin <s.kamardin@tcsbank.ru> */ EventualParser = Parser.extend( /** * @lends EventualParser.prototype */ { parse: function(some) { var self = this, parser; parser = this.parser; return this.async.promise(function(resolve, reject) { _.async.doWhilst( function(truth, value, initial) { var mustRepeat; // if some parser has returned string // try to parse it again mustRepeat = _.isString(value) && value !== initial; truth(mustRepeat); }, function(next, initial) { var test; try { test = parser.test(initial); } catch (err) { next(err); return; } self.async .resolve(test) .then(function(acceptable) { var parsed; if (!acceptable) { next(null, initial, initial); return; } try { parsed = parser.parse(initial); } catch (err) { next(err); return; } self.async .resolve(parsed) .then(function(parsed) { next(null, parsed, initial); }) .catch(function(err) { // hm if (err instanceof SyntaxError) { next(null, initial, initial); return; } next(err); }); }); }, function(err, value) { if (err) { reject(err); return; } resolve(value); }, some ); }); } } ); module.exports = EventualParser;
/** * Passport configuration * * This is the configuration for your Passport.js setup and where you * define the authentication strategies you want your application to employ. * * I have tested the service with all of the providers listed below - if you * come across a provider that for some reason doesn't work, feel free to open * an issue on GitHub. * * Also, authentication scopes can be set through the `scope` property. * * For more information on the available providers, check out: * http://passportjs.org/guide/providers/ */ module.exports.passport = { redirect : { login : "/",//Login successful logout : "/"//Logout successful }, onUserCreated : function (user, providerInfos) { //Send email for example }, onUserLogged : function (session, user) { //Set user infos in session for example }, strategies : {} };
var ev3dev = require('ev3dev-lang'); var socket = require('socket.io-client')('http://10.0.0.122:3000'); // npm install ev3dev-lang socket.io-client // node index.js function Dispatcher() { this.listeners = {}; } Dispatcher.prototype.register = function register(action, listener) { if (!this.listeners[action]) { this.listeners[action] = []; } this.listeners[action].push(listener); }; Dispatcher.prototype.emit = function emit(action, payload) { console.log('Dispatcher: executing ' + action); if (!this.listeners[action]) { console.error('no listener attachted for action' + action); return; } this.listeners[action].forEach(function(listener) { listener(payload); }); }; var dispatcher = new Dispatcher(); var motorA = new ev3dev.Motor(ev3dev.OUTPUT_A); var motorB = new ev3dev.Motor(ev3dev.OUTPUT_B); var runMotorA = function() { motorA.speedSp = 500; motorA.dutyCycleSp = 50; motorA.command = 'run-forever'; } var runMotorB = function() { motorB.speedSp = 500; motorB.dutyCycleSp = 50; motorB.command = 'run-forever'; } dispatcher.register('straight', function(pl) { runMotorA(); runMotorB(); }); dispatcher.register('stop', function(pl) { motorA.stop(); motorB.stop(); }); dispatcher.register('left', function(pl) { motorA.stop(); runMotorB(); }); dispatcher.register('right', function(pl) { runMotorA(); motorB.stop(); }); socket.on('command', function(c) { if (c.target === "lego-ev3") { dispatcher.emit(c.command, {}); } });
require('./Info.less'); var React = require('react'); module.exports = React.createClass({ getInitialState: function () { return { userId: this.props.userId || zn.react.session.json().id, toolbarItems: this.props.userId?[]:[{icon:'fa-edit', text: 'ไฟฎๆ”นไธชไบบไฟกๆฏ', onClick: this.__onEdit}], info: null, formItems: [ { title: 'ๅคดๅƒ', name: 'avatar_img', type: 'ImageUploader', action: '/zn.plugin.admin/uploadFiles' }, { title: '็”จๆˆทๅ', name: 'name', type: 'Input', required: true, error: '็”จๆˆทๅๅฟ…ๅกซ้กน!' }, { title: 'ๅฏ†็ ', name: 'password', type: 'Input', attrs: { type: 'password' }, required: true, error: 'ๅฏ†็ ๅฟ…ๅกซ้กน!' }, { title: '้‚ฎ็ฎฑ', name: 'email', type: 'Input', required: true, error: '้‚ฎ็ฎฑๅฟ…ๅกซ้กน!' }, { title: 'ๆ‰‹ๆœบๅท', name: 'phone', type: 'Input', required: true, error: 'ๆ‰‹ๆœบๅทๅฟ…ๅกซ้กน!' }, { title: 'ๅœฐๅ€', name: 'address', type: 'Input' }, { title: '่ฏดๆ˜Ž', name: 'zn_note', type: 'Textarea' } ], data: zn.store.post('/zn.plugin.admin/model/select', { model: 'ZNPluginAdminRole', where: { zn_tree_pid: 0 } }) } }, componentDidMount: function (){ this.__loadUserInfo(); }, __doSuccess: function (){ zn.notification.success('ไฟฎๆ”นๆˆๅŠŸ'); this.__loadUserInfo(); }, __onEdit: function (data){ zn.dialog({ title: 'ไฟฎๆ”นไธชไบบไฟกๆฏ', content: <zn.react.Form action='/zn.plugin.admin/model/update' exts={{ model: 'ZNPluginAdminUser', where: { id: this.state.info.id } }} merge="updates" value={this.state.info} onSubmitSuccess={this.__doSuccess} items={this.state.formItems} /> }); }, __loadUserInfo: function (){ zn.http.post('/zn.plugin.admin/user/findUserById', { userId: this.state.userId }).then(function (data){ this.setState({ info: data.result, }); }.bind(this)); }, __onTreeMenuItemCheckboxChange: function (value){ zn.http.post('/zn.plugin.admin/user/updateUser', { data: { role_ids: value }, userId: this.state.info.id }).then(function (data){ zn.toast.success('ไฟๅญ˜ๆˆๅŠŸ'); }); }, __itemContentRender: function (props){ var _icon = ''; if(props.data.type==1){ _icon = 'fa-sitemap'; } if(props.data.type==2){ _icon = 'fa-graduation-cap'; } return <span><i style={{margin:5}} className={'fa ' + _icon} />{props.data.id +'ใ€'+ props.data.zn_title}</span>; }, render:function(){ if(!this.state.info){ return <zn.react.DataLoader content="ๆญฃๅœจๅŠ ่ฝฝไธญ..." loader="timer" />; } return ( <zn.react.Page className="zn-plugin-admin-my-info" title={this.state.info.name} toolbarItems={this.state.toolbarItems} > <div className="user-info"> <div className="info-form user-item"> <img className="avatar" src={zn.http.fixURL(this.state.info.avatar_img)||'./images/DefaultAvatar.png'} /> <div className="details"> <span className="last-logintime">ๆœ€่ฟ‘ไธ€ๆฌก็™ปๅฝ•ๆ—ถ้—ด๏ผš{this.state.info.last_login_time||'่ฟ˜ๆœช็™ป้™†'}</span> <div className="name">{this.state.info.name}</div> <div><i className="fa fa-clock-o" />ๅˆ›ๅปบๆ—ถ้—ด๏ผš{this.state.info.zn_create_time}</div> <div><i className="fa fa-envelope" />้‚ฎ็ฎฑ๏ผš{this.state.info.email}</div> <div><i className="fa fa-phone" />ๆ‰‹ๆœบๅท๏ผš{this.state.info.phone}</div> <div><i className="fa fa-qq" />QQๅท๏ผš{this.state.info.qq}</div> <div><i className="fa fa-weixin" />ๅพฎไฟกๅท๏ผš{this.state.info.wechat}</div> <div>{this.state.info.zn_note}</div> </div> </div> <zn.react.Card title="้ƒจ้—จๅŠ่ง’่‰ฒ"> <zn.react.TreeListView disabled={true} cascade={false} enableCheckbox={true} onItemCheckboxChange={this.__onTreeMenuItemCheckboxChange} value={this.state.info.roleIds} itemContentRender={this.__itemContentRender} ref="maintreemenu" activeAll={true} data={this.state.data} /> </zn.react.Card> </div> </zn.react.Page> ); } });
'use strict'; /** * Recall scene command * * Recall a scene */ class RecallScene { /** * Constructor * * @param {string} sceneId Scene Id */ constructor(sceneId) { this.sceneId = String(sceneId); } /** * Invoke command * * @param {Client} client Client * * @return {Promise} Promise for chaining */ invoke(client) { let options = { method: 'PUT', url: `api/${client.username}/groups/0/action`, data: { scene: this.sceneId } }; return client.getTransport() .sendRequest(options) .then(() => true); } } module.exports = RecallScene;
import * as Api from '../api.js'; import PageEventTypes from '../commons/page-event-types.js'; import moment from 'moment'; /** * * @param {function} commit * @param {type} state * @returns {jqXhr} */ export function fetchPagesList( {commit, dispatch, state}){ var $def = $.Deferred(); Api.getPagesList().then((data, textStatus, jqXhr) => { data = data.map(function (page) { page.publishedOn = moment.utc(page.publishedOn); return page; }); commit('setPages', data); $def.resolve(); }, (jqXhr, error) => { $def.reject(); }); return $def.promise(); } /** * @param {number} pageId * @param {function} commit * @param {object} state * @returns {undefined} */ export function deletePage( {commit, state}, pageId){ var $def = $.Deferred(); var pageEvent = { type: PageEventTypes.deleted, success: true, message: '' }; Api.deletePage(pageId).then((data, textStatus, jqXhr) => { commit('deletePage', data); pageEvent.message = 'Page deleted successfully'; $def.resolve(pageEvent); }, (jqXhr, error) => { pageEvent.message = 'Page could not be deleted please try again later'; pageEvent.success = false; $def.reject(pageEvent); }).always(() => { commit('addPageEvent', pageEvent); }); return $def.promise(); } /** @typedef PageDetails @type {object} @property {number} id - an ID. @property {string} title - the page title. @property {string} description - a page description. @property {number} type - one of three numbers Menu(0),Events(1),Content(2). @property {date} publishedOn - when the page was first created. @param {PageDetails} pageDetails */ export function createNewPage( {commit, state}, pageDetails){ var $def = $.Deferred(); var pageEvent = { type: PageEventTypes.created, success: true, message: '' }; Api.createPage(pageDetails).then((data, textStatus, jqXhr) => { commit('addPage', data); pageEvent.message = 'Page created successfully'; $def.resolve(pageEvent); }, (jqXhr, error) => { pageEvent.message = 'Could not create page please try again later'; pageEvent.success = false; $def.reject(pageEvent); }).always(() => { commit('addPageEvent', pageEvent); }); return $def.promise(); } export function updatePage( {commit, state}, pageDetails){ var $def = $.Deferred(); var pageEvent = { type: PageEventTypes.edited, success: true, message: '' }; Api.updatePage(pageDetails).then((data, textStatus, jqXhr) => { console.log('update success'); commit('editPage', pageDetails); pageEvent.message = 'Page updated!'; $def.resolve(pageEvent); }, (jqXhr, error) => { pageEvent.message = 'Could not update page!'; pageEvent.success = false; $def.reject(pageEvent); }).always(() => { commit('addPageEvent', pageEvent); }); return $def.promise(); } export function getPage( {commit, state}, pageId){ var $def = $.Deferred(); Api.getSinglePage(pageId).then((page, textStatus, jqXhr) => { page.publishedOn = moment.utc(page.publishedOn); $def.resolve(page); }, () => { $def.reject(); }); return $def.promise(); } export function clearPageEvents( {commit, state}){ commit('clearPageEvents'); }
Accounts.config({ forbidClientAccountCreation: true });
class microsoft_update_stringcoll_1 { constructor() { // string Item (int) {get} {set} this.Parameterized = undefined; // int Count () {get} this.Count = undefined; // bool ReadOnly () {get} this.ReadOnly = undefined; // IUnknown _NewEnum () {get} this._NewEnum = undefined; } // int Add (string) Add(string) { } // void Clear () Clear() { } // IStringCollection Copy () Copy() { } // void Insert (int, string) Insert(int, string) { } // void RemoveAt (int) RemoveAt(int) { } } module.exports = microsoft_update_stringcoll_1;
'use strict'; /* Controllers */ function DashboardController($resource, $scope, Cluster, Datastore) { Cluster.query({}, function(data){ $scope.clusters = data; }); Datastore.query({}, function(data){ $scope.datastores = data; }); $scope.newCluster = new Cluster(); $scope.submit = function () { var new_cluster = new Cluster($scope.newCluster); new_cluster.datastore_id = new_cluster.datastore.id; new_cluster.$save(); $scope.clusters.push(new_cluster); $scope.newCluster = new Cluster(); }; } DashboardController.$inject = ['$resource', '$scope', 'Cluster', 'Datastore'];
Prices : { `2x8 x 12` : 8.56, `2x6 x 12` : 10.11 }
// var tasks = require('../api/tasks.js'); module.exports = function (app) { app.get('/tasks', function (req, res) { var sampleTasks = require('../api/sampleTasks.js') res.send(JSON.stringify(sampleTasks)); }); }
"use strict"; const CommonJsRequireDependency = require("webpack/lib/dependencies/CommonJsRequireDependency"); const GlobalizeCompilerHelper = require("./GlobalizeCompilerHelper"); const MultiEntryPlugin = require("webpack/lib/MultiEntryPlugin"); const NormalModuleReplacementPlugin = require("webpack/lib/NormalModuleReplacementPlugin"); const RawModule = require("webpack/lib/RawModule"); const SkipAMDPlugin = require("skip-amd-webpack-plugin"); const util = require("./util"); /** * Production Mode: * - Have Globalize modules replaced with their runtime modules. * - Statically extracts formatters and parsers from user code and pre-compile * them into globalize-compiled-data chunks. */ class ProductionModePlugin { constructor(attributes) { this.cldr = attributes.cldr || util.cldr; this.developmentLocale = attributes.developmentLocale; this.messages = attributes.messages && attributes.supportedLocales.reduce((sum, locale) => { sum[locale] = util.readMessages(attributes.messages, locale) || {}; return sum; }, {}); this.moduleFilter = util.moduleFilterFn(attributes.moduleFilter); this.supportedLocales = attributes.supportedLocales; this.output = attributes.output; this.tmpdir = util.tmpdir(); } apply(compiler) { let globalizeSkipAMDPlugin; const output = this.output || "i18n-[locale].js"; const globalizeCompilerHelper = new GlobalizeCompilerHelper({ cldr: this.cldr, developmentLocale: this.developmentLocale, messages: this.messages, tmpdir: this.tmpdir, webpackCompiler: compiler }); compiler.apply( // Skip AMD part of Globalize Runtime UMD wrapper. globalizeSkipAMDPlugin = new SkipAMDPlugin(/(^|[\/\\])globalize($|[\/\\])/), // Replaces `require("globalize")` with `require("globalize/dist/globalize-runtime")`. new NormalModuleReplacementPlugin(/(^|[\/\\])globalize$/, "globalize/dist/globalize-runtime"), // Skip AMD part of Globalize Runtime UMD wrapper. new SkipAMDPlugin(/(^|[\/\\])globalize-runtime($|[\/\\])/) ); const bindParser = (parser) => { // Map each AST and its request filepath. parser.plugin("program", (ast) => { globalizeCompilerHelper.setAst(parser.state.current.request, ast); }); // "Intercepts" all `require("globalize")` by transforming them into a // `require` to our custom precompiled formatters/parsers, which in turn // requires Globalize, set the default locale and then exports the // Globalize object. parser.plugin("call require:commonjs:item", (expr, param) => { const request = parser.state.current.request; if(param.isString() && param.string === "globalize" && this.moduleFilter(request) && !(globalizeCompilerHelper.isCompiledDataModule(request))) { // Statically extract Globalize formatters and parsers from the request // file only. Then, create a custom precompiled formatters/parsers module // that will be called instead of Globalize, which in turn requires // Globalize, set the default locale and then exports the Globalize // object. const compiledDataFilepath = globalizeCompilerHelper.createCompiledDataModule(request); // Skip the AMD part of the custom precompiled formatters/parsers UMD // wrapper. // // Note: We're hacking an already created SkipAMDPlugin instance instead // of using a regular code like the below in order to take advantage of // its position in the plugins list. Otherwise, it'd be too late to plugin // and AMD would no longer be skipped at this point. // // compiler.apply(new SkipAMDPlugin(new RegExp(compiledDataFilepath)); // // 1: Removes the leading and the trailing `/` from the regexp string. globalizeSkipAMDPlugin.requestRegExp = new RegExp([ globalizeSkipAMDPlugin.requestRegExp.toString().slice(1, -1)/* 1 */, util.escapeRegex(compiledDataFilepath) ].join("|")); // Replace require("globalize") with require(<custom precompiled module>). const dep = new CommonJsRequireDependency(compiledDataFilepath, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); }; // Create globalize-compiled-data chunks for the supportedLocales. compiler.plugin("entry-option", (context) => { this.supportedLocales.forEach((locale) => { compiler.apply(new MultiEntryPlugin(context, [], "globalize-compiled-data-" + locale )); }); }); // Place the Globalize compiled data modules into the globalize-compiled-data // chunks. // // Note that, at this point, all compiled data have been compiled for // developmentLocale. All globalize-compiled-data chunks will equally include all // precompiled modules for the developmentLocale instead of their respective // locales. This will get fixed in the subsquent step. let allModules; compiler.plugin("this-compilation", (compilation) => { compilation.plugin("optimize-modules", (modules) => { allModules = modules; }); }); compiler.plugin("this-compilation", (compilation) => { compilation.plugin("after-optimize-chunks", (chunks) => { let hasAnyModuleBeenIncluded; const compiledDataChunks = chunks.filter((chunk) => /globalize-compiled-data/.test(chunk.name)); allModules.forEach((module) => { let chunkRemoved, chunk; if (globalizeCompilerHelper.isCompiledDataModule(module.request)) { hasAnyModuleBeenIncluded = true; while (module.chunks.length) { chunk = module.chunks[0]; chunkRemoved = module.removeChunk(chunk); if (!chunkRemoved) { throw new Error("Failed to remove chunk " + chunk.id + " for module " + module.request); } } compiledDataChunks.forEach((compiledDataChunk) => { compiledDataChunk.addModule(module); module.addChunk(compiledDataChunk); }); } }); compiledDataChunks.forEach((chunk) => { const locale = chunk.name.replace("globalize-compiled-data-", ""); chunk.filenameTemplate = output.replace("[locale]", locale); }); if(!hasAnyModuleBeenIncluded) { console.warn("No Globalize compiled data module found"); } }); // Have each globalize-compiled-data chunks include precompiled data for // each supported locale. In each chunk, merge all the precompiled modules // into a single one. Finally, allow the chunks to be loaded incrementally // (not mutually exclusively). Details below. // // Up to this step, all globalize-compiled-data chunks include several // precompiled modules, which have been mandatory to allow webpack to figure // out the Globalize runtime dependencies. But for the final chunk we need // something a little different: // // a) Instead of including several individual precompiled modules, it's // better (i.e., reduced size due to less boilerplate and due to deduped // formatters and parsers) having one single precompiled module for all // these individual modules. // // b) globalize-compiled-data chunks shouldn't be mutually exclusive to each // other, but users should be able to load two or more of these chunks // and be able to switch from one locale to another dynamically during // runtime. // // Some background: by having each individual precompiled module defining // the formatters and parsers for its individual parents, what happens is // that each parent will load the globalize precompiled data by its id // with __webpack_require__(id). These ids are equally defined by the // globalize-compiled-data chunks (each chunk including data for a // certain locale). When one chunk is loaded, these ids get defined by // webpack. When a second chunk is loaded, these ids would get // overwritten. // // Therefore, instead of having each individual precompiled module // defining the formatters and parsers for its individual parents, we // actually simplify them by returning Globalize only. The precompiled // content for the whole set of formatters and parsers are going to be // included in the entry module of each of these chunks. // So, we accomplish what we need: have the data loaded as soon as the // chunk is loaded, which means it will be available when each // individual parent code needs it. compilation.plugin("after-optimize-module-ids", () => { const globalizeModuleIds = []; const globalizeModuleIdsMap = {}; compilation.chunks.forEach((chunk) => { chunk.modules.forEach((module) => { let aux; const request = module.request; if (request && util.isGlobalizeRuntimeModule(request)) { // While request has the full pathname, aux has something like // "globalize/dist/globalize-runtime/date". aux = request.split(/[\/\\]/); aux = aux.slice(aux.lastIndexOf("globalize")).join("/").replace(/\.js$/, ""); // some plugins, like HashedModuleIdsPlugin, may change module ids // into strings. let moduleId = module.id; if (typeof moduleId === "string") { moduleId = JSON.stringify(moduleId); } globalizeModuleIds.push(moduleId); globalizeModuleIdsMap[aux] = moduleId; } }); }); // rewrite the modules in the localized chunks: // - entry module will contain the compiled formatters and parsers // - non-entry modules will be rewritten to export globalize compilation.chunks .filter((chunk) => /globalize-compiled-data/.test(chunk.name)) .forEach((chunk) => { // remove dead entry module for these reasons // - because the module has no dependencies, it won't be rendered // with __webpack_require__, making it difficult to modify its // source in a way that can import globalize // // - it was a placeholder MultiModule that held no content, created // when we added a MultiEntryPlugin // // - the true entry module should be globalize-compiled-data // module, which has been created as a NormalModule chunk.removeModule(chunk.entryModule); chunk.entryModule = chunk.modules.find((module) => module.context.endsWith(".tmp-globalize-webpack")); const newModules = chunk.modules.map((module) => { let fnContent; if (module === chunk.entryModule) { // rewrite entry module to contain the globalize-compiled-data const locale = chunk.name.replace("globalize-compiled-data-", ""); fnContent = globalizeCompilerHelper.compile(locale) .replace("typeof define === \"function\" && define.amd", "false") .replace(/require\("([^)]+)"\)/g, (garbage, moduleName) => { return `__webpack_require__(${globalizeModuleIdsMap[moduleName]})`; }); } else { // rewrite all other modules in this chunk as proxies for // Globalize fnContent = `module.exports = __webpack_require__(${globalizeModuleIds[0]});`; } // The `module` object in scope here is in each locale chunk, and // any modifications we make will be rendered into every locale // chunk. Create a new module to contain the locale-specific source // modifications we've made. const newModule = new RawModule(fnContent); newModule.context = module.context; newModule.id = module.id; newModule.dependencies = module.dependencies; return newModule; }); // remove old modules with modified clones // chunk.removeModule doesn't always find the module to remove // ยฏ\_(ใƒ„)_/ยฏ, so we have to be be a bit more thorough here. chunk.modules.forEach((module) => module.removeChunk(chunk)); chunk.modules = []; // install the rewritten modules newModules.forEach((module) => chunk.addModule(module)); }); }); // Set the right chunks order. The globalize-compiled-data chunks must // appear after globalize runtime modules, but before any app code. compilation.plugin("optimize-chunk-order", (chunks) => { const cachedChunkScore = {}; function moduleScore(module) { if (module.request && util.isGlobalizeRuntimeModule(module.request)) { return 1; } else if (module.request && globalizeCompilerHelper.isCompiledDataModule(module.request)) { return 0; } return -1; } function chunkScore(chunk) { if (!cachedChunkScore[chunk.name]) { cachedChunkScore[chunk.name] = chunk.modules.reduce((sum, module) => { return Math.max(sum, moduleScore(module)); }, -1); } return cachedChunkScore[chunk.name]; } chunks.sort((a, b) => chunkScore(a) - chunkScore(b)); }); }); compiler.plugin("compilation", (compilation, params) => { params.normalModuleFactory.plugin("parser", bindParser); }); } } module.exports = ProductionModePlugin;
// Copyright IBM Corp. 2015,2016. All Rights Reserved. // Node module: strong-pm // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 'use strict'; var cicada = require('strong-fork-cicada'); var Container = require('./container'); var debug = require('debug'); var EventEmitter = require('events').EventEmitter; var fmt = require('util').format; var inherits = require('util').inherits; var localDeploy = require('../common/local-deploy'); var packReceiver = require('../common/pack-receiver'); var sdb = require('strong-docker-build'); module.exports = exports = Image; function Image(driver, svcDir) { EventEmitter.call(this); this.debug = debug('strong-pm:docker:image'); this.driver = driver; this.docker = driver.docker; // TODO: extract the below to drivers/common and remove from here and direct // driver if possible. // XXX(sam) might be able to use a single cicada, made in the driver, and // using the repo set to the svcId, but this works fine. this._svcDir = svcDir; this.git = cicada(this._svcDir); // this.git.container = this; // emits 'commit' on this.git after unpack this.tar = packReceiver(this.git); // this.tar.on('error', this.emit.bind(this, 'error')); // emits 'prepared' on this when received this.local = localDeploy(this); // this.local.on('error', this.emit.bind(this, 'error')); this.git.on('commit', this._onCommit.bind(this)); this.on('commit', this._onCommit.bind(this)); this.git.on('error', this.emit.bind(this, 'error')); } inherits(Image, EventEmitter); Image.from = function(driver, svcDir, req, res) { var image = new Image(driver, svcDir); image.receive(req, res); return image; }; Image.prototype.receive = function(req, res) { this.debug('Docker::Image.receive()'); var contentType = req.headers['content-type']; this.debug('deploy request: locked? %s method %j content-type %j', !!process.env.STRONG_PM_LOCKED, req.method, contentType); if (process.env.STRONG_PM_LOCKED) { this.debug('deploy rejected: locked'); return rejectDeployments(req, res); } if (req.method === 'PUT') { this.debug('deploy accepted: npm package'); return this.tar.handle(req, res); } if (contentType === 'application/x-pm-deploy') { this.debug('deploy accepted: local deploy'); return this.local.handle(req, res); } this.debug('deploy accepted: git deploy'); return this.git.handle(req, res); }; function rejectDeployments(req, res) { res.status(403) .set('Content-Type', 'text/plain') .end('Forbidden: Server is not accepting deployments'); } Image.prototype._onCommit = function(commit) { this.name = fmt('%s/svc:%s', 'strong-pm', commit.hash); var self = this; this.debug('Image committed', commit); this.commit = commit; var imgOpts = { appRoot: this.commit.dir, imgName: this.name, // XXX(rmg): build the image with a locally modified/unreleased supervisor // supervisor: require('path') // .dirname(require.resolve('strong-supervisor')), }; this.docker.getImage(imgOpts.imgName).inspect(function(err, details) { if (!err && details) { return self.emit('image', {id: details.Id, name: imgOpts.imgName}); } sdb.buildDeployImage(imgOpts, function(err, img) { self.image = img; if (err) { self.emit('error', err); } else { self.emit('image'); } }); }); }; Image.prototype._onPrepared = function(commit) { this.debug('Image prepared', commit); }; Image.prototype.start = function(instance, logger, startOpts) { var container = new Container(this, instance, logger, startOpts); container.once('ready', function() { container.start(); }); return container; };
/** * Created by maglo on 27/09/2016. */ Ext.define("JS.review.ListAdmin",{ extend:"JS.panel.HistoryGridPanelAdmin", config:{ page: { title: "Reviews", data: null, parent: null }, panelData: { url: "", panelClass: "", gridUrl: Routing.generate("get_reviews"), actions: [{ param: { "url": "get_reviews", "panelClass": "JS.review.AdvancedSearchAdmin", "formUrl": "", "gridUrl": "get_reviews" }, libelle: "Advanced search", description: "Advanced search" }], buttons:[ ] }, grid: { store: { proxy: { url: Routing.generate("get_reviews", {_format: "json"}) } }, type: "custom", dynamicTplClass: "JS.review.GridCustomAdmin" }, status:1, eventBound:false, jsApp:null }, initialize:function(){ var me = this; me.config.grid.store.proxy.url=Routing.generate("get_reviews", { _format: "json" }); this.callParent(arguments); }, onGridSelect: function (grid, selectedIndex, selectedRecord, selectedIndexes, selectedRecords) { var me = this; this.callParent(arguments); }, onShow:function(){ var me = this; var grid = me.getGrid(); grid.reload(); }, onStoreLoaded: function () { var me = this; var grid = me.getGrid(); me.callParent(); if(!me.getEventBound()){ grid.binder.on('show-detail', function(e){ me.getJsApp().showPanel("JS.review.View",{ title: e.context.article.titre_court, subtitle: "Review", review: e.context, editor: true, author: false, reviewer:false }); }); grid.binder.on('validate-review', function(e){ console.log("Edit review clicked"); console.log(e); me.validateReview(e.context); }); grid.binder.on('reject-review', function(e){ console.log("Submit review clicked"); console.log(e); me.rejectReview(e.context); }); me.setEventBound(true); } me.getJsApp().addjustHeight(); }, rejectReview:function(review){ var me=this; var id=-1; if(review!=null){ id=review.id; } me.sentAction(Routing.generate('put_review_reject', { _format: 'json', id: id }), function(){ var message="Review rejected successfully!"; Xfr.Msg.show({ message: message, title: "Manuscript review", icon: Xfr.Msg.SUCCESS.iconClass, action:function(btn){ me.getJsApp().back(); } }); }); }, validateReview:function(review){ var me=this; var id=-1; if(review!=null){ id=review.id; } me.sentAction(Routing.generate('put_review_validate', { _format: 'json', id: id }), function(){ var message="Review validated successfully!"; Xfr.Msg.show({ message: message, title: "Manuscript review", icon: Xfr.Msg.SUCCESS.iconClass, action:function(btn){ me.getJsApp().back(); } }); }); }, sentAction: function(url, callback){ var me=this; Xfr.Mask.show("Submitting review...", null, me.$this); $.ajax({ url: url, cache: false, contentType: false, processData: false, type: "PUT", data: null, dataType: "json", success: function (response, textStatus, jqXHR) { Xfr.Mask.hide(); if(response && response.success){ callback(); } else{ console.log("Success False"); } }, error: function (jqXHR, textStatus, errorThrown) { console.log("Error: "+ errorThrown); Xfr.Mask.hide(); } }); }, afterRenderTpl:function(){ var me=this; me.callParent(arguments); } });
nerdtalk.directive('ntPostListItem', ['$log', function($log) { return { scope: { slug: '=ntSlug', onSelected: "&ntOnSelected" }, link: function(scope, el) { // Variables var shareMenu = el.children("[skin-part='shareMenu']"); var faceBookButton = shareMenu.find('a').eq(0); var twitterButton = shareMenu.find('a').eq(1); var gplusButton = shareMenu.find('a').eq(2); // Initialization Methods var init = function() { addEventListeners(); }; // Event Listeners var addEventListeners = function() { el.on('click', function() { if(scope.onSelected) { scope.$apply(function() { scope.onSelected({selectedItem: {slug: scope.slug}}); }); } }); el.on('mouseover', function(e) { el.addClass('post-state-active'); faceBookButton.addClass('icon-facebook-blk'); twitterButton.addClass('icon-twitter-blk'); gplusButton.addClass('icon-gplus-blk'); }); el.on('mouseleave', function() { el.removeClass('post-state-active'); faceBookButton.removeClass('icon-facebook-blk'); twitterButton.removeClass('icon-twitter-blk'); gplusButton.removeClass('icon-gplus-blk'); }); }; init(); } } }])
/* * ๅŽŸๅž‹ๅผ็ปงๆ‰ฟ */ // function object(o) { function F(){} F.prototype = o; return new F(); } var person = { name: 'Nicholas', friends: ['Shelby', 'Court', 'Van'] } var anotherPerson = Object.create(person);
var http = require('http'); var url = require('url'); function start(route, handle, port) { function onRequest(request, response) { var urlObj = url.parse(request.url); var pathname = urlObj.pathname; var query = urlObj.query; console.log('= Request Received: ' + pathname + '; Query: ' + query); route(pathname, query, handle, response); } http.createServer(onRequest).listen(port); console.log('Server has started on %s.', port); } exports.start = start;
console.warn('Package jii-comet is deprecated and moved to jii package.'); module.exports = require('jii');
/* * Extended Grid * Ability to reorder the grid's row * @author: Prakash Paudel */ Ext.namespace('Ext.ux.plugins'); Ext.ux.plugins.GridRowOrder = function(config){ Ext.apply(this,config); } Ext.extend(Ext.ux.plugins.GridRowOrder, Ext.util.Observable,{ init: function(grid){ Ext.apply(grid,{ }); } }); /** * Event Correlation Trigger Plugin * * This is the custom plugin created for the event correlation triggers wizard * * @author Prakash Paudel * */ //Create a constructor for the plugin Ext.ux.plugins.EventCorrelationTriggers = function(config){ Ext.apply(this,config,{ }); } //Extend the plugin to Ext.util.Observable Ext.extend(Ext.ux.plugins.EventCorrelationTriggers, Ext.util.Observable,{ init: function(grid){ Ext.apply(grid,{ /** * Grid row reorder plugin, if includes row up button */ rowUp:true, /** * Grid row reorder plugin, if includes row down button */ rowDown:true, /** * Grid row reorder plugin, if includes row remove button */ rowRemove: true, /** * Grid row reorder plugin, if includes row edit button */ rowEdit: true, /** * Grid row reorder plugin, the header of the row reorder column */ colHeader:'', /** * Preserve order state */ preserveOrder:false, restorePerserveOrder: function(){ Ext.Ajax.request({ url:'/eventmanagement/getPreserveOrder', method:"POST", success: function(r){ var tb = grid.getTopToolbar(); for(var i=0;i<tb.items.items.length;i++){ var ind = tb.items.items[i]; if(ind.name && ind.name == 'preserve-row-order'){ ind.setValue(r.responseText); } } }, failure: function(){ Ext.Msg.alert('Error','Connection to server has been lost<br>Triggers could not be saved. Please try again!') } }) }, // Customize the grid on render onRender: grid.onRender.createSequence(function(ct, position) { /** * Restore the preserve order state on render */ this.restorePerserveOrder(); /** * Create a temporary record object */ // create a Record constructor from a description of the fields var triggerAttr = Ext.data.Record.create([ // creates a subclass of Ext.data.Record {name: 'event'}, {name: 'event_classification'}, {name: 'source_ip'}, {name: 'attacking_ip'}, {name: 'username'}, {name: 'service'} ]); /** * Create a form to add new triggers to the gird */ Ext.QuickTips.init(true); //Form panel var eventCombo = new Ext.form.ComboBox({ name:'event', tpl:new Ext.XTemplate( '<tpl for=".">', '<tpl if="flag == \'parent\'"><div class="x-combo-list-item" style=" background-color:#dfe8f6;display:block"><span style="font-weight:bold;">{value}</span></div></tpl>', '<tpl if="flag == \'child\'"><div class="x-combo-list-item"><span style="padding-left:10px;">{value}</span></div></tpl>', '</tpl>' ), resizable:true, editable:false, typeAhead: true, fieldLabel:'Event', triggerAction: 'all', lazyRender:true, mode: 'local', store: new Ext.data.JsonStore({ url:'/eventmanagement/getEventCorrelationFormData?event', root:'data', autoLoad:true, fields: [ 'key', 'value', 'flag' ] }), valueField: 'key', displayField: 'value', flagField:'flag', allowBlank:false }); var form = new Ext.form.FormPanel({ bodyStyle:'padding:5px', isEdit: false, record:null, rowIndex:null, items:[{ xtype: 'fieldset', title:'Add Trigger', defaultType: 'textfield', autoHeight:true, defaults:{width:200,msgTarget:'title'}, items:[ eventCombo, { name:'source_ip', xtype:'textfield', fieldLabel:'Source Ip' },{ name:'attacking_ip', xtype:'textfield', fieldLabel:'Attacking Ip' },{ name:'username', xtype:'textfield', fieldLabel:'Username' },{ name:'service', xtype:'textfield', fieldLabel:'Service' }] }], buttons:[{ text:'Save', handler: function(){ if(form.getForm().isValid()){ // create Record instance var values = []; if(form.getForm().findField('event').getValue().match(/child:/)){ values['event'] = "("+form.getForm().findField('event').getValue().replace("child:",'')+") "+form.getForm().findField('event').getEl().dom.value; }else{ values['event'] = '-'; } if(form.getForm().findField('event').getValue().match(/parent:/)){ values['event_classification'] = "("+form.getForm().findField('event').getValue().replace("parent:",'')+") "+form.getForm().findField('event').getEl().dom.value; }else{ values['event_classification'] = '-'; } var newTrigger = new triggerAttr({ event: values['event'], event_classification: values['event_classification'], source_ip:form.getForm().findField('source_ip').getValue(), attacking_ip: form.getForm().findField('attacking_ip').getValue(), username: form.getForm().findField('username').getValue(), service: form.getForm().findField('service').getValue() }); // Add the data from the form to the grid's store // This will add the record at the end of the grid if(form.isEdit){ grid.getStore().remove(form.record); grid.getStore().insert(form.rowIndex,newTrigger); grid.getStore().commitChanges(); }else{ grid.getStore().insert(grid.getStore().getCount(),newTrigger); grid.getStore().commitChanges(); } form.getForm().reset(); win.hide(); } } }] }) //Window for the popup add trigger form var win = new Ext.Window({ layout:'form', autoWidth:true, autoHeight:true, closeAction:'hide', items: form }) // Get the toolbar of the grid var tb = grid.getTopToolbar(); // Add a new button to add triggers to the toolbar tb.addButton({ text:'Add Trigger', tooltip:'Add new trigger to the rule', iconCls:'icon-plus', handler: function(){ form.isEdit=false; form.rowIndex = null; win.show(); } }) // Add a tool separator to the toolbar tb.addSeparator(); // Add a new button to reset the grid's data to the toolbar tb.addButton({ text:'Reset', tooltip:'Reset the list to original triggers', iconCls:'icon-default', handler: function(){ Ext.Ajax.request({ url:'/eventmanagement/storeTriggers?reset', method:"POST", success: function(){ grid.getStore().reload(); }, failure: function(){ mask.hide(); Ext.Msg.alert('Error','Connection to server has been lost<br>Please try again!') } }) } }) // Add a tool separator to the toolbar tb.addSeparator(); // Add a checkbox for preserving the grid's row order to the toolbar tb.addField(new Ext.form.Checkbox({ boxLabel:'Preserve order', name:'preserve-row-order' })) // Get the column model of the gird and add a new column at the end // for the new grid's row reorder plugin var cm = grid.getColumnModel(); var columns = cm.getColumnsBy(function(c){return true}); columns.push({ header:this.colHeader, menuDisabled:true, dataIndex:null, renderer:function(value,metadata,record,rowIndex,colIndex,store){ var r = '<div>'; if(grid.rowUp) r+='<a href="#" class="row-re-order-up" qtip="Move record up"></a>'; if(grid.rowDown) r+='<a href="#" class="row-re-order-down" qtip="Move record down"></a>'; if(grid.rowEdit) r+='<a href="#" class="row-re-order-edit" qtip="Edit record"></a>'; if(grid.rowRemove) r+='<a href="#" class="row-re-order-remove" qtip="Remove record"></a>'; r+='</div>'; return r; }, toolTip:"Re-order the rows", width: (this.rowUp?30:0)+(this.rowDown?30:0)+(this.rowEdit?30:0)+(this.rowRemove?30:0) }); /* Alternative for reconfigure *****************/ grid.view.refresh(true) grid.view.initData(grid.getStore(), new Ext.grid.ColumnModel(columns)); grid.store = grid.getStore(); grid.colModel = new Ext.grid.ColumnModel(columns); if(grid.rendered){ grid.view.refresh(true); } /***********************************************/ // Add cell click event to the grid to catch the row reorder requests.. grid.on('cellclick',function(grid,rowIndex,columnIndex,e){ var target = e.getTarget(); // If clicked row up button if(target.className && target.className == 'row-re-order-up'){ var record = grid.getStore().getAt(rowIndex); if(rowIndex>0){ grid.getStore().remove(record); grid.getStore().insert(rowIndex-1,record); var row = grid.getView().getRow(rowIndex-1); Ext.get(row).syncFx(); Ext.get(row).slideIn('b',{ easing: 'easeOut', duration: .5, remove: false, useDisplay: false, callback: function(){ } }); Ext.get(row).highlight("dfe8f6", { attr: "background-color", easing: 'easeIn', duration: 1 }); } } // If clicked row down button if(target.className && target.className == 'row-re-order-down'){ var record = grid.getStore().getAt(rowIndex); if(rowIndex < grid.getStore().getCount()-1){ grid.getStore().remove(record); grid.getStore().insert(rowIndex+1,record); var row = grid.getView().getRow(rowIndex+1); Ext.get(row).syncFx(); Ext.get(row).slideIn('t', { easing: 'easeOut', duration: .5, remove: false, useDisplay: false, callback: function(){ } }); Ext.get(row).highlight("dfe8f6", { attr: "background-color", easing: 'easeIn', duration: 1 }); } } // If clicked row edit button if(target.className && target.className == 'row-re-order-edit'){ var record = grid.getStore().getAt(rowIndex); var event,event_classification,source_ip; if(record.get('event') != "-" && record.get('event') != ''){ var replace =record.get('event').toString().replace("(","").replace(")",""); event = "child:"+replace.match("[0-9]+"); } if(record.get('event_classification') != "-" && record.get('event_classification') != ''){ var replace = record.get('event_classification').toString().replace("(","").replace(")",""); event = "parent:"+replace.match("[0-9]+"); } var editTrigger = new triggerAttr({ event: event, source_ip:record.get('source_ip'), attacking_ip: record.get('attacking_ip'), username: record.get('username'), service: record.get('service') }); win.show(); form.isEdit=true; form.record = record; form.rowIndex = rowIndex; form.getForm().loadRecord(editTrigger); } // If clicked row remove button if(target.className && target.className == 'row-re-order-remove'){ var record = grid.getStore().getAt(rowIndex); var row = grid.getView().getRow(rowIndex); Ext.get(row).syncFx(); Ext.get(row).fadeOut({ duration: .5, callback: function(){ grid.getStore().remove(record); grid.getStore().commitChanges(); } }); } },this); }) }) } })
/* See documentation on https://github.com/frankrousseau/americano-cozy/#requests */ var americano = require("americano"); module.exports = { "product": { "all": americano.defaultRequests.all, // TODO: rename "byName": function(doc) { if (doc.normalizedName) { emit(doc.normalizedName, doc); } }, "byFullName": function(doc) { if (doc.name) { emit(doc.name, doc); } } }, "cart": { "all": americano.defaultRequests.all, }, "recipe": { "all": americano.defaultRequests.all, "allToCook": function (doc) { if (doc.toCook) { emit(doc.name, doc); } }, "byTag": function (doc) { for (i in doc.tags) { emit(doc.tags[i].id, doc); } } }, "receipt": { "all": function(doc) { if (doc.timestamp) { emit(doc.timestamp, doc); } }, "byReceiptId": function(doc) { if (doc.receiptId) { emit(doc.receiptId, doc); } }, }, "receipt_detail": { "all": americano.defaultRequests.all, "byReceiptId": function(doc) { if (doc.receiptId) { emit(doc.receiptId, doc); } else { // Old receiptDetail format. // doc.receiptId = doc.ticketId; emit(doc.ticketId, doc); } }, }, };
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * useLayoutEffect throws an error on the server. On the few occasions where is * problematic, use this hook. * * @flow */ import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; import { useEffect, useLayoutEffect } from 'react'; const useLayoutEffectImpl: typeof useLayoutEffect = canUseDOM ? useLayoutEffect : useEffect; export default useLayoutEffectImpl;
() => { const [startDate, setStartDate] = useState(new Date()); return ( <DatePicker selected={startDate} onChange={date => setStartDate(date)} excludeDateIntervals={[{start: subDays(new Date(), 5), end: addDays(new Date(), 5) }]} placeholderText="Select a date other than the interval from 5 days ago to 5 days in the future" /> ); };
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdControlPointDuplicate(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M32 16h-4v6h-6v4h6v6h4v-6h6v-4h-6v-6zM4 24c0-5.58 3.29-10.39 8.02-12.64V7.05C5.03 9.51 0 16.17 0 24s5.03 14.49 12.02 16.95v-4.31C7.29 34.39 4 29.58 4 24zM30 6c9.93 0 18 8.07 18 18s-8.07 18-18 18-18-8.07-18-18S20.07 6 30 6zm0 32c7.72 0 14-6.28 14-14s-6.28-14-14-14-14 6.28-14 14 6.28 14 14 14z" /> </IconBase> ); } export default MdControlPointDuplicate;
๏ปฟ // lib/paneless-mother-pane.js // Small screens? (mobile) // // ? // sizeable pane ---> small screen // // What happens? Pane fills the screen? Just the width changes? // // Small panes to begin with. Their size change? How do they fit in? // // Small screen: All panes stacked vertically? // // Overlapping panes to begin with. Why not overlapping in the small // screen? // // Do nothing? // // When going to a small screen, the user manually adjusts panes. // // All is remembered per user, device (screen size). // // Per device, specify: // // Whether or not to stack when vertical, chain when horizontal. // // Possibly floating and overlapping. // // Max/min width and height, when vertical/stacking and horizontal/chaining. // // When another user pulls a system choose the layout that most closely // matchs by W x H screen params. // // Changing (adding and removing panes, not size changes) in one WxH will // neccessitate * manual * setting in the other WxHs. But maybe some guesses // can be made. For example, if stacking then stack. // // Small Screen Frames? // // Frames where the layout for small screens is defined. // // Coexist with other frames in large screens. // // On small screens, systems thar don't have a small screen frame defined are not // listed. // (function () { 'use strict'; var directiveId = 'panelessMotherPane'; angular.module('app').directive ( directiveId, ['$document', '$compile', '$interval', panelessMotherPaneDirective] ); function panelessMotherPaneDirective ( $document, $compile, $interval ) { function link ( scope, element, attrs ) { var thisScope = scope; var nNewFrames = 0, startX = 0, startY = 0, orgX = 0, orgY = 0; var dragMe = null, bDragTargetsShowing = false, dragResult = 'no-drag'; scope.addFrame = function ( x, y, type ) { var newHTML, newFrame; console.log ( 'addFrame(): x ' + x + ' y ' + y ); ++nNewFrames; newHTML = '<paneless-frame style="left: ' + x + 'px; ' + 'top: ' + y + 'px; ' + 'width: 300px; ' + 'height: 200px;"> ' + '<paneless-title-bar> ' + '<paneless-mover></paneless-mover> ' + '<paneless-title>Title Goes Here</paneless-title> ' + '</paneless-title-bar> ' + '<paneless-client>' + '<paneless-pane style="width: 100%; height: 100%; overflow: auto;">'; if ( ! type ) { newHTML += '<div>A new pane in the app (' + nNewFrames + ')!</div>' + '<div style="width: 220px; ' + 'height: 120px; ' + 'border: 1px solid blue; ' + 'margin: 8px; ' + 'background-color: darkblue;">' + '</div>'; } newHTML += '</paneless-pane>' + '</paneless-client>' + '<paneless-status-bar>' + '<paneless-status>' + 'status messages here' + '</paneless-status>' + '<paneless-sizer></paneless-sizer>' + '</paneless-status-bar>' + '</paneless-frame>'; newFrame = $compile ( newHTML ) ( scope ); element.append ( newFrame ); newFrame.scope().init ( type ); } // addFrame() scope.addTabs = function ( x, y ) { var newHTML, newFrame; console.log ( 'addTabs(): x ' + x + ' y ' + y ); // For now, in a frame, to get this tabs stuff going. // // A group of labels that look like tabs. For now, along the bottom. // // The main stuff, of course, is what is shown/showing when the tab is // clicked/selected. Each tab has a pane associated with it. In that pane // is the app-specified stuff: maybe, for example, a status view. So we // have - // // The paneless-tabs which contains everything tabic. // // paneless-tab-pane for each tab. newHTML = '<paneless-frame style="left: ' + x + 'px; ' + 'top: ' + y + 'px; ' + 'width: 300px; ' + 'height: 200px;"> ' + '<paneless-title-bar> ' + '<paneless-mover></paneless-mover> ' + '<paneless-title>Title Goes Here</paneless-title> ' + '</paneless-title-bar> ' + '<paneless-client>' + '<paneless-pane style="width: 100%; height: 100%; overflow: auto;">'; newHTML += '<paneless-tabs>' + '</paneless-tabs>'; newHTML += '</paneless-pane>' + '</paneless-client>' + '<paneless-status-bar>' + '<paneless-status>' + 'status messages here' + '</paneless-status>' + '<paneless-sizer></paneless-sizer>' + '</paneless-status-bar>' + '</paneless-frame>'; newFrame = $compile ( newHTML ) ( scope ); element.append ( newFrame ); newFrame.scope().init ( 'tabs' ); } // addTabs() scope.addPane = function ( x, y ) { var newHTML, newPane; console.log ( 'addPane(): x ' + x + ' y ' + y ); newHTML = '<paneless-pane style="left: ' + x + 'px; ' + 'top: ' + y + 'px; ' + 'width: 200px; ' + 'height: 200px;" ' + 'data-paneless-floating> ' + '<paneless-title-bar> ' + '<paneless-mover></paneless-mover> ' + '<paneless-title>Title Goes Here</paneless-title> ' + '</paneless-title-bar> ' + 'A new pane in the app!' // + '<div style="border: 1px solid black; padding: 8px;"> ' + '<div style="width:180px; height:150px; border: 1px solid black"></div>' // + '</div> ' + '<paneless-sizer></paneless-sizer> ' + '</paneless-pane>'; newPane = $compile ( newHTML ) ( scope ); element.append ( newPane ); newPane.scope().init(); } // scope.addPane() scope.$on ( 'PanelessFloatPane', function ( evt, eFloat, eParent ) { var children, eF, x, y, w, newHTML, newPane; // See http://code.angularjs.org/1.2.14/docs/api/ng/type/$rootScope.Scope#$on evt.stopPropagation(); // eFloat The element of the pane to be floated. // // eParent The parent element of eFloat. children = eParent.children(); w = eParent[0].clientWidth; if ( children[0] === eFloat[0] ) { console.log ( 'scope.$on ( PanelessFloatPane, ... ): Top pane is specified to be floated.' ); // Create a new floating pane by cloning eFloat. // eF = eFloat[0].cloneNode(); eF.innerHTML = eFloat[0].innerHTML + '<paneless-sizer></paneless-sizer>'; x = parseInt ( eParent[0].style.left ); y = parseInt ( eParent[0].style.top ); eF.style.position = 'absolute'; eF.style.left = x + 'px'; eF.style.top = y + 'px'; eF.style.width = w + 'px'; eF.style.border = '1px solid lightgray'; eF.attributes.removeNamedItem ( 'data-paneless-docked' ); eF.attributes.setNamedItem ( document.createAttribute ( 'data-paneless-floating' ) ); newHTML = eF.outerHTML; newPane = $compile ( newHTML ) ( scope ); element.append ( newPane ); newPane.scope().init(); // Likewise, clone the pane on the other side of the splitter. It will // float also. // eF = children[2].cloneNode(); eF.innerHTML = children[2].innerHTML + '<paneless-sizer></paneless-sizer>'; x = parseInt ( eParent[0].style.left ) + children[2].offsetLeft; y = parseInt ( eParent[0].style.top ) + children[2].offsetTop; eF.style.position = 'absolute'; eF.style.left = x + 'px'; eF.style.top = y + 'px'; eF.style.width = w + 'px'; eF.style.border = '1px solid lightgray'; eF.attributes.removeNamedItem ( 'data-paneless-docked' ); eF.attributes.setNamedItem ( document.createAttribute ( 'data-paneless-floating' ) ); newHTML = eF.outerHTML; newPane = $compile ( newHTML ) ( scope ); element.append ( newPane ); newPane.scope().init(); } else { console.log ( 'scope.$on ( PanelessFloatPane, ... ): What to do?' ); } // Destroy floated pane's parent element (and the original, docked panes, and // splitter) and scope (and its child scopes). // eParent.remove(); evt.targetScope.$destroy(); } ); // scope.$on ( 'PanelessFloatPane', ... ) scope.$on ( 'PanelessDestroyFrame', function ( evt, eFrame ) { // See http://code.angularjs.org/1.2.14/docs/api/ng/type/$rootScope.Scope#$on evt.stopPropagation(); // Destroy fame element and scope (and its child scopes). // eFrame.remove(); evt.targetScope.$destroy(); } ); // scope.$on ( 'PanelessDestroyFrame', ... ) scope.$on ( 'PanelessContextMenu', function ( evt, menu ) { element.append ( menu ); } ); element.on ( 'contextmenu', function ( evt ) { var ms, menu; evt.preventDefault(); evt.stopPropagation(); scope.menuX = evt.pageX - element[0].offsetLeft; scope.menuY = evt.pageY - element[0].offsetTop; scope.menuCtx = 'mother'; ms = [ evt.pageX, evt.pageY ]; menu = $compile ( '<paneless-menu></paneless-nenu>' ) ( scope ); menu[0].style.left = "" + ms[0] + "px"; menu[0].style.top = "" + ms[1] + "px"; menu[0].style.overflow = "visible"; element.append ( menu ); } ); // element.on ( 'contextmenu', ... function cycleFrame ( frameElement, cb ) { var e2, p, newFrame; // Remember it. e2 = frameElement[0].cloneNode(); e2.innerHTML = frameElement[0].innerHTML; p = frameElement.scope().getP(); // Destroy it. frameElement.scope().$destroy(); frameElement.remove(); // Rebuild it. newFrame = $compile ( e2.outerHTML ) ( scope ); cb ( newFrame ); newFrame.scope().init(); newFrame.scope().setP ( p ); } // cycleFrame() scope.$on ( 'PanelessFrameToFront', function ( evt, frameElement ) { cycleFrame ( frameElement, function ( newFrame ) { element.append ( newFrame ); } ); } ); // scope.$on ( 'PanelessFrameToFront', ... scope.$on ( 'PanelessFrameToBack', function ( evt, frameElement ) { cycleFrame ( frameElement, function ( newFrame ) { element.prepend ( newFrame ); } ); } ); // scope.$on ( 'PanelessFrameToBack', ... scope.$on ( 'PanelessDrag', function ( evt, dragElement ) { // Dragging a pane from one frame to another. // // The source is any pane. A mousedown on a source indicator spcecifies // the associated pane as the source pane. // // Then the indicators become targets. // // Clicking anywhere other than a source indicator, or a mouseup anywhere // other than a target indicator cancels the operation. // Or ... // // See http://www.html5rocks.com/en/tutorials/dnd/basics/ var orgX = 0, orgY = 0, e = dragElement[0], newHTML, startX, startY; evt.stopPropagation(); showDrag ( dragElement ); // Find the center of the element to be dragged in this mother element's // coordinates. while ( e !== element[0] ) { orgX += e.offsetLeft; orgY += e.offsetTop; e = e.offsetParent; } e = dragElement[0]; // Again, because we used it up in the while() just above. orgX += e.offsetWidth / 2; orgY += e.offsetHeight / 2; // Append a drag indicator, centered on x y, to the contents of this mother // element. // newHTML = '<paneless-drag-source ></paneless-drag-source>'; newHTML = '<paneless-drag-source draggable="true"></paneless-drag-source>'; dragMe = $compile ( newHTML ) ( scope ); element.append ( dragMe ); orgX -= dragMe[0].offsetWidth / 2; orgY -= dragMe[0].offsetHeight / 2; dragMe.css ( { visibility: 'visible', left: orgX + 'px', top: orgY + 'px' }) dragMe.on ( 'mousedown', function ( evt ) { // evt.preventDefault(); // To keep from ending before we start. evt.stopPropagation(); // } ); dragMe.on ( 'dragstart', function ( evt ) { var html; console.log ( 'PanelessDrag - dragstart' ); html = e.innerHTML; evt.dataTransfer.effectAllowed = 'move'; evt.dataTransfer.dropEffect = 'move'; html = e.innerHTML; // evt.dataTransfer.setData ( 'text/html', html ); text/html does not work in IE. // http://stackoverflow.com/questions/16720967/datatransfer-setdata-does-not-work-in-ie9 evt.dataTransfer.setData ( 'text', html ); dragResult = 'pending'; } ); // scope.$on ( 'PanelessDrag', ... ) - dragstart dragMe.on ( 'dragend', function ( evt ) { // var d = evt.dataTransfer.getData ( 'text' ); // console.log ( 'PanelessDrag - dragend ' + evt.dataTransfer.dropEffect ); // console.log ( 'PanelessDrag - dragend d ' + d ); var dr = dragResult; console.log ( 'PanelessDrag - dragend ' + dragResult ); endDrag(); if ( dr === 'dropped' ) { dragElement.scope().destroySelf(); } } ); // scope.$on ( 'PanelessDrag', ... ) - dragend $document.on ( 'mousedown', endDrag ); } ); // scope.$on ( 'PanelessDrag', ... ) scope.$on ( 'PanelessDragDrop', function ( evt, result ) { dragResult = result; } ); // scope.$on ( 'PanelessDragDrop', ... function endDrag ( evt ) { console.log ( 'endDrag()' ); hideDrag(); dragResult = 'no-drag'; $document.unbind ( 'mousedown', endDrag ); } // endDrag() function showDrag ( dragElement ) { var children, i; // Always only panelesse-frames. children = element.children(); for ( i = 0; i < children.length; i++ ) { if ( dragMe && (children[i] === dragMe[0]) ) continue; angular.element ( children[i] ).scope().showDragTargets ( dragElement ); } bDragTargetsShowing = true; } // showDrag() function hideDrag() { var children, i; // Always only panelesse-frames. if ( ! bDragTargetsShowing ) { return; } if ( dragMe ) { dragMe.remove(); dragMe = null; } children = element.children(); for ( i = 0; i < children.length; i++ ) { if ( dragMe && (children[i] === dragMe[0]) ) continue; angular.element ( children[i] ).scope().hideDragTargets(); } bDragTargetsShowing = false; } // hideDrag() } // link() return { restrict: 'E', scope: true, // Each pane and splitter gets its own scope. link: link } } // panelessMotherPaneDirective })();
"use strict"; var equalsOperator = require("@collections/equals"); var hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = has; function has(object, soughtValue, equals) { equals = equals || equalsOperator; for (var key in object) { if (hasOwnProperty.call(object, key)) { var value = object[key]; if (equals(soughtValue, value)) { return true; } } } return false; }
var UserConstants = require('../constants/UserConstants'); var AccountActions = require('./AccountActions'); var SecurityActions = require('./SecurityActions'); var ErrorActions = require('./ErrorActions'); var models = require('../models.js'); var User = models.User; var Session = models.Session; var Error = models.Error; function createUser(user) { return { type: UserConstants.CREATE_USER, user: user } } function userCreated(user) { return { type: UserConstants.USER_CREATED, user: user } } function loginUser() { return { type: UserConstants.LOGIN_USER } } function userLoggedIn(session) { return { type: UserConstants.USER_LOGGEDIN, session: session } } function logoutUser() { return { type: UserConstants.LOGOUT_USER } } function userLoggedOut() { return { type: UserConstants.USER_LOGGEDOUT } } function fetchUser(userId) { return { type: UserConstants.FETCH_USER, userId: userId } } function userFetched(user) { return { type: UserConstants.USER_FETCHED, user: user } } function updateUser(user) { return { type: UserConstants.UPDATE_USER, user: user } } function userUpdated(user) { return { type: UserConstants.USER_UPDATED, user: user } } function fetch(userId) { return function (dispatch) { dispatch(fetchUser()); $.ajax({ type: "GET", dataType: "json", url: "v1/users/"+userId+"/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { dispatch(ErrorActions.serverError(e)); } else { var u = new User(); u.fromJSON(data); dispatch(userFetched(u)); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } function initializeSession(dispatch, session) { dispatch(userLoggedIn(session)); dispatch(fetch(session.UserId)); dispatch(AccountActions.fetchAll()); dispatch(SecurityActions.fetchAll()); } function create(user) { return function(dispatch) { dispatch(createUser(user)); $.ajax({ type: "POST", contentType: "application/json", dataType: "json", url: "v1/users/", data: user.toJSON(), success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { dispatch(ErrorActions.serverError(e)); } else { var u = new User(); u.fromJSON(data); dispatch(userCreated(u)); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } function login(user) { return function(dispatch) { dispatch(loginUser()); $.ajax({ type: "POST", contentType: "application/json", dataType: "json", url: "v1/sessions/", data: user.toJSON(), success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { dispatch(ErrorActions.serverError(e)); } else { var s = new Session(); s.fromJSON(data); initializeSession(dispatch, s); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } function tryResumingSession() { return function (dispatch) { $.ajax({ type: "GET", dataType: "json", url: "v1/sessions/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { if (e.ErrorId != 1 /* Not Signed In*/) dispatch(ErrorActions.serverError(e)); } else { var s = new Session(); s.fromJSON(data); dispatch(loginUser()); initializeSession(dispatch, s); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } function logout() { return function (dispatch) { dispatch(logoutUser()); $.ajax({ type: "DELETE", dataType: "json", url: "v1/sessions/", success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { dispatch(ErrorActions.serverError(e)); } else { dispatch(userLoggedOut()); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } function update(user) { return function (dispatch) { dispatch(updateUser()); $.ajax({ type: "PUT", contentType: "application/json", dataType: "json", url: "v1/users/"+user.UserId+"/", data: user.toJSON(), success: function(data, status, jqXHR) { var e = new Error(); e.fromJSON(data); if (e.isError()) { dispatch(ErrorActions.serverError(e)); } else { var u = new User(); u.fromJSON(data); dispatch(userUpdated(u)); } }, error: function(jqXHR, status, error) { dispatch(ErrorActions.ajaxError(error)); } }); }; } module.exports = { create: create, fetch: fetch, login: login, logout: logout, update: update, tryResumingSession: tryResumingSession };
import makeConsoleMock from '../consolemock'; describe('print(message, [message1, ..., messageN])', () => { test('calling .print incorrectly throws a helpful error message', () => { const mock = makeConsoleMock(); const callPrintIncorrectly = () => { mock.print(); }; expect(callPrintIncorrectly).toThrowErrorMatchingSnapshot(); }); });
var DB = require('../lib/db.js'); var Utils = require("../lib/utils"); /** * Read only API for i18n pages * * 1) load page contents by language and slug: /api/<lang>/page/<slug> * 2) load all page contents by language * 3) load all page titles /api/pages * 4) load all page contents /api/contents */ module.exports = function(app) { var db = DB(app.config); var util = Utils(); app.get('/api/pages', function(req, res) { var id = req.params.id; db.connect(function(err, connection){ connection.query('SELECT p.slug, pt.title, pt.language FROM page_page p, ' + 'page_tpage pt where pt.page_id = p.id and p.active=true', function(err, docs) { connection.release(); if (!err) { //pages = util.pickFields(docs, ['slug','title','language']); pages = docs; return res.status(200).send(pages); } else { return res.status(500).send({ message : err }); } }) }); }); app.get('/api/contents', function(req, res) { var id = req.params.id; db.connect(function(err, connection){ connection.query('SELECT c.page_id, c.code, tc.language,tc.text FROM page_content c, page_tcontent tc where tc.content_id = c.id and c.active=true', function(err, docs) { connection.release(); if (!err) { //pages = util.pickFields(docs, ['slug','title','language']); pages = docs; return res.status(200).send(pages); } else { return res.status(500).send({ message : err }); } }) }); }); app.get('/api/page/:slug', function(req, res) { var slug = req.params.slug; db.connect(function(err, connection){ var sql = 'SELECT c.slug, tc.language,tc.text FROM page_page p, page_content c, page_tcontent tc' + ' where tc.content_id = c.id and p.id = c.page_id and p.slug = "' + slug + '" and c.active=true'; //console.log('get page sql=' + sql); connection.query(sql, function(err, docs) { connection.release(); if (!err) { //pages = util.pickFields(docs, ['slug','title','language']); pages = docs; return res.status(200).json(pages); } else { return res.status(500).json({ message : err }); } }) }); }); };
/* * when called on a select box, populates a second, "target" select with data * from a "template" url, which is first passed through a "formatter" callback * * the formatter returns an map of key, value */ (function($) { function Template(string) { this.template = string; } Template.prototype = { constructor: Template, expand : function(map) { var result = this.template; $.each(map, function(key, value) { result = result.replace(new RegExp("\{" + key + "\}"), value); }); return result; } }; function FilterSelect(el, options) { if(el.get(0).tagName.toLowerCase() != 'select') { return null; } this.element = el; this.template = new Template(options.template); this.target = options.target; this.formatter = options.formatter; this.bind(); } FilterSelect.prototype = { constructor: FilterSelect, bind: function() { var self = this; this.element.on('change', function(e) { self.onChange(e); }); }, onChange: function(e) { var self = this; this.target.prop('disabled', true); $.get(this.template.expand({ value: this.element.val() }), function(data) { self.dataReady(data); self.target.prop('disabled', false); }); }, dataReady : function(data) { var self = this; this.target.html(''); $.each(this.formatter(data), function(key, value) { var option = $('<option></option>'); option.attr("value", value); if(self.target.data('selected') == value) { option.prop('selected', true); } option.text(key); self.target.append(option); }); } } $.fn.filterSelect = function(options) { this.each(function() { new FilterSelect($(this), options); }); } })(jQuery);
var Gesture = (function() { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; var videoElementId = "video_cameraDisplay", eventName = "gest", functionToBeFiredOnGest, createDomElement = (function() { var video = document.createElement("video"); video.setAttribute("src", ""); video.setAttribute("style", "display:none;width:400px; height:400px;"); video.setAttribute("id", videoElementId); document.body.appendChild(video); }), capture = (function(video) { var w = video.videoWidth * 0.2, h = video.videoHeight * 0.2, canvas = document.createElement('canvas'), ctx, imageData = {}; canvas.width = w; canvas.height = h; ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, w, h); if (canvas.width) { imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); } return (typeof imageData.data != "undefined") ? imageData.data : {}; }), shoot = (function() { var video = document.getElementById(videoElementId); var imageData = capture(video), imageArray = [], imageDataLength; if (JSON.stringify(imageData) != "{}" && imageData.length != 0) { imageDataLength = imageData.length; var x = 0, y = 0; for (var index = 0; index < imageDataLength; index++) { if (y < 640) { if (typeof imageArray[x] == "undefined") { imageArray[x] = []; } imageArray[x][y] = imageData[index]; y += 1; } else { x += 1; y = 0; if (typeof imageArray[x] == "undefined") { imageArray[x] = []; } imageArray[x][y] = imageData[index]; } } return imageArray; } return []; }), compareWithBasicAndFireEvent = (function(screenShot1, screenShot2) { if (typeof screenShot1[0] != "undefined") { var changeCounter = 0, arrayHeight = screenShot1.length, arrayWidth = screenShot1[0].length, flag = 0; for(var index1=0; index1<arrayHeight; index1++) { for(var index2 = index1; index2<arrayWidth; index2++) { if(screenShot1[index1][index2]!=screenShot2[index1][index2]) { changeCounter += 1; } if(changeCounter > (arrayWidth*arrayHeight*0.6)) { flag = 1; break; } } } if (flag) { functionToBeFiredOnGest("gest"); } } }), chopMatrix = (function(matrix) { var newMatrix = [], indexOfNewMatrix = 0; for(var index=50; index<=70; index++) { if(matrix.length == 0) { return []; } newMatrix[indexOfNewMatrix] = []; for(var index2=300; index2<=400; index2++) { newMatrix[indexOfNewMatrix].push(matrix[index][index2]); } indexOfNewMatrix += 1; } return newMatrix; }), startGestureReading = (function() { window.setInterval(function() { var screenShot1 = chopMatrix(shoot()), screenShot2; window.setTimeout(function() { screenShot2 = chopMatrix(shoot()); compareWithBasicAndFireEvent(screenShot1, screenShot2); }, 500); }, 1000); }); this.gest = (function(functionToBeFired) { var gestObject = {}; functionToBeFiredOnGest = functionToBeFired; }); this.start = (function() { createDomElement(); var camera = document.getElementById(videoElementId), constraints = { video: true }, success = (function(stream) { camera.src = window.URL.createObjectURL(stream); camera.play(); }), failure = (function(error) { alert("Error Occcured " + JSON.stringify(error)); }); navigator.getUserMedia(constraints, success, failure); startGestureReading(); }); });
import extend from "../utils/extend"; import { createUTC } from "./utc"; export function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0 && m._pf.bigHour === undefined; } } return m._isValid; } export function createInvalid (flags) { var m = createUTC(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }
/** * Fairly simply, this plug-in will take the data from an API result set * and sum it, returning the summed value. The data can come from any data * source, including column data, cells or rows. * * @name sum() * @summary Sum the values in a data set. * @author [Allan Jardine](http://sprymedia.co.uk) * @requires DataTables 1.10+ * * @returns {Number} Summed value * * @example * // Simply get the sum of a column * var table = $('#example').DataTable(); * table.column( 3 ).data().sum(); * * @example * // Insert the sum of a column into the columns footer, for the visible * // data on each draw * $('#example').DataTable( { * drawCallback: function () { * var api = this.api(); * api.table().footer().to$().html( * api.column( 4, {page:'current'} ).data().sum() * ); * } * } ); */ jQuery.fn.dataTable.Api.register('sum()', function () { return this.flatten().reduce(function (a, b) { return (a * 1) + (b * 1); // cast values in-case they are strings }); });
"use strict"; const path = require("path"); const fs = require("fs"); const tempy = require("tempy"); const fromPairs = require("lodash/fromPairs"); const prettier = require("prettier-local"); const runPrettier = require("../runPrettier.js"); expect.addSnapshotSerializer(require("../path-serializer.js")); describe("extracts file-info for a js file", () => { runPrettier("cli/", ["--file-info", "something.js"]).test({ status: 0, }); }); describe("extracts file-info for a markdown file", () => { runPrettier("cli/", ["--file-info", "README.md"]).test({ status: 0, }); }); describe("extracts file-info for a known markdown file with no extension", () => { runPrettier("cli/", ["--file-info", "README"]).test({ status: 0, }); }); describe("extracts file-info with ignored=true for a file in .prettierignore", () => { runPrettier("cli/ignore-path/", ["--file-info", "regular-module.js"]).test({ status: 0, }); }); describe("file-info should try resolve config", () => { runPrettier("cli/with-resolve-config/", ["--file-info", "file.js"]).test({ status: 0, }); }); describe("file-info should not try resolve config with --no-config", () => { runPrettier("cli/with-resolve-config/", [ "--file-info", "file.js", "--no-config", ]).test({ status: 0, stderr: "", write: [], }); }); describe("extracts file-info with ignored=true for a file in a hand-picked .prettierignore", () => { runPrettier("cli/", [ "--file-info", "regular-module.js", "--ignore-path=ignore-path/.prettierignore", ]).test({ status: 0, }); }); describe("non-exists ignore path", () => { runPrettier("cli/", [ "--file-info", "regular-module.js", "--ignore-path=ignore-path/non-exists/.prettierignore", ]).test({ status: 0, }); }); describe("extracts file-info for a file in not_node_modules", () => { runPrettier("cli/with-node-modules/", [ "--file-info", "not_node_modules/file.js", ]).test({ status: 0, }); }); describe("extracts file-info with with ignored=true for a file in node_modules", () => { runPrettier("cli/with-node-modules/", [ "--file-info", "node_modules/file.js", ]).test({ status: 0, }); }); describe("extracts file-info with ignored=false for a file in node_modules when --with-node-modules provided", () => { runPrettier("cli/with-node-modules/", [ "--file-info", "node_modules/file.js", "--with-node-modules", ]).test({ status: 0, }); }); describe("extracts file-info with inferredParser=null for file.foo", () => { runPrettier("cli/", ["--file-info", "file.foo"]).test({ status: 0, }); }); describe("extracts file-info with inferredParser=foo when plugins are autoloaded", () => { runPrettier("plugins/automatic/", ["--file-info", "file.foo"]).test({ status: 0, }); }); describe("extracts file-info with inferredParser=foo when plugins are loaded with --plugin-search-dir", () => { runPrettier("cli/", [ "--file-info", "file.foo", "--plugin-search-dir", "../plugins/automatic", ]).test({ status: 0, }); }); describe("extracts file-info with inferredParser=foo when a plugin is hand-picked", () => { runPrettier("cli/", [ "--file-info", "file.foo", "--plugin", "../plugins/automatic/node_modules/@prettier/plugin-foo", ]).test({ status: 0, }); }); test("API getFileInfo with no args", async () => { await expect(prettier.getFileInfo()).rejects.toThrow( new TypeError("expect `filePath` to be a string, got `undefined`") ); }); test("API getFileInfo.sync with no args", () => { expect(() => prettier.getFileInfo.sync()).toThrow( new TypeError("expect `filePath` to be a string, got `undefined`") ); }); test("API getFileInfo with filepath only", async () => { await expect(prettier.getFileInfo("README")).resolves.toMatchObject({ ignored: false, inferredParser: "markdown", }); }); test("API getFileInfo.sync with filepath only", () => { expect(prettier.getFileInfo.sync("README")).toMatchObject({ ignored: false, inferredParser: "markdown", }); }); describe("API getFileInfo resolveConfig", () => { const files = fromPairs( ["foo", "js", "bar", "css"].map((ext) => [ ext, path.resolve( path.join(__dirname, `../cli/with-resolve-config/file.${ext}`) ), ]) ); test("{resolveConfig: undefined}", async () => { await expect(prettier.getFileInfo(files.foo)).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect(prettier.getFileInfo(files.js)).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); await expect(prettier.getFileInfo(files.bar)).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect(prettier.getFileInfo(files.css)).resolves.toMatchObject({ ignored: false, inferredParser: "css", }); }); test("{resolveConfig: true}", async () => { await expect( prettier.getFileInfo(files.foo, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: "foo-parser", }); await expect( prettier.getFileInfo(files.js, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: "override-js-parser", }); await expect( prettier.getFileInfo(files.bar, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( prettier.getFileInfo(files.css, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: "css", }); }); test("sync {resolveConfig: undefined}", () => { expect(prettier.getFileInfo.sync(files.foo)).toMatchObject({ ignored: false, inferredParser: null, }); expect(prettier.getFileInfo.sync(files.js)).toMatchObject({ ignored: false, inferredParser: "babel", }); expect(prettier.getFileInfo.sync(files.bar)).toMatchObject({ ignored: false, inferredParser: null, }); expect(prettier.getFileInfo.sync(files.css)).toMatchObject({ ignored: false, inferredParser: "css", }); }); test("sync {resolveConfig: true}", () => { expect( prettier.getFileInfo.sync(files.foo, { resolveConfig: true, }) ).toMatchObject({ ignored: false, inferredParser: "foo-parser", }); expect( prettier.getFileInfo.sync(files.js, { resolveConfig: true, }) ).toMatchObject({ ignored: false, inferredParser: "override-js-parser", }); expect( prettier.getFileInfo.sync(files.bar, { resolveConfig: true, }) ).toMatchObject({ ignored: false, inferredParser: null, }); expect( prettier.getFileInfo.sync(files.css, { resolveConfig: true, }) ).toMatchObject({ ignored: false, inferredParser: "css", }); }); }); describe("API getFileInfo resolveConfig when no config is present", () => { const files = fromPairs( ["foo", "js"].map((ext) => [ ext, path.resolve(path.join(__dirname, `../cli/non-exists-dir/file.${ext}`)), ]) ); test("{resolveConfig: undefined}", async () => { await expect(prettier.getFileInfo(files.foo)).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect(prettier.getFileInfo(files.js)).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); }); test("{resolveConfig: true}", async () => { await expect( prettier.getFileInfo(files.foo, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( prettier.getFileInfo(files.js, { resolveConfig: true }) ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); }); test("sync {resolveConfig: undefined}", () => { expect(prettier.getFileInfo.sync(files.foo)).toMatchObject({ ignored: false, inferredParser: null, }); expect(prettier.getFileInfo.sync(files.js)).toMatchObject({ ignored: false, inferredParser: "babel", }); }); test("sync {resolveConfig: true}", () => { expect( prettier.getFileInfo.sync(files.foo, { resolveConfig: true }) ).toMatchObject({ ignored: false, inferredParser: null, }); expect( prettier.getFileInfo.sync(files.js, { resolveConfig: true }) ).toMatchObject({ ignored: false, inferredParser: "babel", }); }); }); test("API getFileInfo with ignorePath", async () => { const file = path.resolve( path.join(__dirname, "../cli/ignore-path/regular-module.js") ); const ignorePath = path.resolve( path.join(__dirname, "../cli/ignore-path/.prettierignore") ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); await expect( prettier.getFileInfo(file, { ignorePath }) ).resolves.toMatchObject({ ignored: true, inferredParser: null, }); }); test("API getFileInfo with ignorePath containing relative paths", async () => { const file = path.resolve( path.join( __dirname, "../cli/ignore-relative-path/level1-glob/level2-glob/level3-glob/shouldNotBeFormat.js" ) ); const ignorePath = path.resolve( path.join(__dirname, "../cli/ignore-relative-path/.prettierignore") ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); await expect( prettier.getFileInfo(file, { ignorePath }) ).resolves.toMatchObject({ ignored: true, inferredParser: null, }); }); test("API getFileInfo.sync with ignorePath", () => { const file = path.resolve( path.join(__dirname, "../cli/ignore-path/regular-module.js") ); const ignorePath = path.resolve( path.join(__dirname, "../cli/ignore-path/.prettierignore") ); expect(prettier.getFileInfo.sync(file)).toMatchObject({ ignored: false, inferredParser: "babel", }); expect( prettier.getFileInfo.sync(file, { ignorePath, }) ).toMatchObject({ ignored: true, inferredParser: null, }); }); describe("API getFileInfo.sync with ignorePath", () => { let cwd; let filePath; let options; beforeAll(() => { cwd = process.cwd(); const tempDir = tempy.directory(); process.chdir(tempDir); const fileDir = "src"; filePath = `${fileDir}/should-be-ignored.js`; const ignorePath = path.join(tempDir, ".prettierignore"); fs.writeFileSync(ignorePath, filePath, "utf8"); options = { ignorePath }; }); afterAll(() => { process.chdir(cwd); }); test("with relative filePath", () => { expect( prettier.getFileInfo.sync(filePath, options).ignored ).toMatchInlineSnapshot("true"); }); test("with relative filePath starts with dot", () => { expect( prettier.getFileInfo.sync(`./${filePath}`, options).ignored ).toMatchInlineSnapshot("true"); }); test("with absolute filePath", () => { expect( prettier.getFileInfo.sync(path.resolve(filePath), options).ignored ).toMatchInlineSnapshot("true"); }); }); test("API getFileInfo with withNodeModules", async () => { const file = path.resolve( path.join(__dirname, "../cli/with-node-modules/node_modules/file.js") ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: true, inferredParser: null, }); await expect( prettier.getFileInfo(file, { withNodeModules: true, }) ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", }); }); describe("extracts file-info for a JS file with no extension but a standard shebang", () => { expect( prettier.getFileInfo.sync("tests/integration/cli/shebang/node-shebang") ).toMatchObject({ ignored: false, inferredParser: "babel", }); }); describe("extracts file-info for a JS file with no extension but an env-based shebang", () => { expect( prettier.getFileInfo.sync("tests/integration/cli/shebang/env-node-shebang") ).toMatchObject({ ignored: false, inferredParser: "babel", }); }); describe("returns null parser for unknown shebang", () => { expect( prettier.getFileInfo.sync("tests/integration/cli/shebang/nonsense-shebang") ).toMatchObject({ ignored: false, inferredParser: null, }); }); test("API getFileInfo with plugins loaded using pluginSearchDir", async () => { const file = "file.foo"; const pluginsPath = path.resolve( path.join(__dirname, "../plugins/automatic") ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( prettier.getFileInfo(file, { pluginSearchDirs: [pluginsPath], }) ).resolves.toMatchObject({ ignored: false, inferredParser: "foo", }); }); test("API getFileInfo with hand-picked plugins", async () => { const file = "file.foo"; const pluginPath = path.resolve( path.join( __dirname, "../plugins/automatic/node_modules/@prettier/plugin-foo" ) ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( prettier.getFileInfo(file, { plugins: [pluginPath], }) ).resolves.toMatchObject({ ignored: false, inferredParser: "foo", }); }); test("API getFileInfo with ignorePath and resolveConfig should infer parser with correct filepath", async () => { const dir = path.join(__dirname, "../cli/ignore-and-config/"); const filePath = path.join(dir, "config-dir/foo"); const ignorePath = path.join(dir, "ignore-path-dir/.prettierignore"); const options = { resolveConfig: true, ignorePath, }; await expect(prettier.getFileInfo(filePath, options)).resolves.toMatchObject({ ignored: false, inferredParser: "parser-for-config-dir", }); expect(prettier.getFileInfo.sync(filePath, options)).toMatchObject({ ignored: false, inferredParser: "parser-for-config-dir", }); });
/** * User: udibauman * Date: 2/2/12 * Time: 7:22 PM */ var ClassDiagramDrawer = { svg: null, current_offset: 0, default_class_width: 150, default_member_height: 20, default_member_spacing: 20, class_containers: {}, init: function() { var w = 675, h = 360; var pack = d3.layout.pack() .size([w - 4, h - 4]) .value(function (d) { return d.size; }); this.svg = d3.select("#chart").append("svg") .attr("width", w) .attr("height", h) .attr("class", "pack") .append("g") .attr("transform", "translate(2, 2)"); }, draw_class: function(model) { var data = model.get_all_members(), x = this.current_offset, y = 50, margin = 10; var g = this.svg.append('g') .attr("x", x) .attr("y", y); this.class_containers[model.get('name')] = g; g.append('rect') .attr("x", x) .attr("y", y) .attr("width", this.default_class_width) .attr("height", data.length * this.default_member_height); var that = this; g.selectAll("text") .data(data) .enter().append("text") .attr("x", x + margin) .attr("y", function(d, i) { return y + margin + i * that.default_member_height; }) .attr("dy", ".35em") // vertical-align: middle .text(String); g.append("line") .attr("x1", x) .attr("y1", y + this.default_member_height) .attr("x2", x + this.default_class_width) .attr("y2", y + this.default_member_height); this.current_offset += this.default_class_width + this.default_member_spacing; } }; var drawer = ClassDiagramDrawer;
module.exports = (req, res) => { res.redirect(req.session.redirect || '/profile'); delete req.session.redirect; };
var test = require('tape'), eventuate = require('eventuate-core'), chainable = require('..') test('errors are splittable', function (t) { t.plan(2) var eventuateMap = chainable(function (options, map) { return function upstreamConsumer (data) { this.error(new Error('boom')) this.error('boom') this.finish() } }) var event = eventuate() eventuateMap(event, function (data) { return data.toUpperCase() }).consume(function (data) { t.ok(data instanceof Error, 'got an error') }) event.produce('a') })
//var Wunderground = require('wunderground-api'); var Wunderground = require('wundergroundnode'); var fs = require("fs"); var myKey = 'f84a42eeb50f0783'; var client = new Wunderground(myKey); var opts = '98101'; /* what wundergroud-api expects for opts var opts = { city:'Seattle', state: 'WA' } */ // run once immediately updateHourlyForecasts(); // loop every 30 min getting most recent hourly forecast setInterval(updateHourlyForecasts, 30 * 60 * 1000); function updateHourlyForecasts() { client.hourlyForecast().request(opts, function(err, data) { if (err) { // should update an error log here // do not stop executing - try again next time } else { // write the hourly forecasts to a file fs.writeFile( "hourly.json", JSON.stringify( data.hourly_forecast ), "utf8" ); } }); }
// This file has been autogenerated. exports.setEnvironment = function() { process.env['AZURE_BATCH_ACCOUNT'] = 'batchtestnodesdk'; process.env['AZURE_BATCH_ENDPOINT'] = 'https://batchtestnodesdk.japaneast.batch.azure.com/'; process.env['AZURE_SUBSCRIPTION_ID'] = '603663e9-700c-46de-9d41-e080ff1d461e'; }; exports.scopes = [[function (nock) { var result = nock('http://batchtestnodesdk.japaneast.batch.azure.com:443') .get('/lifetimejobstats?api-version=2016-02-01.3.0') .reply(200, "{\r\n \"odata.metadata\":\"https://batchtestnodesdk.japaneast.batch.azure.com/$metadata#jobstats/@Element\",\"url\":\"https://batchtestnodesdk.japaneast.batch.azure.com/lifetimejobstats\",\"startTime\":\"2016-03-31T21:49:36.4926196Z\",\"lastUpdateTime\":\"2016-03-31T21:49:36.4926196Z\",\"userCPUTime\":\"PT0S\",\"kernelCPUTime\":\"PT0S\",\"wallClockTime\":\"PT0S\",\"readIOps\":\"0\",\"writeIOps\":\"0\",\"readIOGiB\":0.0,\"writeIOGiB\":0.0,\"numTaskRetries\":\"0\",\"numSucceededTasks\":\"0\",\"numFailedTasks\":\"0\",\"waitTime\":\"PT0S\"\r\n}", { 'transfer-encoding': 'chunked', 'content-type': 'application/json;odata=minimalmetadata', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '7c46e42e-3711-4ea7-a538-034e2aa8e719', 'strict-transport-security': 'max-age=31536000; includeSubDomains', dataserviceversion: '3.0', date: 'Fri, 01 Apr 2016 05:56:01 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://batchtestnodesdk.japaneast.batch.azure.com:443') .get('/lifetimejobstats?api-version=2016-02-01.3.0') .reply(200, "{\r\n \"odata.metadata\":\"https://batchtestnodesdk.japaneast.batch.azure.com/$metadata#jobstats/@Element\",\"url\":\"https://batchtestnodesdk.japaneast.batch.azure.com/lifetimejobstats\",\"startTime\":\"2016-03-31T21:49:36.4926196Z\",\"lastUpdateTime\":\"2016-03-31T21:49:36.4926196Z\",\"userCPUTime\":\"PT0S\",\"kernelCPUTime\":\"PT0S\",\"wallClockTime\":\"PT0S\",\"readIOps\":\"0\",\"writeIOps\":\"0\",\"readIOGiB\":0.0,\"writeIOGiB\":0.0,\"numTaskRetries\":\"0\",\"numSucceededTasks\":\"0\",\"numFailedTasks\":\"0\",\"waitTime\":\"PT0S\"\r\n}", { 'transfer-encoding': 'chunked', 'content-type': 'application/json;odata=minimalmetadata', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '7c46e42e-3711-4ea7-a538-034e2aa8e719', 'strict-transport-security': 'max-age=31536000; includeSubDomains', dataserviceversion: '3.0', date: 'Fri, 01 Apr 2016 05:56:01 GMT', connection: 'close' }); return result; }]];
var gulp = require("gulp"), util = require("gulp-util"), localize = require("./build/localizeFiles.js"), updateResources = require("./build/updateResources.js"), createFiddleFiles = require("./build/createFiddleFiles.js"); var version = util.env.version; //should be passed as --version ${TRAVIS_BRANCH} var dist = "./dist", copySrc = [ "./css/**/*", "./js/**/*", "./images/**/*", "./data-files/**/*", "./data-files-ja/**/*" ], config = require("./build/config.json"); // Command line overrides: if (util.env["ignite-ui"]) { // Optional override for the Ignite UI source location, can be passed as --ignite-ui "http://<ignite-ui root>" config.patterns["%%ignite-ui%%"] = util.env["ignite-ui"]; } if (version) { config.patterns["%%ignite-ui%%"] = config.patterns["%%ignite-ui%%"].replace("latest", "20" + version + "/latest"); } else { version = "latest"; } if (util.env["live-url"]) { // Optional override for the live demo URL (without trailing slash). Warning: might be case-sensitive config.liveUrl = util.env["live-url"].replace(/\/$/, ""); } config.version = version.toString(); dist = dist + "/" + version; gulp.task("process-files", function () { console.log("Building samples for: ", version); console.log("Ignite UI source root: ", config.patterns["%%ignite-ui%%"]); console.log("Live URL base: ", config.liveUrl); return gulp.src(["HTMLSamples/**/*.html"]) .pipe(localize(config)) .pipe(updateResources(config)) .pipe(createFiddleFiles(config)) .pipe(gulp.dest(dist)); }); gulp.task("build-samples", ["process-files"], function () { return gulp.src(copySrc, { base: "./" }) .pipe(gulp.dest("./dist")); });
(function() { 'use strict'; function definition(path, Failure, Pledge, handlerModule, isObject, merge, onAnimationFrame) { var settings = { suffix: '.js' }; demand .on('postConfigure:' + path, function(options) { if(isObject(options)) { merge(settings, options); } }); function resolve() { var self = this, dfd = self.dfd, probe = settings[self.path] && settings[self.path].probe, result; handlerModule.process(self); if(probe && (result = probe())) { provide(function() { return result; }); } else { if(probe) { dfd.reject(new Failure('error probing', self.path)); } else { provide(function() { return true; }); } } } function HandlerLegacy() {} HandlerLegacy.prototype = { onPreRequest: function(dependency, suffix) { var dependencies = settings[dependency.path] && settings[dependency.path].dependencies; suffix = (typeof suffix !== 'undefined') ? suffix : settings.suffix; handlerModule.onPreRequest(dependency, suffix || false); if(dependencies) { dependency.enqueue = demand.apply(null, dependencies).then; } }, onPreProcess: function(dependency) { var dependencies = settings[dependency.path] && settings[dependency.path].dependencies; if(dependencies && typeof dependency.enqueue === 'boolean') { dependency.enqueue = demand .apply(null, dependencies) .then(function() { return new Pledge(onAnimationFrame); }); } }, process: function(dependency) { var boundResolve = resolve.bind(dependency); if(dependency.enqueue === true) { boundResolve(); } else { dependency.enqueue .then( boundResolve, function() { dependency.dfd.reject(new Failure('error resolving', dependency.path, arguments)); } ) } } }; return new (HandlerLegacy.extends(handlerModule)); } provide([ 'path', '/demand/failure', '/demand/pledge', '/demand/handler/module', '/demand/validator/isObject', '/demand/function/merge', '/demand/function/onAnimationFrame' ], definition); }());
// Match any single/double quoted string var REGEX_BEGINS_WITH_STRING = new RegExp('^(?:"(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\']*(?:\'\'[^\']*)*)\')', ''); module.exports = { // Parse hxml data and return an array of arguments (compatible with node child_process.spawn) parse_hxml_args: function(raw_hxml) { var args = []; var i = 0; var len = raw_hxml.length; var current_arg = ''; var prev_arg = null; var number_of_parens = 0; var c, m; while (i < len) { c = raw_hxml.charAt(i); if (c === '(') { if (prev_arg === '--macro') { number_of_parens++; } current_arg += c; i++ } else if (number_of_parens > 0 && c === ')') { number_of_parens--; current_arg += c; i++; } else if (c === '"' || c === '\'') { REGEX_BEGINS_WITH_STRING.lastIndex = -1; if (m = raw_hxml.slice(i).match(REGEX_BEGINS_WITH_STRING)) { current_arg += m[0]; i += m[0].length; } else { // This should not happen, but if it happens, just add the character current_arg += c; i++; } } else if (c.trim() === '') { if (number_of_parens == 0) { if (current_arg.length > 0) { prev_arg = current_arg; current_arg = ''; args.push(prev_arg); } } else { current_arg += c; } i++; } else { current_arg += c; i++; } } if (current_arg.length > 0) { args.push(current_arg); } return args; } }
var App; (function (App) { var Common; (function (Common) { "use strict"; /** * ใƒ˜ใƒƒใƒ€ใƒผ ใ‚ณใƒณใƒˆใƒญใƒผใƒฉใƒผ */ var HeaderController = (function () { function HeaderController(navigationService, rootTitle) { this.navigationService = navigationService; this.rootTitle = rootTitle; } Object.defineProperty(HeaderController.prototype, "title", { get: function () { if (this.navigationService.currentName) { return this.navigationService.currentName + " - " + this.rootTitle; } else { return this.rootTitle; } }, enumerable: true, configurable: true }); Object.defineProperty(HeaderController.prototype, "pageName", { get: function () { return this.navigationService.currentName; }, enumerable: true, configurable: true }); return HeaderController; })(); angular.module("app").controller("headerController", ["navigationService", "rootTitle", HeaderController]).directive("appHeader", function () { return { controller: "headerController as header" }; }); })(Common = App.Common || (App.Common = {})); })(App || (App = {})); //# sourceMappingURL=header.js.map
/** * Created by johnson on 2017/1/13. */ mainApp.controller('SharedFileCtrl', ['$scope', '$rootScope', '$http', 'SharedFileService', function ($scope, $rootScope, $http, SharedFileService) { $scope.shares = {}; $scope.copyInfo = { isCopy: false, paths: '' }; $scope.cutInfo = { isCut: false, paths: '' }; /** * get files and directories in specific path * @param path */ $scope.getDatas = function (path) { SharedFileService.getShares({ "path": path }, function (data) { console.log(data); $scope.shares = data; $scope.setParentFolder(data.paths); }); }; /** * when clicked on a folder, dig into it * when clicked on a file, just download it. * * @param index */ $scope.digIn = function (index) { var file = $scope.shares.files[index]; var filePath = ''; var pathNow = $scope.getPathNow($scope.shares.paths); if (file.type == 'directory') { filePath = pathNow + '/' + file.item; $scope.getDatas(filePath); } else if (file.type == 'file') { filePath = pathNow + '/' + file.item; alert(filePath); } }; /** * return which path you are watching at now. * @param paths * @returns {string} */ $scope.getPathNow = function (paths) { var pathNow = ''; if (paths.length == 1) { if (paths[0].length <= 1) { return pathNow; } } for (var i = 0; i < paths.length; i++) { pathNow += paths[i]; } return pathNow; }; $scope.parent = { hasParent: false, path: '' }; /** * set back btn. * @param paths */ $scope.setParentFolder = function (paths) { if (paths.length == 1) { if (paths[0].length <= 1) { $scope.parent.hasParent = false; return; } else { $scope.parent = { hasParent: true, path: '/' }; return; } } var parentPath = ''; for (var i = 0; i < paths.length - 1; i++) { parentPath += paths[i]; } $scope.parent = { hasParent: true, path: parentPath }; }; /** * back */ $scope.backToParent = function () { $scope.getDatas($scope.parent.path); }; $scope.popover = function (id) { $('#' + id).popover('show'); }; $scope.popoverHide = function (id) { $('#' + id).popover('hide'); }; /** * download files and folders * * @param index */ $scope.download = function (index) { var file = $scope.shares.files[index]; var pathNow = $scope.getPathNow($scope.shares.paths); var form = $("<form>"); form.attr("style", "display:none"); form.attr("target", ""); form.attr("method", "post"); form.attr("action", "/shared/download"); var input1 = $("<input>"); input1.attr("type", "hidden"); input1.attr("name", "path"); input1.attr("value", pathNow + "/" + file.item); $("body").append(form); form.append(input1); form.submit(); }; /** * check on/off * @param index */ $scope.doCheck = function (index) { var file = $scope.shares.files[index]; file.checked = !file.checked; }; /** * download choosed files and folders with a zip package */ $scope.downloadPackage = function () { var package = $scope.getCheckedItem(); if (package.count == 0) { return; } var form = $("<form>"); form.attr("style", "display:none"); form.attr("target", ""); form.attr("method", "post"); form.attr("action", "/shared/download"); var input1 = $("<input>"); input1.attr("type", "hidden"); input1.attr("name", "paths"); input1.attr("value", JSON.stringify(package.files)); $("body").append(form); form.append(input1); form.submit(); }; /** * get checked items * * @returns {{count: number, files: Array}} */ $scope.getCheckedItem = function () { var pathNow = $scope.getPathNow($scope.shares.paths); var result = { count: 0, files: new Array() }; var files = $scope.shares.files; for (var i = 0; i < files.length; i++) { var item = files[i]; if (item.checked) { result.count++; result.files.push(pathNow + "/" + item.item); } } return result; }; /** * add new folder */ $scope.addFolder = function () { var folderName = prompt("่พ“ๅ…ฅๆ–‡ไปถๅคนๅ็งฐ"); if (folderName) { var pathNow = $scope.getPathNow($scope.shares.paths); SharedFileService.newFolder({ "path": pathNow + "/" + folderName }, function () { $scope.getDatas(pathNow); }); } }; /** * change folder * * @param index */ $scope.gotoFolder = function (index) { var paths = $scope.shares.paths; var path = ""; for (var i = 0; i <= index; i++) { path += paths[i]; } $scope.getDatas(path); }; /** * delete single file/folder * * @param index */ $scope.delete = function (index) { var r = confirm("็กฎ่ฎคๅˆ ้™ค๏ผŸ"); if (r == true) { var pathNow = $scope.getPathNow($scope.shares.paths); var file = $scope.shares.files[index]; SharedFileService.delete({ "path": pathNow + "/" + file.item }, function () { var pathNow = $scope.getPathNow($scope.shares.paths); $scope.getDatas(pathNow); }); } }; /** * delete select files/folders */ $scope.deleteSelected = function () { var selectItems = $scope.getCheckedItem(); if (selectItems.count == 0) return; if (confirm("็กฎ่ฎคๅˆ ้™ค๏ผŸ")) { SharedFileService.delete({ "paths": selectItems.files }, function () { var pathNow = $scope.getPathNow($scope.shares.paths); $scope.getDatas(pathNow); }); } }; $scope.selectFile = function () { $('#file').trigger("click"); upload.pathNow = $scope.getPathNow($scope.shares.paths); }; /** * refresh this path */ $scope.refresh = function () { var pathNow = $scope.getPathNow($scope.shares.paths); $scope.getDatas(pathNow); }; /** * start to copy selected files/folders */ $scope.copy = function () { var selectItems = $scope.getCheckedItem(); if (selectItems.count == 0) return; $scope.cutInfo.isCut = false; $scope.copyInfo = { isCopy: true, paths: selectItems.files }; }; /** * cancel copy */ $scope.copyCutCancel = function () { $scope.cutInfo = { isCut: false, paths: '' }; $scope.copyInfo = { isCopy: false, paths: '' }; }; /** * copy files and folders */ $scope.doCopy = function () { var pathNow = $scope.getPathNow($scope.shares.paths); SharedFileService.copy({ files: $scope.copyInfo.paths, target: pathNow }, function (data) { $scope.copyCutCancel(); $scope.getDatas(pathNow); }); }; /** * start to cut selected files and folders */ $scope.cut = function () { var selectItems = $scope.getCheckedItem(); if (selectItems.count == 0) return; $scope.copyInfo.isCopy = false; $scope.cutInfo = { isCut: true, paths: selectItems.files }; }; /** * cut files and folders */ $scope.doCut = function () { var pathNow = $scope.getPathNow($scope.shares.paths); SharedFileService.cut({ files: $scope.cutInfo.paths, target: pathNow }, function (data) { $scope.copyCutCancel(); $scope.getDatas(pathNow); }); }; /** * start to rename * * @param index */ $scope.rename = function (index) { var file = $scope.shares.files[index]; var pathNow = $scope.getPathNow($scope.shares.paths); var oldPath = pathNow + "/" + file.item; var newName = prompt("่ฏท่พ“ๅ…ฅๆ–ฐๆ–‡ไปถๅ", file.item); var newPath = pathNow + "/" + newName; SharedFileService.rename({ "oldPath": oldPath, "newPath": newPath }, function (data) { $scope.getDatas(pathNow); }); }; $scope.getDatas('/'); }]); var upload = { pathNow: '', doUpload: function (overWrite) { var data = new FormData($('#uploadForm')[0]); if (overWrite != true) overWrite = false; $.ajax({ url: "/shared/upload?timestamp=" + new Date().getTime(), type: 'POST', data: data, dataType: 'JSON', cache: false, processData: false, contentType: false, headers: { path: upload.pathNow, overWrite: overWrite }, success: function (data) { if (data.hasOwnProperty('error')) { if (data.error == 'sameName') { if (confirm("ๅญ˜ๅœจๅŒๅๆ–‡ไปถ๏ผŒๆ˜ฏๅฆ่ฆ†็›–๏ผŸ")) { upload.doUpload(true); } } else { alert(data.error); } } $("#refresh").trigger('click'); } }); } };
require('./util/utils'); var token = require('./util/token') , jsonPath = require('./util/jsonPath') , mq = require('jm-mq') , jm = require('jm-dao'); jm.token = token; jm.jsonPath = jsonPath; jm.mq = mq; module.exports = jm;
var penthouse = require('../lib/'), chai = require('chai'), should = chai.should(), css = require('css'), read = require('fs').readFileSync, path = require('path'); describe('basic tests of penthouse functionality', function () { var originalCssFilePath = path.join(__dirname, 'static-server', 'main.css'), originalCss = read(originalCssFilePath).toString(), server, port; // phantomjs takes a while to start up this.timeout(5000); before(function (done) { startServer(function (instance, serverPort) { server = instance; port = serverPort; done(); }); }); after(function () { server.close(); }); it('should return a css file', function (done) { penthouse({ url: 'http://localhost:' + port, css: originalCssFilePath }, function (err, result) { if(err) { done(err); } try { css.parse(result); done(); } catch (ex) { done(ex); } }); }); it('should return a css file whose parsed AST is equal to the the original\'s AST when the viewport is large', function (done) { var widthLargerThanTotalTestCSS = 1000, heightLargerThanTotalTestCSS = 1000; penthouse({ url: 'http://localhost:' + port, css: originalCssFilePath, width: widthLargerThanTotalTestCSS, height: heightLargerThanTotalTestCSS }, function (err, result) { try { var resultAst = css.parse(result); var orgAst = css.parse(originalCss); resultAst.should.eql(orgAst); done(); } catch (ex) { done(ex); } }); }); it('should return a subset of the original AST rules when the viewport is small', function (done) { var widthLargerThanTotalTestCSS = 1000, heightSmallerThanTotalTestCSS = 100; penthouse({ url: 'http://localhost:' + port, css: originalCssFilePath, width: widthLargerThanTotalTestCSS, height: heightSmallerThanTotalTestCSS }, function (err, result) { if(err) { done(err); } try { var resultAst = css.parse(result); var orgAst = css.parse(originalCss); resultAst.stylesheet.rules.should.have.length.lessThan(orgAst.stylesheet.rules.length); done(); } catch (ex) { done(ex); } }); }); }); function startServer(done) { var portfinder = require('portfinder'); portfinder.getPort(function (err, port) { // // `port` is guaranteed to be a free port // in this scope. var app = require('./static-server/app.js'); var server = app.listen(port); done(server, port); }); }
var Models = require('../models'); var createContentNodeCollection = require('./vuex/importUtils').createContentNodeCollection; exports.hasRelatedContent = function(contentNodes) { var collection = createContentNodeCollection(contentNodes); return collection.has_related_content(); }; /** * Given an Array of ContentNode IDs, return an Array of the corresponding ContentNode Objects * @param {Array<string>} nodeIds * @returns {Promise<Array<ContentNode>>} */ exports.fetchContentNodesById = function(nodeIds) { var collection = new Models.ContentNodeCollection(); return collection.get_all_fetch_simplified(nodeIds).then(function(nodeCollection) { return nodeCollection.toJSON(); }); }; function fetchItemSearchResults(searchTerm, currentChannelId) { return new Promise(function(resolve, reject) { $.ajax({ method: 'GET', // omitting slash results in 301 url: '/api/search/items/', success: resolve, error: reject, data: { q: searchTerm, exclude_channel: currentChannelId || '', }, }); }); } function fetchTopicSearchResults(searchTerm, currentChannelId) { return new Promise(function(resolve, reject) { $.ajax({ method: 'GET', url: '/api/search/topics/', success: resolve, error: reject, data: { q: searchTerm, exclude_channel: currentChannelId || '', }, }); }); } exports.fetchSearchResults = function(searchTerm, currentChannelId) { return Promise.all([ fetchItemSearchResults(searchTerm, currentChannelId), fetchTopicSearchResults(searchTerm, currentChannelId), ]).then(function(results) { return { searchTerm: searchTerm, itemResults: results[0], topicResults: results[1], }; }); }; exports.getIconClassForKind = function(kind) { switch (kind) { case 'topic': return 'folder'; case 'video': return 'theaters'; case 'audio': return 'headset'; case 'image': return 'image'; case 'exercise': return 'star'; case 'document': return 'description'; case 'html5': return 'widgets'; default: return 'error'; } };
var test = require('tape'), nock = require('nock'), _ = require('lodash'); var versions = require('./../lib/versions'); var fixturesVersionsHtml = './test/fixtures/testVersions.html'; var dlUrl = 'http://dl.node-webkit.org'; var expectedVersions = ['0.10.2','0.10.1','0.10.0','0.10.0-rc1','0.9.3']; test('getLatestVersion', function (t) { t.plan(1); nock(dlUrl).get('/').replyWithFile(200, fixturesVersionsHtml); versions.getLatestVersion(dlUrl).then(function(result){ t.equal(result, expectedVersions[0]); }); }); test('getVersions', function (t) { t.plan(1); nock(dlUrl).get('/').replyWithFile(200, fixturesVersionsHtml); versions.getVersions(dlUrl).then(function(result){ t.deepEqual(result, expectedVersions); }); }); test('getVersionNames', function (t) { t.plan(2); var v = '0.8.4'; var expected = { linux32: 'v'+v+'/node-webkit-v'+v+'-linux-ia32.tar.gz', linux64: 'v'+v+'/node-webkit-v'+v+'-linux-x64.tar.gz', osx32: 'v'+v+'/node-webkit-v'+v+'-osx-ia32.zip', osx64: 'v'+v+'/node-webkit-v'+v+'-osx-x64.zip', win32: 'v'+v+'/node-webkit-v'+v+'-win-ia32.zip', win64: 'v'+v+'/node-webkit-v'+v+'-win-x64.zip', }; var names = versions.getVersionNames(v); t.equal( names.version, v ); t.deepEqual(names.platforms, expected); }); test('getVersionNames for 0.12.0-alpha1', function (t) { t.plan(2); var v = '0.12.0-alpha1'; var expected = { linux32: 'v'+v+'/nwjs-v'+v+'-linux-ia32.tar.gz', linux64: 'v'+v+'/nwjs-v'+v+'-linux-x64.tar.gz', osx32: 'v'+v+'/nwjs-v'+v+'-osx-ia32.zip', osx64: 'v'+v+'/nwjs-v'+v+'-osx-x64.zip', win32: 'v'+v+'/nwjs-v'+v+'-win-ia32.zip', win64: 'v'+v+'/nwjs-v'+v+'-win-x64.zip', }; var names = versions.getVersionNames(v); t.equal( names.version, v ); t.deepEqual(names.platforms, expected); }); test('getVersionNames for 0.12.0-alpha2', function (t) { t.plan(2); var v = '0.12.0-alpha2'; var expected = { linux32: 'v'+v+'/nwjs-v'+v+'-linux-ia32.tar.gz', linux64: 'v'+v+'/nwjs-v'+v+'-linux-x64.tar.gz', osx32: 'v'+v+'/nwjs-v'+v+'-osx-ia32.zip', osx64: 'v'+v+'/nwjs-v'+v+'-osx-x64.zip', win32: 'v'+v+'/nwjs-v'+v+'-win-ia32.zip', win64: 'v'+v+'/nwjs-v'+v+'-win-x64.zip', }; var names = versions.getVersionNames(v); t.equal( names.version, v ); t.deepEqual(names.platforms, expected); }); test('getVersionNames for 0.12.0', function (t) { t.plan(2); var v = '0.12.0'; var expected = { linux32: 'v'+v+'/nwjs-v'+v+'-linux-ia32.tar.gz', linux64: 'v'+v+'/nwjs-v'+v+'-linux-x64.tar.gz', osx32: 'v'+v+'/nwjs-v'+v+'-osx-ia32.zip', osx64: 'v'+v+'/nwjs-v'+v+'-osx-x64.zip', win32: 'v'+v+'/nwjs-v'+v+'-win-ia32.zip', win64: 'v'+v+'/nwjs-v'+v+'-win-x64.zip', }; var names = versions.getVersionNames(v); t.equal( names.version, v ); t.deepEqual(names.platforms, expected); }); test('getVersionNames for 1.0.0-alpha1', function (t) { t.plan(2); var v = '1.0.0-alpha1'; var expected = { linux32: 'v'+v+'/nwjs-v'+v+'-linux-ia32.tar.gz', linux64: 'v'+v+'/nwjs-v'+v+'-linux-x64.tar.gz', osx32: 'v'+v+'/nwjs-v'+v+'-osx-ia32.zip', osx64: 'v'+v+'/nwjs-v'+v+'-osx-x64.zip', win32: 'v'+v+'/nwjs-v'+v+'-win-ia32.zip', win64: 'v'+v+'/nwjs-v'+v+'-win-x64.zip', }; var names = versions.getVersionNames(v); t.equal( names.version, v ); t.deepEqual(names.platforms, expected); });
import createHistory from 'history/createMemoryHistory'; import { NOT_FOUND } from 'redux-first-router'; import configureStore from '../src/configureStore'; export default async (req, res) => { const history = createHistory({ initialEntries: [req.path] }); const { store, thunk } = configureStore(history); await thunk(store); // THE PAYOFF BABY! const { location } = store.getState(); if (doesRedirect(location, res)) return false; const status = location.type === NOT_FOUND ? 404 : 200; res.status(status); return store; }; const doesRedirect = ({ kind, pathname }, res) => { if (kind === 'redirect') { res.redirect(302, pathname); return true; } };
export const freeMode = ` ่‡ช็”ฑใซHTMLใ‚’็ทจ้›†ใงใใ‚‹ๆฉŸ่ƒฝใงใ™ใ€‚<br /> ๆœ‰ๅŠนใซใ™ใ‚‹ใจ่จญๅ•ๅฎš็พฉใงใฎๅค‰ๆ›ดใฏ็”ป้ขใซๅๆ˜ ใ•ใ‚Œใพใ›ใ‚“ใ€‚<br /> <br /> ใพใŸใ€ไธ€่ˆฌใฎใƒฆใƒผใ‚ถใฏ่ฉฒๅฝ“ใƒšใƒผใ‚ธใ‚’็ทจ้›†ใ™ใ‚‹ใ“ใจใฏใงใใชใใชใ‚Šใพใ™ใ€‚<br /> ็ทจ้›†ใ™ใ‚‹ใซใฏ้–‹็™บ่€…ใƒขใƒผใƒ‰ใง้–‹ใๅฟ…่ฆใŒใ‚ใ‚Šใพใ™ใ€‚<br /> <br /> ๆœ‰ๅŠนใซใ—ใŸๅพŒใซ่จญๅ•ๅฎš็พฉใ‚’ๅค‰ๆ›ดใ—ใฆใ‚‚HTMLใซใฏๅๆ˜ ใ•ใ‚Œใชใ„ใฎใงใ€ๅˆฅ้€”HTMLใ‚’ไฟฎๆญฃใใ ใ•ใ„ใ€‚ `; export const itemVisibility = ` ้ …็›ฎใฎ่กจ็คบใƒป้ž่กจ็คบใ‚’่จญๅฎšใ—ใŸๆกไปถใซใ‚ˆใฃใฆๅˆ‡ใ‚Šๆ›ฟใˆใพใ™ใ€‚<br /> ่กจ็คบใ‚’่จญๅฎšใ—ใŸๅ ดๅˆใฏๆกไปถใซใƒžใƒƒใƒใ™ใ‚‹ใจ่กจ็คบใ•ใ‚Œใ€ๆกไปถใซใƒžใƒƒใƒใ—ใชใ„ใจ้ž่กจ็คบใจใชใ‚Šใพใ™ใ€‚<br /> ้ž่กจ็คบใ‚’่จญๅฎšใ—ใŸๅ ดๅˆใฏๆกไปถใซใƒžใƒƒใƒใ™ใ‚‹ใจ้ž่กจ็คบใจใชใ‚Šใ€ๆกไปถใซใƒžใƒƒใƒใ—ใชใ„ใจ่กจ็คบใ•ใ‚Œใพใ™ใ€‚<br /> `; export const matrixHtmlEnabled = ` ใƒ†ใƒผใƒ–ใƒซใ‚’่‡ช็”ฑใซใƒฌใ‚คใ‚ขใ‚ฆใƒˆๅค‰ๆ›ดใงใใ‚‹ๆฉŸ่ƒฝใงใ™ใ€‚ใ‚ปใƒซใฎ็ตๅˆใƒป่กŒๅˆ—ใฎ่ฟฝๅŠ ใชใฉใŒ่กŒใชใˆใพใ™ใ€‚<br /> ใŸใ ใ—ใ€ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใงใใ‚‹่จญๅ•ใฎๅ†…ๅฎนใฏ่กŒ้ …็›ฎใƒปๅˆ—้ …็›ฎใซๅฎš็พฉใ—ใŸใ‚‚ใฎใ ใ‘ใจใชใ‚Šใพใ™ใ€‚<br /> <br /> <span style="color: yellow;">ๆœ‰ๅŠนใซใ™ใ‚‹ใจ่จญๅ•ๅฎš็พฉใฎ็ทจ้›†ๅ†…ๅฎนใซๅˆถ้™ใŒใ‹ใ‹ใ‚Šใ€่กŒ้ …็›ฎใƒปๅˆ—้ …็›ฎใฎ่ฟฝๅŠ ใƒปๅ‰Š้™คใƒป็งปๅ‹•ใชใฉใŒ่กŒใชใˆใพใ›ใ‚“ใ€‚<br /> ้ …็›ฎใŒFIXใ—ใŸๅพŒใซๆœ‰ๅŠนใซใ™ใ‚‹ใ“ใจใ‚’ใŠใ™ใ™ใ‚ใ—ใพใ™ใ€‚</span><br /> <br /> ๅฎš็พฉใ‚’ๅค‰ๆ›ดใ—ใŸใ„ๅ ดๅˆใซใฏไธ€ๅบฆใ“ใฎใƒใ‚งใƒƒใ‚ฏใƒœใƒƒใ‚ฏใ‚นใ‚’่งฃ้™คใ—ใฆ็ทจ้›†ใ—ใฆใใ ใ•ใ„ใ€‚<br /> ใŸใ ใ—ใ€ใƒฌใ‚คใ‚ขใ‚ฆใƒˆใฎ็ทจ้›†ๅ†…ๅฎนใฏๅคฑใ‚ใ‚Œใพใ™ใ€‚ `; export const matrixReverse = ` ้€šๅธธ่ฆ็ด ใ‚’Zๆ–นๅ‘ใซไธฆในใพใ™ใŒใ€Nๆ–นๅ‘ใซไธฆในใพใ™ใ€‚<br /> ใ“ใ‚Œใซใ‚ˆใฃใฆ่จญๅ•ใ‚ฟใ‚คใƒ—ใฎใƒฉใ‚ธใ‚ชใฏ็ธฆๆ–นๅ‘ใฎไธญใ‹ใ‚‰ไธ€ใคๅ€คใ‚’้ธใถใ‚ˆใ†ใซๅ‹•ไฝœใŒๅค‰ใ‚ใ‚Šใพใ™ใ€‚<br /> ใใฎไป–ใฎ่จญๅ•ใ‚ฟใ‚คใƒ—ใงใฏใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ๆ™‚ใซใƒ‡ใƒผใ‚ฟใฎไธฆใณๆ–นใŒๅค‰ใ‚ใ‚Šใพใ™ใ€‚ `; export const javaScriptEditor = ` ไธ‹่จ˜ใฎใ‚ทใƒงใƒผใƒˆใ‚ซใƒƒใƒˆใŒๅˆฉ็”จใงใใพใ™ใ€‚ <table> <tbody> <tr><th>CTRL-F</th><td>ใ‚ฝใƒผใ‚นใ‚ณใƒผใƒ‰ใฎใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆ</td></tr> <tr><th style="vertical-align: top;">CTRL-Space</th><td>ใ‚ฝใƒผใ‚นใ‚ณใƒผใƒ‰ใฎ่ฃœๅฎŒ<br> <table> <tr><th>ๅ…ˆ่กŒใ™ใ‚‹ๆ–‡ๅญ—</th><td>่ฃœๅฎŒใ•ใ‚Œใ‚‹ๅ€ค</td></tr> <tr><th style="padding-right: 1em;">name:</th><td>่ฆ็ด ใฎๅๅ‰ใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">no:</th><td>outputNoใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">dev:</th><td>devIdใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">form:</th><td>่ฆ็ด (HTML)ใฎ่ฃœๅฎŒ</td></tr> </table> </td></tr> </tbody> </table> `; export const pageHtmlEditor = ` ไธ‹่จ˜ใฎใ‚ทใƒงใƒผใƒˆใ‚ซใƒƒใƒˆใŒๅˆฉ็”จใงใใพใ™ใ€‚ <table> <tbody> <tr><th>CTRL-F</th><td>ใ‚ฝใƒผใ‚นใ‚ณใƒผใƒ‰ใฎใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆ</td></tr> <tr><th style="vertical-align: top;">CTRL-Space</th><td>ใ‚ฝใƒผใ‚นใ‚ณใƒผใƒ‰ใฎ่ฃœๅฎŒ<br> <table> <tr><th>ๅ…ˆ่กŒใ™ใ‚‹ๆ–‡ๅญ—</th><td>่ฃœๅฎŒใ•ใ‚Œใ‚‹ๅ€ค</td></tr> <tr><th style="padding-right: 1em;">name:</th><td>่ฆ็ด ใฎๅๅ‰ใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">no:</th><td>outputNoใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">dev:</th><td>devIdใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">form:</th><td>่ฆ็ด (HTML)ใฎ่ฃœๅฎŒ</td></tr> <tr><th style="padding-right: 1em;">reprint:</th><td>ๅ†ๆŽฒใฎ่ฃœๅฎŒ</td></tr> </table> </td></tr> </tbody> </table> `; export const zeroSetting = 'ๆคœ่จผใ‚จใƒฉใƒผๆ™‚ใซๆ•ฐๅ€คใฎๆœชๅ…ฅๅŠ›ใƒ•ใ‚ฃใƒผใƒซใƒ‰ใซ0ใ‚’ๅŸ‹ใ‚ใ‚‹ๆฉŸ่ƒฝใงใ™';
jQuery.noConflict(); jQuery(document).ready(function($){ MYNAMESPACE.namespace('model.ConfigManager'); MYNAMESPACE.model.ConfigManager = function() { this.initialize.apply(this, arguments); }; MYNAMESPACE.model.ConfigManager.prototype = { _instances : {} ,_classname : [] ,_idname : [] ,_Validation : {} ,_SubmitCommentObj : {} ,_AutoAddressIdObj : {} ,initialize: function() {//ๅˆๆœŸ่จญๅฎš็š„ใช var thisObj = this; _.bindAll( this ,'SetIdname' ,'SetClassname' ,'SetValidation' ,'setSubmitComment' ,'setOriginalSubmit' ,'setAutoAddressId' ,'getIdname' ,'getClassname' ,'getValidation' ,'getSubmitComment' ,'getAutoAddressId' ); this._instances = { } this.SetIdname(); // this.SetClassname(); this.SetValidation(); } /*โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•*/ /*Settings Start*/ /*โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•*/ ,SetIdname: function() { var thisObj = this; var formtable = $('form>table>tbody>tr>td>table:eq(1)>tbody>tr:eq(3)>td>table').addClass('formtable') thisObj._idname = [ {'Selecter' : $('input[name="col_19[]"]').eq(0) ,'id': 'AutoAddressNum1'} ] $(thisObj).trigger('onSetIdname'); } ,SetClassname: function() { var thisObj = this; var formtable = $('form>table>tbody>tr>td>table:eq(1)>tbody>tr:eq(3)>td>table').addClass('formtable') thisObj._classname = [ //Placeholder {'Selecter' : $('#txtSeiName') ,'classname': 'firstName'} ,{'Selecter' : $('#txtMeiName') ,'classname': 'lastName'} ,{'Selecter' : $('#txtSeiKana') ,'classname': 'firstNameKatakana'} ,{'Selecter' : $('#txtMeiKana') ,'classname': 'lastNameKatakana'} ,{'Selecter' : $('#txtFirstCode') ,'classname': 'Address_Num_1st'} ,{'Selecter' : $('#txtLastCode') ,'classname': 'Address_Num_2nd'} // ,{'Selecter' : $('#cmbProvince') ,'classname': 'Address_text_1st'} ,{'Selecter' : $('#txtCity') ,'classname': 'Address_text_2nd'} ,{'Selecter' : $('#txtDistrict') ,'classname': 'Address_text_3rd'} ,{'Selecter' : $('#txtAddress') ,'classname': 'Address_text_4th'} ,{'Selecter' : $('#txtBuilding') ,'classname': 'Address_HouseName'} ,{'Selecter' : $('#txtMailPC') ,'classname': 'Mail'} ,{'Selecter' : $('#txtMailMobile') ,'classname': 'MobileMail'} ,{'Selecter' : $('#txtMobilePhone1') ,'classname': 'Tel3_1'} ,{'Selecter' : $('#txtMobilePhone2') ,'classname': 'Tel3_2'} ,{'Selecter' : $('#txtMobilePhone3') ,'classname': 'Tel3_3'} ,{'Selecter' : $('#txtYear') ,'classname': 'BirthYear'} ,{'Selecter' : $('#txtMonth') ,'classname': 'BirthMonth'} ,{'Selecter' : $('#txtDay') ,'classname': 'Birthdate'} // ,{'Selecter' : $('#txtAge') ,'classname': 'Age'} ,{'Selecter' : $('#txtFamilyNum') ,'classname': 'Familiy_Num'} ,{'Selecter' : $('#txtMySelfMoney') ,'classname': 'SelfMoney'} ,{'Selecter' : $('#txtArea') ,'classname': 'AreaSize'} ,{'Selecter' : $('#txtHopeArea') ,'classname': 'HopeArea'} // ,{'Selecter' : $('#choice1,#choice2') ,'classname': 'Reserve_Month'} // ,{'Selecter' : $('#choice1_2,#choice2_2') ,'classname': 'Reserve_Day'} // ,{'Selecter' : $('#choice1_3,#choice2_3') ,'classname': 'Reserve_Time'} //ใ‚ซใƒผใ‚ฝใƒซใƒ•ใ‚ฉใƒผใ‚ซใ‚น ,{'Selecter' : $('input').not('[type="radio"],[type="checkbox"]') ,'classname': 'CursorFocusEvent'} //ใƒžใ‚ฆใ‚นใ‚ชใƒผใƒใƒผ /*radiotext*/ ,{'Selecter' : $('label.labelClass') ,'classname': 'MouseoverRadioEvent'} /*main*/ ,{'Selecter' : $('#tbodyID>tr>td:has(input,select),#privacyID') ,'classname': 'MouseoverEvent'} // //ไฝๆ‰€่‡ชๅ‹•ๅ…ฅๅŠ› // // ,{'Selecter' : $('input[name="col_14"]') ,'classname': 'AutoAddressNum1'} // ,{'Selecter' : $('#AutoAddressNum1') ,'classname': 'AutoAddressNum1'} // ,{'Selecter' : $('#AutoAddressNum2') ,'classname': 'AutoAddressNum2'} // // ,{'Selecter' : $('input[name="col_21"]') ,'classname': 'AutoAddressText1'} // ,{'Selecter' : $('#AutoAddressText1') ,'classname': 'AutoAddressText1'} // ,{'Selecter' : $('#AutoAddressText2') ,'classname': 'AutoAddressText2'} // ,{'Selecter' : $('#AutoAddressText3') ,'classname': 'AutoAddressText3'} //ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใ€€RealtimeCheckManager /*radio,checkไปฅๅค–ใฎinput,select*/ ,{'Selecter' : $('input:not(input[type="radio"],input[type="checkbox"]),select') ,'classname': 'ValidationTextInputAndSelect'} /*radioใฎinput*/ ,{'Selecter' : $('#tbodyID input[type="radio"]') ,'classname': 'ValidationRadioInput'} /*radioๆœช้ธๆŠžใฎ้š›ใซ่‰ฒใ‚’ไป˜ใ‘ใŸใ„ๅ ดๆ‰€*/ ,{'Selecter' : $('#tbodyID>tr>td:has(input[type="radio"])') ,'classname': 'ValidationRadioTd'} /*checkboxใฎinput*/ ,{'Selecter' : $('#tbodyID>tr:eq(11)').find('input[type="checkbox"]') ,'classname': 'ValidationCheckboxInput'} /*checkboxใฎinput*/ ,{'Selecter' : $('#privacyID input') ,'classname': 'ValidationCheckboxInput'} // /*checkboxใฎinput*/ ,{'Selecter' : $('#tbodyID>tr:not(:eq(14),:eq(16)) input[type="checkbox"]') ,'classname': 'ValidationCheckboxInput'} /*checkboxๆœช้ธๆŠžใฎ้š›ใซ่‰ฒใ‚’ไป˜ใ‘ใŸใ„ๅ ดๆ‰€*/ ,{'Selecter' : $('#tbodyID>tr:eq(11)>td:has(input[type="checkbox"])') ,'classname': 'ValidationCheckboxTd'} /*checkboxๆœช้ธๆŠžใฎ้š›ใซ่‰ฒใ‚’ไป˜ใ‘ใŸใ„ๅ ดๆ‰€*/ ,{'Selecter' : $('#privacyID') ,'classname': 'ValidationCheckboxTd'} ] $(thisObj).trigger('onSetClassname'); } ,SetValidation: function() { var thisObj = this; thisObj._Validation = {//ใƒ—ใƒญใƒ‘ใƒ†ใ‚ฃใฏใ‚ณใƒกใƒณใƒˆใงใ‚‚ๅคงไธˆๅคซ // $('.ValidateClass').attr('id') : "chkrequired" /* */ txtSeiName : "chkrequired" /* */ ,txtMeiName : "chkrequired" /* */ ,txtSeiKana : "chkkatakana chkrequired" /* */ ,txtMeiKana : "chkkatakana chkrequired" /* */ ,txtCity : "chkrequired" /* */ ,txtDistrict : "chkrequired" /* */ ,txtAddress : "chkrequired" /* */ ,txtMobilePhone1 : "chknumonly chkrequired chkmax4" /* */ ,txtMobilePhone2 : "chknumonly chkrequired chkmax4" /* */ ,txtMobilePhone3 : "chknumonly chkrequired chkmax4" /* */ ,txtYear : "chknumonly chkrequired chkmin4 chkmax4" /* */ ,txtMonth : "chknumonly chkrequired chkmax2" /* */ ,txtDay : "chknumonly chkrequired chkmax2" /* */ ,txtAge : "chknumonly chkmax2" /* */ ,txtFamilyNum : "chknumonly chkmax2 chkrequired" /* */ ,txtMySelfMoney : "chknumonly" /* */ ,txtArea : "chknumonly chkmax3 chkrequired" /* */ ,txtMailPC : "chkemail chkhankaku chkrequired" /* */ ,txtMailMobile : "chkemail chkhankaku" /* */ ,txtFirstCode : "chknumonly chkrequired chkmax3" /* */ ,txtLastCode : "chknumonly chkrequired chkmax4" /* */ ,cmbJob : "chkselect" /* */ ,cmbEstimate : "chkselect" /* */ ,cmbBuildingType : "chkselect" }; /*โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•*/ /*Settings end */ /*โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•*/ $(thisObj).trigger('onSetValidation'); } ,setSubmitComment: function() { var thisObj = this; thisObj._SubmitCommentObj = { 'mailaddr' : 'ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚น' , 'col_4' : 'ใŠๅๅ‰(ๅง“)' , 'col_5' : 'ใŠๅๅ‰(ๅ)' , 'col_14' : 'ใƒ•ใƒชใ‚ฌใƒŠ(ใ‚ปใ‚ค)' , 'col_15' : 'ใƒ•ใƒชใ‚ฌใƒŠ(ใƒกใ‚ค)' , 'col_16' : '็”Ÿๅนดๆœˆๆ—ฅ๏ผˆๅนด๏ผ‰' , 'col_16_2' : '็”Ÿๅนดๆœˆๆ—ฅ๏ผˆๆœˆ๏ผ‰' , 'col_16_3' : '็”Ÿๅนดๆœˆๆ—ฅ๏ผˆๆ—ฅ๏ผ‰' , 'col_17' : 'ๅนด้ฝข' , '' : 'ๆ€งๅˆฅ' , 'AutoAddressNum1' : 'ใ”ไฝๆ‰€(้ƒตไพฟ็•ชๅท)' , 'AutoAddressNum2' : 'ใ”ไฝๆ‰€(้ƒตไพฟ็•ชๅท)' , 'AutoAddressText1' : 'ใ”ไฝๆ‰€(้ƒฝ้“ๅบœ็œŒ)' , 'AutoAddressText2' : 'ใ”ไฝๆ‰€(ๅธ‚ๅŒบ)' , 'AutoAddressText3' : 'ใ”ไฝๆ‰€(็”บๆ‘)' , 'col_23' : 'ใ”ไฝๆ‰€(ไธ็›ฎใƒป็•ชๅœฐ)' , 'col_13' : '้›ป่ฉฑ็•ชๅท' , 'col_13_2' : '้›ป่ฉฑ็•ชๅท' , 'col_13_3' : '้›ป่ฉฑ็•ชๅท' , 'col_25' : 'ใ”ๅฎถๆ—ๆ•ฐ' , '' : '่ฒทๆ›ฟใฎๆœ‰็„ก' , 'col_26' : '็พๅœจใฎใŠไฝใพใ„' , '' : 'ใ”ๅธŒๆœ›ใฎ้–“ๅ–ใ‚Š' , 'col_28' : 'ใ”ๅธŒๆœ›ใฎๅบƒใ•' , 'col_29' : 'ใ”ไบˆ็ฎ—' , 'col_30' : 'ใ”ๅธŒๆœ›ใฎๅœฐๅŸŸ๏ผˆ็ฌฌ๏ผ‘ๅธŒๆœ›๏ผ‰' , '' : 'ใ‚ฏใƒฉใƒ–ใ‚ชใƒผใƒ™ใƒซไผšๅ“ก่ฆ็ด„ใธใฎๅŒๆ„' , '' : 'ใ‚ฏใƒฉใƒ–ใ‚ชใƒผใƒ™ใƒซใซใŠใ‘ใ‚‹ๅ€‹ไบบๆƒ…ๅ ฑใฎใŠๅ–ๆ‰ฑใ„ใซใคใ„ใฆใธใฎๅŒๆ„' , 'choice1' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไธ€ๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆœˆ)' , 'choice1_2' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไธ€ๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆ—ฅ)' , 'choice1_3' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไธ€ๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆ™‚ๅˆป)' , 'choice2' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไบŒๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆœˆ)' , 'choice2_2' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไบŒๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆ—ฅ)' , 'choice2_3' : 'ใ”ๅธŒๆœ›ใฎๆฅๅ ดๆ—ฅๆ™‚(็ฌฌไบŒๅธŒๆœ›๏ผใ”ๅธŒๆœ›ใฎๆ™‚ๅˆป)' , 'RadioID_1' : 'ใ“ใฎใƒ›ใƒผใƒ ใƒšใƒผใ‚ธใ‚’ใฉใ“ใงใŠ็Ÿฅใ‚Šใซใชใ‚Šใพใ—ใŸใ‹๏ผŸ' , 'RadioID_2' : 'ใ”ๅธŒๆœ›ใฎ้–“ๅ–ใ‚Š' , 'RadioID_3' : '่ณ‡ๆ–™่ซ‹ๆฑ‚ใ€ใŠๅ•ๅˆใ‚ใ›ใซใคใ„ใฆใฎๅ€‹ไบบๆƒ…ๅ ฑไฟ่ญท่ฆ็ด„ใธใฎๅŒๆ„' , 'RadioID_4' : 'ใ‚ฏใƒฉใƒ–ใ‚ชใƒผใƒ™ใƒซใธใฎใ”ๅ…ฅไผšใซใคใ„ใฆใฎๅ€‹ไบบๆƒ…ๅ ฑไฟ่ญท่ฆ็ด„ใธใฎๅŒๆ„' } $(thisObj).trigger('onSetSubmitComment'); } ,setAutoAddressId: function() { var thisObj = this; thisObj._AutoAddressIdObj = { 'Num1' : 'txtFirstCode' , 'Num2' : 'txtLastCode' , 'Txt1' : 'cmbProvince' , 'Txt2' : 'txtCity' , 'Txt3' : 'txtDistrict' } $(thisObj).trigger('onSetAutoAddressId'); } ,setOriginalSubmit: function() { var thisObj = this; frmValidate(1) } ,getIdname : function() { var thisObj = this; return thisObj._idname; } ,getClassname : function() { var thisObj = this; return thisObj._classname; } ,getValidation : function() { var thisObj = this; return thisObj._Validation; } ,getSubmitComment : function() { var thisObj = this; return thisObj._SubmitCommentObj; } ,getAutoAddressId : function() { var thisObj = this; return thisObj._AutoAddressIdObj; } } });
/** * Alerts Controller */ angular.module('MRT').controller('AlertsCtrl', ['$scope', AlertsCtrl]); function AlertsCtrl($scope) { $scope.alerts = [ { type: 'success', msg: 'Thanks for visiting! Feel free to create pull requests to improve the dashboard!' }, { type: 'danger', msg: 'Found a bug? Create an issue with as many details as you can.' } ]; $scope.addAlert = function() { $scope.alerts.push({msg: 'Another alert!'}); }; $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; }
// wrapper for "class" Map (function(){ function Map(width, height){ // map dimensions this.width = width; this.height = height; // map texture this.image = null; this.treasure = null; } Map.prototype.setImage = function(image){ this.image = image; } // generate an example of a large map Map.prototype.generate = function(){ var ctx = document.createElement("canvas").getContext("2d"); ctx.canvas.width = this.width; ctx.canvas.height = this.height; var rows = ~~(this.width/32) + 1; var columns = ~~(this.height/32) + 1; var maxX = 0; var maxY = 0; var color = "green"; ctx.save(); //ctx.fillStyle = color; for (var x = 0, i = 0; i < rows; x+=32, i++) { //ctx.beginPath(); for (var y = 0, j=0; j < columns; y+=32, j++) { var rand = Math.floor((Math.random() * 100) + 1); //alert(rand); var sx = 0; var sy = 0; if(rand <=55){ sx = Terrain["Grass"].x; sy = Terrain["Grass"].y; } else if(rand > 55 && rand <= 65){ sx = Terrain["TallGrass"].x; sy = Terrain["TallGrass"].y; } else if(rand > 65 && rand <=95){ sx = Terrain["Weeds"].x; sy = Terrain["Weeds"].y; } else if(rand > 95){ sx = Terrain["Flowers"].x; sy = Terrain["Flowers"].y; } //console.log("x: " + sx + "y: " + sy); //ctx.save(); ctx.drawImage(texture, sx, sy, 32, 32, x, y, 32, 32); //ctx.restore(); //ctx.rect (x, y, 32, 32); maxY = y; } //color = (color == "green" ? "blue" : "green"); //ctx.fillStyle = color; //ctx.fill(); //ctx.closePath(); maxX = x; } this.treasure = new Game.Rectangle(Math.floor(Math.random() * maxX), Math.floor(Math.random() * maxY), 32, 32); //ctx.fillStyle = "black"; //ctx.fillRect(this.treasure.x, this.treasure.y, this.treasure.width, this.treasure.height); ctx.drawImage(texture, 128, 64, 32, 32, this.treasure.x, this.treasure.y, 32, 32); ctx.restore(); // store the generate map as this image texture this.image = new Image(); this.image.src = ctx.canvas.toDataURL("image/png"); // clear context ctx = null; } // generate an example of a large map Map.prototype.generate_abstract = function(){ var ctx = document.createElement("canvas").getContext("2d"); ctx.canvas.width = this.width; ctx.canvas.height = this.height; var rows = ~~(this.width/44) + 1; var columns = ~~(this.height/44) + 1; var color = "green"; ctx.save(); ctx.fillStyle = color; for (var x = 0, i = 0; i < rows; x+=44, i++) { ctx.beginPath(); for (var y = 0, j=0; j < columns; y+=44, j++) { ctx.rect (x, y, 40, 40); } color = (color == "green" ? "blue" : "green"); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } ctx.restore(); // store the generate map as this image texture this.image = new Image(); this.image.src = ctx.canvas.toDataURL("image/png"); // clear context ctx = null; } Map.prototype.create = function(imgURL){ $.getJSON("test.json", function(json) { console.log(json); // this will show the info it in firebug console }); } // draw the map adjusted to camera Map.prototype.draw = function(context, xView, yView){ // easiest way: draw the entire map changing only the destination coordinate in canvas // canvas will cull the image by itself (no performance gaps -> in hardware accelerated environments, at least) context.drawImage(this.image, 0, 0, this.image.width, this.image.height, -xView, -yView, this.image.width, this.image.height); } // didactic way: Map.prototype.didactic_draw = function(context, xView, yView){ var sx, sy, dx, dy; var sWidth, sHeight, dWidth, dHeight; // offset point to crop the image sx = xView; sy = yView; // dimensions of cropped image sWidth = context.canvas.width; sHeight = context.canvas.height; // if cropped image is smaller than canvas we need to change the source dimensions if(this.image.width - sx < sWidth){ sWidth = this.image.width - sx; } if(this.image.height - sy < sHeight){ sHeight = this.image.height - sy; } // location on canvas to draw the croped image dx = 0; dy = 0; // match destination with source to not scale the image dWidth = sWidth; dHeight = sHeight; context.drawImage(this.image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); } // add "class" Map to our Game object Game.Map = Map; })();
const validNoteLetters = 'ABCDEFG'; const validSharpNotes = 'ACDFG'; const validFlatNotes = 'ABDEG'; const validModifiers = '#b'; export default function (note) { let letter = note.charAt(0).toUpperCase(); let modifier = note.charAt(1) || null; if (modifier === 'b' && validFlatNotes.indexOf(letter) === -1) { letter = validNoteLetters.charAt(validNoteLetters.indexOf(letter) - 1); modifier = null; } if (modifier === '#' && validSharpNotes.indexOf(letter) === -1) { letter = validNoteLetters.charAt(validNoteLetters.indexOf(letter) + 1); modifier = null; } validateLetter(letter); validateModifier(modifier); return { letter: letter, modifier: modifier}; } function validateLetter(letter) { if (validNoteLetters.indexOf(letter) === -1) { throw new Error('Invalid note letter'); } } function validateModifier(modifier) { if (modifier && validModifiers.indexOf(modifier) === -1) { throw new Error('Invalid modifier'); } }
module.exports = function (grunt) { "use strict"; grunt.registerMultiTask("solr", "My solr task.", function () { // Force task into async mode and grab a handle to the "done" function. // var data = this.data; var done = this.async(); // Run some sync stuff. grunt.log.writeln("Processing task..."); // var http = require("http"), Db = require("mongodb").Db, Server = require("mongodb").Server, client, appsJSON; function deleteSolrApps(done) { var options = { host: data.solr.host, port: data.solr.port, path: "/solr/update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E", method: "GET" }, reqDelete, reqCommit; //http://localhost:8983/solr/update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E //http://localhost:8983/solr/update?stream.body=%3Ccommit/%3E reqDelete = http.request(options, function () { grunt.log.writeln("delete..."); options.path = "/solr/update?stream.body=%3Ccommit/%3E"; reqCommit = http.request(options, function () { grunt.log.writeln("commit..."); done(); }); reqCommit.on("error", function (e) { grunt.warn(e.message); }); reqCommit.end(); }); reqDelete.on("error", function (e) { grunt.warn(e.message); }); reqDelete.end(); } function exportToSolr() { grunt.log.writeln("Loading apps to solr..."); var options = { host: data.solr.host, port: data.solr.port, path: "/solr/update/json?commit=true", method: "POST", headers: { "Content-Type": "application/json" } }, req = http.request(options, function (res) { res.setEncoding("utf8"); res.on("data", function (chunk) { grunt.log.writeln("..."); }); res.on("end", function () { done(); grunt.log.writeln("All done!"); }); }); req.on("error", function (e) { grunt.warn(e.message); }); // post the data req.write(appsJSON); req.end(); } client = new Db("wast", new Server(data.mongo.host, data.mongo.port), {safe: true}); client.open(function (err) { if(err) { grunt.log.writeln("Error openinig database..."); throw err; } grunt.log.writeln("Database succesfully opened..."); client.collection("applications", function (err, collection) { if(err) { grunt.log.writeln("Error retreaving collection..."); throw err; } collection.find().toArray(function(error, results) { if(error) { grunt.log.writeln("Error finding apps into collection..."); throw error; } else { appsJSON = JSON.stringify(results); deleteSolrApps(exportToSolr); } }); }); }); }); };
/* * Copyright (c) 2012-2016 Andrรฉ Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // 9.4.1.3 BoundFunctionCreate should use target function's [[Prototype]] // https://bugs.ecmascript.org/show_bug.cgi?id=3819 function F() {} Object.setPrototypeOf(F, Object.prototype); var boundF = Function.prototype.bind.call(F); assertSame(Object.prototype, Object.getPrototypeOf(boundF));
import runSolidityTest from "./helpers/runSolidityTest" runSolidityTest("TestPreciseMathUtils", ["AssertBool", "AssertUint"])
var ComponentFromServer, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; ComponentFromServer = (function(_super) { __extends(ComponentFromServer, _super); function ComponentFromServer(url, json) { this.url = url; this.json = json; } ComponentFromServer.prototype.getContentComponent = function() {}; return ComponentFromServer; })(Component);
'use strict'; const WMSDownloader = require(__dirname + '/../index.js'); //const WMSDownloader = require('wms-downloader'); const dl = new WMSDownloader(); const taskOptions = { 'task': { 'id': 'id_of_my_first_download', 'title': 'My first WMS download.', 'format': 'image/png', 'workspace': __dirname + '/tiles', 'area': { 'bbox': { 'xmin': 455000, 'ymin': 5750000, 'xmax': 479000, 'ymax': 5774000 } } }, 'tiles': { 'maxSizePx': 2500, 'gutterPx': 250, 'resolutions': [{ 'id': 'id_of_resolution_10', 'groundResolution': 1 }] }, 'wms': [{ 'id': 'id_of_wms_stadtbezirke', 'getmap': { 'url': 'http://www.bielefeld01.de/md/WMS/statistische_gebietsgliederung/02?', 'kvp': { 'SERVICE': 'WMS', 'REQUEST': 'GetMap', 'VERSION': '1.3.0', 'LAYERS': 'stadtbezirke_pl', 'STYLES': '', 'CRS': 'EPSG:25832', 'FORMAT': 'image/png', 'TRANSPARENT': 'TRUE', 'MAP_RESOLUTION': 72 } } }] }; // print progress const progressInterval = setInterval(() => { const progress = dl.getProgress(taskOptions.task.id); console.log('Progress: ' + progress.percent + '%, Waiting time: ' + progress.waitingTime + ' ms'); }, 1000); // start download dl.start(taskOptions, (err) => { // stop progress printing clearInterval(progressInterval); if (err) { console.log(err); } else { console.log('Download was finished.'); } }); // cancel download after 10 seconds setTimeout(() => { dl.cancel('id_of_my_first_download',(err, id)=>{ if(err){ console.error(err); }else{ console.log('Download "' + id + '" was canceled.'); } }); }, 10000);
'use strict'; require('bluebird').longStackTraces(); module.exports = require('./commands');
angular.module('MuscleMan').controller('ContestsCtrl', ['$scope', 'User', function($scope, User) { $scope.contests = []; $scope.format_date = function(date) { return moment(date).format('DD.MM.YYYY'); }; User.get_contest('all', function(res) { $scope.contests = res.data; }, function(res) { console.error(res.data); }); } ]);
module.exports = require('./lib/verify');
/* * Package Import */ /* * Local Import */ /* * Code */ /** * NormalizeDatas * @param {Array} datas -> * @return {Object} */ export const normalizeDatas = (datas) => { const structureNormalize = { byId: {}, allIds: [], }; datas.forEach((data) => { const { id, slug, label, logo } = data; const newData = { id, slug, label, logo }; structureNormalize.byId[data.id] = newData; structureNormalize.allIds.push(data.id); }); return structureNormalize; }; /** * Debounce * @param {Func} * @param {Number} Wait -> Default: 20 * @param {Boolean} Immediate -> Defualt: True * @return {Func} */ export const debounce = (func, wait = 20, immediate = true) => { let timeout; return () => { const context = this; const args = arguments; const later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(later, wait); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }; /* * Export */
import * as Scrivito from 'scrivito' import { truncate } from 'lodash-es' Scrivito.provideEditingConfig('TestimonialWidget', { title: 'Testimonial', attributes: { testimonial: { title: 'Testimonial' }, author: { title: 'Author', description: 'Who said it?' }, authorImage: { title: 'Author image' } }, properties: ['testimonial', 'author', 'authorImage'], initialContent: { author: 'Someone', testimonial: 'This is great!' }, titleForContent: widget => `${widget.get('author')}: ${truncate(widget.get('testimonial'))}` })
var app_id = ''; var perm_name = ''; var perm_id = ''; function saveOrgList(){ if(perm_id == '') { alert('่ฏท้€‰ๆ‹ฉๆƒ้™ๆจกๅ—!'); return; } var orgs = document.getElementsByName('orgs'); if(orgs == null || orgs.length <=0){ alert('ๆไบคๅคฑ่ดฅ!'); return; } var params = ''; for(var i=0;i<orgs.length;i++){ var org = orgs[i]; if(org == null || org == undefined){ continue; } if(org.checked){ params += org.value + ','; } } g_utils.load("/portal/web/perm/saveOrgPerm",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(code == 1) { getOrgList(perm_id,app_id,perm_name); alert(json.msg); }else{ //ๅคฑ่ดฅ alert(json.msg); } },"&checkid=" + params + "&appid=" + app_id + "&permid=" + perm_id); } function getOrgList(permid,appid,permname){ gt('org_perm_list').innerHTML = ''; gt('org_permname_show').innerText = permname; g_utils.load("/portal/web/perm/getPermOrgList",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(json.code != null && json.code != undefined) { return; } app_id = appid; perm_id = permid; perm_name = permname; //ๅผ€ๅง‹ๆ‹ผๅˆ—่กจ var content = '<div class="dd dd-draghandle bordered">'; var orgs = json.orgs; if(orgs == null || orgs == undefined) { return; } content += showOrgList(orgs,'check'); content += '</div>'; gt('org_perm_list').innerHTML = content; $('.dd').nestable(); $('.dd-handle a').on('mousedown', function (e) { e.stopPropagation(); }); },"&permid=" + permid + "&appid=" + appid); getExceptUser(permid,appid,permname); } function getExceptUser(permid,appid,permname){ gt('exceptuser_list').innerHTML = ''; gt('exceptuser_permname_show').innerText = perm_name; g_utils.load("/portal/web/perm/getExceptUser",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(json.code != null && json.code != undefined) { return; } //ๅผ€ๅง‹ๆ‹ผๅˆ—่กจ var content = ''; var users = json.users; if(users == null || users == undefined && users.length <= 0) { return; } for(var i=0;i<users.length;i++){ var user = users[i]; if(user == null || user == undefined){ continue; } var showText = ''; var showText2 = ''; var showId = ''; if(user.status == '0'){ //ๅฝ“ๅ‰ไธๅฏ็”จ. showText = "ๅฏ็”จ"; showText2 = "ไธๅฏ็”จ"; showId = '1'; }else{ showText = "ไธๅฏ็”จ"; showText2 = "ๅฏ็”จ"; showId = '0'; } content += '<tr>'; content += ' <td>'+ user.name +'</td>'; content += ' <td>'+ user.orgname +'</td>'; content += ' <td>'+ showText2 +'</td>'; content += ' <td>'; content += ' <a class="btn btn-info btn-xs edit" onclick="authExceptUser(\''+ user.userid +'\',\''+ showId +'\',\''+ user.id +'\');"><i class="fa fa-edit"></i> '+ showText +'</a>'; content += ' <a class="btn btn-danger btn-xs delete" onclick="deleteExceptUser(\''+ user.userid +'\',\''+ user.id +'\',\''+ user.name +'\');"><i class="fa fa-edit"></i> ๅˆ ้™ค</a>'; content += ' </td>'; content += '</tr>'; } gt('exceptuser_list').innerHTML = content; //่ฟ˜่ฆๅˆ†้กต },"&permid=" + permid + "&appid=" + appid); } function authExceptUser(userid,userstatus,permid){ g_utils.load("/portal/web/perm/authExceptUser",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(code == 1) { getExceptUser(perm_id,app_id,perm_name); }else{ alert(json.msg); } },"userstatus=" + userstatus + "&userid=" + userid + "&permid=" + permid); } function deleteExceptUser(userid,permid,username) { bootbox.confirm("็กฎๅฎšๅˆ ้™ค["+ username +"]็”จๆˆทไพ‹ๅค–ไนˆ?", function (result) { if (result) { //็กฎ่ฎคๅˆ ้™ค. g_utils.load("/portal/web/perm/deleteExceptUser",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(code == 1) { getExceptUser(perm_id,app_id,perm_name); } alert(json.msg); },"permid=" + permid + "&userid=" + userid); } }); } function showOrgList(orgs,parentid){ var content = '<ol class="dd-list">'; var index = 1; for(var i=0;i<orgs.length;i++){ var org = orgs[i]; if(org == null || org == undefined){ continue; } var checkId = parentid + '_' + index + ''; content += '<li class="dd-item dd2-item" data-id="1">'; content += ' <div class="ico-border-style dd2-handle">'; content += ' <div class="checkbox org_checkbox_mg"><label>'; if(org.isOrg == 'true'){ if(org.checked == 'true'){ content += '<input type="checkbox" class="inverted" onclick="changecheck(this);" checked name="orgs" value="'+ org.id +'" id="'+ checkId +'"><span class="text"></span>'; }else{ content += '<input type="checkbox" class="inverted" onclick="changecheck(this);" name="orgs" value="'+ org.id +'" id="'+ checkId +'"><span class="text"></span>'; } } content += ' </label></div>'; content += ' </div>'; content += ' <div class="dd2-content">'+ org.name +'</div>'; index ++; var childs = org.orgs; if(childs != null && childs != undefined && childs.length > 0) { content += showOrgList(childs,checkId); } //ๅŠ ่ฝฝๅญ็บง. //content += getPermList(perm.id,perm.name); content += '</li>'; } content += '</ol>'; return content; } function getAppList(){ //ๅ…ˆ่Žทๅ–ๅบ”็”จๅˆ—่กจ,ไฝœไธบๆ น่Š‚็‚น; //็„ถๅŽๆ นๆฎappid่Žทๅ–ๆƒ้™ๅˆ—่กจ,ๆฒกๆœ‰้€’ๅฝ’.app_perm_list g_utils.load("/portal/web/perm/showPermList",false,function(html){ var json = eval("(" + html + ")"); var code = json.code; if(json.code != null && json.code != undefined) { return; } //ๅผ€ๅง‹ๆ‹ผๅˆ—่กจ var content = '<div class="dd dd-draghandle bordered">'; var perms = json.perms; if(perms == null || perms == undefined) { return; } content += showPermList(perms); content += '</div>'; gt('app_perm_list').innerHTML = content; $('.dd').nestable(); $('.dd-handle a').on('mousedown', function (e) { e.stopPropagation(); }); var listClick = $(".perm-none.dd2-content"); if(listClick != null && listClick != undefined && listClick.length > 0) { listClick[0].click(); } },""); } function showPermList(perms){ var content = '<ol class="dd-list">'; for(var i=0;i<perms.length;i++){ var perm = perms[i]; if(perm == null || perm == undefined){ continue; } content += '<li class="dd-item dd2-item" data-id="1">'; if(perm.click == 'true'){ content += ' <div class="ico-border-style-active dd2-handle">'; }else{ content += ' <div class="ico-border-style dd2-handle">'; } content += ' <i class="normal-icon fa fa-android"></i><i class="drag-icon fa fa-arrows-alt "></i>'; content += ' </div>'; if(perm.click == 'true'){ content += ' <div class="perm-none dd2-content" onclick="listpick(this);getOrgList(\''+ perm.id +'\',\''+ perm.appid +'\',\''+ perm.name +'\');">'+ perm.name +'</div>'; }else{ content += ' <div class="dd2-content">'+ perm.name +'</div>'; } var childs = perm.perms; if(childs != null && childs != undefined && childs.length > 0) { content += showPermList(childs); } //ๅŠ ่ฝฝๅญ็บง. //content += getPermList(perm.id,perm.name); content += '</li>'; } content += '</ol>'; return content; } window.onload = function(){ getAppList(); }
var gulp = require('gulp'); var plumber = require('gulp-plumber'); var add = require('gulp-add'); var filter = require('gulp-filter'); var replace = require('gulp-replace-task'); var notify = require('gulp-notify'); // utils var pumped = require('../../utils/pumped'); // config var project = require('../../../../project.config'); var config = require('../../config/theme'); // templates var style = require('../../templates/wordpress-style-css.js'); var phpHeaders = require('../../templates/wordpress-php-headers.js'); /** * Move the Theme to * the build directory * and add required files * * @returns {*} */ module.exports = function () { var filterPHP = filter('**/*.php', { restore: true }); return gulp.src(config.paths.src) .pipe(plumber()) .pipe(filterPHP) // Filter php files and transform // them to simply include the file // from the dev theme. This is to // make it possible to debug php from // within the dev theme .pipe(replace({ patterns: [ { json: phpHeaders } ] })) .pipe(filterPHP.restore) .pipe(add({ '.gitignore': '*', 'style.css': style })) .pipe(gulp.dest(config.paths.dest)) .pipe(notify({ message: pumped('Theme Moved!'), onLast: true })); };
module.exports = { load() { console.log('This is the module!'); console.log('Wow, I can change this and reload it'); }, unload() { // Nothing } }
'use strict'; function nameA(args) { let a = +args[0]; let b = +args[1]; console.log((a * b).toFixed(2) + ' ' + ((a + b) * 2).toFixed(2)); } nameA(['6', '5']);
output = { db: $.create(mongojs($.connection_string)) }
/* global describe, it, expect */ const obey = require('src/index') const modelFixtures = require('test/fixtures/core') const ValidationError = require('src/lib/error') describe('integration:core', () => { let stub afterEach(() => { if (stub) stub.restore() }) it('builds a model and successfully validates passing object', () => { const testModel = obey.model(modelFixtures.basicExtended) const testData = { fname: 'John', lname: 'Smith', type: 'foo' } return testModel.validate(testData).then(res => { expect(res).to.deep.equal(testData) }) }) it('builds a model and fails validation on type', () => { const testModel = obey.model(modelFixtures.basicExtended) const testData = { fname: 5, lname: 'Smith', type: 'foo', nested: { foo: 'bar' } } return testModel.validate(testData).catch(e => { expect(e).to.be.instanceOf(ValidationError) }) }) it('builds a model and passes when non-required field is undefined', () => { const testModel = obey.model(modelFixtures.basicExtended) const testData = { fname: 'John' } return testModel.validate(testData) .then((res) => { expect(res.fname).to.equal('John') expect(res.lname).to.be.undefined expect(res.type).to.be.undefined }) }) it('builds a models and passes with response including supplied undefined value', () => { const testModel = obey.model(modelFixtures.basicExtended) const testData = { fname: 'John', lname: undefined } return testModel.validate(testData) .then((res) => { expect(res.fname).to.equal('John') expect(res).to.have.property('lname') expect(res).to.not.have.property('type') }) }) it('builds a model and fails when required field is undefined', () => { stub = sinon.stub(console, 'log') const testModel = obey.model(modelFixtures.basicRequired) const testData = { fname: 'John' } return testModel.validate(testData) .then(() => { throw new Error('Should fail') }) .catch((err) => { expect(err.message).to.equal('lname (undefined): Property \'lname\' is required') expect(stub).calledWith('-----\nObey Warning: `require` should be `required`\n-----') }) }) it('builds a model and successfully validates when nested object present', () => { const testModel = obey.model(modelFixtures.basicNested) const testData = { name: 'fizz', someobj: { foo: 'buzz' } } return testModel.validate(testData).then(res => { expect(res).to.deep.equal(testData) }) }) it('builds a model and fails validates when nested object present', () => { const testModel = obey.model(modelFixtures.basicNested) const testData = { name: true, someobj: { foo: 5 } } return testModel.validate(testData) .then(() => { throw new Error('Should fail') }) .catch(err => { expect(err.collection).to.deep.equal([ { type: 'string', sub: 'default', key: 'name', value: true, message: 'Value must be a string' }, { type: 'string', sub: 'default', key: 'someobj.foo', value: 5, message: 'Value must be a string' } ]) }) }) it('builds a model and passes with empty string (allowed with flag)', () => { const testModel = obey.model(modelFixtures.basicEmpty) const testData = { name: '' } return testModel.validate(testData) .then(data => { expect(data.name).to.equal('') }) }) it('builds a model and fails with empty string (not allowed with flag)', () => { const testModel = obey.model(modelFixtures.basicNoEmpty) const testData = { name: '' } return testModel.validate(testData) .then(() => { throw new Error('Should have thrown') }) .catch(err => { expect(err.message).to.equal('name (): Value must be a string') }) }) it('builds a model and passes with empty array (allowed with flag)', () => { const testModel = obey.model(modelFixtures.basicEmptyArray) const testData = { names: [] } return testModel.validate(testData) .then(data => { expect(data.names).to.deep.equal([]) }) }) it('builds a model and fails with empty array (not allowed with flag)', () => { const testModel = obey.model(modelFixtures.basicNoEmptyArray) const testData = { names: [] } return testModel.validate(testData) .then(() => { throw new Error('Should have thrown') }) .catch(err => { expect(err.message).to.equal('names (): Value must not be empty array') }) }) it('builds a model and passes validation when partial option is set to true', () => { const testModel = obey.model(modelFixtures.basicExtended) const testData = { lname: 'Smith' } return testModel.validate(testData, { partial: true }) .then(data => { expect(data).to.deep.equal(testData) }) }) it('builds a model and passes validation when partial option is set to true, does not run creators', () => { obey.creator('testCreator', () => 'fizz') const testModel = obey.model(modelFixtures.basicCreator) const testData = { bar: 'buzz' } return testModel.validate(testData, { partial: true }) .then(data => { expect(data).to.deep.equal(testData) }) }) })
'use strict'; module.exports = function(/* environment, appConfig */) { var bootstrapPath = require('path').join(__dirname, '..', 'bower_components', 'bootstrap-sass', 'assets', 'stylesheets'); return { sassOptions: { includePaths: [ bootstrapPath ] } }; };
/** Copyright 2015 Board of Trustees of University of Illinois * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Use Passport logout function, to stop user session and redirect to the homepage router.get('/logout', function(request, response) { request.logout(); response.redirect('/'); }); module.exports = router;
import webpack from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import autoprefixer from 'autoprefixer'; import path from 'path'; export default { resolve: { extensions: ['*', '.js', '.jsx', '.json'] }, devtool: 'eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool entry: [ // must be first entry to properly set public path './src/webpack-public-path', 'webpack-hot-middleware/client?reload=true', path.resolve(__dirname, 'src/index.js') // Defining path seems necessary for this to work consistently on Windows machines. ], target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test output: { path: path.resolve(__dirname, 'dist-server'), // Note: Physical files are only output by the production build task `npm run build`. publicPath: '/', filename: 'bundle.js' }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom) __DEV__: true }), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS. template: 'src/index.ejs', minify: { removeComments: true, collapseWhitespace: true }, inject: true }), new webpack.LoaderOptionsPlugin({ minimize: false, debug: true, noInfo: true, // set to false to see a list of every file being bundled. options: { sassLoader: { includePaths: [path.resolve(__dirname, 'src', 'scss')] }, context: '/', postcss: () => [autoprefixer], } }) ], module: { rules: [ {test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader']}, {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader'}, {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff'}, {test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream'}, {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml'}, {test: /\.(jpe?g|png|gif)$/i, loader: 'file-loader?name=[name].[ext]'}, {test: /\.ico$/, loader: 'file-loader?name=[name].[ext]'}, {test: /(\.css|\.scss|\.sass)$/, loaders: ['style-loader', 'css-loader?sourceMap', 'postcss-loader', 'sass-loader?sourceMap']} ] } };
// Try to use vanilla javascript instead of jQuery when possible! // Much love <3 window.addEventListener('load', function() { var LAYOUT = { HORIZONTAL : 0 , VERTICAL : 1 }; var dropped = [ 'rand paul' , 'jeb bush' ]; var data = [], total = 0, side = 'rep', head; var drawBars = function() { if (data == null || data.length <= 0) { return; } var hasDropped = function(d) { return dropped.indexOf(d.name.toLowerCase()) >= 0; }; var getColor = function(d) { return d.isFirst ?ย '#d09f00' : hasDropped(d) ?ย '#e6e6e6' : d.color; }; // Do our thing for every barchart container [].slice.call(document.querySelectorAll('.bars-container')).forEach(function(container) { var containerWidth = window.getInnerWidth(container, 0), containerHeight = window.getInnerHeight(container); var width = containerWidth, height, xScale, yScale, layout = window.innerWidth <= 990 ? LAYOUT.VERTICAL : LAYOUT.HORIZONTAL; // Set up scales if (layout === LAYOUT.HORIZONTAL) { xScale = d3.scale.linear().domain([0, total]).range([0, width]); var rangeBand = 40, rangeBandPadding = rangeBand * 0.5; height = rangeBandPadding + ((rangeBand + rangeBandPadding) * data.length); } else if (layout === LAYOUT.VERTICAL) { height = containerHeight; xScale = d3.scale.ordinal().domain(_.pluck(data, 'name')).rangeRoundBands([0, width], 0.15, 0.15); yScale = d3.scale.linear().domain([0, total]).range([0, height]); } // Get or create SVG tag var svg = d3.select(container).select('svg'); if (svg[0][0] == null) { svg = d3.select(container).append('svg'); svg.append('defs'); // svg.append('g').attr('class', 'guides'); svg.append('g').attr('class', 'bars'); svg.append('g').attr('class', 'circles'); svg.append('g').attr('class', 'labels'); } var defs = svg.select('defs'), // guidesGroup = svg.select('g.guides'), barsGroup = svg.select('g.bars'), circlesGroup = svg.select('g.circles'), labelsGroup = svg.select('g.labels'); // Set SVG size svg.attr('width', width).attr('height', height); var pattern = defs.selectAll('pattern').data(data, function(d) { return d.name; }), bar = barsGroup.selectAll('.bar').data(data, function(d) { return d.name; }), circle = circlesGroup.selectAll('.circle').data(data, function(d) { return d.name; }), label = labelsGroup.selectAll('.label').data(data, function(d) { return d.name; }), name = labelsGroup.selectAll('.name').data([head], function(d) { return d.name; }); // Remove old bars and guides pattern.exit().remove(); bar.exit().remove(); circle.exit().remove(); label.exit().remove(); name.exit().remove(); // Append new ones pattern.enter().append('pattern').attr({ id: function(d) { return d.name.split(' ')[1].replace(/'/, '').toLowerCase(); }, patternUnits: 'objectBoundingBox', width: '100%', height: '100%', viewBox: '0 0 1 1', preserveAspectRatio: 'xMidYMid slice' }).append('image').attr({ 'xlink:href': function(d) { return 'img/' +ย side +ย '/' + d.name.split(' ')[1].replace(/'/, '').toLowerCase() + (d.isFirst ?ย '-or' : hasDropped(d) ? '-gr' : '') + '.jpg'; }, 'width': 1, 'height': 1, 'preserveAspectRatio': 'xMidYMid slice' }); bar.enter().append('rect').attr('class', 'bar'); circle.enter().append('circle').attr('class', 'circle'); label.enter().append('text').attr('class', 'label'); name.enter().append('text').attr('class', 'name gold').text(function(d) { return d.name; }); // Update size and position for everything left if (layout === LAYOUT.HORIZONTAL) { bar.attr({ x: 0, y: function(datum, index) { return rangeBandPadding + ((rangeBand + rangeBandPadding) * index); }, width: function(d) { return xScale(d.score); }, height: rangeBand, }).style('fill', getColor); circle.attr({ cx: function(d) { return xScale(d.score); }, cy: function(d, i) { return rangeBandPadding + ((rangeBand + rangeBandPadding) * i) + (rangeBand / 2); }, r: (rangeBand * 1.3) /ย 2, 'xlink:href': function(d) { return 'img/' +ย side + '/' + d.name.split(' ')[1].toLowerCase().replace(/'/, '') +ย '.png' } }).style({ 'fill': function(d) { return 'url(#' + d.name.split(' ')[1].toLowerCase().replace(/'/, '') +ย ')'; }, 'opacity': '1', 'pointer-events': 'all' }); label.style({ 'text-anchor' : function(d) { return d.percent >= 5 ? 'end' : 'start'; }, 'pointer-events' : function(d) { return d.percent >= 5 ? 'none' : 'all'; }, 'transform': function(d) { return 'translateX(' + String(d.percent >= 5 ? -1.4 : 1.4) + 'em)' + 'translateY(.4em)'; } }).attr({ class : function(d) { return 'label' + (d.percent < 5 ? ' inverse' : '') +ย (hasDropped(d) ? ' grey' : ''); }, x : function(d) { return xScale(d.score); }, y : function(d, i) { return rangeBandPadding + ((rangeBand + rangeBandPadding) * i) + (rangeBand / 2); } }); name.attr({ x : function(d) { return xScale(d.score); }, y : function(d) { var i = -1; while (++i < data.length) { if (data[i].name === d.name) { break; } } return rangeBandPadding + ((rangeBand + rangeBandPadding) * i) + (rangeBand / 2); } }).style({ 'transform': 'translateX(1.2em)' + 'translateY(.4em)' }); circle.on('mouseenter', function(d) { var tt = document.querySelector('.tt'); tt.querySelector('p').innerHTML = d.name; tt.classList.remove('hidden'); tt.querySelector('.tt--arrow').style.opacity = 0; }); circle.on('mousemove', function() { var tt = document.querySelector('.tt'), thisBoundingRect = this.getBoundingClientRect(); tt.style.top = String( thisBoundingRect.top + window.getScrollTop() + (thisBoundingRect.height /ย 2) - (tt.getBoundingClientRect().height /ย 2) ) +ย 'px'; tt.style.left = String(thisBoundingRect.rightย +ย 4) +ย 'px'; }); circle.on('mouseleave', function() { document.querySelector('.tt').classList.add('hidden'); }); } else if (layout === LAYOUT.VERTICAL) { bar.attr({ x: function(d) { return xScale(d.name); }, y: 0, width: function(d) { return xScale.rangeBand(); }, height: function(d) { return yScale(d.score); } }).style({ 'fill': function(d) { return 'url(#' + d.name.split(' ')[1].toLowerCase().replace(/'/, '') +ย ')'; } }); circle.style({ 'opacity': 0, 'pointer-events': 'none' }); label.style({ 'text-anchor' : 'middle', 'transform': 'translateX(0)' + 'translateY(1.2em)' }).attr({ class : function(d) { return 'label ' +ย (d.isFirst ? 'gold' : 'inverse'); }, x : function(d) { return xScale(d.name) + (xScale.rangeBand() / 2); }, y : function(d) { return yScale(d.score); } }); name.attr({ x : function(d) { return xScale(d.name) +ย (xScale.rangeBand() * 0.5); }, y : function(d) { return yScale(d.score); } }).style({ 'text-anchor': 'middle', 'transform': 'translateX(0)' + 'translateY(2.4em)' }); } // Common stuff (horizontal & vertical) label.text(function(d) { return String(d.score).replace(/\./, ','); }); // Handle events var getOpacity = function(reference) { return function(d) { return reference.name === d.name ? 1 : 0.7; }; }; }); }; window.startBars = function(input, _side) { side = _side; // Refine results data = _.reduce(_.map(_.pluck(input, 'results'), function(row) { // We only want delegates count return _.mapValues(row, function(result) { return result.delegates; }); }), function(a, b) { // Sum every round return _.mapValues(a, function(n, k) { return n +ย b[k]; }); }); total = _.sum(data); while (total++ %ย 10 >ย 0); --total; data = _.map(data, function(v, k) { return { name : k, score : v, percent : (v * 100) /ย total }; }); data = _.sortByOrder(data, 'score', 'desc'); data[0].isFirst = true; head = _.head(data); var tail = _.shuffle(_.tail(data)); data = _.take(tail, Math.floor(tail.length /ย 2)).concat(head).concat(_.takeRight(tail, Math.ceil(tail.length /ย 2))); // Call on resize window.addEventListener('resize', _.debounce(drawBars, 200)); //ย Initial call drawBars(); // Draw lines window.startLines(input); // Draw rounds window.startRounds(input); drawBars(); window.dispatchEvent(new Event('resize')); }; });
module.exports = { extractCSS: process.env.NODE_ENV === 'production', preserveWhitespace: false, postcss: [ require('autoprefixer')({ browsers: ['last 3 versions'] }) ] }
var searchData= [ ['rad_5f2_5fdeg',['rad_2_deg',['../group___number_kinds.html#gaadb33c76ca6311bf704590f5fe6fcb03',1,'numberkindsmodule']]], ['radius',['radius',['../group___sphere_b_v_e.html#ga033af4224781d26a9aa852ad034e7cf0',1,'spherebvemodule::bvemesh::radius()'],['../structsphereswemodule_1_1swemesh.html#ad1e72c8cfcf273ccbef3dd45a20aa456',1,'sphereswemodule::swemesh::radius()']]], ['read_5funit',['read_unit',['../group___number_kinds.html#gae275628322d1dedf50a022f740d88e22',1,'numberkindsmodule']]], ['realwork',['realwork',['../group___b_i_v_a_r_interface.html#gacb0a652d68c820a9dd21e05b32c740d3',1,'bivarinterfacemodule::bivarinterface']]], ['refineflag',['refineflag',['../group___refinement.html#gaf15b4507daa011b4f3719472674edcbf',1,'refinementmodule::refinesetup']]], ['relstream',['relstream',['../group___beta_plane.html#ga3947b8a611b978d91069cd03cf3cee4d',1,'betaplanemeshmodule::betaplanemesh::relstream()'],['../group___sphere_b_v_e.html#ga7bc983fda92cad621316ca52fe332e8b',1,'spherebvemodule::bvemesh::relstream()']]], ['relvort',['relvort',['../group___beta_plane.html#ga70e4f4891f1b7fa43655022a9ec15955',1,'betaplanemeshmodule::betaplanemesh::relvort()'],['../group___planar_s_w_e.html#gaa015023ceff15dd17c713825491bccdb',1,'planarswemodule::swemesh::relvort()'],['../group___sphere_b_v_e.html#gae58099cc1f13b4982bdefc60ea1fa0e1',1,'spherebvemodule::bvemesh::relvort()'],['../structsphereswemodule_1_1swemesh.html#a6e342f5e84e2e420204b79d676f786a1',1,'sphereswemodule::swemesh::relvort()']]], ['relvortin',['relvortin',['../group___beta_plane_solver.html#ga136b5bda983a61da46b058076bf2f33c',1,'betaplanesolvermodule::betaplanesolver::relvortin()'],['../group___sphere_b_v_e_solver.html#ga352a56528c7ece54d94828002d068d3b',1,'spherebvesolvermodule::bvesolver::relvortin()'],['../structsphereswesolvermodule_1_1swesolver.html#a5328c6a136a2f179f85aaad971199cf2',1,'sphereswesolvermodule::swesolver::relvortin()'],['../group___s_w_e_plane_solver.html#gae1144df4c6447837bafeb8396a9332b0',1,'sweplanesolvermodule::swesolver::relvortin()']]], ['relvortsource',['relvortsource',['../group___s_s_r_f_p_a_c_k_remesh.html#ga0391e587635f5f4b201d7c5f9373be3b',1,'ssrfpackremeshmodule::bveremeshsource']]], ['relvortstage1',['relvortstage1',['../group___beta_plane_solver.html#ga44e02ef197b23f399730c88fb4f14b55',1,'betaplanesolvermodule::betaplanesolver::relvortstage1()'],['../group___sphere_b_v_e_solver.html#ga482ae2aff8eb1cee896eb0903bfa71d3',1,'spherebvesolvermodule::bvesolver::relvortstage1()'],['../structsphereswesolvermodule_1_1swesolver.html#af3e4fbcbbbcd357bb10f3c2c22d1f8d0',1,'sphereswesolvermodule::swesolver::relvortstage1()'],['../group___s_w_e_plane_solver.html#gade096890ede994b6c1b4ac3cf1916f15',1,'sweplanesolvermodule::swesolver::relvortstage1()']]], ['relvortstage2',['relvortstage2',['../group___beta_plane_solver.html#ga8a8d27e1d6cf8bcb1f8c6aed571fcf0b',1,'betaplanesolvermodule::betaplanesolver::relvortstage2()'],['../group___sphere_b_v_e_solver.html#gacf091ccc30c57ea86c36467599047933',1,'spherebvesolvermodule::bvesolver::relvortstage2()'],['../structsphereswesolvermodule_1_1swesolver.html#a9ecf5b507302f305426b05dcdc920801',1,'sphereswesolvermodule::swesolver::relvortstage2()'],['../group___s_w_e_plane_solver.html#ga92eb20ba162f9866500b928574b9a2b5',1,'sweplanesolvermodule::swesolver::relvortstage2()']]], ['relvortstage3',['relvortstage3',['../group___beta_plane_solver.html#ga405313c8472613740e46bba436f53ba6',1,'betaplanesolvermodule::betaplanesolver::relvortstage3()'],['../group___sphere_b_v_e_solver.html#ga2c2eb62b2f8f00e3dfe9d38c221462f0',1,'spherebvesolvermodule::bvesolver::relvortstage3()'],['../structsphereswesolvermodule_1_1swesolver.html#ad3f38d5a7ca4136be1e7044d56ad99f6',1,'sphereswesolvermodule::swesolver::relvortstage3()'],['../group___s_w_e_plane_solver.html#ga254f5ccd6ba1938b58206936efd4bd09',1,'sweplanesolvermodule::swesolver::relvortstage3()']]], ['relvortstage4',['relvortstage4',['../group___beta_plane_solver.html#ga9fdc5060d02e09c583e6f5c20f6cc39e',1,'betaplanesolvermodule::betaplanesolver::relvortstage4()'],['../group___sphere_b_v_e_solver.html#ga4a60e1f53aa141e8a51e1365b79306ee',1,'spherebvesolvermodule::bvesolver::relvortstage4()'],['../structsphereswesolvermodule_1_1swesolver.html#a087bb2384754abc78c688d85de72bb9f',1,'sphereswesolvermodule::swesolver::relvortstage4()'],['../group___s_w_e_plane_solver.html#ga84a41df6d49199fa74aff0f1fbdd51fd',1,'sweplanesolvermodule::swesolver::relvortstage4()']]], ['relvortstart',['relvortstart',['../group___sphere_b_v_e_solver.html#ga6b6931e1eb25a85cee94d827e032ba53',1,'spherebvesolvermodule::bvesolver::relvortstart()'],['../structsphereswesolvermodule_1_1swesolver.html#a318826121b2d8f5bf11a564427d88373',1,'sphereswesolvermodule::swesolver::relvortstart()'],['../group___s_w_e_plane_solver.html#ga61f30226d7d2cfc76e6ac068109f5634',1,'sweplanesolvermodule::swesolver::relvortstart()']]], ['remeshcounter',['remeshcounter',['../group___s_s_r_f_p_a_c_k_remesh.html#ga56fe800aea09db7f0b55375bfc66a11e',1,'ssrfpackremeshmodule']]], ['rightface',['rightface',['../group___edges.html#ga3ca2402246c4dbae6a7b294b6932bc65',1,'edgesmodule::edges']]], ['rotationrate',['rotationrate',['../group___sphere_b_v_e.html#ga876a56818a0966d9c8a3be4e91f00193',1,'spherebvemodule::bvemesh::rotationrate()'],['../structsphereswemodule_1_1swemesh.html#a424967ce1104e65dfb369795a39c6557',1,'sphereswemodule::swemesh::rotationrate()']]] ];
define(['./_', './core'], function (_, jdb) { // EVENTS - data event callbacks // 'use strict'; // build ignore:line var fn = {}; // build ignore:line var rnotwhite = (/\S+/g), //jquery.js:3028 rbefore = (/^before/i); // Attach an event handler. fn.on = function (events, callback) { var db = this._root || this; _.each(events.match(rnotwhite), function (event) { event = event.toLowerCase(); if (!_.inArray(callback, db._on[event])) { db._on[event].push(callback); }//end if: added callback }); return db; }; // Remove one or more event handlers. fn.off = function (events, callback) { var db = this._root || this; _.each(events.match(rnotwhite), function (event) { event = event.toLowerCase(); if (!callback) { // clear all db._on[event] = {}; } else { // clear one callback var pos = db._on[event].indexOf(callback); if (pos > -1) { db._on[event].splice(pos, 1); } }//end if: removed callback }); return db; }; // Trigger an event handler. fn.trigger = function (events, items, args) { var db = this._root || this, result = this; args = args || []; _.each(events.match(rnotwhite), function (name) { name = name.toLowerCase(); if (!rbefore.test(name)) { args.unshift(items); _.each(db._on[name], function (f) { f.apply(items, args); }); } else { // special before events args.unshift(null); for(var i = 0, L = db._on[name].length; i < L; i++) { args[0] = items; items = db._on[name][i].apply(items, args); if (_.isFalsy(items)) { items = []; } }//end for result = items; }//end if: callbacks fired }); return result; }; /* build ignore:start */ _.extend(jdb.fn, fn); return fn; /* build ignore:end */ });
var Path = require('path') module.exports = function * generateModel (util, vfs, config, name) { if ( ! name ) { name = ( yield util.prompt('Name of Model (user, comment, etc.): ') ) || util.fail('`pult generate model` requires a model name.') } name = util.inflection.singularize(name).toLowerCase() var namePlural = util.inflection.pluralize(name) var templateVars = { name: name, nameCapitalized: util.inflection.capitalize(name), namePlural: namePlural, namePluralCapitalized: util.inflection.capitalize(namePlural), } vfs.copyTpl( util.projectFile(`generators/model/model-template.ejs`), util.projectFile(`server/models/${ name }.js`), templateVars ) vfs.copyTpl( util.projectFile(`generators/model/model-test-template.ejs`), util.projectFile(`test/server/models/${ name }-test.js`), templateVars ) }
setCssToHead([".",[1],"animation-element-wrapper { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; width: 100%; padding-top: ",[0,150],"; padding-bottom: ",[0,150],"; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; overflow: hidden; background-color: #ffffff; }\n.",[1],"animation-element { width: ",[0,200],"; height: ",[0,200],"; background-color: #1AAD19; }\n.",[1],"animation-buttons { padding:",[0,30]," 0; width: 100%; height: ",[0,360],"; }\n.",[1],"animation-button { float: left; line-height: 2; width: 44%; margin: ",[0,15]," 3%; }\n.",[1],"animation-button-reset { width: 94%; }\n",],undefined,{path:"./pages/API/animation/animation.wxss"})(); document.dispatchEvent(new CustomEvent("generateFuncReady", { detail: { generateFunc: $gwx('./pages/API/animation/animation.wxml') } }));
import expect from 'expect.js'; import sinon from 'sinon'; import nock from 'nock'; import glob from 'glob-all'; import rimraf from 'rimraf'; import mkdirp from 'mkdirp'; import Logger from '../../lib/logger'; import { UnsupportedProtocolError } from '../../lib/errors'; import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } from '../download'; import { join } from 'path'; describe('kibana cli', function () { describe('plugin downloader', function () { const testWorkingPath = join(__dirname, '.test.data'); const tempArchiveFilePath = join(testWorkingPath, 'archive.part'); const settings = { urls: [], workingPath: testWorkingPath, tempArchiveFile: tempArchiveFilePath, timeout: 0 }; const logger = new Logger(settings); function expectWorkingPathEmpty() { const files = glob.sync('**/*', { cwd: testWorkingPath }); expect(files).to.eql([]); } function expectWorkingPathNotEmpty() { const files = glob.sync('**/*', { cwd: testWorkingPath }); const expected = [ 'archive.part' ]; expect(files.sort()).to.eql(expected.sort()); } function shouldReject() { throw new Error('expected the promise to reject'); } beforeEach(function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); rimraf.sync(testWorkingPath); mkdirp.sync(testWorkingPath); }); afterEach(function () { logger.log.restore(); logger.error.restore(); rimraf.sync(testWorkingPath); }); describe('_downloadSingle', function () { beforeEach(function () { }); describe('http downloader', function () { it('should throw an ENOTFOUND error for a http ulr that returns 404', function () { const couchdb = nock('http://example.com') .get('/plugin.tar.gz') .reply(404); const sourceUrl = 'http://example.com/plugin.tar.gz'; return _downloadSingle(settings, logger, sourceUrl) .then(shouldReject, function (err) { expect(err.message).to.match(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); it('should throw an UnsupportedProtocolError for an invalid url', function () { const sourceUrl = 'i am an invalid url'; return _downloadSingle(settings, logger, sourceUrl) .then(shouldReject, function (err) { expect(err).to.be.an(UnsupportedProtocolError); expectWorkingPathEmpty(); }); }); it('should download a file from a valid http url', function () { const filePath = join(__dirname, 'replies/banana.jpg'); const couchdb = nock('http://example.com') .defaultReplyHeaders({ 'content-length': '341965', 'content-type': 'application/zip' }) .get('/plugin.zip') .replyWithFile(200, filePath); const sourceUrl = 'http://example.com/plugin.zip'; return _downloadSingle(settings, logger, sourceUrl) .then(function () { expectWorkingPathNotEmpty(); }); }); }); describe('local file downloader', function () { it('should throw an ENOTFOUND error for an invalid local file', function () { const filePath = join(__dirname, 'replies/i-am-not-there.zip'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); return _downloadSingle(settings, logger, sourceUrl) .then(shouldReject, function (err) { expect(err.message).to.match(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); it('should copy a valid local file', function () { const filePath = join(__dirname, 'replies/banana.jpg'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); return _downloadSingle(settings, logger, sourceUrl) .then(function () { expectWorkingPathNotEmpty(); }); }); }); }); describe('_getFilePath', function () { it('should decode paths', function () { expect(_getFilePath('Test%20folder/file.zip')).to.equal('Test folder/file.zip'); }); it('should remove the leading slash from windows paths', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); expect(_getFilePath('/C:/foo/bar')).to.equal('C:/foo/bar'); Object.defineProperty(process, 'platform', platform); }); }); describe('Windows file:// deprecation', function () { it('should log a warning if a file:// path is used', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); const logger = { log: sinon.spy() }; _checkFilePathDeprecation('file://foo/bar', logger); _checkFilePathDeprecation('file:///foo/bar', logger); expect(logger.log.callCount).to.be(1); expect(logger.log.calledWith('Install paths with file:// are deprecated, use file:/// instead')).to.be(true); Object.defineProperty(process, 'platform', platform); }); }); describe('download', function () { it('should loop through bad urls until it finds a good one.', function () { const filePath = join(__dirname, 'replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', 'http://example.com/badfile2.tar.gz', 'I am a bad uri', 'http://example.com/goodfile.tar.gz' ]; const couchdb = nock('http://example.com') .defaultReplyHeaders({ 'content-length': '10' }) .get('/badfile1.tar.gz') .reply(404) .get('/badfile2.tar.gz') .reply(404) .get('/goodfile.tar.gz') .replyWithFile(200, filePath); return download(settings, logger) .then(function () { expect(logger.log.getCall(0).args[0]).to.match(/badfile1.tar.gz/); expect(logger.log.getCall(1).args[0]).to.match(/badfile2.tar.gz/); expect(logger.log.getCall(2).args[0]).to.match(/I am a bad uri/); expect(logger.log.getCall(3).args[0]).to.match(/goodfile.tar.gz/); expectWorkingPathNotEmpty(); }); }); it('should stop looping through urls when it finds a good one.', function () { const filePath = join(__dirname, 'replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', 'http://example.com/badfile2.tar.gz', 'http://example.com/goodfile.tar.gz', 'http://example.com/badfile3.tar.gz' ]; const couchdb = nock('http://example.com') .defaultReplyHeaders({ 'content-length': '10' }) .get('/badfile1.tar.gz') .reply(404) .get('/badfile2.tar.gz') .reply(404) .get('/goodfile.tar.gz') .replyWithFile(200, filePath) .get('/badfile3.tar.gz') .reply(404); return download(settings, logger) .then(function () { for (let i = 0; i < logger.log.callCount; i++) { expect(logger.log.getCall(i).args[0]).to.not.match(/badfile3.tar.gz/); } expectWorkingPathNotEmpty(); }); }); it('should throw an error when it doesn\'t find a good url.', function () { settings.urls = [ 'http://example.com/badfile1.tar.gz', 'http://example.com/badfile2.tar.gz', 'http://example.com/badfile3.tar.gz' ]; const couchdb = nock('http://example.com') .defaultReplyHeaders({ 'content-length': '10' }) .get('/badfile1.tar.gz') .reply(404) .get('/badfile2.tar.gz') .reply(404) .get('/badfile3.tar.gz') .reply(404); return download(settings, logger) .then(shouldReject, function (err) { expect(err.message).to.match(/no valid url specified/i); expectWorkingPathEmpty(); }); }); }); }); });
'use strict'; const { createController } = require('../index'); const supertest = require('supertest'); const assert = require('assert'); const db = require('./db'); describe('PUT /<model>/<id>', () => { before(async () => { await db.sequelize.sync({ force: true }) await db.author.bulkCreate([ { id: 1, name: 'Bud' }, { id: 2, name: 'Frank' } ]); await db.post.bulkCreate([ { id: 1, authorId: 1, title: 'One Title' }, { id: 2, authorId: 1, title: 'Two Titles' }, { id: 3, authorId: 2, title: 'Three Titles' } ]); }); it('should throw validation error for missing fields', (done) => { const app = require('express')(); app.use('/authors', createController(db.author)); const request = supertest(app); request.put('/authors/1') .set('Content-Type', 'application/json') .send({ author: { id: 1, name: null } }) .expect(422, (e, res) => { assert.equal(res.body.errors.length, 1); assert.equal(res.body.errors[0].message, 'author.name cannot be null'); done(); }); }); it('should disallow changing primary key', (done) => { const app = require('express')(); app.use('/authors', createController(db.author)); const request = supertest(app); request.put('/authors/1') .set('Content-Type', 'application/json') .send({ author: { id: 10, name: 'NewName' } }) .expect(422, (e, res) => { assert.equal(res.body.errors.length, 1); assert.equal(res.body.errors[0].message, 'cannot change record primary key'); done(); }); }); it('should successfully update record with valid request', (done) => { const app = require('express')(); app.use('/authors', createController(db.author)); const request = supertest(app); request.put('/authors/1') .set('Content-Type', 'application/json') .send({ author: { name: 'NewName' } }) .expect(200, (e, res) => { assert.equal(res.body.author.name, 'NewName'); assert.equal(res.body.author.id, 1); done(); }); }); });
// Text rendering style import Texture from '../../gl/texture'; import WorkerBroker from '../../utils/worker_broker'; import Utils from '../../utils/utils'; import Geo from '../../geo'; import {Style} from '../style'; import {Points} from '../points/points'; import CanvasText from './canvas_text'; import Collision from '../../labels/collision'; import LabelPoint from '../../labels/label_point'; import LabelLine from '../../labels/label_line'; import TextSettings from './text_settings'; import {StyleParser} from '../style_parser'; import log from 'loglevel'; export let TextStyle = Object.create(Points); Object.assign(TextStyle, { name: 'text', super: Points, built_in: true, selection: false, // no feature selection for text by default init() { this.super.init.apply(this, arguments); // Provide a hook for this object to be called from worker threads this.main_thread_target = 'TextStyle-' + this.name; if (Utils.isMainThread) { WorkerBroker.addTarget(this.main_thread_target, this); } // Point style (parent class) requires texturing to be turned on // (labels are always drawn with textures) this.defines.TANGRAM_POINT_TEXTURE = true; // Manually un-multiply alpha, because Canvas text rasterization is pre-multiplied this.defines.TANGRAM_UNMULTIPLY_ALPHA = true; this.reset(); }, reset() { this.super.reset.call(this); if (Utils.isMainThread) { this.canvas = new CanvasText(); } else if (Utils.isWorkerThread) { this.texts = {}; // unique texts, grouped by tile, by style } }, // Called on worker thread to release tile-specific resources freeTile (tile) { delete this.texts[tile]; }, // Free tile-specific resources before finshing style construction finishTile(tile) { this.freeTile(tile); return Style.endData.call(this, tile); }, // Override to queue features instead of processing immediately addFeature (feature, draw, context) { let tile = context.tile; if (tile.generation !== this.generation) { return; } // Called here because otherwise it will be delayed until the feature queue is parsed, // and we want the preprocessing done before we evaluate text style below draw = this.preprocess(draw); if (!draw) { return; } // Compute label text let text = this.parseTextSource(feature, draw, context); if (text == null) { return; // no text for this feature } // Compute text style and layout settings for this feature label let layout = this.computeLayout({}, feature, draw, context, tile, text); let text_settings = TextSettings.compute(feature, draw, context); let text_settings_key = TextSettings.key(text_settings); // first label in tile, or with this style? this.texts[tile.key] = this.texts[tile.key] || {}; this.texts[tile.key][text_settings_key] = this.texts[tile.key][text_settings_key] || {}; // unique text strings, grouped by text drawing style if (!this.texts[tile.key][text_settings_key][text]) { // first label with this text/style/tile combination, make a new label entry this.texts[tile.key][text_settings_key][text] = { text_settings, ref: 0 // # of times this text/style combo appears in tile }; } // Queue the feature for processing if (!this.tile_data[tile.key]) { this.startData(tile.key); } if (!this.queues[tile.key]) { this.queues[tile.key] = []; } this.queues[tile.key].push({ feature, draw, context, text, text_settings_key, layout }); // Register with collision manager Collision.addStyle(this.name, tile.key); }, // Override endData (tile) { let queue = this.queues[tile]; this.queues[tile] = []; if (Object.keys(this.texts[tile]||{}).length === 0) { return Promise.resolve(); } // first call to main thread, ask for text pixel sizes return WorkerBroker.postMessage(this.main_thread_target+'.calcTextSizes', tile, this.texts[tile]).then(texts => { if (!texts) { Collision.collide({}, this.name, tile); return this.finishTile(tile); } this.texts[tile] = texts; let labels = this.createLabels(tile, queue); return Collision.collide(labels, this.name, tile).then(labels => { if (labels.length === 0) { return this.finishTile(tile); // no labels visible for this tile } this.cullTextStyles(texts, labels); // second call to main thread, for rasterizing the set of texts return WorkerBroker.postMessage(this.main_thread_target+'.rasterizeTexts', tile, texts).then(({ texts, texture }) => { if (texts) { this.texts[tile] = texts; // Build queued features labels.forEach(q => { let text_settings_key = q.text_settings_key; let text_info = this.texts[tile] && this.texts[tile][text_settings_key] && this.texts[tile][text_settings_key][q.text]; // setup styling object expected by Style class let style = this.feature_style; style.label = q.label; style.size = text_info.size.logical_size; style.angle = Utils.radToDeg(q.label.angle) || 0; style.texcoords = text_info.texcoords; Style.addFeature.call(this, q.feature, q.draw, q.context); }); } return this.finishTile(tile).then(tile_data => { // Attach tile-specific label atlas to mesh as a texture uniform if (texture && tile_data) { tile_data.uniforms = { u_texture: texture }; tile_data.textures = [texture]; // assign texture ownership to tile return tile_data; } }); }); }); }); }, createLabels (tile, feature_queue) { let labels = []; for (let f=0; f < feature_queue.length; f++) { let { feature, draw, context, text, text_settings_key, layout } = feature_queue[f]; let text_info = this.texts[tile][text_settings_key][text]; let feature_labels = this.buildLabelsFromGeometry(text_info.size.collision_size, feature.geometry, layout); for (let i = 0; i < feature_labels.length; i++) { let label = feature_labels[i]; labels.push({ feature, draw, context, text, text_settings_key, layout, label }); } } return labels; }, // Remove unused text/style combinations to avoid unnecessary rasterization cullTextStyles(texts, labels) { // Count how many times each text/style combination is used for (let i=0; i < labels.length; i++) { texts[labels[i].text_settings_key][labels[i].text].ref++; } // Remove text/style combinations that have no visible labels for (let style in texts) { for (let text in texts[style]) { // no labels for this text if (texts[style][text].ref < 1) { // console.log(`drop label text ${text} in style ${style}`); delete texts[style][text]; } } } for (let style in texts) { // no labels for this style if (Object.keys(texts[style]).length === 0) { // console.log(`drop label text style ${style}`); delete texts[style]; } } }, // Called on main thread from worker, to compute the size of each text string, // were it to be rendered. This info is then used to perform initial label culling, *before* // labels are actually rendered. calcTextSizes (tile, texts) { return this.canvas.textSizes(tile, texts); }, // Called on main thread from worker, to create atlas of labels for a tile rasterizeTexts (tile, texts) { let canvas = new CanvasText(); let texture_size = canvas.setTextureTextPositions(texts, this.max_texture_size); log.trace(`text summary for tile ${tile}: fits in ${texture_size[0]}x${texture_size[1]}px`); // fits in max texture size? if (texture_size[0] < this.max_texture_size && texture_size[1] < this.max_texture_size) { // update canvas size & rasterize all the text strings we need canvas.resize(...texture_size); canvas.rasterize(tile, texts, texture_size); } else { log.error([ `Label atlas for tile ${tile} is ${texture_size[0]}x${texture_size[1]}px, `, `but max GL texture size is ${this.max_texture_size}x${this.max_texture_size}px`].join('')); } // create a texture let t = 'labels-' + tile + '-' + (TextStyle.texture_id++); Texture.create(this.gl, t, { element: canvas.canvas, filtering: 'linear', UNPACK_PREMULTIPLY_ALPHA_WEBGL: true }); return { texts, texture: t }; // texture is returned by name (not instance) }, // Sets up caching for draw rule properties _preprocess (draw) { if (!draw.font) { return; } // Colors draw.font.fill = StyleParser.cacheObject(draw.font.fill); if (draw.font.stroke) { draw.font.stroke.color = StyleParser.cacheObject(draw.font.stroke.color); } // Convert font and text stroke sizes draw.font.px_size = StyleParser.cacheObject(draw.font.size, CanvasText.fontPixelSize); if (draw.font.stroke && draw.font.stroke.width != null) { draw.font.stroke.width = StyleParser.cacheObject(draw.font.stroke.width, parseFloat); } // Offset (2d array) draw.offset = StyleParser.cacheObject(draw.offset, v => (Array.isArray(v) && v.map(parseFloat)) || 0); // Buffer (1d value or or 2d array) draw.buffer = StyleParser.cacheObject(draw.buffer, v => (Array.isArray(v) ? v : [v, v]).map(parseFloat) || 0); // Repeat rules draw.repeat_distance = StyleParser.cacheObject(draw.repeat_distance, parseFloat); return draw; }, // Compute the label text, default is value of feature.properties.name // - String value indicates a feature property look-up, e.g. `short_name` means use feature.properties.short_name // - Function will use the return value as the label text (for custom labels) // - Array (of strings and/or functions) defines a list of fallbacks, evaluated according to the above rules, // with the first non-null value used as the label text // e.g. `[name:es, name:en, name]` prefers Spanish names, followed by English, and last the default local name parseTextSource (feature, draw, context) { let text; let source = draw.text_source || 'name'; if (Array.isArray(source)) { for (let s=0; s < source.length; s++) { if (typeof source[s] === 'string') { text = feature.properties[source[s]]; } else if (typeof source[s] === 'function') { text = source[s](context); } if (text) { break; // stop if we found a text property } } } else if (typeof source === 'string') { text = feature.properties[source]; } else if (typeof source === 'function') { text = source(context); } return text; }, // Additional text-specific layout settings computeLayout (target, feature, draw, context, tile, text) { let layout = target || {}; // common settings w/points layout = Points.computeLayout(layout, feature, draw, context, tile); // tile boundary handling layout.cull_from_tile = (draw.cull_from_tile != null) ? draw.cull_from_tile : true; layout.move_into_tile = (draw.move_into_tile != null) ? draw.move_into_tile : true; // label line exceed percentage if (draw.line_exceed && draw.line_exceed.substr(-1) === '%') { layout.line_exceed = parseFloat(draw.line_exceed.substr(0,draw.line_exceed.length-1)); } else { layout.line_exceed = 80; } // repeat minimum distance layout.repeat_distance = StyleParser.cacheProperty(draw.repeat_distance, context); if (layout.repeat_distance == null) { layout.repeat_distance = Geo.tile_size; } layout.repeat_distance *= layout.units_per_pixel; // repeat group key if (typeof draw.repeat_group === 'function') { layout.repeat_group = draw.repeat_group(context); } else if (typeof draw.repeat_group === 'string') { layout.repeat_group = draw.repeat_group; } else { layout.repeat_group = draw.key; // default to unique set of matching layers } layout.repeat_group += '/' + text; return layout; }, // Builds one or more labels for a geometry buildLabelsFromGeometry (size, geometry, options) { let labels = []; if (geometry.type === "LineString") { let lines = geometry.coordinates; labels.push(new LabelLine(size, lines, options)); } else if (geometry.type === "MultiLineString") { let lines = geometry.coordinates; for (let i = 0; i < lines.length; ++i) { let line = lines[i]; labels.push(new LabelLine(size, line, options)); } } else if (geometry.type === "Point") { labels.push(new LabelPoint(geometry.coordinates, size, options)); } else if (geometry.type === "MultiPoint") { let points = geometry.coordinates; for (let i = 0; i < points.length; ++i) { let point = points[i]; labels.push(new LabelPoint(point, size, options)); } } else if (geometry.type === "Polygon") { let centroid = Geo.centroid(geometry.coordinates[0]); labels.push(new LabelPoint(centroid, size, options)); } else if (geometry.type === "MultiPolygon") { let centroid = Geo.multiCentroid(geometry.coordinates); labels.push(new LabelPoint(centroid, size, options)); } return labels; } }); TextStyle.texture_id = 0; // namespaces per-tile label textures
/*! * router * Copyright(c) 2015-2017 Fangdun Cai * MIT Licensed */ 'use strict' // Static Param Any `*` `/` `:` const [SKIND, PKIND, AKIND, STAR, SLASH, COLON] = [0, 1, 2, 42, 47, 58] class Node { constructor( prefix = '/', children = [], kind = SKIND, map = Object.create(null) ) { this.label = prefix.charCodeAt(0) this.prefix = prefix this.children = children this.kind = kind this.map = map } addChild(n) { this.children.push(n) } findChild(c, t, l, e, i = 0) { for (l = this.children.length; i < l; i++) { e = this.children[i] if (c === e.label && t === e.kind) { return e } } } findChildWithLabel(c, l, e, i = 0) { for (l = this.children.length; i < l; i++) { e = this.children[i] if (c === e.label) { return e } } } findChildByKind(t, l, e, i = 0) { for (l = this.children.length; i < l; i++) { e = this.children[i] if (t === e.kind) { return e } } } addHandler(method, handler, pnames) { this.map[method] = { handler, pnames } } findHandler(method) { return this.map[method] } } class Router { constructor() { this.tree = new Node() } add(method, path, handler) { // Pnames: Param names let [i, l, pnames, ch, j] = [0, path.length, []] for (; i < l; ++i) { ch = path.charCodeAt(i) if (ch === COLON) { j = i + 1 this.insert(method, path.substring(0, i), SKIND) while (i < l && path.charCodeAt(i) !== SLASH) { i++ } pnames.push(path.substring(j, i)) path = path.substring(0, j) + path.substring(i) i = j l = path.length if (i === l) { this.insert(method, path.substring(0, i), PKIND, pnames, handler) return } this.insert(method, path.substring(0, i), PKIND, pnames) } else if (ch === STAR) { this.insert(method, path.substring(0, i), SKIND) pnames.push('*') this.insert(method, path.substring(0, l), AKIND, pnames, handler) return } } this.insert(method, path, SKIND, pnames, handler) } insert(method, path, t, pnames, handler) { // Current node as root let [cn, prefix, sl, pl, l, max, n, c] = [this.tree] while (true) { prefix = cn.prefix sl = path.length pl = prefix.length l = 0 // LCP max = sl < pl ? sl : pl while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) { l++ } /* If (l === 0) { // At root node cn.label = search.charCodeAt(0) cn.prefix = search if (handler !== undefined) { cn.addHandler(method, { pnames, handler }) } } else if (l < pl) { */ if (l < pl) { // Split node n = new Node(prefix.substring(l), cn.children, cn.kind, cn.map) cn.children = [n] // Add to parent // Reset parent node cn.label = prefix.charCodeAt(0) cn.prefix = prefix.substring(0, l) cn.map = Object.create(null) cn.kind = SKIND if (l === sl) { // At parent node cn.addHandler(method, handler, pnames) cn.kind = t } else { // Create child node n = new Node(path.substring(l), [], t) n.addHandler(method, handler, pnames) cn.addChild(n) } } else if (l < sl) { path = path.substring(l) c = cn.findChildWithLabel(path.charCodeAt(0)) if (c !== undefined) { // Go deeper cn = c continue } // Create child node n = new Node(path, [], t) n.addHandler(method, handler, pnames) cn.addChild(n) } else if (handler !== undefined) { // Node already exists cn.addHandler(method, handler, pnames) } return } } find(method, path, cn, n = 0, result = [undefined, []]) { cn = cn || this.tree // Current node as root const sl = path.length const prefix = cn.prefix const pvalues = result[1] // Params let i, pl, l, max, c let preSearch // Pre search // Search order static > param > match-any if (sl === 0 || path === prefix) { // Found const r = cn.findHandler(method) if ((result[0] = r && r.handler) !== undefined) { const pnames = r.pnames if (pnames !== undefined) { for (i = 0, l = pnames.length; i < l; ++i) { pvalues[i] = { name: pnames[i], value: pvalues[i] } } } } return result } pl = prefix.length l = 0 // LCP max = sl < pl ? sl : pl while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) { l++ } if (l === pl) { path = path.substring(l) } preSearch = path // Static node c = cn.findChild(path.charCodeAt(0), SKIND) if (c !== undefined) { this.find(method, path, c, n, result) if (result[0] !== undefined) { return result } path = preSearch } // Not found node if (l !== pl) { return result } // Param node c = cn.findChildByKind(PKIND) if (c !== undefined) { l = path.length i = 0 while (i < l && path.charCodeAt(i) !== SLASH) { i++ } pvalues[n] = path.substring(0, i) n++ preSearch = path path = path.substring(i) this.find(method, path, c, n, result) if (result[0] !== undefined) { return result } n-- pvalues.pop() path = preSearch } // Any node c = cn.findChildByKind(AKIND) if (c !== undefined) { pvalues[n] = path path = '' // End search this.find(method, path, c, n, result) } return result } } Router.Node = Node module.exports = Router
๏ปฟfunction first() { jsConsole.writeLine("=== 1 ================"); var array = Array(20); for (var i = 0, len = array.length; i < len; i++) { array[i] = i * 5; jsConsole.write(array[i]+" "); } jsConsole.writeLine(); jsConsole.writeLine("======================"); } function second() { jsConsole.writeLine("=== 2 ================"); var chars1 = "sometexthere".split(''); var chars2 = "anothertexthere".split(''); var min=(chars1.length >chars2.length) ? chars2.length : chars1.length; for (var i = 0; i < min; i++) { var compared = chars1[i].charCodeAt(0) - chars2[i].charCodeAt(0); var result=compared>0 ? 'bigger' : compared<0 ? 'smaller' : 'equal'; jsConsole.writeLine("index:" + i + " " + result); } jsConsole.writeLine("======================"); } function third() { jsConsole.writeLine("=== 3 ================"); var array = "arrayofelements 2112332221".split(""); var currentMax=0, max=0; for (var i = 0, len = array.length; i < len; i++) { currentMax = 0; for (var j = i ; j < len; j++) { if(array[j]==array[i]){ currentMax++; } else { break; } } if (currentMax > max) { max = currentMax; } } jsConsole.writeLine(max); jsConsole.writeLine("======================"); } function fourth() { jsConsole.writeLine("=== 4 ================"); var array = "3234224".split(""); var currentMax = 0, max = 0; for (var i = 0, len = array.length; i < len; i++) { currentMax = 0; for (var j = i ; j < len; j++) { if (parseInt(array[i]) == parseInt(array[j]-(j-i))) { currentMax++; } else { break; } } if (currentMax > max) { max = currentMax; } } jsConsole.writeLine(max); jsConsole.writeLine("======================"); } function fifth() { jsConsole.writeLine("=== 5 ================"); var array = "9 123 34 5 76 45 23 1 -10 -23".split(" "); var startArray = array.slice(); var helpArray = []; var min; var minIndex = 0; for (var i = 0, len = array.length; i < len; i++) { min = Number.MAX_VALUE; for (var j = 0; j < len; j++) { if (parseInt(array[j]) < min) { min = parseInt(array[j]); minIndex = j; } } helpArray.push(min); array[minIndex] = undefined; } jsConsole.writeLine(startArray); jsConsole.writeLine(helpArray); jsConsole.writeLine("======================"); } function sixth() { jsConsole.writeLine("=== 6 ================"); var array = "4 1 1 4 2 3 4 4 1 2 4 9 3".split(" "); var max = 0, current = 0, maxNumber = 0; for (var i = 0,len=array.length; i < len; i++) { current=0; for (var j = i; j < len; j++) { if (array[j] == array[i]) { current++; } } if (current > max) { max = current; maxNumber = array[i]; } } jsConsole.writeLine(maxNumber + " (" + max + " times)"); jsConsole.writeLine("======================"); } function seventh() { jsConsole.writeLine("=== 7 ================"); var array = "1 4 8 20 25 50 60 63 54 123 235 390 480 501 705 1006 2007 3008 3570 3760".split(" "); var numberToSearch = 480; var left = 0,right=array.length; var middle = (left+right)/2; while (true) { var middle = Math.floor((left + right) / 2); if (parseInt(array[middle]) == numberToSearch) { jsConsole.write("Index found:" + middle); return; } else if(parseInt(array[middle]) > numberToSearch) { right = middle; } else { left = middle; } } jsConsole.writeLine("======================"); }