text
stringlengths
2
6.14k
export var meanDocs = { name: 'mean', category: 'Statistics', syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'], description: 'Compute the arithmetic mean of a list of values.', examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'], seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance'] };
import InfiniteScroll from './directive'; import 'bh-mint-ui2/src/style/empty.css'; import Vue from 'vue'; const install = function(Vue) { Vue.directive('InfiniteScroll', InfiniteScroll); }; if (!Vue.prototype.$isServer && window.Vue) { window.infiniteScroll = InfiniteScroll; Vue.use(install); // eslint-disable-line } InfiniteScroll.install = install; export default InfiniteScroll;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const config_1 = require("../models/config"); const version_1 = require("../upgrade/version"); const common_tags_1 = require("common-tags"); const Command = require('../ember-cli/lib/models/command'); const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal(); const pollDefault = config.config.defaults && config.config.defaults.poll; // defaults for BuildOptions exports.baseBuildCommandOptions = [ { name: 'target', type: String, default: 'development', aliases: ['t', { 'dev': 'development' }, { 'prod': 'production' }], description: 'Defines the build target.' }, { name: 'environment', type: String, aliases: ['e'], description: 'Defines the build environment.' }, { name: 'output-path', type: 'Path', aliases: ['op'], description: 'Path where output will be placed.' }, { name: 'aot', type: Boolean, description: 'Build using Ahead of Time compilation.' }, { name: 'sourcemaps', type: Boolean, aliases: ['sm', 'sourcemap'], description: 'Output sourcemaps.' }, { name: 'vendor-chunk', type: Boolean, default: true, aliases: ['vc'], description: 'Use a separate bundle containing only vendor libraries.' }, { name: 'base-href', type: String, aliases: ['bh'], description: 'Base url for the application being built.' }, { name: 'deploy-url', type: String, aliases: ['d'], description: 'URL where files will be deployed.' }, { name: 'verbose', type: Boolean, default: false, aliases: ['v'], description: 'Adds more details to output logging.' }, { name: 'progress', type: Boolean, default: true, aliases: ['pr'], description: 'Log progress to the console while building.' }, { name: 'i18n-file', type: String, description: 'Localization file to use for i18n.' }, { name: 'i18n-format', type: String, description: 'Format of the localization file specified with --i18n-file.' }, { name: 'locale', type: String, description: 'Locale to use for i18n.' }, { name: 'extract-css', type: Boolean, aliases: ['ec'], description: 'Extract css from global styles onto css files instead of js ones.' }, { name: 'watch', type: Boolean, default: false, aliases: ['w'], description: 'Run build when files change.' }, { name: 'output-hashing', type: String, values: ['none', 'all', 'media', 'bundles'], description: 'Define the output filename cache-busting hashing mode.', aliases: ['oh'] }, { name: 'poll', type: Number, default: pollDefault, description: 'Enable and define the file watching poll time period (milliseconds).' }, { name: 'app', type: String, aliases: ['a'], description: 'Specifies app name or index to use.' }, { name: 'delete-output-path', type: Boolean, default: true, aliases: ['dop'], description: 'Delete output path before build.' }, { name: 'preserve-symlinks', type: Boolean, default: false, description: 'Do not use the real path when resolving modules.' }, { name: 'extract-licenses', type: Boolean, default: true, description: 'Extract all licenses in a separate file, in the case of production builds only.' } ]; const BuildCommand = Command.extend({ name: 'build', description: 'Builds your app and places it into the output path (dist/ by default).', aliases: ['b'], availableOptions: exports.baseBuildCommandOptions.concat([ { name: 'stats-json', type: Boolean, default: false, description: common_tags_1.oneLine `Generates a \`stats.json\` file which can be analyzed using tools such as: \`webpack-bundle-analyzer\` or https://webpack.github.io/analyse.` } ]), run: function (commandOptions) { // Check angular version. version_1.Version.assertAngularVersionIs2_3_1OrHigher(this.project.root); const BuildTask = require('../tasks/build').default; const buildTask = new BuildTask({ project: this.project, ui: this.ui, }); return buildTask.run(commandOptions); } }); BuildCommand.overrideCore = true; exports.default = BuildCommand; //# sourceMappingURL=/users/arick/angular-cli/commands/build.js.map
/* Add Fish Form */ import React from 'react'; import autobind from 'autobind-decorator'; class AddFishForm extends React.Component{ @autobind createFish(event){ //1. Stop the form from submitting event.preventDefault(); //2. Take the data from the form and create an object var fish = { name : this.refs.name.value, price : this.refs.price.value, status :this.refs.status.value, desc : this.refs.desc.value, image :this.refs.image.value } //3. Add the fish to the App State this.props.addFish(fish); //asdf this.refs.fishForm.reset(); } render(){ return( <form className="fish-edit" refs="fishForm" onSubmit={this.createFish}> <input type="text" ref="name" placeholder="Fish Name"/> <input type="text" ref="price" placeholder="Fish Price"/> <select ref="status"> <option value="available">Fresh!</option> <option value="unavailable">Sold Out!</option> </select> <textarea type="text" ref="desc" placeholder="Desc"></textarea> <input type="text" ref="image" placeholder="URL to image"/> <button type="submit">+ Add Item </button> </form> ) } } export default AddFishForm;
import Ember from 'ember'; export default Ember.Route.extend({ appState: Ember.inject.service('app-state'), actions: { toggleLeftSidebar(){ this.set('appState.isLeftSidebarOpen', !this.get('appState.isLeftSidebarOpen')); }, toggleRightSidebar(){ this.set('appState.isRightSidebarOpen', !this.get('appState.isRightSidebarOpen')); }, toggleScrollingX(){ this.set('appState.scrollingX', !this.get('appState.scrollingX')); }, toggleScrollingY(){ this.set('appState.scrollingY', !this.get('appState.scrollingY')); }, toggleAnimating(){ this.set('appState.animating', !this.get('appState.animating')); }, toggleBouncing(){ this.set('appState.bouncing', !this.get('appState.bouncing')); }, toggleLocking(){ this.set('appState.locking', !this.get('appState.locking')); }, togglePaging(){ this.set('appState.paging', !this.get('appState.paging')); }, toggleZooming(){ this.set('appState.zooming', !this.get('appState.zooming')); }, toggleUseNativeScroll(){ this.set('appState.useNativeScroll', !this.get('appState.useNativeScroll')); }, onSelectOption(value){ this.set('appState.selectValue',value); } }, renderTemplate(){ this._super(...arguments); /* this.render('dummy-sidebar', { outlet: 'left-sidebar', into: 'application' });*/ this.render('content', { outlet: 'content', into: 'application' }); this.render('header', { outlet: "header-content", into: 'application' }); /*this.render('dummy-right-sidebar', { outlet: 'right-sidebar', into: 'application' }); var self = this; this.render('nested-header-content', { outlet: "another-header-content", into: 'dummy-content' }); this.render('nested-right-sidebar-content', { outlet: "right-sidebar", into: 'dummy-content' }); this.render('nested-left-sidebar-content', { outlet: "left-sidebar", into: 'dummy-content' }); this.render('nested-content', { outlet: "content", into: 'dummy-content' });*/ } });
const Webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin') const package = require('./package.json') const { join } = require('path') const externals = () => { const dependencies = package.dependencies return Object .keys(dependencies) .reduce((modules, module) => Object.assign({}, modules, { [module]: `commonjs ${module}` }), {} ) } module.exports = { context: join(__dirname, './build'), entry: { boleto: './resources/boleto/index.js', database: './functions/database/index.js' }, output: { path: join(__dirname, './dist'), libraryTarget: 'commonjs2', filename: '[name].js' }, devtool: 'inline-source-map', target: 'node', externals: externals(), module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['source-map-loader'], enforce: 'pre' } ] }, plugins: [ new Webpack.DefinePlugin({ 'process.env.ENV': JSON.stringify('production'), 'process.env.NODE_ENV': JSON.stringify('production'), }), new Webpack.BannerPlugin({ banner: ` require("source-map-support").install(); require("core-js"); `, raw: true, entryOnly: false }), new CopyWebpackPlugin([{ from: './database/migrations', to: './migrations', context: join(__dirname, './build') }]) ] }
/** * todo service */ class Todo { // id = 0; // text = ''; // checked = false; constructor(id, text, checked) { this.id = id; this.text = text; this.checked = checked; } }
var mongoose = require('mongoose'); var urlSchema = require('../schemas/UrlSchema'); var Url = mongoose.model('Url', urlSchema); var insertUrl = function(url, urlMinifie) { var link = new Url({ url, urlMinifie }); link.save(function(err) { if (err) return handleError(err); }); }; var getUrls = function() { return Url.find().exec(); }; module.exports = {Url, insertUrl, getUrls};
Template.botanikaLogo.events({ 'click .botanika-logo' (evt) { evt.preventDefault(); Meteor.swiperV.slideTo(0); } });
const event = { on(element, type, listener, options) { element.addEventListener(type, listener, options); return () => event.off(element, type, listener, options); }, off(element, type, listener, options) { element.removeEventListener(type, listener, options); }, once(element, type, listener) { const fn = function (...args) { listener.apply(this, args); event.off(element, type, fn); }; event.on(element, type, fn); }, }; export default event;
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'iframe', 'bg', { border: 'Показва рамка на карето', noUrl: 'Моля въведете URL за iFrame', scrolling: 'Активира прелистване', title: 'IFrame настройки', toolbar: 'IFrame' } );
/* * y * * * Copyright (c) 2013 ssddi456 * Licensed under the MIT license. */ 'use strict'; var iconvLite = require('iconv-lite'); var _ = require('underscore'); var path = require('path'); module.exports = function(grunt) { function detectDestType (dest) { if (grunt.util._.endsWith(dest, path.sep)) { return 'directory'; } else { return 'file'; } }; function unixifyPath (filepath) { if (process.platform === 'win32') { return filepath.replace(/\\/g, '/'); } else { return filepath; } }; grunt.registerMultiTask('grunt-iconv-lite', 'trans encoding', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ fromEncoding : 'utf8', toEncoding : 'gb2312' }); // Iterate over all specified file groups. this.files.forEach(function(f) { var isExpandedPair = f.orig.expand || false; // Concat specified files. f.src.filter(function(src) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(src)) { grunt.log.warn('Source file "' + src + '" not found.'); return false; } else { return true; } }).forEach(function(src) { var dest; if (detectDestType(f.dest) === 'directory') { dest = (isExpandedPair) ? f.dest : unixifyPath(path.join(f.dest, src)); } else { dest = f.dest; } if (grunt.file.isDir(src)) { // grunt.log.writeln('Creating ' + dest.cyan); grunt.file.mkdir(dest); } else { // grunt.log.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan); // Read file source. grunt.file.copy(src, dest, { encoding : options.fromEncoding, process : function( content ){ return iconvLite.encode(new Buffer(content),options.toEncoding); } }); // Print a success message. grunt.log.writeln('File "' + f.dest + '" transed.'); } }); }); }); };
var Bluebird = require('bluebird'); var connection = require('./connection'); var errors = require('./errors'); var mockOptions = {}; var offlineMode = false; module.exports.errors = errors; module.exports.connect = function connect(options) { if (offlineMode) { throw new Error('Real connections to ' + options.host + ' are not allowed in offline mode'); } return new connection.Connection(options).connect(); }; module.exports.connectMock = function connectMock(options) { return new connection.MockConnection(options, mockOptions).connect(); }; module.exports.setMockOptions = function setMockOptions(options) { mockOptions = options; }; module.exports.setOfflineMode = function setOfflineMode(value) { offlineMode = !!value; };
"use strict"; const hamt = require('../hamt'); const assert = require('chai').assert; describe('entries', () => { it('should be empty for empty map', () => { const h = hamt.make(); const it = hamt.entries(h); let v = it.next(); assert.ok(v.done); for (let x of h) assert.isFalse(true); }); it('should visit single child', () => { const h = hamt.make().set('a', 3); const it = hamt.entries(h); let v = it.next(); assert.deepEqual(['a', 3], v.value); assert.notOk(v.done); v = it.next(); assert.ok(v.done); assert.deepEqual([['a', 3]], Array.from(h)); }); it('should visit all children', () => { const h = hamt.make() .set('a', 3) .set('b', 5) .set('c', 7); const expected = [['a', 3], ['b', 5], ['c', 7]]; { const it = h.entries(); const results = []; let v; for (var i = 0; i < h.count(); ++i) { v = it.next(); assert.notOk(v.done); results.push(v.value) } v = it.next(); assert.isTrue(v.done); assert.deepEqual(expected, results); } assert.deepEqual(expected, Array.from(h)); }); it('should handle collisions', () => { const h = hamt.make() .setHash(0, 'a', 3) .setHash(0, 'b', 5) .setHash(0, 'c', 7) const expected = [['b', 5], ['a', 3], ['c', 7]]; { const it = h.entries(); const results = []; let v; for (var i = 0; i < h.count(); ++i) { v = it.next(); assert.notOk(v.done); results.push(v.value) } v = it.next(); assert.isTrue(v.done); assert.deepEqual(expected, results); } assert.deepEqual(expected, Array.from(h)); }); it('should handle large map correctly', () => { let h = hamt.make(); let sum = 0; for (let i = 0; i < 20000; ++i) { h = h.set(i + '', i); sum += i; } let foundSum = 0; for (let x of h) foundSum += x[1]; assert.strictEqual(sum, foundSum); }); });
import { each } from "../helpers"; import TablesHandler from "../TablesHandler"; each("table", table => { const tables = new TablesHandler(table); tables.enable(); });
#!/usr/bin/env node 'use strict'; var program = require('commander'); var pluck = require('pluck-keys'); var credential = require('../credential'); var stdin = ''; program .command('hash [password]') .description('Hash password') .option('-w --work <work>', 'relative work load (0.5 for half the work)', Number) .option('-k --key-length <key-length>', 'length of salt', Number) .action(function (password, options){ var pw = credential(pluck([ 'keyLength', 'hashMethod', 'work' ], options)); pw.hash(stdin || password, function (err, result){ if (err){ return console.error(err); } console.log(result); }); }); program .command('verify [hash] <password>') .description('Verify password') .action(function (hash, password){ credential().verify(stdin || hash, password, function (err, valid){ if (err){ return console.error(err); } if (!valid){ throw new Error('Invalid'); } console.log('Verified'); }); }); if (process.stdin.isTTY) { program.parse(process.argv); } else { process.stdin.on('readable', function (){ stdin += this.read() || ''; }); process.stdin.on('end', function (){ program.parse(process.argv); }); }
var app = angular.module('app',[]); app.controller('adderController', function($scope) { $scope.firstNumber = 2; $scope.secondNumber = 2; $scope.lvalue = 2+2; $scope.thirdNumber = function () { if (!$scope.firstNumber || !$scope.secondNumber) { return $scope.lvalue; } else { $scope.lvalue=parseInt($scope.firstNumber)+ parseInt($scope.secondNumber); return $scope.lvalue; } }; });
var expect = require('expect.js'); var request = require('supertest'); var app = require(process.cwd() + '/app.js'); describe('GET /api/artists', function() { this.timeout(15000); it('should return a single JSON artist object', function(done) { request(app) .get('/api/artists') .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/artists/:slug', function() { this.timeout(15000); it('should return a JSON array of artists', function(done) { var slug = 'deserto-rosso'; request(app) .get('/api/artists/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.artist).to.be.an('object'); done(); }); }); }); describe('GET /api/artists/genre/:slug', function() { this.timeout(15000); it('should return a JSON array of artist within a specific genre', function(done) { var slug = 'rock'; request(app) .get('/api/artists/genre/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.genre.slug).to.be.equal(slug); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/artists/tag/:slug', function() { this.timeout(15000); it('should return a JSON array of artist within a specific tag', function(done) { var slug = 'pop'; request(app) .get('/api/artists/tag/' + slug) .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; expect(res).to.be.an('object'); expect(res.body.status).to.be.equal('ok'); expect(res.body.tag.slug).to.be.equal(slug); expect(res.body.artists).to.be.an('array'); expect(res.body.count).to.be.equal(res.body.artists.length); done(); }); }); }); describe('GET /api/genres/artists', function() { this.timeout(15000); it('should return a JSON array of all artists genre', function(done) { request(app) .get('/api/genres/artists') .set('Accept', 'application/json') .expect(200) .end(function(err, res) { if (err) throw err; done(); }); }); });
var searchData= [ ['upmixtype',['UpmixType',['../struct_upmix_type.html',1,'']]] ];
import { suite, test, equal, isUndefined, isFalse, isTrue } from "../assert"; import CompositeContext from "di/CompositeContext"; import Context from "di/Context"; suite("CompositeContext", () => { test("no contexts", () => { const composite = new CompositeContext(); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isFalse(hasFirst); isUndefined(firstValue); }); test("single context", () => { const context = new Context({ first: "first expected" }); const composite = new CompositeContext([context]); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isTrue(hasFirst); equal("first expected", firstValue); }); test("multiple contexts", () => { const primaryContext = new Context({ first: "first expected" }); const secondaryContext = new Context({ first: "nothing", second: "second expected" }); const composite = new CompositeContext([primaryContext, secondaryContext]); const hasFirst = composite.has("first"); const firstValue = composite.get("first"); isTrue(hasFirst); equal("first expected", firstValue); const hasSecond = composite.has("second"); const secondValue = composite.get("second"); isTrue(hasSecond); equal("second expected", secondValue); }); });
var xue =xue || {}; xue.formCheck = xue.formCheck || {}; var fCheck = xue.formCheck; /* 提示信息的css样式 */ fCheck.setTips = function(select, tips){ $(select).css({ 'display': 'block', }).html(tips); }; /* 输入正确时,清除提醒 */ fCheck.clearTips = function(select){ $(select).css({ 'display':'none' }).html(null); }; /* 边框样式 */ fCheck.bordercss = function(argument) { if($(argument).val() !== ''){ $(argument).css('border','1px solid #68c04a'); }else{$(argument).css('border','1px solid #d2d2d2');} } /* 验证昵称 */ $(function(){ var nickname = $('.nickname'); $(nickname).on('focus',function(){ nickname.data('lastVal', $.trim(nickname.val())); $('.prompt-empty').html('请输入不超过6个汉字、18个字母或18个数字').css({ color: '#999', display: 'block' }); $(".nickname-warning").css({ display: 'none', }); }); $(nickname).on('blur',function(){ fCheck.clearTips(".prompt-empty"); if (nickname.val() == '') { $(".nickname-warning").html('请输入昵称').css({ display: 'block', }); }else{ if(nickname.data('lastVal') != $.trim(nickname.val())) { $(".nickname").css('border','1px solid #d2d2d2'); fCheck.clearTips(".nickname-warning"); $.fn.nickname(); }else{ $(".nickname-warning").css({ display: 'block', }); } } }); }); var boxs = { nickname: '.nickname', school:'.school' } $.fn.nickname = function(){ var box = $(boxs.nickname), val = box.val(); if (val == '') { fCheck.setTips(".nickname-warning",'请输入昵称'); }else { var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,18}$/; if(reg.test(val)){ $.fn.nicknameajax(); }else{ fCheck.setTips(".nickname-warning",'只能输入数字、汉字和字母'); } } }; $.fn.nicknameajax = function(){ var box = $(boxs.nickname), val = box.val(), d_val = $.trim(box.data('lastVal')); if($.trim(val) != d_val){ $.ajax({ url : '/MyInfos/getNicknameUseful', type : 'GET', dataType : 'json', data : 'nickname=' + $('.nickname').val(), timeout: 7000, async: true, success : function(result){ if(result.sign == false){ fCheck.setTips(".nickname-warning",result.msg); return false; } else { fCheck.clearTips(".nickname-warning"); fCheck.bordercss('.nickname'); $(box).data('lastVal',val); return true; } if(result.sign === 2){ window.location.href = result.msg; } } }); } } /* 学校格式验证 */ $.fn.school = function(){ var box = $(boxs.school), val = box.val(); var text = box.next('.school-warning'), block = text.addClass('success'); if (val == '') { fCheck.clearTips(".school-warning"); }else { var reg = /^[0-9a-zA-Z\u4e00-\u9fa5]{1,50}$/; if(reg.test(val)){ fCheck.clearTips(".school-warning"); fCheck.bordercss('.school'); }else{ fCheck.setTips(".school-warning",'只能输入数字、汉字和字母'); $('.school').css('border','1px solid #d2d2d2'); return false; } } }; $('.school').on('blur',function(){ $.fn.school(); }); /* 点击提交按钮验证 */ function inforCheckform () { if ($(".nickname").val() == $(".nickname").data("nickname") && $(".school").val() == $(".school").data("school") && $("#year").find("option:selected").text() == $("#year").attr("rel") && $("#month").find("option:selected").text() == $("#month").attr("rel") && $("#day").find("option:selected").text() == $("#day").attr("rel")) { alert('您没有修改或新增任何资料'); return false; }else{ setTimeout($.fn.nickname(),200); $.fn.school(); } if ($('.nickname-warning').is(":empty") && $('.school-warning').is(":empty") && $('.date-warning').is(":empty")) { }else{ return false; }; } var messageError = $(".message-error span").is(":empty"); if (messageError == '0') { $('.message-error').css({ display: 'block' }); setTimeout("$('.message-error').css({display: 'none'});",6000); }
webpackJsonp([2,3],[function(n,c){}]);
import React, { Component, PropTypes } from 'react'; import ReactDOM from 'react-dom'; export default class TaskForm extends Component { constructor(props, context) { super(props, context); this.state = { text: this.props.text || '' }; } componentWillReceiveProps(nextProps) { this.state = { text: nextProps.text || '' }; } handleSubmit() { const text = this.refs.taskInput.value.trim(); this.props.onAddClick(text); } handlePressEnter(e) { const text = e.target.value.trim(); if (e.which === 13) { this.props.onAddClick(text); } } handleChange(e) { const text = e.target.value.trim(); this.setState({text: text}); } render() { const style = { btn: { margin: "0 5px", backgroundColor: "#dfe", paddingLeft: "5px", paddingRight: "5px" } }; const { addTodo } = this.props; return ( <div style={{float: 'right', display: 'inline'}}> <input type="text" size="20" ref="taskInput" value={this.state.text} onChange={this.handleChange.bind(this)} onKeyDown={this.handlePressEnter.bind(this)}/> <button className="btn btn-sm" style={style.btn} onClick={ () => this.handleSubmit()} >add</button> </div> ); } } TaskForm.propTypes = { text: PropTypes.string, onAddClick: PropTypes.func.isRequired };
export default class Storage { constructor(type, storageItemName) { this.type = type || 'localStorage'; this.itemName = storageItemName || 'document'; this.available = Storage.storageAvailable(this.type); } static storageAvailable(type) { try { let storage = window[type]; let x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch(e) { console.warn(`${type} is not available`); return false; } } saveDoc(document) { if (!this.available) return; let storage = window[this.type]; storage.setItem(this.itemName, JSON.stringify(document)); } loadDoc() { if (!this.available) return; const storage = window[this.type]; const item = storage.getItem(this.itemName); if (item) return JSON.parse(item) return item; } }
import TriggerableMixin from '../Common/TriggerableMixin.js'; import Introspectable from '../Common/Introspectable.js'; class GenericWrapper extends TriggerableMixin(Introspectable) { constructor (options) { super(); this.index = options.index; this.table = options.table; if (this.index === undefined || !this.table) { throw new Error(`index and table are required`); } this.classObj = options.classObj || null; this.row = options.row || {}; this.connectedItems = options.connectedItems || {}; this.duplicateItems = options.duplicateItems || []; } registerDuplicate (item) { this.duplicateItems.push(item); } connectItem (item) { this.connectedItems[item.table.tableId] = this.connectedItems[item.table.tableId] || []; if (this.connectedItems[item.table.tableId].indexOf(item) === -1) { this.connectedItems[item.table.tableId].push(item); } for (const dup of this.duplicateItems) { item.connectItem(dup); dup.connectItem(item); } } disconnect () { for (const itemList of Object.values(this.connectedItems)) { for (const item of itemList) { const index = (item.connectedItems[this.table.tableId] || []).indexOf(this); if (index !== -1) { item.connectedItems[this.table.tableId].splice(index, 1); } } } this.connectedItems = {}; } get instanceId () { return `{"classId":"${this.classObj.classId}","index":"${this.index}"}`; } get exportId () { return `${this.classObj.classId}_${this.index}`; } get label () { return this.classObj.annotations.labelAttr ? this.row[this.classObj.annotations.labelAttr] : this.index; } equals (item) { return this.instanceId === item.instanceId; } async * handleLimit (options, iterators) { let limit = Infinity; if (options.limit !== undefined) { limit = options.limit; delete options.limit; } let i = 0; for (const iterator of iterators) { for await (const item of iterator) { yield item; i++; if (item === null || i >= limit) { return; } } } } async * iterateAcrossConnections (tableIds) { // First make sure that all the table caches have been fully built and // connected await Promise.all(tableIds.map(tableId => { return this.classObj.model.tables[tableId].buildCache(); })); yield * this._iterateAcrossConnections(tableIds); } * _iterateAcrossConnections (tableIds) { if (this.reset) { return; } const nextTableId = tableIds[0]; if (tableIds.length === 1) { yield * (this.connectedItems[nextTableId] || []); } else { const remainingTableIds = tableIds.slice(1); for (const item of this.connectedItems[nextTableId] || []) { yield * item._iterateAcrossConnections(remainingTableIds); } } } } Object.defineProperty(GenericWrapper, 'type', { get () { return /(.*)Wrapper/.exec(this.name)[1]; } }); export default GenericWrapper;
'use strict'; var getSubplotCalcData = require('../get_data').getSubplotCalcData; var counterRegex = require('../../lib').counterRegex; var createPolar = require('../polar/polar'); var constants = require('./constants'); var attr = constants.attr; var name = constants.name; var counter = counterRegex(name); var attributes = {}; attributes[attr] = { valType: 'subplotid', dflt: name, editType: 'calc', description: [ 'Sets a reference between this trace\'s data coordinates and', 'a smith subplot.', 'If *smith* (the default value), the data refer to `layout.smith`.', 'If *smith2*, the data refer to `layout.smith2`, and so on.' ].join(' ') }; function plot(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var subplotIds = fullLayout._subplots[name]; for(var i = 0; i < subplotIds.length; i++) { var id = subplotIds[i]; var subplotCalcData = getSubplotCalcData(calcData, name, id); var subplot = fullLayout[id]._subplot; if(!subplot) { subplot = createPolar(gd, id, true); fullLayout[id]._subplot = subplot; } subplot.plot(subplotCalcData, fullLayout, gd._promises); } } function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldIds = oldFullLayout._subplots[name] || []; for(var i = 0; i < oldIds.length; i++) { var id = oldIds[i]; var oldSubplot = oldFullLayout[id]._subplot; if(!newFullLayout[id] && !!oldSubplot) { oldSubplot.framework.remove(); for(var k in oldSubplot.clipPaths) { oldSubplot.clipPaths[k].remove(); } } } } module.exports = { attr: attr, name: name, idRoot: name, idRegex: counter, attrRegex: counter, attributes: attributes, layoutAttributes: require('./layout_attributes'), supplyLayoutDefaults: require('./layout_defaults'), plot: plot, clean: clean, toSVG: require('../cartesian').toSVG };
function extend(child, super) { for (var property in super.prototype) { if (typeof child.prototype[property] == "undefined") child.prototype[property] = new super.prototype[property]; } return child; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _IconBase = require('./../components/IconBase/IconBase'); var _IconBase2 = _interopRequireDefault(_IconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Easel = function (_React$Component) { _inherits(Easel, _React$Component); function Easel() { _classCallCheck(this, Easel); return _possibleConstructorReturn(this, Object.getPrototypeOf(Easel).apply(this, arguments)); } _createClass(Easel, [{ key: 'render', value: function render() { if (this.props.bare) { return _react2.default.createElement( 'g', null, _react2.default.createElement( 'g', null, _react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }), _react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }), _react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }), _react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }), _react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }), _react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' }) ) ); }return _react2.default.createElement( _IconBase2.default, null, _react2.default.createElement( 'g', null, _react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }), _react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }), _react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }), _react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }), _react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }), _react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' }) ) ); } }]); return Easel; }(_react2.default.Component); exports.default = Easel; ;Easel.defaultProps = { bare: false };
// Read the Docs // http://readthedocs.org/ // Searching as the user types. (function(){ // Save a reference to the global object. var root = this; // Global Search object on which public functions can be added var Search; Search = root.Search = {}; // for instituting a delay between keypresses and searches var timer = null; var delay = 250; var lastQuery = null; var useApi = false; // Check if the browser supports history manipulation so // we can change the URL upon instant searches var replaceStateSupported = (typeof history.replaceState === "function"); // queue of current requests var xhr = []; var $input, $button, $results, $title, $selected_facets = null; function init() { $input = $('#id_site_search_2'); $button = $('#id_search_button'); $results = $("#id_search_result"); $title = $("#id_search_title"); $selected_facets = $("#id_selected_facets"); // minimum requirements for this script to kick in... if(!$input.length || !$results.length) { return false; } else { lastQuery = queryString() bind(); } } Search.init = init; // Setup the bindings for clicking search or keypresses function bind() { // Set a delay so not _every_ keystroke sends a search $input.keyup(function(ev) { // Don't do anything unless the query has changed if(lastQuery == queryString()) { return; } if(timer) { clearTimeout(timer); } timer = setTimeout("Search.run()", delay); }); $button.click(Search.run); } // Abort all existing XHR requests, since a new search is starting function abortCurrentXHR() { var request = xhr.pop(); while(request) { request.abort(); request = xhr.pop(); } } // Replace the search results HTML with `html` (string) function replaceResults(html) { $results.empty(); $results.append(html); $title.html(getTitle()); $results.show(); } // Construct the results HTML // TODO: Use a template! function buildHTML(results) { var html = []; for (var i=0; i<results.length; i++) { html.push([ '<li class="module-item">', '<p class="module-item-title">', 'File: <a href="', results[i].absolute_url, '?highlight=', $("#id_site_search_2").val(), '">', results[i].project.name, " - ", results[i].name, "</a>", "</p>", "<p>", results[i].text, "</p>", "</li>"].join('') ); } return html.join(''); } // Pop the last search off the queue and render the `results` function onResultsReceived(results) { // remove the request from the queue xhr.pop(); lastQuery = queryString() replaceResults(buildHTML(results)); replaceState(); $("#id_remove_facets").attr('href', removeFacetsUrl()); } // Replace the URL with the one corresponding to the current search function replaceState() { if(!replaceStateSupported) { return; } var url = "/search/project/?" + queryString(); var title = getTitle() + ' | Read the Docs'; window.history.replaceState({}, title, url); } // Page title function getTitle() { return "Results for " + $("#id_site_search_2").val(); } // Params used in the search function getSearchData() { var data = { q: getKeywords(), } var selected_facets = $selected_facets.val() || '' if(selected_facets) { data['selected_facets'] = selected_facets; } return data; } // e.g. q=my+search&selected_facets=project_exact:Read%20The%20Docs function queryString() { return jQuery.param(getSearchData()); } // The active query value function getKeywords() { return $input.val() } // Url for the current query with any facet filters removed function removeFacetsUrl() { return '?' + jQuery.param({q: getKeywords()}); } // Perform the ajax request to get the search results from the API function run(ev) { if(ev) { ev.preventDefault(); } abortCurrentXHR(); // Don't do anything if there is no query if(getKeywords() == '') { $results.empty(); $results.hide(); $title.html("No search term entered"); return; } var data = getSearchData(); if(useApi) { apiSearch(data); } else { htmlSearch(data); } } Search.run = run; // TODO: The api search is incomplete. It doesn't take into account // facets nor pagination. It's a partial implemenation. function apiSearch(data) { xhr.push(jQuery.ajax({ type: 'GET', url: "/api/v1/file/search/", data: data, dataType: 'jsonp', success: function(res, text, xhqr) { onResultsReceived(res.objects); } })); } // Alternative search implementation not using the API. function htmlSearch(data) { xhr.push(jQuery.ajax({ type: 'GET', url: "/search/project/", data: data, success: function(res, text, xhqr) { onHtmlReceived(res); } })); } // Alternative implementation not using the API. Receives // the full HTML including title, pagination, facets, etc. function onHtmlReceived(html) { xhr.pop(); // remove the request from the queue lastQuery = queryString() $("#search_module").replaceWith(html); replaceState(); } }).call(this);
import * as types from './actionTypes'; export function addNote(newNote) { return { type: types.ADD_NOTE, newNote }; } export function deleteNote(id) { return { type: types.DELETE_NOTE, id }; } export function updateNote(updatedNote) { return { type: types.UPDATE_NOTE, updatedNote }; } export function getNotes(notes) { return { type: types.GET_NOTES, notes }; } export function selectNote(id) { return { type: types.SELECT_NOTE, id }; } export function login(userEmail, accessToken) { return { type: types.LOGIN, userEmail, accessToken }; } export function logout() { return { type: types.LOGOUT }; } export function saveAccessToken(userEmail, accessToken) { return { type: types.SAVE_ACCESS_TOKEN, userEmail, accessToken }; } export function authFail(userEmail) { return { type: types.AUTH_FAIL, userEmail }; }
(function (module) { 'use strict'; module.service("Dialog", dialogService); module.constant("dialogMap", dialogMap()); function dialogMap() { return { 'product-details': { controller: 'ProductDetailsController', templateUrl: '/views/widgets/product-details.html' }, 'category-details': { controller: 'CategoryDetailsController', templateUrl: '/views/widgets/category-details.html' } }; } dialogService.$inject = ['$rootScope', '$modal', 'dialogMap']; function dialogService($rootScope, $modal, dialogMap) { return { open: function (id, data, options) { var dialogContext = dialogMap[id]; var scope = ng.extend($rootScope.$new(), {options: options}); return $modal.open({ templateUrl: dialogContext.templateUrl, controller: dialogContext.controller, scope: scope, resolve: { data: function () { return ng.copy(data); } } }).result; } }; } })(ng.module('korann.modal', []));
"use strict"; const ID = require("./ID.js"); class Finger{ constructor(node, index){ this.node = node; this.start = node.id.add(ID.powerOfTwoBuffer(index)); } } module.exports = Finger;
var $$ = React.createElement; var Substance = require("substance"); var Scrollbar = require("./scrollbar"); var _ = require("substance/helpers"); var PanelMixin = require("./panel_mixin"); var ContentPanelMixin = _.extend({}, PanelMixin, { contextTypes: { app: React.PropTypes.object.isRequired, componentFactory: React.PropTypes.object.isRequired, }, // Since component gets rendered multiple times we need to update // the scrollbar and reattach the scroll event componentDidMount: function() { var app = this.context.app; this.updateScrollbar(); $(window).on('resize', this.updateScrollbar); var doc = app.doc; doc.connect(this, { 'document:changed': this.onDocumentChange }); }, componentWillUnmount: function() { var app = this.context.app var doc = app.doc; doc.disconnect(this); $(window).off('resize'); }, onDocumentChange: function() { setTimeout(function() { this.updateScrollbar(); }.bind(this), 0); }, componentDidUpdate: function() { this.updateScrollbar(); }, updateScrollbar: function() { var scrollbar = this.refs.scrollbar; var panelContentEl = this.refs.panelContent.getDOMNode(); // We need to await next repaint, otherwise dimensions will be wrong Substance.delay(function() { scrollbar.update(panelContentEl); },0); // (Re)-Bind scroll event on new panelContentEl $(panelContentEl).off('scroll'); $(panelContentEl).on('scroll', this._onScroll); }, _onScroll: function(e) { var panelContentEl = this.refs.panelContent.getDOMNode(); this.refs.scrollbar.update(panelContentEl); }, // Rendering // ----------------- getContentEditor: function() { var app = this.context.app; var doc = app.doc; var componentFactory = this.context.componentFactory; var ContainerClass = componentFactory.get("container"); return $$(ContainerClass, { doc: doc, node: doc.get("content"), ref: "contentEditor" }); }, render: function() { var app = this.context.app; return $$("div", {className: "panel content-panel-component"}, // usually absolutely positioned $$(Scrollbar, { id: "content-scrollbar", contextId: app.state.contextId, highlights: app.getHighlightedNodes.bind(app), ref: "scrollbar" }), $$('div', {className: "panel-content", ref: "panelContent"}, // requires absolute positioning, overflow=auto this.getContentEditor() ) ); } }); var ContentPanel = React.createClass({ mixins: [ContentPanelMixin], displayName: "ContentPanel", }); module.exports = ContentPanel;
var s = document.createElement('script'); s.src = chrome.extension.getURL('flourish.js'); s.onload = function() { this.parentNode.removeChild(this); }; (document.head||document.documentElement).appendChild(s);
import PropTypes from 'prop-types'; import Element from './Element'; export default class Rect extends Element { static displayName = 'Rect'; static propTypes = { x: PropTypes.oneOfType([PropTypes.func, PropTypes.number]), y: PropTypes.oneOfType([PropTypes.func, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.func, PropTypes.number]), width: PropTypes.oneOfType([PropTypes.func, PropTypes.number]), }; static defaultProps = { ...Element.defaultProps, }; defaultComponent='rect' }
'use strict'; // var Boom = require('boom'); var BPromise = require('bluebird'); module.exports = function (handler) { return function (req, res) { return new BPromise(function (resolve) { resolve(handler(req, res)); }) .then(function (response) { if (response === undefined) { // [KE] assume the response is handled, eg in a res.redirect return; } if (response.isBoom) { res.error(response); return; } res.json(response); }, res.error).catch(res.error); }; };
(function() { if (typeof module === "undefined") self.queue = queue; else module.exports = queue; queue.version = "1.0.1"; function queue(parallelism) { var queue = {}, active = 0, // number of in-flight deferrals remaining = 0, // number of deferrals remaining head, tail, // singly-linked list of deferrals error = null, results = [], await = noop, awaitAll; if (arguments.length < 1) parallelism = Infinity; queue.defer = function() { if (!error) { var node = arguments; node.index = results.push(undefined) - 1; if (tail) tail.next = node, tail = tail.next; else head = tail = node; ++remaining; pop(); } return queue; }; queue.await = function(f) { await = f; awaitAll = false; if (!remaining) notify(); return queue; }; queue.awaitAll = function(f) { await = f; awaitAll = true; if (!remaining) notify(); return queue; }; function pop() { if (head && active < parallelism) { var node = head, f = node[0], a = Array.prototype.slice.call(node, 1), i = node.index; if (head === tail) head = tail = null; else head = head.next; ++active; a.push(function(e, r) { --active; if (error != null) return; if (e != null) { // clearing remaining cancels subsequent callbacks // clearing head stops queued tasks from being executed // setting error ignores subsequent calls to defer error = e; remaining = results = head = tail = null; notify(); } else { results[i] = r; if (--remaining) pop(); else notify(); } }); f.apply(null, a); } } function notify() { if (error != null) await(error); else if (awaitAll) await(null, results); else await.apply(null, [null].concat(results)); } return queue; } function noop() {} })();
const exec = require('child_process').exec; module.exports = { onLivingRoomLightOn, onLivingRoomLightOff, }; function onLivingRoomLightOn() { return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOn.csv`, (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); } function onLivingRoomLightOff() { return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOff.csv`, (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); }
import {StyleSheet} from 'react-native' const styles = StyleSheet.create({ container: { flex: 1 } }) export default styles
module.exports = { test: { src: [ 'test/vendor/assert.js', 'test/test-adapter.js', 'transpiled/tests.cjs.js' ], options: { reporter: 'spec' } } };
import { Map } from 'immutable'; const BLOCK_MAP = Map({ 'header-one': { element: 'h1', }, 'header-two': { element: 'h2', }, 'header-three': { element: 'h3', }, 'header-four': { element: 'h4', }, 'header-five': { element: 'h5', }, 'header-six': { element: 'h6', }, blockquote: { element: 'blockquote', }, 'code-block': { element: 'pre', }, atomic: { element: 'figure', }, 'unordered-list-item': { element: 'li', }, 'ordered-list-item': { element: 'li', }, unstyled: { element: 'div', }, }); export default BLOCK_MAP;
var _base = require('./bog.domain.repositories._base.js'); var StatusDataRepo = require('../../data/repositories/bog.data.repositories.status'); var StatusRepository = function (current_user) { var self = this; var user = current_user; // Return All Items var All = function (callback) { var dataRepo = new StatusDataRepo(); dataRepo.all(function (err, coll) { if (err) { callback(self.err.wrap(1001, null, err)); } else { callback(null, coll); } }); }; return { all: All }; }; StatusRepository.prototype = new _base(); module.exports = StatusRepository;
var utils = { handleError: function(dataToLogToConsole, errorMessage, errorObj) { console.log(dataToLogToConsole || errorMessage); if (errorMessage) { var alertMessage = errorMessage; // if error object is passed, then append error message in the error object if (errorObj && errorObj.hasOwnProperty('message')) { // message returned from the server is actually stringified json. Try to parse it as json // It contains code and message var errorJSON = JSON.parse(errorObj.message); if (errorJSON.hasOwnProperty('message')) { alertMessage += ". " + errorJSON.message; } else { alertMessage += ". " + errorObj.message; } } alert(alertMessage); } } } module.exports = utils;
(function($){ $(function(){ triggerNavigation(); triggerScrollTop(); triggerTooltips(); initMQ(); }); function autoplayVideo(video, autoplay) { autoplay = autoplay || false; var $carousel = $('.carousel'); $carousel.on('slide.bs.carousel', function(e) { video.pause(); }); $(video).on('ended', function (e) { setTimeout(function () { $carousel.carousel('next'); $carousel.carousel('cycle'); }, 1000); }); if (autoplay) { $(window).on('scroll.video.trigger resize.video.trigger', function () { if ($(video).isOnScreen(0.8)) { $(window).off('scroll.video.trigger resize.video.trigger'); video.play(); } }); } } function triggerNavigation() { var $nav_trigger = $('.js-navi-trigger'); $nav_trigger.on('mouseenter', function (e) { $('#'+$(this).data('trigger')).addClass('navi-open-icons'); }); $nav_trigger.on('mouseleave', function (e) { $('#'+$(this).data('trigger')).removeClass('navi-open-icons'); }); $nav = $('.js-nav'); $nav.on('mouseenter', function (e) { $(this).addClass('navi-open-full'); }); $nav.on('mouseleave', function (e) { $(this).removeClass('navi-open-full'); }); } function triggerScrollTop() { var $up_trigger = $('.js-up-trigger'); $up_trigger.hide().on('click', function (e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0 }, 500); }); $(window).on('scroll.up.trigger resize.up.trigger', function () { if ($(this).scrollTop() > $(this).outerHeight() / 2) { $up_trigger.fadeIn(); } else { $up_trigger.fadeOut(); } }); } function triggerTooltips() { $('[data-toggle="tooltip"]').tooltip(); } function initMQ() { var queries = [ { context: 'default', match: function() { $('img').each(function() { if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src')); var small = $(this).data('default'); if (small) $(this).attr('src', small); }); } }, { context: 'medium', match: function() { $('img').each(function() { if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src')); var medium = $(this).data('medium'); if (medium) $(this).attr('src', medium); }); } }, { context: 'wide', match: function() { $('img').each(function() { if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src')); var large = $(this).data('large'); if (large) $(this).attr('src', large); }); } } ]; MQ.init(queries); } $.fn.isOnScreen = function(percentage) { percentage = percentage || 0; var win = $(window); var viewport = { top : win.scrollTop(), left : win.scrollLeft() }; viewport.right = viewport.left + win.width(); viewport.bottom = viewport.top + win.height(); var bounds = this.offset(); var height = this.outerHeight(); var width = this.outerWidth(); bounds.right = bounds.left + height; bounds.bottom = bounds.top + width; return (!( viewport.right < bounds.left + width * percentage || viewport.left > bounds.right - width * percentage || viewport.bottom < bounds.top + height * percentage || viewport.top > bounds.bottom - height * percentage )); }; })(window.jQuery);
module.exports = MnInputCustomElement() function MnInputCustomElement() { const supportsCustomElements = 'customElements' in window if (!supportsCustomElements) { require('@webcomponents/custom-elements') } if (!window.customElements.get('mn-input')) { window.customElements.define('mn-input', require('./input.class.js')) } return window.customElements.get('mn-input') }
( function () { 'use strict'; function isPlainObject(stuff) { if ( typeof stuff !== 'object' || stuff === null // Не объект || stuff === stuff.window // window || stuff.nodeType // DOM node || !stuff.constructor || !stuff.constructor.prototype.hasOwnProperty('isPrototypeOf') // Проверка, что прототип объекта равняется "Object.prototype" ) { return false; } else { return true; } } Object.defineProperty( Object, 'isPlainObject', { value: isPlainObject } ); } () );
global.SETTINGS = require('./settings'); global.log = require('./lib/log'); let app = require('./lib/server'); app.listen(SETTINGS.PORT, () => { log.info(`#server Listening on port ${SETTINGS.PORT}`); });
define(['underscore', 'util', 'collection/abstract'], function(_, Util, AbstractCollection) { 'use strict'; var _parent = AbstractCollection.prototype; var ArrayCollection = Util.extend(AbstractCollection, { _registry: null, create: function() { var me = this; _parent.create.apply(me, arguments); me._registry = []; }, add: function(item) { var me = this; if (arguments.length > 1) { _.each(arguments, function(arg) { me.add(arg) }); return; } if (!_.contains(me._registry, item)) { me._registry.push(item); _parent.add.apply(me, arguments); } }, remove: function(item) { var me = this; if (arguments.length > 1) { _.each(arguments, function(arg) { me.remove(arg); }); return; } var index = _.indexOf(me._registry, item); if (index >= 0) { me._registry.splice(index, 1); _parent.remove.apply(me, arguments); } }, each: function(iterator) { _.each(this._registry, iterator); }, some: function(iterator) { return _.some(this._registry, iterator); }, count: function() { return this._registry.length; }, getAll: function() { return this._map.slice(); } }); return ArrayCollection; });
var ViewportContainers = function ( editor ) { var container = new UI.Panel(); container.setId( 'ViewportContainers' ); return container; };
import view from './views/home' export { view }
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * sisane: The stunning micro-library that helps you to develop easily * AJAX web applications by using Angular.js 1.x & sisane-server * sisane is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; moduloEstado.controller('EstadoViewController', ['$scope', '$routeParams', 'serverService', '$location', 'estadoService', '$uibModal', function ($scope, $routeParams, serverService, $location, estadoService, $uibModal) { $scope.fields = estadoService.getFields(); $scope.obtitle = estadoService.getObTitle(); $scope.icon = estadoService.getIcon(); $scope.ob = estadoService.getTitle(); $scope.title = "Vista de " + $scope.obtitle; $scope.id = $routeParams.id; $scope.status = null; $scope.debugging = serverService.debugging(); serverService.promise_getOne($scope.ob, $scope.id).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { $scope.status = null; $scope.bean = response.data.message; } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/' + $scope.ob + '/plist'); }; $scope.back = function () { window.history.back(); }; }]);
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var DebugLogtron = require('debug-logtron'); var fs = require('fs'); var crypto = require('crypto'); var HyperbahnClient = require('tchannel/hyperbahn/index.js'); module.exports = runTests; if (require.main === module) { runTests(require('../lib/hyperbahn-cluster.js')); } function runTests(HyperbahnCluster) { HyperbahnCluster.test('can advertise', { size: 5 }, function t(cluster, assert) { var bob = cluster.remotes.bob; var client = new HyperbahnClient({ serviceName: 'hello-bob', callerName: 'hello-bob-test', hostPortList: cluster.hostPortList, tchannel: bob.channel, logger: DebugLogtron('hyperbahnClient') }); client.once('advertised', onResponse); client.advertise(); function onResponse() { var result = client.latestAdvertisementResult; cluster.checkExitPeers(assert, { serviceName: 'hello-bob', hostPort: bob.channel.hostPort }); assert.equal(result.head, null); // Because of duplicates in a size 5 cluster we know // that we have at most 5 kValues assert.ok(result.body.connectionCount <= 5, 'expect to have at most 5 advertise results'); client.destroy(); assert.end(); } }); HyperbahnCluster.test('can advertise using hostPortFile', { size: 5 }, function t(cluster, assert) { var bob = cluster.remotes.bob; var hostPortFile; do { hostPortFile = '/tmp/host-' + crypto.randomBytes(4).readUInt32LE(0) + '.json'; } while (fs.existsSync(hostPortFile)); fs.writeFileSync(hostPortFile, JSON.stringify(cluster.hostPortList), 'utf8'); var client = new HyperbahnClient({ serviceName: 'hello-bob', callerName: 'hello-bob-test', hostPortFile: hostPortFile, tchannel: bob.channel, logger: DebugLogtron('hyperbahnClient') }); assert.once('end', function cleanup() { client.destroy(); if (fs.existsSync(hostPortFile)) { fs.unlinkSync(hostPortFile); } }); client.once('advertised', onResponse); client.advertise(); function onResponse() { var result = client.latestAdvertisementResult; cluster.checkExitPeers(assert, { serviceName: 'hello-bob', hostPort: bob.channel.hostPort }); assert.equal(result.head, null); // Because of duplicates in a size 5 cluster we know // that we have at most 5 kValues assert.ok(result.body.connectionCount <= 5, 'expect to have at most 5 advertise results'); assert.end(); } }); }
module.exports = { _id: '5731eb718dc033bc69d9660f', email: 'register_user@test.com', name: 'New Test User', password: '09a3fcee233197960eb1bafe82e20021ad2807e8b12c79e9822ba0d5addfdcb7f786a365b2e8de0419f24cf671f2bd8bac9e6aacd5ff5bece1e5e7346fc19c1741e0286659e39577aaa4a6fd4fe0eab30b95d4437f3821838e27f311bda42a70ae47656eea65afd65a856c9079c866d591df466538cfe7abff4578f3d93fb9e6', passwordSalt: 'a6a465b8c1baf79bb9423c249ef8a523bd7e34600b3b2215562870a35895fdab' };
//you will need an API key from https://developer.voicesignin.com var https = require('https'); exports.handler = (event, context, callback) => { const crypto = require('crypto'); const hash = crypto.createHash('sha256'); console.log(JSON.stringify(event)); configureParams(); //validate input function configureParams() { var nameRequest = event["body-json"]; hash.update(event["context"]["source-ip"]); var hashedIpAddress = hash.digest('hex'); var blocking_string = hashedIpAddress; var session_expiry = 3600; if (nameRequest.vname) { var v1ValidationFilter = /^The ([a-z]|[A-Z])+ ([a-z]|[A-Z])+ of ([a-z]|[A-Z]|[0-9]|-| )+([a-z]|[A-Z]|[0-9])$/i; if (v1ValidationFilter.test(nameRequest.vname)) { var vname_components = []; var vname_version = 'v1'; var vnameMacroParts = nameRequest.vname.split(' of '); var vnameCity = vnameMacroParts[1]; var vnameColorAndAnimal = vnameMacroParts[0]; var vnameMicroParts = vnameColorAndAnimal.split(' '); var vnameColor = vnameMicroParts[1]; var vnameAnimal = vnameMicroParts[2]; vname_components = [vnameColor, vnameAnimal, vnameCity]; } else { context.done(null, { "error": "vname doesn't match current versions" }); return null; } /* SAMPLE DATA, uncomment if you want to use it vname_version = 'v1'; vname_components = ['brown','bear','Chicago']; blocking_string = 0383176601762cf74cb95607034b9c7712a431325074396e073d7eb4e5206edc; //just a hash of the user's IP address, you could use a cookie or deviceId as well session_expiry = 600; // 10 minute connection */ sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry); } else { return null; } return null; } function sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry) { var payload = { "vname_version": vname_version, "vname_components": vname_components, "blocking_string": blocking_string, "session_expiry_sec": session_expiry }; payload = JSON.stringify(payload); console.log(payload); const options = { hostname: 'api.voicesignin.com', port: 443, path: '/ask', method: 'POST', headers: { 'Content-Type': 'application/json', //******************************************************************** 'Authorization': '' // add your API key here //******************************************************************** } }; const req = https.request(options, (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); // console.log('data:',res.data); var rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { var requestResponse = JSON.parse(rawData); console.log('reqresp: ' + JSON.stringify(requestResponse)); if (requestResponse.request_id !== undefined) { context.done(null, requestResponse); return null; } else { context.done(null, { "error": "invalid request" }); return null; } }); }); req.on('error', (e) => { console.error(e); }); req.write(payload); req.end(); } };
const path = require('path'); const nodeExternals = require('webpack-node-externals'); // 외부 Node.js 모듈들을 포함하지 않기 위해 로드. const WebpackShellPlugin = require('webpack-shell-plugin'); const OutputFileName = 'aether.agent.package.js'; var serverCfg = { context: path.resolve(__dirname, 'src'), entry: './app.js', target: 'node', externals: [nodeExternals()],//node_modules는 무시하도록 설정 output: { path: path.resolve(__dirname, 'dist'), filename: OutputFileName }, module: { rules:[{ test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /node_modules/, use: [{ loader: 'babel-loader', options: { presets: [ ['es2016'] ], plugins: [require('babel-plugin-transform-strict-mode')]// 'use strict'가 없어도 별다른 경고 뱉지 않도록 빌드시 페이지마다 'use strict' 자동삽입 } }] }] }, plugins: [ new WebpackShellPlugin({ onBuildStart:['echo "Webpack Start"'], onBuildEnd:['echo "Build End: ' + path.resolve(__dirname, 'dist') + '/' + OutputFileName + '"'], }) ] }; module.exports = serverCfg;
import explicitElementToString from './elementToString'; import * as util from './util'; /** * converts an explicit dataSet to a javascript object * @param dataSet * @param options */ export default function explicitDataSetToJS (dataSet, options) { if (dataSet === undefined) { throw 'dicomParser.explicitDataSetToJS: missing required parameter dataSet'; } options = options || { omitPrivateAttibutes: true, // true if private elements should be omitted maxElementLength: 128 // maximum element length to try and convert to string format }; var result = { }; for (var tag in dataSet.elements) { var element = dataSet.elements[tag]; // skip this element if it a private element and our options specify that we should if (options.omitPrivateAttibutes === true && util.isPrivateTag(tag)) { continue; } if (element.items) { // handle sequences var sequenceItems = []; for (var i = 0; i < element.items.length; i++) { sequenceItems.push(explicitDataSetToJS(element.items[i].dataSet, options)); } result[tag] = sequenceItems; } else { var asString; asString = undefined; if (element.length < options.maxElementLength) { asString = explicitElementToString(dataSet, element); } if (asString !== undefined) { result[tag] = asString; } else { result[tag] = { dataOffset: element.dataOffset, length: element.length }; } } } return result; }
'use strict'; var _ = require('lodash'); var Bacon = require('baconjs'); var logger = require('./logger'); var bus = new Bacon.Bus(); var dirtyStores = []; var dispatching = false; function dispatch(type, payload) { if (dispatching) { return Promise.reject('Cascading dispatches are prohibited. Fix your flux.'); } return new Promise(function (resolve, reject) { dispatching = true; logger.logMessage(type, payload); try { bus.push({type: type, payload: payload}); pushChanges(); resolve(); } finally { logger.logMessageEnd(); dispatching = false; } }); } function input(type) { var payloads = bus.filter(function (msg) { return msg.type === type; }).map('.payload'); return payloads; } function markStoreAsDirty(store) { if (!_.contains(dirtyStores, store)) { dirtyStores.push(store); } } function pushChangesOnce() { var stores = dirtyStores; dirtyStores = []; _.each(stores, function (store) { store.changes.push(store.output); }); } function pushChanges() { if (!dirtyStores.length) { logger.logNoDirtyStores(); return; } var also = false; while(dirtyStores.length > 0) { logger.logDirtyStores(dirtyStores, also); pushChangesOnce(); also = true; } } module.exports = { dispatch: dispatch, input: input, markStoreAsDirty: markStoreAsDirty };
import * as React from 'react'; // import of a small, pure module in a private demo // bundle size and module duplication is negligible /* eslint-disable-next-line no-restricted-imports */ import { convertLength } from '@mui/material/styles/cssUtils'; import { createTheme, responsiveFontSizes } from '@mui/material/styles'; import Box from '@mui/material/Box'; import { Legend, Tooltip, LineChart, Line, XAxis, YAxis, Label, ResponsiveContainer, } from 'recharts'; let theme = createTheme(); theme = responsiveFontSizes(theme); const colors = [ '#443dc2', '#2060df', '#277e91', '#378153', '#4d811d', '#63780d', '#996600', ]; const variants = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1']; export default function ResponsiveFontSizes() { const convert = convertLength(theme.typography.htmlFontSize); const toPx = (rem) => parseFloat(convert(rem, 'px')); const series = variants.map((variantName) => { const variant = theme.typography[variantName]; const data = []; data.push({ viewport: 0, fontSize: toPx(variant.fontSize), }); theme.breakpoints.keys.forEach((key) => { const viewport = theme.breakpoints.values[key]; const value = theme.breakpoints.up(key); if (variant[value]) { data.push({ viewport: viewport - 1, fontSize: data[data.length - 1].fontSize, }); data.push({ viewport, fontSize: toPx(variant[value].fontSize), }); } else if (key === 'xl') { data.push({ viewport, fontSize: data[data.length - 1].fontSize, }); } }); return { name: variantName, data, }; }); return ( <Box sx={{ height: 380, width: '100%', color: 'black' }}> <ResponsiveContainer> <LineChart margin={{ top: 50, right: 140, bottom: 0, left: 30, }} > <XAxis dataKey="viewport" type="number"> <Label position="right" offset={30}> viewport (px) </Label> </XAxis> <YAxis dataKey="fontSize" type="number"> <Label position="top" offset={20}> font-size (rem) </Label> </YAxis> <Tooltip /> <Legend /> {series.map((serie, index) => ( <Line dataKey="fontSize" stroke={colors[index % colors.length]} data={serie.data} name={serie.name} key={serie.name} /> ))} </LineChart> </ResponsiveContainer> </Box> ); }
import Mirage from 'ember-cli-mirage'; import Schema from 'ember-cli-mirage/orm/schema'; import Model from 'ember-cli-mirage/orm/model'; import Db from 'ember-cli-mirage/db'; export default { setup() { let db = new Db(); this.schema = new Schema(db); this.schema.registerModels({ wordSmith: Model.extend({ blogPosts: Mirage.hasMany() }), blogPost: Model.extend({ wordSmith: Mirage.belongsTo(), fineComments: Mirage.hasMany() }), fineComment: Model.extend({ blogPost: Mirage.belongsTo() }), greatPhoto: Model, foo: Model.extend({ bar: Mirage.belongsTo() }), bar: Model.extend({ baz: Mirage.belongsTo() }), baz: Model.extend({ quuxes: Mirage.hasMany() }), quux: Model.extend({ zomgs: Mirage.hasMany() }), zomg: Model.extend({ lol: Mirage.belongsTo() }), lol: Model, roflCopter: Model }); return this.schema; } };
define([ 'webgl/createProgram', 'webgl/shader/compileShaderFromFile' ], function( createProgram, compileShaderFromFile ) { /** * Creates a program from 2 script tags. * * @param {!WebGLRenderingContext} gl The WebGL Context. * @param {string} vertexShaderFileName The file name of the vertex shader. * @param {string} fragmentShaderFileName The file name of the fragment shader. * @return {!WebGLProgram} A program */ return function createProgramFromScripts(gl, vertexShaderFileName, fragmentShaderFileName, callback) { var async = !!callback; if(async) { compileShaderFromFile(gl, vertexShaderFileName, 'vertex', function(vertexShader) { compileShaderFromFile(gl, fragmentShaderFileName, 'fragment', function(fragmentShader) { callback(createProgram(gl, vertexShader, fragmentShader)); }); }); } else { return createProgram(gl, compileShaderFromFile(gl, vertexShaderFileName, 'vertex'), compileShaderFromFile(gl, fragmentShaderFileName, 'fragment')); } }; });
import styled from "styled-components" export const Code = styled.code` padding: 3px 8px; background-color: ${({ theme }) => theme.posts.inlineCodeBackground}; color: ${({ theme }) => theme.posts.inlineCodeColor}; border-radius: 6px; `
var searchData= [ ['textobject',['TextObject',['../class_oxy_1_1_framework_1_1_objects_1_1_text_object.html',1,'Oxy::Framework::Objects']]], ['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html',1,'Oxy::Framework']]], ['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html#aaefdc30b6a2d1b161cf9561092425ea6',1,'Oxy::Framework::TextRenderer']]], ['texture',['Texture',['../class_oxy_1_1_framework_1_1_text_renderer.html#a8f88234b584876dbbdb015c3e1d4636b',1,'Oxy::Framework::TextRenderer']]], ['translate',['Translate',['../class_oxy_1_1_framework_1_1_graphics.html#ac854767976984446279c8cfbc04f2099',1,'Oxy::Framework::Graphics']]] ];
'use strict'; angular.module('polaris.directives') .directive('spinner', [function() { function link(scope) { scope.$watch('disappear', function() { if (scope.disappear) { scope.hideSpinner = true; } else { scope.hideSpinner = false; } }); } var tpl = '<div ng-hide="hideSpinner" class="loading">' + '<div class="aligner"></div>' + '<div class="spinner">' + '<div class="rect1"></div>' + '<div class="rect2"></div>' + '<div class="rect3"></div>' + '<div class="rect4"></div>' + '<div class="rect5"></div>' + '</div>' + '</div>'; return { restrict: 'E', template: tpl, replace: true, scope: { 'disappear': '=' }, link: link }; }]);
'use strict'; var should = require('chai').should(); describe('Cache', function(){ var Hexo = require('../../../lib/hexo'); var hexo = new Hexo(); var Cache = hexo.model('Cache'); it('_id - required', function(){ return Cache.insert({}).catch(function(err){ err.should.have.property('message', 'ID is not defined'); }); }); });
class MenuController { constructor(translate) { this.languages = [{locale: 'es', name: 'Español'}, {locale: 'en', name: 'English'}]; this.translate = translate; this.loc = 'es'; } changeLocale(loc) { this.loc = loc || this.loc; this.translate.use(this.loc); } } MenuController.$inject = ['$translate']; export { MenuController };
(function() { 'use strict'; var mergeModuleExports = require('../../utils/mergemoduleexports'); mergeModuleExports(module.exports, require('./loader')); mergeModuleExports(module.exports, require('./any')); })();
var Message = function() { this._data = { 'push_type': 1, 'android': { 'doings': 1 } }; return this; }; /* * Notification bar上显示的标题 * 必须 */ Message.prototype.title = function(title) { return this.setAndroid('notification_title', title); }; /* * Notification bar上显示的内容 * 必须 */ Message.prototype.content = function(content) { return this.setAndroid('notification_content', content); }; /* * 系统小图标名称 * 该图标预置在客户端,在通知栏顶部展示 */ Message.prototype.status_icon = function(status_icon) { return this.setAndroid('notification_status_icon', status_icon); }; /* * 用户自定义 dict * "extras":{"season":"Spring", "weather":"raining"}] */ Message.prototype.extras = function(extras) { if (!Array.isArray(extras)) { var extraArray = []; var keys = Object.keys(extras); keys.forEach(function(key){ var v = {}; v[key] = extras[key]; extraArray.push(v) }) extras = extraArray } return this.setAndroid('extras', extras); }; /* * 推送范围 * 1:指定用户,必须指定tokens字段 * 2:所有人,无需指定tokens,tags,exclude_tags * 3:一群人,必须指定tags或者exclude_tags字段 */ Message.prototype.push_type = function(push_type) { return this.set('push_type', push_type); }; /* * 用户标签,目前仅对android用户生效 * 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]} * 含义:在广州或者上海,并且年龄为20或30岁的用户 */ Message.prototype.tags = function(tags) { return this.set('tags', tags); }; /* * 需要剔除的用户的标签,目前仅对android用户生效 * 样例:{"exclude_tags":[{"music":["blue"]},{"fruit":["apple"]}]} * 含义:不给喜欢蓝调音乐的用户,或者喜欢苹果的用户发送消息 */ Message.prototype.exclude_tags = function(exclude_tags) { return this.set('exclude_tags', exclude_tags); }; /* * 消息生效时间。如果不携带该字段,则表示消息实时生效。实际使用时,该字段精确到分 * 消息发送时间戳,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00 */ Message.prototype.send_time = function(send_time) { return this.set('send_time', send_time); }; /* * 消息过期删除时间 * 消息过期时间,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00 */ Message.prototype.expire_time = function(expire_time) { return this.set('expire_time', expire_time); }; /* * 目标设备类型 * 1:android * 2:ios * 默认为android */ Message.prototype.device_type = function(device_type) { return this.set('device_type', device_type); }; /* * 1:直接打开应用 * 2:通过自定义动作打开应用 * 3:打开URL * 4:富媒体消息 * 5:短信收件箱广告 * 6:彩信收件箱广告 * 注意:当手机收到短信、彩信收件箱广告后,在收件人一栏显示的是应用在联盟上注册的名字哦~ */ Message.prototype.doings = function(doings) { return this.setAndroid('doings', doings); }; Message.prototype.setAndroid = function(key, value) { this._data['android'][key] = value; return this; }; Message.prototype.set = function(key, value) { this._data[key] = value; return this; }; Message.prototype.getAndroidData = function() { return this._data; }; Message.prototype.getData = function() { return this._data; }; Message.prototype.toString = function() { return JSON.stringify(this._data); }; module.exports = Message;
var Court = artifacts.require("./Court.sol"); contract('Court', (accounts) => { it("test kleroterion", () => {}) })
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }); } onFormSubmit(event) { event.preventDefault(); //We need to fetch data this.props.fetchWeather(this.state.term); //Reset the search bar this.setState({ term: '' }); } render() { return( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Give a five-day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Search</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } //Passing null to connect in first argument (application state or Redux state) is indicating //that our container or SmartComponent does not care about the application state export default connect(null, mapDispatchToProps)(SearchBar);
/** * 检查文件名后缀,判断是否为合法的日志文件 * * @param fileName 文件名字符串 * @returns {bool} 文件名是否合法,true 合法,false 非法 */ function isValidLogFile(fileName) { if(fileName === null || fileName === '') throw new Error('file name empty!'); return (lastValid = /.*\.slf$/.test(fileName)); } var lastValid = false; function wasLastFileNameValid() { return lastValid; } module.exports.isValidLogFile = isValidLogFile; module.exports.wasLastFileNameValid = wasLastFileNameValid;
version https://git-lfs.github.com/spec/v1 oid sha256:9e6f79a284bf0e25e4a049856c97549792145e4af30916b5044b69d4779caae2 size 23494
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['ur'] = [ 'ur', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], u, u ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر' ], u ], u, [['قبل مسیح', 'عیسوی'], u, u], 0, [6, 0], ['d/M/yy', 'd MMM، y', 'd MMMM، y', 'EEEE، d MMMM، y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'PKR', 'Rs', 'پاکستانی روپیہ', {'JPY': ['JP¥', '¥'], 'PKR': ['Rs'], 'THB': ['฿'], 'TWD': ['NT$']}, 'rtl', plural, [ [ ['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, [ 'آدھی رات', 'صبح میں', 'دوپہر میں', 'سہ پہر', 'شام میں', 'رات میں' ] ], [['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, u], [ '00:00', ['04:00', '12:00'], ['12:00', '16:00'], ['16:00', '18:00'], ['18:00', '20:00'], ['20:00', '04:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
import { Meteor } from 'meteor/meteor' import { composeWithTracker } from 'react-komposer' import { Semesters, RegStatuses, Classrooms, Sessions, Categories, Classes, Terms } from '../../api/data/data' import CourseCreation from '../components/CourseCreation' import Loading from '../components/loading' const composer = (params, onData) => { const subSemesters = Meteor.subscribe('semesters') const subRegStatuses = Meteor.subscribe('semesters') const subClassrooms = Meteor.subscribe('classrooms') const subSessions = Meteor.subscribe('sessions') const subCategories = Meteor.subscribe('categories') const subClasses = Meteor.subscribe('classes') const subTerms = Meteor.subscribe('terms') if (subSemesters.ready() && subRegStatuses.ready() && subClassrooms.ready() && subSessions.ready() && subCategories.ready() && subTerms.ready() && subClasses.ready()) { const semesters = Semesters.find().fetch() const regstatuses = RegStatuses.find().fetch() const classrooms = Classrooms.find().fetch() const sessions = Sessions.find().fetch() const categories = Categories.find().fetch() const classes = Classes.find().fetch() const terms = Terms.find().fetch() onData(null, { semesters, regstatuses, classrooms, sessions, categories, classes, terms }) } } export default composeWithTracker(composer, Loading)(CourseCreation)
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'toolbar', 'zh', { toolbarCollapse: '摺疊工具列', toolbarExpand: '展開工具列', toolbarGroups: { document: '文件', clipboard: '剪貼簿/復原', editing: '編輯選項', forms: '格式', basicstyles: '基本樣式', paragraph: '段落', links: '連結', insert: '插入', styles: '樣式', colors: '顏色', tools: '工具' }, toolbars: '編輯器工具列' } );
/** @constructor */ Libraries.SyntaxHighlighter = function (){}; /** @type {Function} */ Libraries.SyntaxHighlighter.all; /** @type {Object} */ Libraries.SyntaxHighlighter.defaults; /** @type {Function} */ Libraries.SyntaxHighlighter.highlight; /** @type {Object} */ Libraries.SyntaxHighlighter.Highlighter; /** @type {Object} */ Libraries.SyntaxHighlighter.brushes; /** @type {Object} */ Libraries.SyntaxHighlighter.regexLib; /** @type {RegExp} */ SyntaxHighlighter.regexLib.aspScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.doubleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineCComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineDoubleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineSingleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.phpScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.scriptScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleLineCComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleLinePerlComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.xmlComments
 /** * @ngdoc controller * @name NavigationController * @function * * @description * Handles the section area of the app * * @param {navigationService} navigationService A reference to the navigationService */ function NavigationController($scope,$rootScope, $location, $log, navigationService, dialogService, historyService, sectionResource, angularHelper) { //Put the navigation service on this scope so we can use it's methods/properties in the view. // IMPORTANT: all properties assigned to this scope are generally available on the scope object on dialogs since // when we create a dialog we pass in this scope to be used for the dialog's scope instead of creating a new one. $scope.nav = navigationService; $scope.selectedId = navigationService.currentId; $scope.sections = navigationService.sections; sectionResource.getSections() .then(function(result) { $scope.sections = result; }); //This reacts to clicks passed to the body element which emits a global call to close all dialogs $rootScope.$on("closeDialogs", function (event) { if (navigationService.ui.stickyNavigation && (!event.target || $(event.target).parents(".umb-modalcolumn").size() == 0)) { navigationService.hideNavigation(); angularHelper.safeApply($scope); } }); //this reacts to the options item in the tree $scope.$on("treeOptionsClick", function (ev, args) { $scope.currentNode = args.node; args.scope = $scope; navigationService.showMenu(ev, args); }); //this reacts to tree items themselves being clicked //the tree directive should not contain any handling, simply just bubble events $scope.$on("treeNodeSelect", function (ev, args) { var n = args.node; //here we need to check for some legacy tree code if (n.jsClickCallback && n.jsClickCallback !== "") { //this is a legacy tree node! var jsPrefix = "javascript:"; var js; if (n.jsClickCallback.startsWith(jsPrefix)) { js = n.jsClickCallback.substr(jsPrefix.length); } else { js = n.jsClickCallback; } try { var func = eval(js); //this is normally not necessary since the eval above should execute the method and will return nothing. if (func != null && (typeof func === "function")) { func.call(); } } catch(ex) { $log.error("Error evaluating js callback from legacy tree node: " + ex); } } else { //add action to the history service historyService.add({name: n.name, link: n.view, icon: n.icon}); //not legacy, lets just set the route value and clear the query string if there is one. $location.path(n.view).search(null); } }); /** Opens a dialog but passes in this scope instance to be used for the dialog */ $scope.openDialog = function (currentNode, action, currentSection) { navigationService.showDialog({ scope: $scope, node: currentNode, action: action, section: currentSection }); }; } //register it angular.module('umbraco').controller("NavigationController", NavigationController);
import { remove, attempt, isError } from 'lodash'; import uuid from 'uuid/v4'; import { fileExtension } from 'Lib/pathHelper' import AuthenticationPage from './AuthenticationPage'; window.repoFiles = window.repoFiles || {}; function getFile(path) { const segments = path.split('/'); let obj = window.repoFiles; while (obj && segments.length) { obj = obj[segments.shift()]; } return obj || {}; } export default class TestRepo { constructor(config) { this.config = config; this.assets = []; } authComponent() { return AuthenticationPage; } restoreUser(user) { return this.authenticate(user); } authenticate() { return Promise.resolve(); } logout() { return null; } getToken() { return Promise.resolve(''); } entriesByFolder(collection, extension) { const entries = []; const folder = collection.get('folder'); if (folder) { for (const path in window.repoFiles[folder]) { if (fileExtension(path) !== extension) { continue; } const file = { path: `${ folder }/${ path }` }; entries.push( { file, data: window.repoFiles[folder][path].content, } ); } } return Promise.resolve(entries); } entriesByFiles(collection) { const files = collection.get('files').map(collectionFile => ({ path: collectionFile.get('file'), label: collectionFile.get('label'), })); return Promise.all(files.map(file => ({ file, data: getFile(file.path).content, }))); } getEntry(collection, slug, path) { return Promise.resolve({ file: { path }, data: getFile(path).content, }); } persistEntry(entry, mediaFiles = [], options) { const newEntry = options.newEntry || false; const folder = entry.path.substring(0, entry.path.lastIndexOf('/')); const fileName = entry.path.substring(entry.path.lastIndexOf('/') + 1); window.repoFiles[folder] = window.repoFiles[folder] || {}; window.repoFiles[folder][fileName] = window.repoFiles[folder][fileName] || {}; if (newEntry) { window.repoFiles[folder][fileName] = { content: entry.raw }; } else { window.repoFiles[folder][fileName].content = entry.raw; } return Promise.resolve(); } getMedia() { return Promise.resolve(this.assets); } persistMedia({ fileObj }) { const { name, size } = fileObj; const objectUrl = attempt(window.URL.createObjectURL, fileObj); const url = isError(objectUrl) ? '' : objectUrl; const normalizedAsset = { id: uuid(), name, size, path: url, url }; this.assets.push(normalizedAsset); return Promise.resolve(normalizedAsset); } deleteFile(path, commitMessage) { const assetIndex = this.assets.findIndex(asset => asset.path === path); if (assetIndex > -1) { this.assets.splice(assetIndex, 1); } else { const folder = path.substring(0, path.lastIndexOf('/')); const fileName = path.substring(path.lastIndexOf('/') + 1); delete window.repoFiles[folder][fileName]; } return Promise.resolve(); } }
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import TutorialScreen from '../components/tutorialScreen'; import { toggleAutoplay, } from '../actions/audio'; import { tutorialPageDidChange, hideTutorial, } from '../actions/tutorial'; const mapStateToProps = (state) => { return { timerActive: state.bottomPlayer.timerActive, autoplayOn: state.bottomPlayer.autoplayOn, bluetoothOn: state.beacon.bluetoothOn, locationServicesStatus: state.beacon.locationServicesStatus, currentPage: state.tutorial.currentPage, tutorialHidden: state.tutorial.tutorialHidden, }; }; const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators({ toggleAutoplay, tutorialPageDidChange, hideTutorial, }, dispatch), }; }; export default connect( mapStateToProps, mapDispatchToProps )(TutorialScreen);
/* Copyright Ben Trask and other contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = unique; function unique(array) { var r = [], l = array.length, x; for(var i = 0; i < l; ++i) { x = array[i]; if(-1 === r.indexOf(x)) r.push(x); } return r; }
// Karma configuration // Generated on Sat Jul 04 2015 21:07:22 GMT-0300 (BRT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.min.js', 'bower_components/angular-mocks/angular-mocks.js', 'node_modules/*', 'src/FormulaOne/DataServices/GERequest.js', 'tests/unit/FormulaOne/DataServices/GERequestSpec.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
import Ember from 'ember'; export default Ember.Component.extend({ hasErrors: Ember.computed.notEmpty('model.errors.[]') });
import fetch from '../api' import config from '../config' export const login = (source, token) => fetch( 'POST', `${config.API_URL}/login`, {}, false, {'X-Auth-Source': source, 'X-Auth-Token': token} )
var Taco = Taco || {}; Taco.Util = Taco.Util || {}; Taco.Util.HTML = Taco.Util.HTML || {}; Taco.Util.HTML.render = function(str, html) { html = (typeof html != 'undefined') ? html : false; return (html === true) ? str : Taco.Util.Str.htmlEntities(str); }; Taco.Util.HTML.attribs = function(attribs, leading_space) { leading_space = (typeof leading_space != 'undefined') ? leading_space : true; if(Taco.Util.Obj.getObjectLength(attribs) < 1) return ''; var out = []; for(var key in attribs) { var value = attribs[key]; value = (typeof value == 'object') ? Taco.Util.Obj.objectJoin(' ', value) : value; out.push(key + '="' + String(value).replace(/\"/, '\"') + '"'); } return ((leading_space) ? ' ' : '') + out.join(' '); }; Taco.Util.HTML.getTextInputTypes = function() { return [ 'text', 'image', 'file', 'search', 'email', 'url', 'tel', 'number', 'range', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'color' ]; }; Taco.Util.HTML.tag = function(element_type, body, attribs, close, is_html) { body = (typeof body == 'undefined' || body === null) ? '' : body; attribs = (typeof attribs == 'undefined') ? [] : attribs; close = (typeof close == 'undefined') ? true : close; is_html = (typeof is_html == 'undefined') ? false : is_html; var not_self_closing = ['a', 'div', 'iframe', 'textarea']; var is_self_closing = false; if(close && Taco.Util.General.empty(body) && !Taco.Util.Arr.inArray( element_type.toLowerCase(), not_self_closing )) { is_self_closing = true; } if(is_self_closing) { return '<' + element_type + this.attribs(attribs) + ' />'; } return [ '<' + element_type + this.attribs(attribs) + '>', this.render(body, is_html), (close) ? '</' + element_type + '>' : '' ].join(''); }; Taco.Util.HTML.selecty = function(options, selected, attribs) { selected = (typeof selected != 'undefined') ? selected : null; attribs = (typeof attribs != 'undefined') ? attribs : []; var htmls = []; htmls.push(this.tag('select', null, attribs, false)); if(Taco.Util.Obj.isIterable(options)) { for(var key in options) { value = options[key]; var option_attribs = { value: key }; if(String(selected) === String(value)) { option_attribs.selected = 'selected'; } htmls.push(this.tag('option', value, option_attribs)); } } htmls.push('</select>'); return htmls.join("\n"); };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { emailChanged, passwordChanged, signinUser } from '../core/actions'; import { Container, Content, Form, Item, Input, Grid, Col, Spinner, Toast, Icon, Button, Text } from 'native-base'; class Login extends Component { static navigationOptions = { title: 'Login', header: { backTitle: null, visible: false, } }; onLogin() { const { email, password, navigation } = this.props; this.props.signinUser(navigation, email, password); } onRegister() { this.props.navigation.navigate('Register'); } componentWillMount() { } onEmailChange(text) { this.props.emailChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } renderSpinner() { if (this.props.loading) { return (<Spinner />); } else { return ( <Grid> <Col> <Button full rounded onPress={this.onLogin.bind(this)}> <Text>Login</Text> </Button> </Col> <Col> <Button full rounded onPress={this.onRegister.bind(this)}> <Text>Register</Text> </Button> </Col> </Grid> ); } } render() { const { navigate } = this.props.navigation; return ( <Container> <Content> <Form> <Item rounded> <Input placeholder="E-Mail" value={this.props.email} keyboardType='email-address' onChangeText={this.onEmailChange.bind(this)} /> </Item> <Item rounded> <Input placeholder="Password" value={this.props.password} secureTextEntry onChangeText={this.onPasswordChange.bind(this)} /> </Item> <Item> <Text style={styles.errorTextStyle}> {this.props.loginError} </Text> </Item> <Item last> {this.renderSpinner()} </Item> </Form> </Content> </Container> ); } } const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' }, imageStyle: { width: 50, height: 50, } }; const mapStateToProps = ({ authReducer }) => { const { email, password, loginError, loading } = authReducer; return { email, password, loginError, loading }; }; export default connect(mapStateToProps, { emailChanged, passwordChanged, signinUser })(Login);
Miogen.require(['Component.BaseComponent', 'Component.Button'], function () { Miogen.define('Component.Toolbar', Miogen.Component.BaseComponent.extend({ construct: function (cfg) { this._super(cfg); }, build: function (cb) { var t = this; // // t.addComponent(new Miogen.Component.Button()); // t.addComponent(new Miogen.Component.Button()); // Render the base widget and newly added components this._super(function () { cb.call(this); this.el.addClass('toolbar'); }); //this.el = $('<div class="miogen-widget"><div class="pad">Collection widget</div></div>'); } })); });
/** * syntaxEnvironment.js * Andrea Tino - 2015 */ /** * Main collection point for types to be rendered. */ module.exports = function() { var tsClass = require('./class.js'); var tsInterface = require('./interface.js'); var tsEnum = require('./enum.js'); // Configuration: { classIds = [], interfaceIds = [], enumIds = [] } var config = null; // Associative arrays: id -> Typescript mapper (ts[Class|Interface|Enum]) var classes = {}; var interfaces = {}; var enums = {}; return { /** * Initializes the module. * _config: Configuration: * { classIds = [], interfaceIds = [], enumIds = [] } */ initialize: function(_config) { if (!_config) { throw 'Error: Configuration cannot be null or undefined!'; } config = _config; }, /** * Builds TypeScript classes. */ buildClasses: function() { }, /** * Builds TypeScript interfaces. */ buildInterfaces: function() { }, /** * Build enums. */ buildEnums: function() { } }; };
;(function() { MozVisibility = { _MAX_TRIES: 10, _date: new Date, _tries: 0, _timer: null, _isVisible: undefined, _proxy: function(fn, context) { context = context || window; return function() { fn.apply(context, arguments); }; }, _getEvent: function() { if (!this._event) { this._event = document.createEvent('HTMLEvents'); this._event.initEvent('mozvisibilitychange', true, true); this._event.eventName = 'mozvisibilitychange'; } return this._event; }, _setVisibilityState: function(state) { this._isVisible = (state === 'visible'); document.mozVisibilityState = state; document.mozHidden = !this._isVisible; document.dispatchEvent(this._getEvent()); }, _visibilityCheck: function() { this._date = new Date; this._tries = 0; this._timer = setTimeout(this._invisibilityCheckTimeout, 0); }, _invisibilityCheckTimeoutTemplate: function() { var newdate = new Date; var delta = newdate - this._date; this._date = newdate; this._tries++; if (delta > 1000) { this._setVisibilityState('hidden'); } else if (this._tries < this._MAX_TRIES) { this._timer = setTimeout(this._invisibilityCheckTimeout, 0); } }, _onFocus: function() { clearTimeout(this._timer); if (!this._isVisible) { this._setVisibilityState('visible'); } }, _onBlur: function() { if (!this._isVisible) { return; } this._visibilityCheck(); }, canBeEmulated: function() { var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, ua = navigator.userAgent.toLowerCase(); var match = ua.indexOf('compatible') < 0 && rmozilla.exec(ua) || []; return (window.top === window && // not in IFRAME match[2] && parseInt(match[2]) >= 5 && // Firefox 5.0+ !document.visibilityState && !document.MozVisibilityState); // visibility API is not already supported }, emulate: function() { if (!this.canBeEmulated()) { return false; } this._invisibilityCheckTimeout = this._proxy(this._invisibilityCheckTimeoutTemplate, this); window.addEventListener("focus", this._proxy(this._onFocus, this), false); window.addEventListener("blur", this._proxy(this._onBlur, this), false); this._visibilityCheck(); return true; } }; MozVisibility.emulate(); })();
const { createCompileTsFilesTask, createDeleteDistFolderTask, createLintTsFilesTask, createRunIntegrationTestsTask, createRunUnitTestsTask, } = require("../tasks"); const {parallel, series} = require("gulp"); const failAfterError = true; exports.createBuildWorkflow = (moduleName) => series( createDeleteDistFolderTask(moduleName), parallel( createCompileTsFilesTask(moduleName, "main.js", failAfterError), createCompileTsFilesTask(moduleName, "unit.js", failAfterError), createCompileTsFilesTask(moduleName, "integration.js", failAfterError) ), createLintTsFilesTask(moduleName, failAfterError), createRunUnitTestsTask(moduleName, failAfterError), createRunIntegrationTestsTask(moduleName, failAfterError) );
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { app: './src/main.js' }, output: { filename: '[name].min.js', path: path.join(__dirname, 'dist'), publicPath: '' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production'), }, '__DEV_TOOLS__': false }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), //new ExtractTextPlugin('app.css', { allChunks: true }), new HtmlWebpackPlugin({ title: 'Redux Boilerplate', filename: 'index.html', template: 'index.template.html', favicon: path.join(__dirname, 'assets/images/favicon.ico') }) ], module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader') }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, cssnext: { browsers: 'last 2 versions' } };
$(function () { $.widget("as24.qr", { _create: function () { var self = this; $(self.element).find('[data-description="QR-Code Generation"]').find("p").hide(); $(self.element).find('[data-generate="qr-code"]').click(function () { $(self.element).find('[data-description="QR-Code Generation"]').find("p").show(); var url = $(self.element).find('[name="urlQRCode"]').val(); var featureName = $(self.element).find('[name="name"]').val(); var featureEnabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=true#" }); var featureDisabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=false#" }); $(self.element).find('#qrcode_enable').empty(); $(self.element).find('#qrcode_enable').qrcode(featureEnabled); $(self.element).find('#qrcode_disable').empty(); $(self.element).find('#qrcode_disable').qrcode(featureDisabled); }); } }); })
(function () { 'use strict'; angular .module('app.web') .service('fileUpload', Service); Service.$inject = ['$http']; function Service($http) { this.uploadFile = uploadFile; //////////////// function uploadFile(file, url, done) { var fd = new FormData(); fd.append('file',file); $http.post(url, fd, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }).success(function (response) { done(null, response); }).error(function (e) { done(e, null); }); } } })();
function util() { var self = this; if (typeof Object.beget !== 'function') { Object.beget = function (o) { var F = function () {}; F.prototype = o; return new F(); }; } }; exports.util = new util();
const times = require('lodash/times'); const {GameEngine} = require('../../lib/common/engine'); const {R, G, B, _} = require('../../lib/common/panel-league/util'); module.exports.testAdd = ((test) => { const game = new GameEngine(); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: game.width, height: 1} }); game.step(); const state = game.step(); test.expect(1); test.strictEqual(state.garbage.length, 1, "No garbage slab found"); test.done(); }); module.exports.testFit = ((test) => { const game = new GameEngine({initialRows: 0, width: 6}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: 2, height: 1} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 2, width: 2, height: 2} }); times(100, () => game.step()); state = game.step(); test.expect(6); for (let i = 0; i < 4; ++i) { test.ok(state.blocks[i + state.width * (state.height - 1)].color, "Empty block found"); } for (let i = 4; i < 6; ++i) { test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found"); } test.done(); }); module.exports.testOverhang = ((test) => { const game = new GameEngine({initialRows: 0}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: 1, height: 2} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); times(100, () => game.step()); state = game.step(); test.expect(2 * game.width - 1); for (let i = 1; i < game.width; ++i) { test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found"); } for (let i = 0; i < game.width; ++i) { test.ok(state.blocks[i + state.width * (state.height - 3)].color, "Empty block found"); } test.done(); }); module.exports.testShock = ((test) => { setup = [ _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, G, R, G, G, B, B, ]; const game = new GameEngine({width: 6, height: 5, colors: setup}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); game.addEvent({ time: 101, type: 'swap', index: 24 }); test.expect(2 + 2 * game.width); times(99, () => game.step()); let state = game.step(); let numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0); test.strictEqual(numGarbage, game.width * 4, 'Not enough garbage found'); times(99, () => game.step()); state = game.step(); numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0); test.strictEqual(numGarbage, game.width * 2, 'Garbage not released correctly'); // We don't control RNG here so prepare for rare matches. const shift = game.width * !state.blocks[0].color; for (let i = 0; i < game.width; ++i) { test.ok(state.blocks[i + shift].garbage, "Garbage not preserved"); test.ok(!state.blocks[i + game.width + shift].garbage, "Garbage not released"); } test.done(); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { let root = arguments.length <= 0 || arguments[0] === undefined ? '.' : arguments[0]; let options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; root = (0, _path.normalize)((0, _path.resolve)(root)); options.routes = clone(options.routes || []); options = Object.assign({ routes: null, index: '/index' }, options); for (let route of options.routes) { route.url = (0, _pathToRegexp2.default)(route.url); } return function* (next) { for (let route of options.routes) { let matched, params; if (this.path === '/') { break; } if (!(matched = route.url.exec(this.path))) { continue; } params = {}; matched = matched.slice(1); route.url.keys.forEach((item, index) => { params[item.name] = matched[index]; }); this.params = params; this.path = route.controller; break; } if (this.params) { if (!this.state.renderData) { this.state.renderData = {}; } Object.assign(this.state.renderData, this.params); } let path = (0, _path.join)(root, (this.path === '/' ? options.index : this.path) + '.js'); try { if ((yield _coFs2.default.stat(path)).isFile()) { yield _interopRequireDefault(require(path)).default().call(this); } } catch (err) { if (~['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'].indexOf(err.code)) { return; } } yield next; }; }; var _coFs = require('co-fs'); var _coFs2 = _interopRequireDefault2(_coFs); var _pathToRegexp = require('path-to-regexp'); var _pathToRegexp2 = _interopRequireDefault2(_pathToRegexp); var _path = require('path'); function _interopRequireDefault2(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); }
'use strict'; /** * Home controller simply lists all the videos */ angular.module("nodeVideoCMS.videos").controller("VideosCtrl", function($scope, $routeParams, api){ var videosPerPage = 12, criteria; $scope.maxSize = 5; $scope.currentPage = 1; $scope.paginationVisible = false; if($routeParams && $routeParams.categoryID) { criteria = { category : parseInt($routeParams.categoryID) } } api.videos.list(0, videosPerPage, criteria).success(function (res) { $scope.totalItems = res.total_record_count; $scope.videos = res.records; $scope.paginationVisible = $scope.totalItems > videosPerPage; }); api.categories.list().success(function (categories) { $scope.categories = categories; }); $scope.pageChanged = function() { var start = videosPerPage * ($scope.currentPage - 1), end = videosPerPage * $scope.currentPage; api.videos.list(start, end, criteria).success(function (res) { $scope.videos = res.records; }); }; });
/* global window */ import React from 'react' import NProgress from 'nprogress' import PropTypes from 'prop-types' import { connect } from 'dva' import { Helmet } from 'react-helmet' import { withRouter } from 'dva/router' let lastHref const App = ({ children, dispatch, app, loading, location }) => { const href = window.location.href if (lastHref !== href) { NProgress.start() if (!loading.global) { NProgress.done() lastHref = href } } return ( <div> <Helmet> <title>DVA DEMO</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </Helmet> <div> { children } </div> </div> ) } App.propTypes = { children: PropTypes.element.isRequired, location: PropTypes.object, dispatch: PropTypes.func, app: PropTypes.object, loading: PropTypes.object, } export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App))
'use strict'; describe("Calling the fromTo-function of a moment", function(){ moment.period .add({name: 'fromTo15Minutes', count: 15, unit: 'minute'}) .add({name: 'fromTo1Month', count: 1, unit: 'month'}); it("should create an object with properties for from and to", function(){ expect(moment().fromTo().from).toBeDefined(); expect(moment().fromTo().to).toBeDefined(); }); it("should return a fromTo where from and to are same as moment if no period is defined", function(){ var testMoment = moment(); expect(testMoment.isSame(testMoment.fromTo().from)).toBe(true); expect(testMoment.isSame(testMoment.fromTo().to)).toBe(true); }); it("should return the start and the end of the period of a moment", function() { var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes'); expect(testMoment.clone().period(true).isSame(testMoment.fromTo().from)).toBe(true); expect(testMoment.clone().period(false).isSame(testMoment.fromTo().to)).toBe(true); }); it("should return the start and the end of a named period for a moment", function() { var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes'); expect(testMoment.clone().period('fromTo1Month').period(true).isSame(testMoment.fromTo('fromTo1Month').from)).toBe(true); expect(testMoment.clone().period('fromTo1Month').period(false).isSame(testMoment.fromTo('fromTo1Month').to)).toBe(true); }); });
(function() { 'use strict'; angular.module('journal.component.editor') .service('EditorService', ['$http', 'AuthService', 'CONFIG', EditorService]); function EditorService($http, AuthService, CONFIG) { this.apiUrl = CONFIG.API_URL; this.checkSlug = function(title, id) { var url = this.apiUrl + '/posts/check_slug?slug=' + (title || ''); // check if id is set if (id) { url += '&post_id=' + id; } // do an API request return $http.get(url); }; this.getPost = function(id) { return $http.get(this.apiUrl + '/posts/get_post?post_id=' + id); }; this.getTags = function() { return $http.get(this.apiUrl + '/tags/all'); }; this.save = function(post) { var token = AuthService.getToken(), url = this.apiUrl + '/posts/save?token=' + token, authorId = post.author_id || '', title = post.title || '', markdown = post.markdown || '', featuredImage = post.featured_image || '', slug = post.slug || '', status = post.status || 2, tags = post.tags || [], publishedAt = post.published_at.getTime() / 1000 || Math.floor(Date.now() / 1000); // check if post_id is set if (post.id) { url += '&post_id=' + post.id; } // send the request to the API return $http.post(url, { author_id : authorId, title : title, markdown : markdown, featured_image : featuredImage, slug : slug, status : status, tags : tags, published_at : publishedAt}); }; } })();
/*global module, process*/ /*eslint no-use-before-define:0 */ var webpack = require('webpack'); var webpackDevServer = require('webpack-dev-server'); var path = require('path'); // Support for extra commandline arguments var argv = require('optimist') //--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX') .alias('e', 'env').default('e', 'dev') .argv; var config = { context: __dirname, entry: {'bundle': './main'}, output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: isDevServer() ? '/' : '' }, devServer: { publicPath: '/' }, reload: isDevServer() ? 'localhost' : null, module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' }, { test: /\.eot$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.ttf$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.svg$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.woff$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /index\.html$/, loader: 'file-loader?name=[path][name].[ext]&context=.' } ] }, resolve: { alias: { 'famous-flex': 'famous-flex/src' } }, plugins: [ new webpack.DefinePlugin({ VERSION: JSON.stringify(require('../package.json').version), ENV: JSON.stringify(argv.env) }) ] }; function isDevServer() { return process.argv.join('').indexOf('webpack-dev-server') > -1; } module.exports = config;
var hello = function() { alert("My name is" name) };