text
stringlengths
2
6.14k
/* eslint-disable */ const NODE_ENV = process.env.NODE_ENV; if (NODE_ENV !== 'development' && NODE_ENV !== 'production') { throw new Error('NODE_ENV must either be set to development or production.'); } global.__DEV__ = NODE_ENV === 'development'; global.requestAnimationFrame = function(callback) { setTimeout(callback); }; global.requestIdleCallback = function(callback) { return setTimeout(() => { callback({ timeRemaining() { return Infinity; }, }); }); }; global.cancelIdleCallback = function(callbackID) { clearTimeout(callbackID); }; // By default React console.error()'s any errors, caught or uncaught. // However it is annoying to assert that a warning fired each time // we assert that there is an exception in our tests. This lets us // opt out of extra console error reporting for most tests except // for the few that specifically test the logging by shadowing this // property. In real apps, it would usually not be defined at all. Error.prototype.suppressReactErrorLogging = true; if (typeof window !== 'undefined') { // Same as above. DOMException.prototype.suppressReactErrorLogging = true; // Also prevent JSDOM from logging intentionally thrown errors. // TODO: it might make sense to do it the other way around. // https://github.com/facebook/react/issues/11098#issuecomment-355032539 window.addEventListener('error', event => { if (event.error != null && event.error.suppressReactErrorLogging) { event.preventDefault(); } }); } // Preserve the empty object identity across module resets. // This is needed for some tests that rely on string refs // but reset modules between loading different renderers. const obj = require.requireActual('fbjs/lib/emptyObject'); jest.mock('fbjs/lib/emptyObject', () => obj);
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Favorites', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, userId: { type: Sequelize.STRING }, recipeId: { type: Sequelize.STRING }, recipeId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Recipes', key: 'id' } }, userId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Users', key: 'id' } }, createdAt: { allowNull: false, type: Sequelize.DATE }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Favorites'); } };
var group___d_m_a_ex = [ [ "DMAEx Exported Types", "group___d_m_a_ex___exported___types.html", "group___d_m_a_ex___exported___types" ], [ "DMAEx Exported Functions", "group___d_m_a_ex___exported___functions.html", "group___d_m_a_ex___exported___functions" ], [ "DMAEx Private Functions", "group___d_m_a_ex___private___functions.html", null ] ];
var relativeImports = /import\s*{[a-zA-Z\,\s]+}\s*from\s*'\.\/[a-zA-Z\-]+';\s*/g; var nonRelativeImports = /import\s*{?[a-zA-Z\*\,\s]+}?\s*from\s*'[a-zA-Z\-]+';\s*/g; var importGrouper = /import\s*{([a-zA-Z\,\s]+)}\s*from\s*'([a-zA-Z\-]+)'\s*;\s*/; exports.extractImports = function(content, importsToAdd){ var matchesToKeep = content.match(nonRelativeImports); if(matchesToKeep){ matchesToKeep.forEach(function(toKeep){ importsToAdd.push(toKeep) }); } content = content.replace(nonRelativeImports, ''); content = content.replace(relativeImports, ''); return content; }; exports.createImportBlock = function(importsToAdd){ var finalImports = {}, importBlock = ''; importsToAdd.forEach(function(toAdd){ var groups = importGrouper.exec(toAdd); if(!groups) { toAdd = toAdd.trim(); if(importBlock.indexOf(toAdd) === -1){ importBlock += toAdd + '\n'; } return; }; var theImports = groups[1].split(','); var theSource = groups[2].trim(); var theList = finalImports[theSource] || (finalImports[theSource] = []); theImports.forEach(function(item){ item = item.trim(); if(theList.indexOf(item) === -1){ theList.push(item); } }); }); Object.keys(finalImports).forEach(function(key) { importBlock += 'import {' + finalImports[key].join(',') + '} from \'' + key + '\';\n'; }); return importBlock + '\n'; };
'use strict'; module.exports = function(app) { // Root routing var core = require('../../app/controllers/core.server.controller'); app.route('/').get(core.index); app.route('/check').put(core.check); };
const AuthUtil = require('../thulib/auth') const User = require('../models/user') const updateCourseInfo = require('./update_course_info') const updateCurriculumInfo = require('./update_curriculum_info') const updateScheduleInfo = require('./update_schedule_info') const taskScheduler = require('./task_scheduler') const register = async(username, password) => { const authResult = await AuthUtil.auth(username, password) if (authResult) { let user = await User.findOne({username: username}) const existed = !!user if (!existed) { const info = await AuthUtil.getUserInfo(username, password) user = new User({ username: username, password: password, info: info }) await user.save() taskScheduler.add(updateCourseInfo, user, 3600000) taskScheduler.add(updateCurriculumInfo, user, 3600000) taskScheduler.add(updateScheduleInfo, user, 3600000) } else if (existed && user.getPassword() !== password) { user.password = password user.save() } return [user, existed] } else { return [null, false] } } module.exports = register
/** * Created by hbzhang on 8/5/15. */ 'use strict'; angular.module('mean.helpers').factory('AllWidgetData',['$resource','$rootScope', function($resource,$rootScope) { var allwidgets=[ { name: 'Announcement', data: [] }, { name: 'Information', data: [] } ]; return { allwidgets:allwidgets }; }]);
import JoiBase from 'joi'; import {postHandlerFactory, getHandlerFactory} from './common'; import FullDateValidator from '../../../../shared/lib/joi-full-date-validator'; const Joi = JoiBase.extend(FullDateValidator); const schema = Joi.object().keys({ 'day': Joi.number().integer().min(1).max(31).required().label('Day') .meta({ componentType: 'numeric', fieldset: true, legendText:'What is your date of birth?', legendClass: 'legend-hidden' }) .options({ language: { number: { base: 'Please enter a valid day using numbers only', min: 'Please enter a valid day', max: 'Please enter a valid day' } } }), 'month': Joi.number().integer().min(1).max(12).required().label('Month').meta({ componentType: 'numeric' }).options({ language: { number: { base: 'Please enter a valid month using numbers only', min: 'Please enter a valid month', max: 'Please enter a valid month' } } }), 'year': Joi.number().integer().min(1885).max(2025).required().label('Year') .meta({ componentType: 'numeric', fieldsetEnd: true }) .options({ language: { number: { base: 'Please enter a valid year using numbers only', min: 'Please enter a year after 1885', max: 'Please enter a valid year' } } }), 'submit': Joi.any().optional().strip() }).fulldate(); const title = 'What is your date of birth?'; const key = 'dateOfBirth'; const slug = 'date-of-birth'; const defails = { hint: 'For example, 31 3 1980' }; const handlers = { GET: (prevSteps) => getHandlerFactory(key, title, schema, prevSteps, defails), POST: (prevSteps, nextSteps) => postHandlerFactory(key, title, schema, prevSteps, nextSteps, defails), }; /** * @type Step */ export default { key, slug, title, schema, handlers };
const gulp = require('gulp'); const size = require('gulp-size'); const sass = require('gulp-sass'); const plumber = require('gulp-plumber'); const cleanCss = require('gulp-clean-css'); const sourcemaps = require('gulp-sourcemaps'); const autoprefixer = require('gulp-autoprefixer'); /** * Copy app.css to dist/ without any minification */ gulp.task('styles:dev', ['styles:scss'], () => { gulp.src('app/styles/app.css') .pipe(gulp.dest('dist/css/')); }); /** * Miniy app.css (which was created in the styles:scss task). Copy the result to dist/. */ gulp.task('styles:prod', ['styles:scss'], () => { gulp.src('app/styles/app.css') .pipe(size({ showFiles: true, title: 'size of initial css' })) .pipe(cleanCss({processImport: false})) .pipe(size({ showFiles: true, title: 'size of css after minify' })) .pipe(gulp.dest('dist/css/')); }); /** * Compile app.scss into a CSS file. This is a synchronous task (using the "return a stream" * paradigm) so that it will finish before "styles:dev" or "styles:prod" attempt to copy the * generated CSS. */ gulp.task('styles:scss', () => { return gulp.src('app/styles/app.scss') .pipe(size({ showFiles: true, title: 'initial scss files' })) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(sass({ errLogToConsole: true })) .pipe(sourcemaps.write()) .pipe(size({ showFiles: true, title: 'compiled css files with sourcemaps' })) .pipe(gulp.dest('app/styles/')); }); /** * Watch for changes to our SCSS files. If an SCSS file changes, run the 'styles:dev' task again. */ gulp.task('styles:watch', () => { gulp.watch('app/styles/**/*.scss', ['styles:dev']); });
import React, { Component } from 'react'; import axios from 'axios'; import { Router, Link } from 'react-router'; import { Button } from 'react-bootstrap'; export default class trueMenu extends Component { constructor(props) { super(); this.state = { displayCreateBoard: false, displayJoin: false, name: '', placeholder: 'Join a room', userId: 0, list: [], isValid: true }; this.handleName = this.handleName.bind(this); this.handleJoination = this.handleJoination.bind(this); } handleJoination(e) { e.preventDefault(); if(this.state.name === ''){ this.setState({placeholder: "Please enter a room name", isValid: false}) return; } else if (this.state.name.indexOf(' ') !== -1){ this.setState({placeholder: "Room names can not contain spaces", name: '', isValid: false}) return; }else if (/[^a-zA-Z0-9\-\/]/.test(this.state.name)) { this.setState({placeholder: "Special characters are not allowed", name: '', isValid: false}) return; } socket.emit('create board', {name: this.state.name}); window.location.assign('/#/code') } handleName(event) { window.roomName = event.target.value; this.setState({ name: event.target.value }); } render() { const logoStyle = { 'marginTop': '14%' } const imageSize = { width: '400px' } return ( <div className="center-roomselect" id="createroom"> <form style={logoStyle} className="animated fadeInUp" onSubmit={this.handleJoination}> <img style={imageSize} src="./media/codeout.png" /> <br /> <input placeholder={this.state.placeholder} value={this.state.name} onChange={(e) => this.handleName(e)} className={!this.state.isValid ? 'animated shake search-style' : 'search-style'} /> <p> <button className="btn btn-primary button-spacing" onClick={this.handleJoination}>Enter Room </button> </p> </form> </div> ) }; };
/* eslint-disable no-param-reassign */ import Vue from 'vue'; export default { namespaced: true, state: { cache: null, }, mutations: { setCache(state, value) { state.cache = value; }, }, actions: { get({ state, commit }, cache = true) { if (cache && state.cache) { return new Promise((resolve) => { resolve(state.cache); }); } return Vue.http.get('api/server/self-update').then( response => response.body, (response) => { if (response.status === 501) { return { current_version: null, latest_version: null, channel: 'dev', supported: false, error: null, }; } throw response; }, ).then((result) => { commit('setCache', result); return result; }); }, async latest() { const response = await Vue.http.get('https://download.contao.org/contao-manager/stable/contao-manager.version'); return response.body.version; }, }, };
$(function () { $('.imageUploadMultiple').each(function (index, item) { var $item = $(item); var $group = $item.closest('.form-group'); var $innerGroup = $item.find('.form-group'); var $errors = $item.find('.errors'); var $input = $item.find('.imageValue'); var flow = new Flow({ target: $item.data('target'), testChunks: false, chunkSize: 1024 * 1024 * 1024, query: { _token: $item.data('token') } }); var updateValue = function () { var values = []; $item.find('img[data-value]').each(function () { values.push($(this).data('value')); }); $input.val(values.join(',')); }; flow.assignBrowse($item.find('.imageBrowse')); flow.on('filesSubmitted', function (file) { flow.upload(); }); flow.on('fileSuccess', function (file, message) { flow.removeFile(file); $errors.html(''); $group.removeClass('has-error'); var result = $.parseJSON(message); var template = $($('#thumbnail_template').html()); template.find('img').attr('src', result.url).attr('data-value', result.value); $innerGroup.append(template); updateValue(); }); flow.on('fileError', function (file, message) { flow.removeFile(file); var response = $.parseJSON(message); var errors = ''; $.each(response, function (index, error) { errors += '<p class="help-block">' + error + '</p>' }); $errors.html(errors); $group.addClass('has-error'); }); $item.on('click', '.imageRemove', function (e) { e.preventDefault(); $(this).closest('.imageThumbnail').remove(); updateValue(); }); $innerGroup.sortable({ onUpdate: function () { updateValue(); } }); }); });
export class App { constructor (router) { this.router = router; } configureRouter (config, router) { this.router = router; config.map([ { name: 'orders', route: ['', 'orders'], moduleId: 'modules/orders/index', nav: true, title: "Orders" } , { name: 'order', route: 'order/:name', moduleId: 'modules/order/index' } ]); } }
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import '../resources/fonts/fonts.global.css'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
function solve(input){ let result=input.toString(); let sum=0; let count=0; while(input>=1){ sum+=input%10; count++; input=Math.floor(input/10); } while(sum/count<=5){ sum+=9; count++; result+='9'; } console.log(result) } solve(101);
import Zip from 'adm-zip'; /** * @param {Type} * @return {Type} */ export default function (filePath) { let courseZip = new Zip(filePath); let courseFileScanner = { getZipObject: () => { return courseZip; }, getCourseFiles: () => { return courseZip.getEntries().filter(courseFileScanner._isCourseFile).map(courseFileScanner._getCourseFileId); }, _isCourseFile: (file) => { return file.entryName.match(/^(?=.*\bcsfiles\/home_dir\b)(?!.*\b.xml\b).*$/ig); }, _getCourseFileId: (file) => { let fileName = file.entryName; let startIndex = fileName.lastIndexOf('xid-') + 4; let endIndex = fileName.indexOf('_', startIndex); file.courseFileId = fileName.substring(startIndex, endIndex); return file; }, getDatFiles: () => { return courseZip.getEntries().filter(courseFileScanner._isDatFile); }, _isDatFile: (file) => { return file.entryName.match(/^(?=.*res)(?=.*\b\.dat\b).*$/g); } }; return courseFileScanner; }
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ // ESLint configuration // http://eslint.org/docs/user-guide/configuring module.exports = { parser: 'babel-eslint', extends: [ 'airbnb', 'plugin:flowtype/recommended', 'plugin:css-modules/recommended', 'prettier', 'prettier/flowtype', 'prettier/react', ], plugins: ['flowtype', 'css-modules', 'prettier'], globals: { __DEV__: true, }, env: { browser: true, }, rules: { // `js` and `jsx` are common extensions // `mjs` is for `universal-router` only, for now 'import/extensions': [ 'error', 'always', { js: 'never', jsx: 'never', mjs: 'never', }, ], // Not supporting nested package.json yet // https://github.com/benmosher/eslint-plugin-import/issues/458 'import/no-extraneous-dependencies': 'off', // Recommend not to leave any console.log in your code // Use console.error, console.warn and console.info instead 'no-console': [ 'error', { allow: ['warn', 'error', 'info'], }, ], // a11y removed rule, ignore them 'jsx-a11y/href-no-hash': 'off', // https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/308#issuecomment-322954274 'jsx-a11y/label-has-for': 'warn', // Allow js files to use jsx syntax, too 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }], // Automatically convert pure class to function by // babel-plugin-transform-react-pure-class-to-function // https://github.com/kriasoft/react-starter-kit/pull/961 'react/prefer-stateless-function': 'off', // ESLint plugin for prettier formatting // https://github.com/prettier/eslint-plugin-prettier 'prettier/prettier': [ 'error', { // https://github.com/prettier/prettier#options singleQuote: true, trailingComma: 'all', }, ], }, settings: { // Allow absolute paths in imports, e.g. import Button from 'components/Button' // https://github.com/benmosher/eslint-plugin-import/tree/master/resolvers 'import/resolver': { node: { moduleDirectory: ['node_modules', 'src'], }, }, }, };
function getShortMessages(messages) { return messages.map(function(m) { return m.message; }).filter(function(message) { return message.length < 50; }) } module.exports = getShortMessages;
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; console.log(response); // And redirect to the index page $location.path('/'); }).error(function(response) { $scope.error = response.message; }); }; } ]);
/* ======================================================================== * DOM-based Routing * Based on http://goo.gl/EUTi53 by Paul Irish * * Only fires on body classes that match. If a body class contains a dash, * replace the dash with an underscore when adding it to the object below. * * .noConflict() * The routing is enclosed within an anonymous function so that you can * always reference jQuery with $, even when in .noConflict() mode. * ======================================================================== */ (function($) { // Use this variable to set up the common and page specific functions. If you // rename this variable, you will also need to rename the namespace below. var Sage = { // All pages 'common': { init: function() { // JavaScript to be fired on all pages }, finalize: function() { // JavaScript to be fired on all pages, after page specific JS is fired } }, // Home page 'home': { init: function() { $("#slide0").addClass("active"); $("#data0").addClass("active"); // JavaScript to be fired on the about us page } }, 'process': { init: function() { $("#design_slide0").addClass("active"); $("#design_data0").addClass("active"); $("#construction_slide0").addClass("active"); $("#administration_slide0").addClass("active"); // JavaScript to be fired on the about us page } }, // About us page, note the change from about-us to about_us. 'single_project': { init: function() { $("#slide0").addClass("active"); $("#data0").addClass("active"); // JavaScript to be fired on the about us page } } }; // The routing fires all common scripts, followed by the page specific scripts. // Add additional events for more control over timing e.g. a finalize event var UTIL = { fire: function(func, funcname, args) { var fire; var namespace = Sage; funcname = (funcname === undefined) ? 'init' : funcname; fire = func !== ''; fire = fire && namespace[func]; fire = fire && typeof namespace[func][funcname] === 'function'; if (fire) { namespace[func][funcname](args); } }, loadEvents: function() { // Fire common init JS UTIL.fire('common'); // Fire page-specific init JS, and then finalize JS $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) { UTIL.fire(classnm); UTIL.fire(classnm, 'finalize'); }); // Fire common finalize JS UTIL.fire('common', 'finalize'); } }; // Load Events $(document).ready(UTIL.loadEvents); $(function(){ $('#carousel-project-page').carousel({ interval:false }); }); })(jQuery); // Fully reference jQuery after this point.
//{block name="backend/connect/store/import/local_products"} Ext.define('Shopware.apps.Connect.store.import.LocalProducts', { extend : 'Ext.data.Store', autoLoad: false, pageSize: 10, fields: [ { name: 'Article_id', type: 'integer' }, { name: 'Detail_number', type: 'string' }, { name: 'Article_name', type: 'string' }, { name: 'Supplier_name', type: 'string' }, { name: 'Article_active', type: 'boolean' }, { name: 'Detail_purchasePrice', type: 'float' }, { name: 'Price_price', type: 'float' }, { name: 'Tax_name', type: 'string' }, { name: 'Attribute_connectMappedCategory', type: 'int' } ], proxy : { type : 'ajax', api : { read : '{url controller=Import action=loadBothArticleTypes}' }, reader : { type : 'json', root: 'data', totalProperty:'total' } } }); //{/block}
import Microcosm from 'microcosm' describe('History node children', function() { const action = n => n it('can determine children', function() { const repo = new Microcosm() const a = repo.append(action) const b = repo.append(action) repo.checkout(a) const c = repo.append(action) expect(a.children.map(n => n.id)).toEqual([b.id, c.id]) }) it('does not lose children when checking out nodes on the left', function() { const repo = new Microcosm() repo.append(action) const b = repo.append(action) const c = repo.append(action) repo.checkout(b) const d = repo.append(action) expect(b.children).toEqual([c, d]) }) it('does not lose children when checking out nodes on the right', function() { const repo = new Microcosm() repo.append(action) const b = repo.append(action) const c = repo.append(action) repo.checkout(b) const d = repo.append(action) repo.checkout(c) expect(b.children).toEqual([c, d]) }) })
// The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design import {Parser} from "./state" import {types as tt} from "./tokentype" import {lineBreak} from "./whitespace" export class TokContext { constructor(token, isExpr, preserveSpace, override) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override } } export const types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", true), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, p => p.readTmplToken()), new TokContext("function", true); } const pp = Parser.prototype; pp.initialContext = function() { return [types.b_stat] }; pp.braceIsBlock = function(prevType) { if (prevType === tt.colon) { let parent = this.curContext(); if (parent === types.b_stat || parent === types.b_expr) return !parent.isExpr } if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true; if (prevType == tt.braceL) return this.curContext() === types.b_stat; return !this.exprAllowed }; pp.updateContext = function(prevType) { let update, type = this.type; if (type.keyword && prevType == tt.dot) this.exprAllowed = false; else if (update = type.updateContext) update.call(this, prevType); else this.exprAllowed = type.beforeExpr }; // Token-specific context update code tt.parenR.updateContext = tt.braceR.updateContext = function() { if (this.context.length == 1) { this.exprAllowed = true; return } let out = this.context.pop(); if (out === types.b_stat && this.curContext() === types.f_expr) { this.context.pop(); this.exprAllowed = false } else if (out === types.b_tmpl) { this.exprAllowed = true } else { this.exprAllowed = !out.isExpr } }; tt.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true }; tt.dollarBraceL.updateContext = function() { this.context.push(types.b_tmpl); this.exprAllowed = true }; tt.parenL.updateContext = function(prevType) { let statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true }; tt.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; tt._function.updateContext = function() { if (this.curContext() !== types.b_stat) this.context.push(types.f_expr); this.exprAllowed = false }; tt.backQuote.updateContext = function() { if (this.curContext() === types.q_tmpl) this.context.pop(); else this.context.push(types.q_tmpl); this.exprAllowed = false };
import {eventMixin} from "./event" export class MarkedRange { constructor(from, to, options) { this.options = options || {} this.from = from this.to = to } clear() { this.signal("removed", this.from) this.from = this.to = null } } eventMixin(MarkedRange) class RangeSorter { constructor() { this.sorted = [] } find(at) { let min = 0, max = this.sorted.length for (;;) { if (max < min + 10) { for (let i = min; i < max; i++) if (this.sorted[i].at.cmp(at) >= 0) return i return max } let mid = (min + max) >> 1 if (this.sorted[mid].at.cmp(at) > 0) max = mid else min = mid } } insert(obj) { this.sorted.splice(this.find(obj.at), 0, obj) } remove(at, range) { let pos = this.find(at) for (let dist = 0;; dist++) { let leftPos = pos - dist - 1, rightPos = pos + dist if (leftPos >= 0 && this.sorted[leftPos].range == range) { this.sorted.splice(leftPos, 1) return } else if (rightPos < this.sorted.length && this.sorted[rightPos].range == range) { this.sorted.splice(rightPos, 1) return } } } resort() { for (let i = 0; i < this.sorted.length; i++) { let cur = this.sorted[i] let at = cur.at = cur.type == "open" ? cur.range.from : cur.range.to let pos = i while (pos > 0 && this.sorted[pos - 1].at.cmp(at) > 0) { this.sorted[pos] = this.sorted[pos - 1] this.sorted[--pos] = cur } } } } export class RangeStore { constructor(pm) { this.pm = pm this.ranges = [] this.sorted = new RangeSorter } addRange(range) { this.ranges.push(range) this.sorted.insert({type: "open", at: range.from, range: range}) this.sorted.insert({type: "close", at: range.to, range: range}) this.pm.markRangeDirty(range) } removeRange(range) { let found = this.ranges.indexOf(range) if (found > -1) { this.ranges.splice(found, 1) this.sorted.remove(range.from, range) this.sorted.remove(range.to, range) this.pm.markRangeDirty(range) range.clear() } } transform(mapping) { for (let i = 0; i < this.ranges.length; i++) { let range = this.ranges[i] range.from = mapping.map(range.from, range.options.inclusiveLeft ? -1 : 1).pos range.to = mapping.map(range.to, range.options.inclusiveRight ? 1 : -1).pos let diff = range.from.cmp(range.to) if (range.options.clearWhenEmpty !== false && diff >= 0) { this.removeRange(range) i-- } else if (diff > 0) { range.to = range.from } } this.sorted.resort() } activeRangeTracker() { return new RangeTracker(this.sorted.sorted) } } class RangeTracker { constructor(sorted) { this.sorted = sorted this.pos = 0 this.current = [] } advanceTo(pos) { let next while (this.pos < this.sorted.length && (next = this.sorted[this.pos]).at.cmp(pos) <= 0) { let className = next.range.options.className if (!className) continue if (next.type == "open") this.current.push(className) else this.current.splice(this.current.indexOf(className), 1) this.pos++ } } nextChangeBefore(pos) { for (;;) { if (this.pos == this.sorted.length) return null let next = this.sorted[this.pos] if (!next.range.options.className) this.pos++ else if (next.at.cmp(pos) >= 0) return null else return next.at.offset } } }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('receive-for', 'Integration | Component | receive for', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" this.render(hbs`{{receive-for}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" this.render(hbs` {{#receive-for}} {{else}} template block text {{/receive-for}} `); assert.equal(this.$().text().trim(), 'template block text'); });
var process = function (json) { var x = 0, r = Raphael("chart", 2350, 550), labels = {}, textattr = {"font": '9px "Arial"', stroke: "none", fill: "#fff"}, pathes = {}, nmhldr = $("#name")[0], nmhldr2 = $("#name2")[0], lgnd = $("#legend")[0], usrnm = $("#username")[0], lgnd2 = $("#legend2")[0], usrnm2 = $("#username2")[0], plchldr = $("#placeholder")[0]; function finishes() { for (var i in json.authors) { var start, end; for (var j = json.buckets.length - 1; j >= 0; j--) { var isin = false; for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) { isin = isin || (json.buckets[j].i[k][0] == i); } if (isin) { end = j; break; } } for (var j = 0, jj = json.buckets.length; j < jj; j++) { var isin = false; for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) { isin = isin || (json.buckets[j].i[k][0] == i); }; if (isin) { start = j; break; } } for (var j = start, jj = end; j < jj; j++) { var isin = false; for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) { isin = isin || (json.buckets[j].i[k][0] == i); } if (!isin) { json.buckets[j].i.push([i, 0]); } } } } function block() { var p, h; finishes(); for (var j = 0, jj = json.buckets.length; j < jj; j++) { var users = json.buckets[j].i; h = 0; for (var i = 0, ii = users.length; i < ii; i++) { p = pathes[users[i][0]]; if (!p) { p = pathes[users[i][0]] = {f:[], b:[]}; } p.f.push([x, h, users[i][1]]); p.b.unshift([x, h += Math.max(Math.round(Math.log(users[i][1]) / Math.log(1.2) * 2.5), 1)]); h += 2; } var dt = new Date(json.buckets[j].d * 1000); var dtext = dt.getDate() + "." + (dt.getMonth()+1) + "." + dt.getFullYear(); r.text(x + 25, h + 10, dtext).attr({"font": '9px "Arial"', stroke: "none", fill: "#aaa"}); x += 100; } var c = 0; for (var i in pathes) { labels[i] = r.set(); var clr = Raphael.getColor(); pathes[i].p = r.path().attr({fill: clr, stroke: clr}); var path = "M".concat(pathes[i].f[0][0], ",", pathes[i].f[0][1], "L", pathes[i].f[0][0] + 50, ",", pathes[i].f[0][1]); var th = Math.round(pathes[i].f[0][1] + (pathes[i].b[pathes[i].b.length - 1][1] - pathes[i].f[0][1]) / 2 + 3); labels[i].push(r.text(pathes[i].f[0][0] + 25, th, pathes[i].f[0][2]).attr(textattr)); var X = pathes[i].f[0][0] + 50, Y = pathes[i].f[0][1]; for (var j = 1, jj = pathes[i].f.length; j < jj; j++) { path = path.concat("C", X + 20, ",", Y, ","); X = pathes[i].f[j][0]; Y = pathes[i].f[j][1]; path = path.concat(X - 20, ",", Y, ",", X, ",", Y, "L", X += 50, ",", Y); th = Math.round(Y + (pathes[i].b[pathes[i].b.length - 1 - j][1] - Y) / 2 + 3); if (th - 9 > Y) { labels[i].push(r.text(X - 25, th, pathes[i].f[j][2]).attr(textattr)); } } path = path.concat("L", pathes[i].b[0][0] + 50, ",", pathes[i].b[0][1], ",", pathes[i].b[0][0], ",", pathes[i].b[0][1]); for (var j = 1, jj = pathes[i].b.length; j < jj; j++) { path = path.concat("C", pathes[i].b[j][0] + 70, ",", pathes[i].b[j - 1][1], ",", pathes[i].b[j][0] + 70, ",", pathes[i].b[j][1], ",", pathes[i].b[j][0] + 50, ",", pathes[i].b[j][1], "L", pathes[i].b[j][0], ",", pathes[i].b[j][1]); } pathes[i].p.attr({path: path + "z"}); labels[i].hide(); var current = null; (function (i) { pathes[i].p.mouseover(function () { if (current != null) { labels[current].hide(); } current = i; labels[i].show(); pathes[i].p.toFront(); labels[i].toFront(); usrnm2.innerHTML = json.authors[i].n + " <em>(" + json.authors[i].c + " votes, " + json.authors[i].a + " for, " + json.authors[i].d + " against)</em>"; lgnd2.style.backgroundColor = pathes[i].p.attr("fill"); nmhldr2.className = ""; plchldr.className = "hidden"; }); })(i); } } if (json.error) { alert("Project not found. Try again."); } else { block(); } }; $(function () { process(json); });
import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions'; import mutations from './mutations'; import state from './state'; Vue.use(Vuex); export default () => new Vuex.Store({ actions, mutations, state, });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'templates', 'km', { button: 'ពុម្ព​គំរូ', emptyListMsg: '(មិន​មាន​ពុម្ព​គំរូ​ត្រូវ​បាន​កំណត់)', insertOption: 'ជំនួស​ក្នុង​មាតិកា​បច្ចុប្បន្ន', options: 'ជម្រើស​ពុម្ព​គំរូ', selectPromptMsg: 'សូម​រើស​ពុម្ព​គំរូ​ដើម្បី​បើក​ក្នុង​កម្មវិធី​សរសេរ​អត្ថបទ', title: 'ពុម្ព​គំរូ​មាតិកា' });
var twimap; twimap = require("twimap"); var Twit = require("twit"); var util = require("util"); var _current_index = -1; var _followers_list ; var thanks_temp; thanks_temp = [ "Dear %s, thank you for following :)", "%s = awesome. Me = grateful for following :)", "Is there no limit to your awesomeness %s? Thank you for following!", "You can’t see me %s! but I’m totally doing a happy dance! Big thanks for following me on twitter :)", "hey %s!Do you practice being so wonderful? Thank you kindly for following." ]; // create twitter client twit_cli = new Twit({ consumer_key: "---consumer-key---" , consumer_secret: "---consumer-secret---" , access_token: "---access-token---" , access_token_secret: "---access-token-secret---" }); //config TWIMAP imap account twimap.configImap({ user : '---username---@gmail.com', password : '---password---', host : 'imap.gmail.com', port : 993, secure : true }); // stores last imap try var last_check = now(); //call this function periodically to get new followers //callback is called when new information is available function load_followers_priodically() { try{ twimap.followersAsync(last_check, function(result) { if(typeof result != "undefined" && result.length >=1){ //save it in our variable _followers_list = result; last_check = now(); msg_followers_thanks(); } },function (err){ // I command you to stay silent reset_values(); }); }catch(e){ //still... reset_values(); console.log(e); } } //this function iterates through followers listed in variable //_followers_list function msg_followers_thanks(){ //move cursor _current_index++; //if there is no followers OR finished messaging followers stop if(_current_index >= _followers_list.length ){ _current_index = -1; _followe_list = null; return; } //otherwise get user name from twitter twit_cli.get("users/show",{screen_name:_followers_list[_current_index]}, function (err,dt){ //clean up the name var dude = filter_name(dt.name); //message the user twit_cli.post("direct_messages/new" , {screen_name:_followers_list[_current_index],text:random_msg(dude)}, function (err,dt){ if(!err) console.log("done..."); //go for another round msg_followers_thanks(); }); }); } //cut names bigger that 40 characters function filter_name(name){ if ( typeof name == "undefined" || name=="" || name==null) name = "my friend"; if(name.length > 40 ) name = name.substr(0,40); return name; } //generate a random message function random_msg(name){ name = filter_name(name); return util.format(thanks_temp[Math.floor(Math.random()*10)%(thanks_temp.length-1)] , name); } //return current day function now() { var d; d = new Date(); return d.toUTCString(); } //reset values on error function reset_values(){ _current_index = -1; _followers_list = null; } // run safe and sound :| function run(){ _interval = setInterval(load_followers_priodically,1000*60*30); //run now , I can't wait ;) load_followers_priodically(); } //cheers to a happy running ;) run();
import { expect } from 'chai'; import { validateRegister, validateLogin } from '../../src/universal/validation/authValidation'; describe('validation', () => { describe('validateRegister', () => { it('passes for acceptable details', () => { const username = 'username'; const password = 'password'; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors).to.be.empty; }); it('fails with no username', () => { const username = ''; const password = 'password'; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors.username).to.equal('Please provide a username'); }); it('fails for a username with non alpha numeric or hypen', () => { const username = 'B4D4$$!!!!'; const password = 'password'; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen'); }); it('fails for a username with spaces', () => { const username = 'bad username'; const password = 'password'; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen'); }); it('fails with no password', () => { const username = 'username'; const password = ''; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors.password).to.equal('Please supply a password'); }); it('fails for a password under 6 characters', () => { const username = 'username'; const password = 'passw'; const email = 'valid@example.com'; const errors = validateRegister(username, password, email); expect(errors.password).to.equal('Please supply a password over 6 characters'); }); it('fails with no email', () => { const username = 'username'; const password = 'password'; const email = ''; const errors = validateRegister(username, password, email); expect(errors.email).to.equal('Please provide an email'); }); it('fails with an invalid email', () => { const username = 'username'; const password = 'password'; const email = '234567'; const errors = validateRegister(username, password, email); expect(errors.email).to.equal('Please provide a valid email address'); }); }); describe('validateLogin', () => { it('passes with both username and password', () => { const username = 'username'; const password = 'password'; const errors = validateLogin(username, password); expect(errors).to.be.empty; }); it('fails with no username', () => { const username = ''; const password = 'password'; const errors = validateLogin(username, password); expect(errors.username).to.equal('Please provide a username'); }); it('fails with no password', () => { const username = 'username'; const password = ''; const errors = validateLogin(username, password); expect(errors.password).to.equal('Please supply a password'); }); }); });
const NUM_HASHES = HASHES.length; function verify(id, accessCode) { var token = id.replace(/\s+/g, '').toLowerCase() + accessCode; for (var i = 0; i < NUM_HASHES; ++i) { var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1); if (/^https?:\/\/[^\s]+$/.test(result)) { window.location = result; return true; } } // Display denial $("#lit-header").removeClass("power-on"); document.getElementById("go").className = "denied"; document.getElementById("go").value = "Access Denied"; return false; } $(document).ready(function() { var state = false; var numAttempts = 0; $('#access-panel').on('submit', function(evt) { evt.preventDefault(); if (!state && numAttempts < 10) { state = true; $("#lit-header").addClass("power-on"); document.getElementById("go").className = ""; document.getElementById("go").value = "Verifying..."; numAttempts += 1; setTimeout(function() { verify($('#name').val(), $('#password').val()); state = false; }, 2000); } }); });
const Promise = require('bluebird'); const {expect} = require('chai'); const sinon = require('sinon'); const CMD = 'MODE'; describe(CMD, function () { let sandbox; const mockClient = { reply: () => Promise.resolve() }; const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient); beforeEach(() => { sandbox = sinon.sandbox.create().usingPromise(Promise); sandbox.spy(mockClient, 'reply'); }); afterEach(() => { sandbox.restore(); }); it('S // successful', () => { return cmdFn({command: {arg: 'S'}}) .then(() => { expect(mockClient.reply.args[0][0]).to.equal(200); }); }); it('Q // unsuccessful', () => { return cmdFn({command: {arg: 'Q'}}) .then(() => { expect(mockClient.reply.args[0][0]).to.equal(504); }); }); });
export { default } from './BottomNavigation'; export { default as BottomNavigationAction } from './BottomNavigationAction';
// @flow import * as React from 'react' import {StyleSheet, Image, Alert} from 'react-native' import {Column, Row} from '../components/layout' import {ListRow, Detail, Title} from '../components/list' import type {StoryType} from './types' type Props = { onPress: string => any, story: StoryType, thumbnail: false | number, } export class NewsRow extends React.PureComponent<Props> { _onPress = () => { if (!this.props.story.link) { Alert.alert('There is nowhere to go for this story') return } this.props.onPress(this.props.story.link) } render() { const {story} = this.props const thumb = this.props.thumbnail !== false ? story.featuredImage ? {uri: story.featuredImage} : this.props.thumbnail : null return ( <ListRow arrowPosition="top" onPress={this._onPress}> <Row alignItems="center"> {thumb !== null ? ( <Image source={thumb} style={styles.image} /> ) : null} <Column flex={1}> <Title lines={2}>{story.title}</Title> <Detail lines={3}>{story.excerpt}</Detail> </Column> </Row> </ListRow> ) } } const styles = StyleSheet.create({ image: { borderRadius: 5, marginRight: 15, height: 70, width: 70, }, })
{ var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== "unknown") { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }
// saskavi.js // client side script for calling saskavi functions // (function() { "use strict"; var Saskavi = function(fbRoot, uid) { if (!uid) throw new Error("uid not supplied, an authenticated user id is required"); this.rpcBus = fbRoot.child("__saskavi-rpc").child(uid); }; function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } Saskavi.prototype.call = function() { var params = Array.prototype.slice.call(arguments, 0); var funcName = params[0]; if (!isFunction(params[params.length - 1])) throw new Error("Callback function as last parameter is required, promises may come soon"); var cb = params[params.length - 1]; console.log(params); var ps = params.slice(1, params.length - 1); console.log(ps); var rpcData = { "function": funcName, "args": ps }; var rpcRef = this.rpcBus.push(rpcData); var resultRef = rpcRef.child('result'); resultRef.on('value', function(snapshot) { if (snapshot !== null && snapshot.val() !== null) { resultRef.off('value'); cb(null, snapshot.val()); } }); }; window.Saskavi = Saskavi; })();
function checkNeighbours(arr, i) { var result, inputArray, position; if (arr == null) { inputArray = document.getElementById('numbersArray2').value.split(' '), position = +document.getElementById('num6').value; } else { inputArray = arr, position = i; } if ((position === 0 || position === inputArray.length) && arr == null) { result = 'Not enough neighbours!'; document.getElementById('result6').innerHTML = result; return result; } if ((+inputArray[position] > +inputArray[position - 1]) && (+inputArray[position] > +inputArray[position + 1])) result = true; else result = false; if (arr == null) document.getElementById('result6').innerHTML = result; return result; }
'use strict'; var $ = require('./main') , getViewportRect = require('./get-viewport-rect') , getElementRect = require('./get-element-rect'); module.exports = $.showInViewport = function (el/*, options*/) { var vpRect = getViewportRect() , elRect = getElementRect(el) , options = Object(arguments[1]) , padding = isNaN(options.padding) ? 0 : Number(options.padding) , elTopLeft = { x: elRect.left, y: elRect.top } , elBottomRight = { x: elRect.left + elRect.width, y: elRect.top + elRect.height } , vpTopLeft = { x: vpRect.left + padding, y: vpRect.top + padding } , vpBottomRight = { x: vpRect.left + vpRect.width - padding, y: vpRect.top + vpRect.height - padding } , diffPoint = { x: 0, y: 0 }, diff; if (elBottomRight.x > vpBottomRight.x) { // right beyond diff = elBottomRight.x - vpBottomRight.x; elTopLeft.x -= diff; elBottomRight.x -= diff; diffPoint.x -= diff; } if (elBottomRight.y > vpBottomRight.y) { // bottom beyond diff = elBottomRight.y - vpBottomRight.y; elTopLeft.y -= diff; elBottomRight.y -= diff; diffPoint.y -= diff; } if (elTopLeft.x < vpTopLeft.x) { // left beyond diff = vpTopLeft.x - elTopLeft.x; elTopLeft.x += diff; elBottomRight.x += diff; diffPoint.x += diff; } if (elTopLeft.y < vpTopLeft.y) { // top beyond diff = vpTopLeft.y - elTopLeft.y; elTopLeft.y += diff; elBottomRight.y += diff; diffPoint.y += diff; } if (diffPoint.x) el.style.left = (el.offsetLeft + diffPoint.x) + "px"; if (diffPoint.y) el.style.top = (el.offsetTop + diffPoint.y) + "px"; };
'use strict'; require('babel/register'); // controls application file let app = require('app'); // control main window let BrowserWindow = require('browser-window'); let mainWindow = null; // quite when all windows are closed app.on('window-all-closed', () => { if (process.platform != 'darwin') { app.quit(); } }); // This is called when Electron is ready to create windows app.on('ready', () => { // create the main window mainWindow = new BrowserWindow({ width: 800, height: 600 }); // load main file mainWindow.loadUrl(`file://${__dirname}/index.html`); // open dev tools mainWindow.openDevTools(); // when the window is closed mainWindow.on('close', () => { // clean the window object for garbage collector mainWindow = null; }); });
[comment /**] [comment Plain text doesn't have any special ] [comment indentation. {][comment&tag @link][comment foo}] [comment&tag @fileoverview][comment Doesn't have any special] [comment indentation.] [comment&tag @see][comment https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler] [comment&tag @constructor] [comment&tag @foo] [comment&tag @param][comment {] [comment * ][comment&type !Foo][comment } ] [comment * ][comment&def param][comment Some ] [comment description.] [comment&tag @param][comment {][comment&type {] [comment ][comment&type foo: objectRulesApplyAndParamNameIsRequired}][comment }] [comment ][comment&def Desc] [comment */] [string "use strict"]
var path = require('path') var AtomicFile = require('atomic-file') function id (e) { return e } var none = { encode: id, decode: id } module.exports = function (dir, name, codec) { codec = codec || require('flumecodec/json') var af = AtomicFile(path.join(dir, name+'.json'), '~', none) var self return self = { size: null, get: function (cb) { af.get(function (err, value) { if(err) return cb(err) if(value == null) return cb() try { self.size = value.length value = codec.decode(value) value.size = self.size } catch(err) { return cb(err) } cb(null, value) }) }, set: function (value, cb) { value = codec.encode(value) self.size = value.length af.set(value, cb) }, destroy: function (cb) { value = null self.size = 0 af.destroy(cb) } } }
angular.module('ModuleGlobal').service('LoginService', ['$http', 'urlService', function($http, urlService) { var self = this; var url = urlService.getLoginUrl(); var connected = false; self.identifier = ''; self.isConnected = function() { return connected; }; self.connect = function(identifier, password, remember) { var logs = { login : identifier, mdp : password, }; return $http.post(url, logs).then(function(response) { connected = true; if (remember) self.identifier = identifier; else self.identifier = ''; return {connected: true, status: response.status}; }, function(response) { return {connected: false, status: response.status}; }); }; self.disconnect = function() { connected = false; }; }]);
import React from 'react'; import {Link} from "react-router"; import Subheading from '../components/Subheading'; import Portfolio4col from '../components/Portfolio/Portfolio4col'; export default class Layout extends React.Component { constructor() { super(); this.state = { title:"Welcome to Momoware!", }; } changeTitle(title){ this.setState({title}); } navigate() { console.log(this.props); } render() { return( <div> <Subheading title="Portfolio4col"/> <Portfolio4col projectImgPic1="http://placehold.it/700x300" projectImgPic2="http://placehold.it/700x300" projectImgPic3="http://placehold.it/700x300" projectImgPic4="http://placehold.it/700x300" /> <Portfolio4col projectImgPic1="http://placehold.it/700x300" projectImgPic2="http://placehold.it/700x300" projectImgPic3="http://placehold.it/700x300" projectImgPic4="http://placehold.it/700x300" /> <Portfolio4col projectImgPic1="http://placehold.it/700x300" projectImgPic2="http://placehold.it/700x300" projectImgPic3="http://placehold.it/700x300" projectImgPic4="http://placehold.it/700x300" /> </div> ); } }
/*****************************************************************************/ /* PayRunResultModal: Event Handlers */ /*****************************************************************************/ import Ladda from 'ladda'; Template.PayRunResultModal.events({ }); /*****************************************************************************/ /* PayRunResultModal: Helpers */ /*****************************************************************************/ Template.PayRunResultModal.helpers({ }); /*****************************************************************************/ /* PayRunResultModal: Lifecycle Hooks */ /*****************************************************************************/ Template.PayRunResultModal.onCreated(function () { let self = this; }); Template.PayRunResultModal.onRendered(function () { }); Template.PayRunResultModal.onDestroyed(function () { });
/* global Mousetrap */ import { typeOf } from '@ember/utils'; import { get } from "@ember/object"; export function bindKeyboardShortcuts(context) { const shortcuts = get(context, 'keyboardShortcuts'); if (typeOf(shortcuts) !== 'object') { return; } context._mousetraps = []; Object.keys(shortcuts).forEach(function(shortcut) { const actionObject = shortcuts[shortcut]; let mousetrap; let preventDefault = true; function invokeAction(action, eventType) { let type = typeOf(action); let callback; if (type === 'string') { callback = function() { context.send(action); return preventDefault !== true; }; } else if (type === 'function') { callback = action.bind(context); } else { throw new Error('Invalid value for keyboard shortcut: ' + action); } mousetrap.bind(shortcut, callback, eventType); } if (typeOf(actionObject) === 'object') { if (actionObject.global === false) { mousetrap = new Mousetrap(document); } else if (actionObject.scoped) { if (typeOf(actionObject.scoped) === 'boolean') { mousetrap = new Mousetrap(get(context, 'element')); } else if (typeOf(actionObject.scoped) === 'string') { mousetrap = new Mousetrap( document.querySelector(actionObject.scoped) ); } } else if (actionObject.targetElement) { mousetrap = new Mousetrap(actionObject.targetElement); } else { mousetrap = new Mousetrap(document.body); } if (actionObject.preventDefault === false) { preventDefault = false; } invokeAction(actionObject.action, actionObject.eventType); } else { mousetrap = new Mousetrap(document.body); invokeAction(actionObject); } context._mousetraps.push(mousetrap); }); } export function unbindKeyboardShortcuts(context) { const _removeEvent = (object, type, callback) => { if (object.removeEventListener) { object.removeEventListener(type, callback, false); return; } object.detachEvent('on' + type, callback); }; Array.isArray(context._mousetraps) && context._mousetraps.forEach(mousetrap => { // manually unbind JS event _removeEvent(mousetrap.target, 'keypress', mousetrap._handleKeyEvent); _removeEvent(mousetrap.target, 'keydown', mousetrap._handleKeyEvent); _removeEvent(mousetrap.target, 'keyup', mousetrap._handleKeyEvent); mousetrap.reset(); }); context._mousetraps = []; }
/** * Transforms __ref to ref * @param {object} props * @returns {object} * @private */ export default (oldProps = {}) => { const { __ref, ...props } = oldProps if (!__ref) return oldProps return { ...props, ref: __ref } }
sdkaskdj
export var SKIP_DJ_START = 'moderation/SKIP_DJ_START'; export var SKIP_DJ_COMPLETE = 'moderation/SKIP_DJ_COMPLETE'; export var MOVE_USER_START = 'moderation/MOVE_USER_START'; export var MOVE_USER_COMPLETE = 'moderation/MOVE_USER_COMPLETE'; export var REMOVE_USER_START = 'moderation/REMOVE_USER_START'; export var REMOVE_USER_COMPLETE = 'moderation/REMOVE_USER_COMPLETE'; export var MUTE_USER_START = 'moderation/MUTE_USER_START'; export var MUTE_USER_COMPLETE = 'moderation/MUTE_USER_COMPLETE'; export var UNMUTE_USER_START = 'moderation/UNMUTE_USER_START'; export var UNMUTE_USER_COMPLETE = 'moderation/UNMUTE_USER_COMPLETE'; export var BAN_USER_START = 'moderation/BAN_USER_START'; export var BAN_USER_COMPLETE = 'moderation/BAN_USER_COMPLETE'; export var ADD_USER_ROLES_START = 'moderation/ADD_USER_ROLES_START'; export var ADD_USER_ROLES_COMPLETE = 'moderation/ADD_USER_ROLES_COMPLETE'; export var REMOVE_USER_ROLES_START = 'moderation/REMOVE_USER_ROLES_START'; export var REMOVE_USER_ROLES_COMPLETE = 'moderation/REMOVE_USER_ROLES_COMPLETE'; //# sourceMappingURL=moderation.js.map
export { default } from 'supertree-auth/login/serializer';
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import './GridItem.css'; const placeholder = require('../../assets/imgholder.png'); class GridItem extends Component { static defaultProps = { aspect: "cover", }; constructor(props) { super(props); // Check if the img value is null; if so we need to input placeholder let img = this.props.img; let empty = false; if(img == null) { img = placeholder; empty = true; } this.state = { imageStyle: { backgroundImage: "url(" + img + ")", // Use the given backgroundSize unless using placeholder backgroundSize: empty ? "cover" : this.props.aspect } } } render() { return ( <Link to={ this.props.url } className="grid-item"> <div className="grid-item-container"> <div className="cover-image" style={this.state.imageStyle}> <div className="item-detail-list"> { this.props.details.map( d => <div key={d.title} className="item"> <div className="item-detail-title">{d.title}</div> <div className="item-detail-content">{d.content}</div> </div> ) } </div> </div> <div className="item-detail"> <div className="item-title">{ this.props.name.length > 23 ? this.props.name.substring(0, 20) + "..." : this.props.name }</div> </div> </div> </Link> ); } } export default GridItem;
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('wpsite generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
const jwt = require("jsonwebtoken"); module.exports = (UserModel, Config, CryptoHelper) => { function _transformUser (user) { return { "id": user._id, "name": user.name, "isAdmin": user.isAdmin, "created": user.createdAt, "updated": user.updatedAt } } async function signIn (username, userpassword) { // search for username const foundUser = await UserModel.findOne({ name: username }).lean(); // validate founduser if (!foundUser) throw new Error("Authentication failed. User not found.") if (userpassword !== CryptoHelper.decrypt(foundUser.passwordHash)) throw new Error("Authentication failed. Wrong password."); // create a token const token = await jwt.sign(foundUser, Config.tokenSecret, { expiresIn: Config.tokenExpires, issuer: Config.tokenIssuer }); // delete password before return the user delete foundUser.passwordHash; // return token and user return { token: token, user: this._transformUser(foundUser) } } async function signUp (username, userpassword, isAdmin) { // try to find the user const foundUser = await UserModel.findOne({name: username}).lean(); // check if user is available if (foundUser) throw new Error("Username is already registered. Please use another Username."); // create new User object const newUser = new UserModel({ name: username, passwordHash: CryptoHelper.encrypt(userpassword), isAdmin: isAdmin }); // save new User object const createdUser = await newUser.save(); // delete password before return the user delete createdUser.passwordHash; // return user return { user: this._transformUser(createdUser) } } return { _transformUser, signIn, signUp } }
var express = require('express'); var app = express(); app.use(function(req,res,next){ console.log(req.url); next(); }); app.all('/jsonp',function(req,res){ var data = req.query; var callback = data.cb; res.send(callback+'({s:["a","a2","a3"]})'); }); app.listen(8080);
class Button { constructor(arg) { arg.type = 'button' this.element = buildElement(arg) this.addTo = function(parentId) { var parent = document.getElementById(parentId) parent.appendChild(this.element) } } } class Input { constructor(arg) { arg.type = 'input' this.element = buildElement(arg) this.addTo = function(parentId) { var parent = document.getElementById(parentId) parent.appendChild(this.element) } } } class Header { constructor(arg) { var headerWrapping = buildElement({type: 'div', attributes: {id: 'header-wrapping'}}) headerWrapping.appendChild(buildElement({type: 'h1', attributes: {id: 'header-title'}, innerHTML: arg.title || 'Titel'})) headerWrapping.appendChild(buildElement({type: 'div', attributes: {id: 'header-actions'}})) document.body.appendChild(headerWrapping) this.setTitle = function(newTitle) { document.getElementById('header-title').innerHTML = newTitle } this.remove = function() { this.parentNode.removeChild(this) } } } function buildElement(arg) { if(typeof arg.type == 'undefined') {throw new Error(['Missing build arguments'])} var element = document.createElement(arg.type) element.appendChild(document.createTextNode(arg.innerHTML || '')) for(var key in arg.attributes) { element.setAttribute(key, arg.attributes[key]) } var style = "" for(var key in arg.styles) { style = style + key + ': ' + arg.styles[key] + '; ' } if(style.length > 0) { element.setAttribute('style', style) } return element }
var mongo = require('../'); var db = mongo.db('192.168.0.103/test'); // var db = mongo.db('127.0.0.1/test'); var myconsole = require('myconsole'); var foo = db.collection('foo'); setInterval(function() { foo.insert({foo:'foo'}, function(err, result){ if(err) return myconsole.error(err); foo.count(function(err, count){ if(err) return myconsole.error(err); myconsole.log('count: %d', count); foo.find().limit(10).toArray(function(err, arr) { if(err) return myconsole.error(err); myconsole.log('arr: %d', arr.length); }) }) }) }, 500); process.on('SIGINT', function(){ myconsole.log('SIGINT') foo.drop(function(err){ if(err) myconsole.error(err); process.exit(); }) })
// Only publish invitation codes for the logged in user Meteor.publish("invitations", function (all) { if(!this.userId) return []; // XXX in the future the admin page requires to fetch // all invitations. Then do somehting with 'all'. return Invitations.find({$or: [ {broadcastUser: this.userId}, {receivingUser: this.userId} ]}); });
const {CookieJar} = require('tough-cookie'); const {cookieToString, jarFromCookies, cookiesFromJar} = require('..'); describe('jarFromCookies()', () => { it('returns valid cookies', done => { const jar = jarFromCookies([{ key: 'foo', value: 'bar', domain: 'google.com' }]); jar.store.getAllCookies((err, cookies) => { expect(err).toBeNull(); expect(cookies[0].domain).toEqual('google.com'); expect(cookies[0].key).toEqual('foo'); expect(cookies[0].value).toEqual('bar'); expect(cookies[0].creation instanceof Date).toEqual(true); expect(cookies[0].expires).toEqual('Infinity'); done(); }); }); it('handles malformed JSON', () => { const jar = jarFromCookies('not a jar'); expect(jar.constructor.name).toBe('CookieJar'); }); }); describe('cookiesFromJar()', () => { it('returns valid jar', async () => { const d = new Date(); const initialCookies = [{ key: 'bar', value: 'baz', domain: 'insomnia.rest', expires: d }, { // This one will fail to parse, and be skipped bad: 'cookie' }]; const jar = CookieJar.fromJSON({cookies: initialCookies}); const cookies = await cookiesFromJar(jar); expect(cookies[0].domain).toBe('insomnia.rest'); expect(cookies[0].key).toBe('bar'); expect(cookies[0].value).toBe('baz'); expect(cookies[0].creation).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/); expect(cookies[0].expires).toEqual(d.toISOString()); }); it('handles bad jar', async () => { const jar = CookieJar.fromJSON({cookies: []}); // MemoryStore never actually throws errors, so lets mock the // function to force it to this time. jar.store.getAllCookies = cb => cb(new Error('Dummy Error')); const cookies = await cookiesFromJar(jar); // Cookies failed to p expect(cookies.length).toBe(0); }); });
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import { Card, CardText } from 'material-ui/Card'; import IconButton from 'material-ui/IconButton'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import FlatButton from 'material-ui/FlatButton'; import AutoComplete from 'material-ui/AutoComplete'; import LoadingIndicator from '../../components/LoadingIndicator'; import CategorySelector from '../../components/CategorySelector'; const blockStyle = { display: 'block' } class EditReco extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(); this.state = { ...props.reco }; this.handleNameChange = this.handleNameChange.bind(this); this.handleRecommenderChange = this.handleRecommenderChange.bind(this); this.handleCategoryChange = this.handleCategoryChange.bind(this); this.saveButtonClicked = this.saveButtonClicked.bind(this); this.dispatchSaveButtonClicked = props.dispatchSaveButtonClicked; //Probably there is a better way to have evrything being into this. this.recommenders = props.recommenders; this.props = props; } handleNameChange(event) { this.setState({ name: event.target.value }); } handleRecommenderChange(value) { this.setState({ recommender: value }); } handleCategoryChange(newCategory) { if(this.state.category === newCategory) { newCategory = null; } this.setState({ category: newCategory }); } saveButtonClicked() { this.dispatchSaveButtonClicked(this.state.key, { name: this.state.name, recommender: this.state.recommender, category: this.state.category, }); } closeButtonClicked() { browserHistory.goBack(); } getHeaderSaveButton() { if(this.state.name) { return <FlatButton label="Save" />; } else { return null; } } render() { if(this.props.isLoading) { return <LoadingIndicator />; } return ( <div> <Header title={'Edit Reco'} iconElementLeft={<IconButton><NavigationClose /></IconButton>} onLeftIconButtonTouchTap={this.closeButtonClicked} /> <Card> <CardText> <TextField hintText={'Recommendation name'} style={blockStyle} type='text' value={this.state.name} onChange={this.handleNameChange} /> <AutoComplete hintText='Who recommended it?' searchText={this.state.recommender} dataSource={this.recommenders} onUpdateInput={this.handleRecommenderChange} onNewRequest={this.handleRecommenderChange} style={blockStyle} filter={AutoComplete.fuzzyFilter} maxSearchResults={5} /> <CategorySelector value={this.state.category} onChange={this.handleCategoryChange}/> <RaisedButton label={'Save'} style={blockStyle} primary={true} onClick={this.saveButtonClicked} disabled={!this.state.name} /> </CardText> </Card> </div> ); } } const mapStateToProps = (state, { params }) => { return { recommenders: getRecommenders(state).map( reco => reco.name), reco: getReco(state, params.recoId), isLoading: isEditing(state) }; }; const mapDispatchToProps = (dispatch) => { return { dispatchSaveButtonClicked: (id, reco) => { dispatch(recosActions.editReco(id, reco)) .then(() => { browserHistory.goBack(); }); } }; }; const EditRecoContainer = connect(mapStateToProps, mapDispatchToProps)(EditReco); export default EditRecoContainer;
var fs = require('fs') var path = require('path') module.exports.getConfig = getConfig var env = process.env.NODE_ENV || 'development' var configDirs = fs.readdirSync(path.resolve(__dirname, '../config')) var configObj = {} configDirs.forEach(function(dirName) { if (dirName.indexOf('.') !== 0) { // skip hidden folder like .DS_Store in Mac var config = require('../config/' + dirName + '/' + env) configObj[dirName] = config } }) function getConfig() { return configObj }
'use strict' const { test } = require('tap') const Fastify = require('..') const { codes: { FST_ERR_DEC_ALREADY_PRESENT, FST_ERR_MISSING_MIDDLEWARE } } = require('../lib/errors') test('Should throw if the basic use API has not been overridden', t => { t.plan(1) const fastify = Fastify() try { fastify.use() t.fail('Should throw') } catch (err) { t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE) } }) test('Should be able to override the default use API', t => { t.plan(1) const fastify = Fastify() fastify.decorate('use', () => true) t.strictEqual(fastify.use(), true) }) test('Cannot decorate use twice', t => { t.plan(1) const fastify = Fastify() fastify.decorate('use', () => true) try { fastify.decorate('use', () => true) } catch (err) { t.ok(err instanceof FST_ERR_DEC_ALREADY_PRESENT) } }) test('Encapsulation works', t => { t.plan(2) const fastify = Fastify() fastify.register((instance, opts, next) => { instance.decorate('use', () => true) t.strictEqual(instance.use(), true) next() }) fastify.register((instance, opts, next) => { try { instance.use() t.fail('Should throw') } catch (err) { t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE) } next() }) fastify.ready() })
import React from "react"; import { storiesOf } from "@storybook/react"; import { withKnobs, boolean } from "@storybook/addon-knobs"; import centered from "@storybook/addon-centered/react"; import DarkModeKnobWrapper from "./DarkModeKnobWrapper"; import Heart from "../components/dots/Heart"; import Pride from "../components/dots/Pride"; import Triangle from "../components/dots/Triangle"; import Vroom from "../components/dots/Vroom"; import Pulse from "../components/dots/Pulse"; storiesOf("Dots", module) .addDecorator(withKnobs) .addDecorator(centered) .add("Heart", () => { const on = boolean("On", false); return ( <div> <Heart on={on} /> <Heart on={!on} /> </div> ); }) .add("Pride", () => ( <DarkModeKnobWrapper> <Pride on={boolean("On", false)} /> </DarkModeKnobWrapper> )) .add("Triangle", () => <Triangle on={boolean("On", false)} />) .add("Vroom", () => <Vroom on={boolean("On", false)} />) .add("Pulse", () => <Pulse on={boolean("On", false)} />);
define(function(require) { /** * The Promises/A+ compliance test suite * * Converted from https://github.com/promises-aplus/promises-tests * Thanks @domenic and A+ team for this massive work! **/ require('spec/base/promiseSpec/aplus/2.1.2'); require('spec/base/promiseSpec/aplus/2.1.3'); require('spec/base/promiseSpec/aplus/2.2.1'); require('spec/base/promiseSpec/aplus/2.2.2'); require('spec/base/promiseSpec/aplus/2.2.3'); require('spec/base/promiseSpec/aplus/2.2.4'); require('spec/base/promiseSpec/aplus/2.2.5'); require('spec/base/promiseSpec/aplus/2.2.6'); require('spec/base/promiseSpec/aplus/2.2.7'); require('spec/base/promiseSpec/aplus/2.3.1'); require('spec/base/promiseSpec/aplus/2.3.2'); require('spec/base/promiseSpec/aplus/2.3.3'); require('spec/base/promiseSpec/aplus/2.3.4'); });
import React from 'react' import { Image, Reveal } from 'shengnian-ui-react' const RevealExampleHidden = () => ( <Reveal animated='small fade'> <Reveal.Content visible> <Image src='/assets/images/wireframe/square-image.png' size='small' /> </Reveal.Content> <Reveal.Content hidden> <Image src='/assets/images/avatar/large/ade.jpg' size='small' /> </Reveal.Content> </Reveal> ) export default RevealExampleHidden
/* global appSettings */ var $result, $resultContainer, $resultsButton, $resultsPane, $renderingLabel, $window = $(window), path = require('path'), _ = require('lodash'), isEnabled = true, messenger = require(path.resolve(__dirname, '../messenger')), renderer = require(path.resolve(__dirname, './asciidoc.js')).get(), formats = require(path.resolve(__dirname, '../formats')), source = '', shell = require('shell'), formatter = null, subscriptions = [], _fileInfo, _buildFlags = []; var detectRenderer = function (fileInfo) { var rendererPath, currentFormatter; currentFormatter = formats.getByFileExtension(fileInfo.ext); if (formatter === null || currentFormatter.name !== formatter.name) { formatter = currentFormatter; rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase()); renderer = require(rendererPath).get(); messenger.publish.file('formatChanged', formatter); } }; var handlers = { opened: function(fileInfo){ refreshSubscriptions(); $result.animate({ scrollTop: $result.offset().top }, 10); }, sourceChanged: function(fileInfo){ handlers.contentChanged(fileInfo); }, contentChanged: function (fileInfo) { if (isEnabled && $result) { _fileInfo = fileInfo; if (!_.isUndefined(_fileInfo)) { if (_fileInfo.isBlank) { $result.html(''); } else { if(_fileInfo.contents.length > 0){ var flags = ''; detectRenderer(_fileInfo); source = _fileInfo.contents; _buildFlags.forEach(function (buildFlag) { flags += ':' + buildFlag + ':\n' }); source = flags + source; if(!$renderingLabel.is(':visible')){ $renderingLabel.fadeIn('fast'); } renderer(source, function (e) { $result.html(e.html); if($renderingLabel.is(':visible')){ $renderingLabel.fadeOut('fast'); } }); } } } } }, clearBuildFlags: function (params) { _buildFlags = []; }, buildFlags: function (buildFlags) { _buildFlags = buildFlags; handlers.contentChanged(_fileInfo); }, showResults: function() { subscribe(); $resultsPane.css('visibility', 'visible'); $resultsButton .removeClass('fa-chevron-left') .addClass('fa-chevron-right') .one('click', handlers.hideResults); messenger.publish.layout('showResults'); }, hideResults: function () { unsubscribe(); $resultsPane.css('visibility', 'hidden'); $resultsButton .removeClass('fa-chevron-right') .addClass('fa-chevron-left') .one('click', handlers.showResults); messenger.publish.layout('hideResults'); }, fileSelected: function(){ refreshSubscriptions(); _buildFlags = []; }, allFilesClosed: function () { $result.html(''); $renderingLabel.fadeOut('fast'); } }; var subscribe = function () { isEnabled = true; subscriptions.push(messenger.subscribe.file('new', handlers.opened)); subscriptions.push(messenger.subscribe.file('opened', handlers.opened)); subscriptions.push(messenger.subscribe.file('contentChanged', handlers.contentChanged)); subscriptions.push(messenger.subscribe.file('sourceChange', handlers.sourceChanged)); subscriptions.push(messenger.subscribe.file('allFilesClosed', handlers.allFilesClosed)); subscriptions.push(messenger.subscribe.format('buildFlags', handlers.buildFlags)); subscriptions.push(messenger.subscribe.metadata('buildFlags.clear', handlers.clearBuildFlags)); }; var unsubscribe = function () { isEnabled = false; subscriptions.forEach(function (subscription) { messenger.unsubscribe(subscription); }); subscriptions = []; }; var refreshSubscriptions = function(){ unsubscribe(); subscribe(); }; subscribe(); messenger.subscribe.file('selected', handlers.fileSelected); messenger.subscribe.file('rerender', function (data, envelope) { renderer(source, function (e) { $result.html(e.html); }); }); var openExternalLinksInBrowser = function (e) { var href; var element = e.target; if (element.nodeName === 'A') { href = element.getAttribute('href'); shell.openExternal(href); e.preventDefault(); } }; document.addEventListener('click', openExternalLinksInBrowser, false); var setHeight = function (offSetValue) { $resultsPane.css('height', $window.height() - offSetValue + 'px'); $window.on('resize', function (e) { $resultsPane.css('height', $window.height() - offSetValue + 'px'); }); }; $(function () { $result = $('#result'); $resultContainer = $('#result-container'); $resultsPane = $('#result-pane'); $resultsButton = $('#result-button'); $renderingLabel = $('#rendering-label'); $resultsPane .css('left', appSettings.split()) .css('width', appSettings.resultsWidth()); $resultsButton.one('click', handlers.hideResults); setHeight(appSettings.editingContainerOffset()); });
(function(forp, $){ /** * BarChart Class */ forp.BarChart = function(conf) { forp.Graph.call(this, conf); this.tmp = null; this.restore = function() { if(this.tmp) { this.ctx.clearRect(0, 0, this.element.width, this.element.height); this.ctx.drawImage(this.tmp, 0, 0); } }; this.highlight = function(idx) { if(!this.tmp) { this.tmp = document.createElement('canvas'); this.tmp.width = this.element.width; this.tmp.height = this.element.height; this.tmp.style.width = '100%'; this.tmp.style.height = '100px'; var context = this.tmp.getContext('2d'); context.drawImage(this.element, 0, 0); } this.ctx.beginPath(); this.ctx.strokeStyle = '#4D90FE'; this.ctx.lineWidth = 60; this.ctx.moveTo(idx, this.conf.yaxis.length); this.ctx.lineTo( idx, this.conf.yaxis.length - ( (this.conf.val.call(this, idx) * 100) / this.conf.yaxis.max ) ); this.ctx.closePath(); this.ctx.stroke(); }; this.draw = function() { if(!this.drawn) { this.drawn = true; var len = this.datas.length; this.element.width = document.body.clientWidth*2; this.element.height = this.conf.yaxis.length; this.element.style.width = '100%'; this.element.style.height = this.conf.yaxis.length + 'px'; this.element.style.marginBottom = '-3px'; this.element.style.backgroundColor = '#333'; var x = 0; for(var i = 0; i < len; i++) { this.ctx.beginPath(); this.ctx.strokeStyle = this.conf.color.call(this, i); this.ctx.lineWidth = 50; this.ctx.moveTo( x, 25 ); this.ctx.lineTo( x += ( (this.conf.val.call(this, i) * this.element.width) / this.conf.xaxis.max ) +2, 25 ); this.ctx.closePath(); this.ctx.stroke(); } if(this.conf.mousemove) { var self = this; this.bind( 'mousemove', function(e) { self.conf.mousemove.call(self,e); } ) } } return this; }; }; })(forp, jMicro);
const Parse = require('./parser'); describe('test_parse', () => { describe('test_parse_key_values', () => { it('should return the key values specified in the config from the body', () => { const config = { keys: ['to', 'from'], }; const request = { body: { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', subject: 'Test Subject', }, }; const parse = new Parse(config, request); const keyValues = parse.keyValues(); const expectedValues = { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', }; expect(keyValues).to.be.an('object'); expect(keyValues).to.deep.equal(expectedValues); }); it('should return the key values specified in the config from the payload', () => { const config = { keys: ['to', 'from'], }; const request = { payload: { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', subject: 'Test Subject', }, }; const parse = new Parse(config, request); const keyValues = parse.keyValues(); const expectedValues = { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', }; expect(keyValues).to.be.an('object'); expect(keyValues).to.deep.equal(expectedValues); }); }); describe('test_parse_get_raw_email', () => { it('should return null if no raw email property in payload', (done) => { const parse = new Parse({}, {}); function callback(email) { expect(email).to.be.null(); done(); } parse.getRawEmail(callback); }); it('should parse raw email from payload and return a mail object', (done) => { const request = { body: { email: 'MIME-Version: 1.0\r\nReceived: by 0.0.0.0 with HTTP; Wed, 10 Aug 2016 14:44:21 -0700 (PDT)\r\nFrom: Example User <test@example.com>\r\nDate: Wed, 10 Aug 2016 14:44:21 -0700\r\nSubject: Inbound Parse Test Raw Data\r\nTo: inbound@inbound.inbound.com\r\nContent-Type: multipart/alternative; boundary=001a113ee97c89842f0539be8e7a\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nHello Twilio SendGrid!\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n<html><body><strong>Hello Twilio SendGrid!</body></html>\r\n\r\n--001a113ee97c89842f0539be8e7a--\r\n', }, }; const parse = new Parse({}, request); function callback(email) { expect(email).to.be.an('object'); done(); } parse.getRawEmail(callback); }); }); });
var Connection = require(['tedious']).Connection; var config = { userName: 'masproject2017', password: 'MAS.2017', server: 'masproject.database.windows.net', // If you are on Microsoft Azure, you need this: options: { encrypt: true, database: 'AdventureWorks' } }; var connection = new Connection(config); connection.on('connect', function (err) { // If no error, then good to proceed. console.log("Connected"); });
const PlayerError = require('./errors.js').UnknownPlayerIdException; const Player = require('./player.js'); const Map = require('./map.js'); const Resources = require('./resources.js'); const Virus = require('./virus.js'); class Game { constructor(playerId, id, tick, timeLeft, players, resources, map, viruses) { this.id = id; this.tick = tick; this.timeLeft = timeLeft; this.players = players; this.resources = resources; this.map = map; this.viruses = viruses; this.me = players.find(p => p.id === playerId); if(this.me === undefined) { throw new PlayerError(); } this.enemies = players.filter(p => p.id !== playerId); } static parse(payload, playerId) { return new Game( playerId, payload.id, payload.tick, payload.timeLeft, payload.players.map(p => Player.parse(p)), Resources.parse(payload.resources), Map.parse(payload.map), payload.viruses.map(v => Virus.parse(v)) ); } static get RANKED_GAME_ID() { return -1; } static get UPDATE_PER_SECOND() { return 3; } get actions() { return this.me.actions; } } module.exports = Game;
var assert = require("assert") var RequestSet = require("../lib/request_set") var node = { request: function () {} } var unhealthy = { request: function (options, callback) { callback({ message: 'no nodes'}) } } function succeeding_request(options, cb) { return cb(null, {}, "foo") } function failing_request(options, cb) { return cb({ message: "crap", reason: "ihateyou" }) } function hangup_request(options, cb) { return cb({ message: "hang up", reason: "socket hang up" }) } function aborted_request(options, cb) { return cb({ message: "aborted", reason: "aborted" }) } var pool = { options: { maxRetries: 5 }, get_node: function () { return node }, onRetry: function () {}, length: 3 } describe("RequestSet", function () { it("defaults attempt count to at least 2", function () { var r = new RequestSet({length: 1, options: { maxRetries: 5 }}, {}, null) assert.equal(r.attempts, 2) }) it("defaults attempt count to at most maxRetries + 1", function () { var r = new RequestSet({length: 9, options: { maxRetries: 4 }}, {}, null) assert.equal(r.attempts, 5) }) it("defaults attempt count to pool.length", function () { var r = new RequestSet({length: 4, options: { maxRetries: 5 }}, {}, null) assert.equal(r.attempts, 4) }) describe("request()", function () { it("calls the callback on success", function (done) { node.request = succeeding_request RequestSet.request(pool, {}, function (err, res, body) { assert.equal(err, null) assert.equal(body, "foo") done() }) }) it("calls the callback on error", function (done) { node.request = failing_request RequestSet.request(pool, {}, function (err, res, body) { assert.equal(err.message, "crap") done() }) }) it("calls the callback with a 'no nodes' error when there's no nodes to service the request", function (done) { var p = { options: { maxRetries: 5 }, get_node: function () { return unhealthy }, length: 0, onRetry: function () {} } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err.message, "no nodes") done() }) }) it("retries hangups once", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 2, nodes: [{ request: hangup_request }, { request: succeeding_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err, null) assert.equal(body, "foo") done() }) }) it("retries hangups once then fails", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 3, nodes: [{ request: hangup_request }, { request: hangup_request }, { request: succeeding_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err.reason, "socket hang up") done() }) }) it("retries aborts once", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 2, nodes: [{ request: aborted_request }, { request: succeeding_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err, null) assert.equal(body, "foo") done() }) }) it("retries aborts once then fails", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 3, nodes: [{ request: aborted_request }, { request: aborted_request }, { request: succeeding_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err.reason, "aborted") done() }) }) it("retries up to this.attempts times", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 3, nodes: [{ request: failing_request }, { request: failing_request }, { request: aborted_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err.reason, "aborted") done() }) }) it("retries up to the first success", function (done) { var p = { i: 0, options: { maxRetries: 5 }, get_node: function () { return this.nodes[this.i++]}, onRetry: function () {}, length: 4, nodes: [{ request: failing_request }, { request: failing_request }, { request: succeeding_request }, { request: failing_request }] } RequestSet.request(p, {}, function (err, res, body) { assert.equal(err, null) assert.equal(body, "foo") done() }) }) }) })
/** * Created by sakura on 16/3/28. */ // $(function () { // $('#myTab a:last').tab("show"); // }) document.getElementById("btn-normal").disabled = '';
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-5-b-84 description: > Object.defineProperties - 'descObj' is the global object which implements its own [[Get]] method to get 'configurable' property (8.10.5 step 4.a) includes: - runTestCase.js - fnGlobalObject.js ---*/ function testcase() { var obj = {}; try { fnGlobalObject().configurable = true; Object.defineProperties(obj, { prop: fnGlobalObject() }); var result1 = obj.hasOwnProperty("prop"); delete obj.prop; var result2 = obj.hasOwnProperty("prop"); return result1 === true && result2 === false; } finally { delete fnGlobalObject().configurable; } } runTestCase(testcase);
var Helper = require("@kaoscript/runtime").Helper; module.exports = function() { function min() { return ["female", 24]; } let foo = Helper.namespace(function() { const [gender, age] = min(); return { gender: gender, age: age }; }); console.log(foo.age); console.log(Helper.toString(foo.gender)); };
module.exports = { SearchClient: require("./ddg/search-client") }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mongoose = require('mongoose'); var _mongoose2 = _interopRequireDefault(_mongoose); var _validator = require('validator'); var _findOrCreatePlugin = require('./find-or-create-plugin'); var _findOrCreatePlugin2 = _interopRequireDefault(_findOrCreatePlugin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Schema = _mongoose2.default.Schema; var userSchema = new Schema({ id: { type: String, required: true, match: /\d+/ }, displayName: { type: String, required: true, match: /^([A-Za-z]+((\s[A-Za-z]+)+)?)$/ }, emails: [{ value: { type: String, required: true, unique: true, validate: [{ validator: function validator(value) { return (0, _validator.isEmail)(value); }, message: 'Invalid email.' }] } }], photos: [{ value: { type: String, validate: { validator: _validator.isURL } } }] }); userSchema.plugin(_findOrCreatePlugin2.default); var User = _mongoose2.default.model('User', userSchema); exports.default = User;
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports BMNGOneImageLayer * @version $Id: BMNGOneImageLayer.js 2942 2015-03-30 21:16:36Z tgaskins $ */ define([ '../layer/RenderableLayer', '../geom/Sector', '../shapes/SurfaceImage', '../util/WWUtil' ], function (RenderableLayer, Sector, SurfaceImage, WWUtil) { "use strict"; /** * Constructs a Blue Marble image layer that spans the entire globe. * @alias BMNGOneImageLayer * @constructor * @augments RenderableLayer * @classdesc Displays a Blue Marble image layer that spans the entire globe with a single image. */ var BMNGOneImageLayer = function () { RenderableLayer.call(this, "Blue Marble Image"); var surfaceImage = new SurfaceImage(Sector.FULL_SPHERE, WorldWind.configuration.baseUrl + "images/BMNG_world.topo.bathy.200405.3.2048x1024.jpg"); this.addRenderable(surfaceImage); this.pickEnabled = false; this.minActiveAltitude = 3e6; }; BMNGOneImageLayer.prototype = Object.create(RenderableLayer.prototype); return BMNGOneImageLayer; });
var SimpleSuperclass = Hotcake.define(SimpleSuperclass, { ctor: function () { this.value = 100; }, incrementReturn: function () { this.value += 100; return this.value; } }); var SimpleSubclass = Hotcake.define(SimpleSubclass, { returnValue: function () { return -11; } }, SimpleSuperclass); var SimpleSubclass2 = Hotcake.define(SimpleSubclass, { returnNothing: function () { return -1999; } }, SimpleSubclass2);
enyo.kind({ name: "bootstrap.Breadcrumb", tag: "ul", classes: "breadcrumb", defaultKind: "bootstrap.MenuItem", });
'use strict'; module.exports = { "plugins": [], "recurseDepth": 10, "source": { "includePattern": ".+\\.js(doc|x)?$", "excludePattern": "(^|\\/|\\\\)_" }, "sourceType": "module", "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc","closure"] }, "templates": { "cleverLinks": false, "monospaceLinks": false, "default": { "outputSourceFiles": false, "includeDate": false, "useLongnameInNav": false } }, "opts": { "template": "templates/default", // same as -t templates/default //"template": "node_modules/tui-jsdoc-template", //"template": "node_modules/docdash", //"template": "node_modules/minami", //"template": "node_modules/postman-jsdoc-theme", //"template": "node_modules/jaguarjs-jsdoc", "encoding": "utf8", // same as -e utf8 "destination": "./docs/", // same as -d ./out/ "recurse": true, // same as -r "debug": true, // same as --debug "readme": "./README.md" //"package": "./package.json", // same as --package //"tutorials": "./tutorials/" // same as -u path/to/tutorials } };
import * as actions from './actions'; import mutations from './mutations'; import getters from './getters'; const state = { transactions: [], businesses: [] }; export default { state, actions, mutations, getters };
var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, .1, 1000 ); var renderer = new THREE.WebGLRenderer(); var container = document.getElementById('container'); container.appendChild(renderer.domElement); renderer.setSize(window.innerWidth, window.innerHeight); var loader = new THREE.STLLoader(); loader.load('../data/MonkeyBrain.stl', function(geometry) { console.log(geometry) var material = new THREE.MeshNormalMaterial({visible: true, transparent: true, opacity: 0.5}); // var material = new THREE.MeshBasicMaterial({visible: true, wireframe:true}); var mesh = new THREE.Mesh(geometry, material); scene.add(mesh); renderer.render(scene, camera); });
function registerListeners() { window.addEventListener("keydown", function(event) { switch (event.keyCode) { case 87: // w keyStatus[0] = true; break; case 65: // a keyStatus[1] = true; break; case 83: // s keyStatus[2] = true; break; case 68: // d keyStatus[3] = true; break; } }, false); window.addEventListener("keyup", function(event) { switch (event.keyCode) { case 87: // w keyStatus[0] = false; break; case 65: // a keyStatus[1] = false; break; case 83: // s keyStatus[2] = false; break; case 68: // d keyStatus[3] = false; break; } }, false); }
export class Validation { constructor() { this.errors = []; } get validationArray() { return []; } get valid() { let self = this; return this.validationArray.reduce((isValid, isPartValid) => { if(!isPartValid) return isValid; if (typeof isPartValid.valid === 'boolean' && !isPartValid.valid) { self.errors.push(isPartValid); } return isValid && isPartValid.valid; }, true); } addErrors(newErrors) { let self = this; newErrors.forEach((errorObj) => { self.errors.push(errorObj) }) } };
var helper = require('../support/spec_helper'); var ORM = require('../../'); describe("Model keys option", function () { var db = null; before(function () { db = helper.connect(); }); after(function () { return db.closeSync(); }); describe("if model id is a property", function () { var Person = null; before(function () { Person = db.define("person", { uid: String, name: String, surname: String }, { id: "uid" }); return helper.dropSync(Person); }); it("should not auto increment IDs", function () { var JohnDoe = Person.createSync({ uid: "john-doe", name: "John", surname: "Doe" }); assert.equal(JohnDoe.uid, "john-doe"); assert.notProperty(JohnDoe, "id"); }); }); describe("if model defines several keys", function () { var DoorAccessHistory = null; before(function () { DoorAccessHistory = db.define("door_access_history", { year: { type: 'integer' }, month: { type: 'integer' }, day: { type: 'integer' }, user: String, action: ["in", "out"] }, { id: ["year", "month", "day"] }); return helper.dropSync(DoorAccessHistory, function () { DoorAccessHistory.createSync([{ year: 2013, month: 7, day: 11, user: "dresende", action: "in" }, { year: 2013, month: 7, day: 12, user: "dresende", action: "out" } ]); }); }); it("should make possible to get instances based on all keys", function () { var HistoryItem = DoorAccessHistory.getSync(2013, 7, 11); assert.equal(HistoryItem.year, 2013); assert.equal(HistoryItem.month, 7); assert.equal(HistoryItem.day, 11); assert.equal(HistoryItem.user, "dresende"); assert.equal(HistoryItem.action, "in"); }); it("should make possible to remove instances based on all keys", function () { var HistoryItem = DoorAccessHistory.getSync(2013, 7, 12); HistoryItem.removeSync(); var exists = DoorAccessHistory.existsSync(2013, 7, 12); assert.isFalse(exists); }); }); });
function loadProjects(loadTarget) { console.log(loadTarget); $('.filter li').removeClass(); $('#filter-' + loadTarget).addClass('active'); var isLoaded = true; switch (loadTarget) { case 'all': renderProjects(featured); $('.load-more').removeClass('display-none'); $('.more-work').removeClass('isLoaded'); isLoaded = false; break; case 'all-more': addProjects(); $('#filter-all').addClass('active'); break; case 'design': renderProjects(design); break; case 'dev': renderProjects(dev); break; case 'hackathon': renderProjects(hackathon); break; } if (isLoaded) { $('.load-more').addClass('display-none'); $('.more-work').addClass('isLoaded'); } } function renderProjects(projects) { $('.js-project--container').html(''); $('.js-project--container').html(projects); } function addProjects() { $('.js-project--container').append(all); }
require('dotenv').config(); const api_key = process.env.MAILGUN_API_KEY; const domain = process.env.MAILGUN_DOMAIN; const mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); const list = mailgun.lists('subscriberlist@example.com'); const data = { from: 'Dylan <me@me.com>', to: 'dylantoyne@gmail.com', subject: 'Testing', text: 'Testing, Testing, Testing' }; list.info((err, data) => { // 'data' is mailing list info console.log(data); }); let user = { subscribed: true, address: 'dylantoyne@gmail.com', name: 'Dylan', moreInfo: {age: 24} }; list.members().create(bob, ((err, data) => { // 'data is the members details' console.log(data); }); list.members().list((err, members) => { console.log(members); }); list.members('dylan@gmail.com').update({name: 'John' }, (err, body) => { console.log(body); }); mailgun.lists('dylan@gmail.com').members().add({ members: members, subscribed: true }, (err, body) => { console.log(body); }); const sendMail = (id, email) => { mailgun.messages().send(data(id, email), (error, body) => { if(error) { console.log(error) } console.log(`Sending the email to ${email}. Email content: ${body}`); }) }; module.exports = sendMail;
/** * @author Toru Nagashima * @copyright 2016 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ "use strict" module.exports = { generate: require("./lib/generate"), createFixer: require("./lib/fixer"), }
define([ '../core', '../var/rnotwhite', './accepts' ], function (jQuery, rnotwhite) { function Data () { // Support: Android<4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty(this.cache = {}, 0, { get: function () { return {} } }) this.expando = jQuery.expando + Data.uid++ } Data.uid = 1 Data.accepts = jQuery.acceptData Data.prototype = { key: function (owner) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if (!Data.accepts(owner)) { return 0 } var descriptor = {} // Check if the owner object already has a cache key var unlock = owner[this.expando] // If not, create one if (!unlock) { unlock = Data.uid++ // Secure it in a non-enumerable, non-writable property try { descriptor[this.expando] = { value: unlock } Object.defineProperties(owner, descriptor) // Support: Android<4 // Fallback to a less secure definition } catch (e) { descriptor[this.expando] = unlock jQuery.extend(owner, descriptor) } } // Ensure the cache object if (!this.cache[unlock]) { this.cache[unlock] = {} } return unlock }, set: function (owner, data, value) { var prop // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed var unlock = this.key(owner) var cache = this.cache[unlock] // Handle: [ owner, key, value ] args if (typeof data === 'string') { cache[data] = value // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if (jQuery.isEmptyObject(cache)) { jQuery.extend(this.cache[unlock], data) // Otherwise, copy the properties one-by-one to the cache object } else { for (prop in data) { cache[prop] = data[prop] } } } return cache }, get: function (owner, key) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[this.key(owner)] return key === undefined ? cache : cache[key] }, access: function (owner, key, value) { var stored // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if (key === undefined || ((key && typeof key === 'string') && value === undefined)) { stored = this.get(owner, key) return stored !== undefined ? stored : this.get(owner, jQuery.camelCase(key)) } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set(owner, key, value) // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key }, remove: function (owner, key) { var i; var name; var camel var unlock = this.key(owner) var cache = this.cache[unlock] if (key === undefined) { this.cache[unlock] = {} } else { // Support array or space separated string of keys if (jQuery.isArray(key)) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat(key.map(jQuery.camelCase)) } else { camel = jQuery.camelCase(key) // Try the string as a key before any manipulation if (key in cache) { name = [key, camel] } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel name = name in cache ? [name] : (name.match(rnotwhite) || []) } } i = name.length while (i--) { delete cache[name[i]] } } }, hasData: function (owner) { return !jQuery.isEmptyObject( this.cache[owner[this.expando]] || {} ) }, discard: function (owner) { if (owner[this.expando]) { delete this.cache[owner[this.expando]] } } } return Data })
const { describe, it, beforeEach } = require('kocha') const { createStore, documentObject } = require('./helper') const genel = require('genel') const { expect } = require('chai') const { Action } = require('~') const { make } = capsid let store describe('Store', () => { beforeEach(async () => { store = await createStore() }) describe('save', () => { it('saves the user object', done => { store.userRepository = { save (user) { expect(user).to.equal(store.user) done() } } store.save() }) it('saves the currentJournal if exists', async () => { await store.dispatch({ type: Action.CREATE_JOURNAL_DOCUMENT, detail: documentObject }) await store.dispatch({ type: Action.LOAD_CHART }) const journalSaved = new Promise(resolve => { store.journalRepository = { save (journal) { expect(journal).to.equal(store.currentJournal) resolve() } } }) await store.save() return journalSaved }) }) describe('notifyUpdate', () => { it('notifies the model update', async () => { const store = make( 'js-store', genel.div`<p class="is-model-observer">hello</p>` ) store.languageReady = Promise.resolve() const p = new Promise(resolve => { store.el.firstChild.addEventListener(Action.MODEL_UPDATE, () => resolve() ) }) expect(await store.notifyUpdate()).to.equal(store) return p }) }) })
import React, { Component } from 'react' import { Icon, Menu } from 'shengnian-ui-react' export default class MenuExampleIcons extends Component { state = { activeItem: 'gamepad' } handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( <Menu icon> <Menu.Item name='gamepad' active={activeItem === 'gamepad'} onClick={this.handleItemClick}> <Icon name='gamepad' /> </Menu.Item> <Menu.Item name='video camera' active={activeItem === 'video camera'} onClick={this.handleItemClick}> <Icon name='video camera' /> </Menu.Item> <Menu.Item name='video play' active={activeItem === 'video play'} onClick={this.handleItemClick}> <Icon name='video play' /> </Menu.Item> </Menu> ) } }
'use strict'; var React = require('react'); var LoginForm = require('./LoginForm'); var SignUpForm = require('./SignUpForm'); var Tab = require('./tabs/Tab'); var TabContents = require('./tabs/TabContents'); var TabbedPanel = require('./tabs/TabbedPanel'); var Tabs = require('./tabs/Tabs'); var ObtainUser = React.createClass({ render: function() { return ( <TabbedPanel selected={0}> <Tabs> <Tab>I have an account</Tab> <Tab>I don't have an account</Tab> </Tabs> <TabContents> <LoginForm/> <SignUpForm/> </TabContents> </TabbedPanel> ); } }); module.exports = ObtainUser;
'use strict'; /* * Creates a fake project object for unit tests. * * @method getProject * @private */ function getProject(options) { options = options || {}; let root = options.root || 'default-root'; let pkg = options.pkg || { version: '1.0.0' }; return { root, pkg, }; } /* * Creates a context (`this`) for `ember-cli` command to be able to successfully * execute and test `run` method. * * In unit tests, we could simply * * @method contextFor * @protected * @param {String} type A name of the command, e.g. 'publish' * @param {Object} options Any additional options that needs to be overwritten * on the command (`project`, etc.) */ function contextFor(name, options) { options = options || {}; let command = require(`../../lib/commands/${name}`); command.project = getProject(options); return command; } module.exports = { contextFor }
var curVersion = 'v34'; var request = require('request'); module.exports = function(grunt) { var firebaseUrl = 'webhook'; var firebaseUri = null; if(firebaseUrl) { firebaseUri = 'https://' + firebaseUrl + '.firebaseio.com/generator_version.json'; } var checkVersion = function(callback) { if(firebaseUri === null) { callback(); } else { request({ url: firebaseUri, json: true }, function(e, r, body) { if(body) { if(body !== curVersion) { console.log('========================================================'.red); console.log('# This site is using old Webhook code. #'.red); console.log('========================================================'.red); console.log('#'.red + ' To update, run "wh update" in this folder.') console.log('# ---------------------------------------------------- #'.red) } callback(); } else { callback(); } }); } }; var generator = require('../libs/generator').generator(grunt.config, grunt.log, grunt.file, root); grunt.registerTask('buildTemplates', 'Generate static files from templates directory', function() { var done = this.async(); generator.renderTemplates(done, generator.reloadFiles); }); grunt.registerTask('buildPages', 'Generate static files from pages directory', function() { var done = this.async(); generator.renderPages(done, generator.reloadFiles); }); grunt.registerTask('scaffolding', 'Generate scaffolding for a new object', function(name) { var done = this.async(); var force = grunt.option('force'); var result = generator.makeScaffolding(name, done, force); }); grunt.registerTask('watch', 'Watch for changes in templates and regenerate site', function() { generator.startLiveReload(); grunt.task.run('simple-watch'); }); grunt.registerTask('webListener', 'Listens for commands from CMS through websocket', function() { var done = this.async(); generator.webListener(done); }); grunt.registerTask('webListener-open', 'Listens for commands from CMS through websocket', function() { var done = this.async(); generator.webListener(done); grunt.util.spawn({ grunt: true, args: ['open:wh-open'].concat(grunt.option.flags()), opts: { stdio: 'inherit' } }, function (err, result, code) { if (err || code > 0) { grunt.log.warn('A problem occured while trying to open a browser window to connect to the site.') grunt.log.warn(result.stderr || result.stdout); grunt.log.warn('In order to access the site, please navigate to \'localhost:2002\' in your web browser.') } grunt.log.writeln('\n' + result.stdout); }); }); grunt.registerTask('clean', 'Clean build files', function() { var done = this.async(); generator.cleanFiles(done); }); // Build Task. grunt.registerTask('build', 'Clean files and then generate static site into build', function() { var done = this.async(); var strict = grunt.option('strict'); if(strict === true) { generator.enableStrictMode(); } checkVersion(function() { generator.buildBoth(done, generator.reloadFiles); }) }); // Change this to optionally prompt instead of requiring a sitename grunt.registerTask('assets', 'Initialize the firebase configuration file (installer should do this as well)', function() { generator.assets(grunt); }); grunt.registerTask('assetsMiddle', 'Initialize the firebase configuration file (installer should do this as well)', function() { generator.assetsMiddle(grunt); }); grunt.registerTask('assetsAfter', 'Initialize the firebase configuration file (installer should do this as well)', function() { generator.assetsAfter(grunt); }); // Change this to optionally prompt instead of requiring a sitename grunt.registerTask('init', 'Initialize the firebase configuration file (installer should do this as well)', function() { var done = this.async(); var sitename = grunt.option('sitename'); var secretkey = grunt.option('secretkey'); var copyCms = grunt.option('copycms'); generator.init(sitename, secretkey, copyCms, done); }); // Check if initialized properly before running all these tasks grunt.registerTask('default', 'Clean, Build, Start Local Server, and Watch', function() { grunt.task.run('configureProxies:wh-server') grunt.task.run('connect:wh-server'); grunt.task.run('build'); grunt.task.run('concurrent:wh-concurrent'); }); };
(function (global, factory) { if (typeof define === "function" && define.amd) { define('/Plugin/bootstrap-treeview', ['exports', 'jquery', 'Plugin', 'Config'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('jquery'), require('Plugin'), require('Config')); } else { var mod = { exports: {} }; factory(mod.exports, global.jQuery, global.Plugin, global.Config); global.PluginBootstrapTreeview = mod.exports; } })(this, function (exports, _jquery, _Plugin2, _Config) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _jquery2 = babelHelpers.interopRequireDefault(_jquery); var _Plugin3 = babelHelpers.interopRequireDefault(_Plugin2); var Config = babelHelpers.interopRequireWildcard(_Config); var NAME = 'treeview'; var Treeview = function (_Plugin) { babelHelpers.inherits(Treeview, _Plugin); function Treeview() { babelHelpers.classCallCheck(this, Treeview); return babelHelpers.possibleConstructorReturn(this, (Treeview.__proto__ || Object.getPrototypeOf(Treeview)).apply(this, arguments)); } babelHelpers.createClass(Treeview, [{ key: 'getName', value: function getName() { return NAME; } }, { key: 'render', value: function render() { if (!_jquery2.default.fn.treeview) { return; } var $el = this.$el, options = this.options; if (typeof options.source === 'string' && _jquery2.default.isFunction(window[options.source])) { options.data = window[options.source](); delete options.source; } else if (_jquery2.default.isFunction(options.souce)) { options.data = options.source(); delete options.source; } $el.treeview(options); } }], [{ key: 'getDefaults', value: function getDefaults() { return { injectStyle: false, expandIcon: 'icon wb-plus', collapseIcon: 'icon wb-minus', emptyIcon: 'icon', nodeIcon: 'icon wb-folder', showBorder: false, // color: undefined, // "#000000", // backColor: undefined, // "#FFFFFF", borderColor: Config.colors('blue-grey', 200), onhoverColor: Config.colors('blue-grey', 100), selectedColor: '#ffffff', selectedBackColor: Config.colors('primary', 600), searchResultColor: Config.colors('primary', 600), searchResultBackColor: '#ffffff' }; } }]); return Treeview; }(_Plugin3.default); _Plugin3.default.register(NAME, Treeview); exports.default = Treeview; });
var Game = { tileW: 16, tileH: 16, width: 400, height: 300, System: {}, Map: {} }; Game.BOOT = function() {}; Game.BOOT.prototype = { preload: function() { this.game.stage.backgroundColor = '#eee'; Game.operate = new Game.System.Operate(this.game); Game.player = new Game.System.Player(this.game); Game.npc = new Game.System.Npc(this.game); }, create: function() { this.game.state.start('LOAD'); } };
'use strict'; notesApp.controller('showNotesController', function showNotesController($scope, $location, NotesData) { $scope.notes = NotesData.getNotes(); $scope.searchFor = ''; $scope.$watch('[searchFor]', function () { if ($scope.searchFor.trim() === '') { $scope.notes = NotesData.getNotes(); } else { $scope.notes = NotesData.search($scope.searchFor); } }, true); $scope.goto = function(note) { $location.path('/edit/' + note.id); }; });
// LICENSE : MIT "use strict"; import {RuleHelper} from "textlint-rule-helper"; import alex from "alex"; const defaultOptions = { allow: undefined, deny: undefined, noBinary: false, profanitySureness: 0 }; module.exports = function textlintRuleAlex(context, options = {}) { const {Syntax, RuleError, report, getSource} = context; const helper = new RuleHelper(context); const opts = {...defaultOptions, ...options}; /* { [1:5-1:14: `boogeyman` may be insensitive, use `boogey` instead] message: '`boogeyman` may be insensitive, use `boogey` instead', name: '1:5-1:14', file: '', reason: '`boogeyman` may be insensitive, use `boogey` instead', line: 1, column: 5, location: Position { start: [Object], end: [Object] }, fatal: false, ruleId: 'boogeyman-boogeywoman', source: 'retext-equality' } */ const reportError = (node, result) => { const ruleError = new RuleError(`[${result.ruleId}] ${result.message}`, { line: result.line - 1, column: result.column - 1 }); report(node, ruleError); }; return { [Syntax.Str](node){ if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) { return; } const text = getSource(node); const messages = alex(text, opts).messages; messages.forEach((result) => { reportError(node, result); }); } } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _Node2 = require('../Node'); var _Node3 = _interopRequireDefault(_Node2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CatchClause = function (_Node) { (0, _inherits3.default)(CatchClause, _Node); function CatchClause(childNodes) { (0, _classCallCheck3.default)(this, CatchClause); return (0, _possibleConstructorReturn3.default)(this, (CatchClause.__proto__ || (0, _getPrototypeOf2.default)(CatchClause)).call(this, 'CatchClause', childNodes)); } (0, _createClass3.default)(CatchClause, [{ key: '_acceptChildren', value: function _acceptChildren(children) { children.passToken('Keyword', 'catch'); children.skipNonCode(); children.passToken('Punctuator', '('); children.skipNonCode(); var param = children.passPattern(); children.skipNonCode(); children.passToken('Punctuator', ')'); children.skipNonCode(); var body = children.passStatement('BlockStatement'); children.assertEnd(); this.param = param; this.body = body; } }]); return CatchClause; }(_Node3.default); exports.default = CatchClause; //# sourceMappingURL=CatchClause.js.map
var uuid = require('uuid'), logging = require('@tryghost/logging'); /** * @TODO: * - move middleware to ignition? */ module.exports = function logRequest(req, res, next) { var startTime = Date.now(), requestId = uuid.v1(); function logResponse() { res.responseTime = (Date.now() - startTime) + 'ms'; req.requestId = requestId; req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null; if (req.err) { logging.error({req: req, res: res, err: req.err}); } else { logging.info({req: req, res: res}); } res.removeListener('finish', logResponse); res.removeListener('close', logResponse); } res.on('finish', logResponse); res.on('close', logResponse); next(); };
/* globals Promise:true */ var _ = require('lodash') var EventEmitter = require('events').EventEmitter var inherits = require('util').inherits var timers = require('timers') var Promise = require('bluebird') var bitcore = require('bitcore') var p2p = require('bitcore-p2p') var RpcClient = require('bitcoind-rpc') var config = require('../../lib/config') var errors = require('../../lib/errors') var logger = require('../../lib/logger').logger var util = require('../../lib/util') /** * @event Network#block * @param {string} hash */ /** * @event Network#tx * @param {string} txid */ /** * @class Network */ function Network () { EventEmitter.call(this) } inherits(Network, EventEmitter) /** * @return {Promise} */ Network.prototype.init = function () { return Promise.all([this._initBitcoind(), this._initTrustedPeer()]) } /** * @return {Promise} */ Network.prototype._initBitcoind = function () { var self = this // create rpc client self.bitcoind = Promise.promisifyAll(new RpcClient({ host: config.get('bitcoind.rpc.host'), port: config.get('bitcoind.rpc.port'), user: config.get('bitcoind.rpc.user'), pass: config.get('bitcoind.rpc.pass'), protocol: config.get('bitcoind.rpc.protocol') })) // request info return self.bitcoind.getInfoAsync() .then(function (ret) { // check network var bitcoindNetwork = ret.result.testnet ? 'testnet' : 'livenet' if (bitcoindNetwork !== config.get('chromanode.network')) { throw new errors.InvalidBitcoindNetwork() } // show info logger.info( 'Bitcoind checked. (version %d, bestHeight: %s, connections: %s)', ret.result.version, ret.result.blocks, ret.result.connections) }) } /** * @return {Promise} */ Network.prototype._initTrustedPeer = function () { var self = this // create trusted peer self.peer = new p2p.Peer({ host: config.get('chromanode.host'), port: config.get('chromanode.port'), network: config.get('chromanode.network') }) timers.setImmediate(function () { self.peer.connect() }) // inv event self.peer.on('inv', function (message) { var names = [] message.inventory.forEach(function (inv) { // store inv type name names.push(p2p.Inventory.TYPE_NAME[inv.type]) // store inv if tx type if (inv.type === p2p.Inventory.TYPE.TX) { self.emit('tx', util.encode(inv.hash)) } // emit block if block type if (inv.type === p2p.Inventory.TYPE.BLOCK) { self.emit('block', util.encode(inv.hash)) } }) logger.verbose('Receive inv (%s) message from peer %s:%s', names.join(', '), self.peer.host, self.peer.port) }) // connect event self.peer.on('connect', function () { logger.info('Connected to network peer %s:%s', self.peer.host, self.peer.port) }) // disconnect event self.peer.on('disconnect', function () { logger.info('Disconnected from network peer %s:%s', self.peer.host, self.peer.port) }) // ready event self.peer.on('ready', function () { logger.info( 'Peer %s:%s is ready (version: %s, subversion: %s, bestHeight: %s)', self.peer.host, self.peer.port, self.peer.version, self.peer.subversion, self.peer.bestHeight) }) // waiting peer ready return new Promise(function (resolve) { self.peer.on('ready', resolve) }) } /** * @return {Promise<Object>} */ Network.prototype.getBitcoindInfo = function () { return this.bitcoind.getInfoAsync() .then(function (ret) { return ret.result }) } /** * @return {Promise<number>} */ Network.prototype.getBlockCount = function () { return this.bitcoind.getBlockCountAsync() .then(function (ret) { return ret.result }) } /** * @param {number} height * @return {Promise<string>} */ Network.prototype.getBlockHash = function (height) { return this.bitcoind.getBlockHashAsync(height) .then(function (ret) { return ret.result }) } /** * @param {(number|string)} id * @return {Promise<bitcore.Block>} */ Network.prototype.getBlock = function (id) { var self = this return Promise.try(function () { if (_.isNumber(id)) { return self.getBlockHash(id) } return id }) .then(function (hash) { return self.bitcoind.getBlockAsync(hash, false) }) .then(function (ret) { var rawBlock = new Buffer(ret.result, 'hex') return new bitcore.Block(rawBlock) }) } /** * @return {Promise<{hash: string, height: number}>} */ Network.prototype.getLatest = function () { var self = this return self.getBlockCount() .then(function (height) { return Promise.all([height, self.getBlockHash(height)]) }) .spread(function (height, hash) { return {hash: hash, height: height} }) } /** * @todo Add concurrency * @param {string} txid * @return {Promise<bitcore.Transaction>} */ Network.prototype.getTx = function (txid) { return this.bitcoind.getRawTransactionAsync(txid) .then(function (ret) { var rawtx = new Buffer(ret.result, 'hex') return new bitcore.Transaction(rawtx) }) } /** * @param {string} rawtx * @return {Promise} */ Network.prototype.sendTx = function (rawtx) { return this.bitcoind.sendRawTransactionAsync(rawtx) } /** * @return {Promise<string[]>} */ Network.prototype.getMempoolTxs = function () { return this.bitcoind.getRawMemPoolAsync() .then(function (ret) { return ret.result }) } module.exports = Network
import React from 'react'; import { header, tabs, tab, description, importExample, title, columns, divider, example, playground, api, testkit, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import BasicExample from '!raw-loader!./examples/BasicExample'; import FootnoteExample from '!raw-loader!./examples/FootnoteExample'; import ModalExample from '!raw-loader!./examples/ModalExample'; import PageExample from '!raw-loader!./examples/PageExample'; import PersistentDividersExample from '!raw-loader!./examples/PersistentDividersExample'; import TableExample from '!raw-loader!./examples/TableExample'; import MarketingExample from '!raw-loader!./examples/MarketingExample'; import HelpButtonExample from '!raw-loader!./examples/HelpButtonExample'; import DropdownExample from '!raw-loader!./examples/DropdownExample'; import InputExample from '!raw-loader!./examples/InputExample'; import CustomModalLayout from '..'; import Checkbox from '../../Checkbox'; import Text from '../../Text'; import Box from '../../Box'; export default { category: storySettings.category, storyName: storySettings.storyName, component: CustomModalLayout, componentPath: '..', componentProps: { title: 'Modal title', children: ( <Box border={'1px dashed grey'} padding={2}> <Text>Your content goes here...</Text> </Box> ), primaryButtonText: 'Confirm', secondaryButtonText: 'Cancel', sideActions: <Checkbox>Check</Checkbox>, footnote: ( <Text size="small"> By sending an invite, you agree to the <a>Wix Terms of Use</a> </Text> ), onCloseButtonClick: () => {}, }, sections: [ header({ issueUrl: 'https://github.com/wix/wix-style-react/issues/new/choose', sourceUrl: 'https://github.com/wix/wix-style-react/tree/master/src/CustomModalLayout/', }), tabs([ tab({ title: 'Description', sections: [ columns([ description({ title: 'Description', text: 'Use this component inside a Modal component to display content in this layout. You may place a title and/or a footer with actions relevant to the displayed content.', }), ]), columns([ importExample( "import { CustomModalLayout } from 'wix-style-react';", ), ]), divider(), title('Examples'), example({ title: 'Basic Usage', text: 'A Basic example with compact preview', source: BasicExample, }), example({ title: 'Footnote Example', text: 'Same as the basic example, with the addition of a footnote', source: FootnoteExample, }), example({ title: 'Opening in a modal', text: 'Opening the CustomModalLayout is done with the Modal component, usually in the regular size of full-screen', source: ModalExample, }), example({ title: 'Persistent Dividers Example', text: 'If you need the header or footer dividers to always show, you can use the `showHeaderDivider` and `showFooterDivider` props', source: PersistentDividersExample, }), example({ title: 'Table example - No content padding', text: 'A simple example with a table as the content and without content padding.', source: TableExample, }), example({ title: 'Help Button Example', text: 'A basic example with a help button shown.', source: HelpButtonExample, }), example({ title: 'Marketing Layout Example', text: 'A custom modal example with a marketing layout.', source: MarketingExample, }), example({ title: 'Custom Page & Title Example', text: 'Open a custom page in a modal with a custom title.', source: PageExample, }), example({ title: 'Input Example', text: 'When Input element is inside modal, outline at the top and bottom is cut. In order to see full outline, Box component with 3px of height has to be used before and after Input element.', source: InputExample, }), example({ title: 'Opening popovers from a modal', text: "CustomModalLayout doesn't let to overflow the content. To make popover elements work properly they need to be used with popover prop appendTo set to window.", source: DropdownExample, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };